view software/eXist/mpdl-modules/src/de/mpg/mpiwg/berlin/mpdl/escidoc/TestESciDocEXist.java @ 0:408254cf2f1d

Erstellung
author Josef Willenborg <jwillenborg@mpiwg-berlin.mpg.de>
date Wed, 24 Nov 2010 17:24:23 +0100
parents
children
line wrap: on
line source

package de.mpg.mpiwg.berlin.mpdl.escidoc;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import de.mpg.mpiwg.berlin.mpdl.exception.ApplicationException;
import de.mpg.mpiwg.berlin.mpdl.util.XmlUtil;

public class TestESciDocEXist {
  private String protocol = "http";
  private String host = "mpdl-test.mpiwg-berlin.mpg.de";
  private int port = 30030;
  private String userName = "jwillenborg";
  private HttpClient httpClient;
  private String eSciDocCookieId;

  public static void main(String[] args) throws ApplicationException {
    try {
      TestESciDocEXist test = new TestESciDocEXist();
      test.init();
      test.testCalls();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void init() throws ApplicationException {
    httpClient = new HttpClient();
    Scanner in = new Scanner(System.in);
    System.out.print("Username: " + userName + ", Type your password: ");
    String password = in.nextLine();
    in.close();
    eSciDocCookieId = ESciDocRestSession.login(userName, password);
  }
  
  private void testCalls() throws ApplicationException {
    String result = "";
    xQuery();
    // xQueryPath();
    // xQueryByEscidocItemId();
    // result = createItem();
    // result = deleteItem();
  }
  
  private void xQuery() throws ApplicationException {
    String result = "";
    try {
      String xquery = 
        "xquery version \"1.0\"; \n" + 
        "declare namespace echo=\"http://www.mpiwg-berlin.mpg.de/ns/echo/1.0/\"; \n" + 
        "let $doc := doc(\"/db/mpdl/documents/standard/echo/zh/SongYingxing_1637.xml\") \n" +
        "let $sentences := $doc//echo:s \n" +
        "return $sentences \n";
      String xQueryEncoded = URLEncoder.encode(xquery, "utf-8");
      String request = "/mpdl/escidoc/exist:xquery/execute?query=" + xQueryEncoded + "&startRecord=1&maximumRecords=50";
      result = performGetRequest(request);
      System.out.println(result);
    } catch (UnsupportedEncodingException e) {
      throw new ApplicationException(e);      
    }
  }
  
  
  private void xQueryPath() throws ApplicationException {
    String result = "";
    try {
      String xqueryPath = "/mpdl/interface/doc-query.xql";
      String xQueryPathEncoded = URLEncoder.encode(xqueryPath, "utf-8");
      String xqueryPathParams = 
        "<params>" +
        "<param name=\"queryType\">fulltextMorph</param>" +
        "<param name=\"document\">/echo/la/Benedetti_1585.xml</param>" +
        "<param name=\"mode\">text</param>" +
        "<param name=\"query\">multiplicare</param>" +
        "<param name=\"queryResultPN\">1</param>" +
        "<param name=\"queryResultPageSize\">10</param>" +
        "</params>";
      String xqueryPathParamsEncoded = URLEncoder.encode(xqueryPathParams, "utf-8");
      String request = "/mpdl/escidoc/exist:xquery/execute?queryPath=" + xQueryPathEncoded + "&parameters=" + xqueryPathParamsEncoded;
      result = performGetRequest(request);
    } catch (UnsupportedEncodingException e) {
      throw new ApplicationException(e);      
    }
    System.out.println(result);
  }
  
  private void xQueryByEscidocItemId() throws ApplicationException {
    // /ir/item/escidoc:47344 is fulltext item of "/echo/la/Benedetti_1585"
    String result = "";
    try {
      String xquery = "//echo:s";
      String xqueryEncoded = URLEncoder.encode(xquery, "utf-8");
      String request = "/mpdl/escidoc/ir/item/escidoc:47344/exist:xquery/execute?query=" + xqueryEncoded + "&startRecord=1&maximumRecords=50";
      result = performGetRequest(request);
    } catch (UnsupportedEncodingException e) {
      throw new ApplicationException(e);      
    }
    System.out.println(result);
  }
  
  private String createItem() throws ApplicationException {
    String xmlDocumentFileName = "/Users/jwillenborg/tmp/echo/la/Archimedes_1565.xml";
    ESciDocRestSession escidocRestSession = ESciDocRestSession.getInstance(eSciDocCookieId);
    String eSciDocStageAreaUrl = escidocRestSession.uploadFileToESciDocStageArea(xmlDocumentFileName);  
    String contentModelId = "/cmm/content-model/escidoc:persistent4";  // TODO  take final contentModelId: "/cmm/content-model/escidoc:exist-xml"
    String contextId = "/ir/context/escidoc:38600";  // TODO take final contextId
    String pid = escidocRestSession.getPid();
    MetadataRecord mdRecord = new MetadataRecord();
    String docBase = "echo";
    mdRecord.setCreator("Archimedes");
    mdRecord.setTitle("Archimedis De iis quae ve huntur in aqua libri duo");
    Date py = XmlUtil.getInstance().toDate("1565" + "-01-01T00:00:00.000Z");
    mdRecord.setDate(py);
    mdRecord.setMediaType("fulltext");
    mdRecord.setDocBase(docBase);
    mdRecord.setLanguage("la");
    mdRecord.setEXistIdentifier("/echo/la/Archimedes_1565.xml");
    ArrayList<Component> components = new ArrayList<Component>();
    String contentCategory = "fulltext XML - ECHO";
    if (docBase != null && docBase.equals("archimedes"))
      contentCategory = "fulltext XML - Archimedes";
    Component componentXmlFulltext = new Component("valid", "public", contentCategory, "text/xml", eSciDocStageAreaUrl, "internal-managed");
    components.add(componentXmlFulltext);
    Item xmlFulltextItem = new Item(contextId, pid, mdRecord, contentModelId, components);
    String xmlFulltextItemStr = xmlFulltextItem.toXmlString();
    String containerIdOfFulltextItem = "/ir/container/escidoc:51122";
    String newItemXmlStr = performPostRequest("/mpdl/escidoc" + containerIdOfFulltextItem + "/create-item", xmlFulltextItemStr, null);
    return newItemXmlStr; 
  }
  
  private String deleteItem() {
    String itemId = "/ir/item/escidoc:73012";
    String retStr = performDeleteRequest("/mpdl/escidoc" + itemId);
    return retStr; 
  }

  private String createContainer() throws ApplicationException {
    String containerIdOfEchoDocBase = "/ir/container/escidoc:51122";  // TODO
    String contentModelId = "/cmm/content-model/escidoc:persistent4";  // TODO  take final contentModelId: "/cmm/content-model/escidoc:exist-xml"
    String contextId = "/ir/context/escidoc:38600";  // TODO take final contextId
    ESciDocRestSession escidocRestSession = ESciDocRestSession.getInstance(eSciDocCookieId);
    String pid = escidocRestSession.getPid();
    MetadataRecord mdRecord = new MetadataRecord();
    mdRecord.setEXistIdentifier("/echo");
    Container container = new Container(contentModelId, contextId, pid, mdRecord);
    String xmlContainerStr = container.toXmlString();
    String newContainerXmlStr = performPostRequest("/mpdl/escidoc" + containerIdOfEchoDocBase + "/create-container", xmlContainerStr, null);
    return newContainerXmlStr; 
  }
  
  private String deleteContainer() {
    String containerId = "/ir/container/escidoc:71010";  // TODO
    String retStr = performDeleteRequest("/mpdl/escidoc" + containerId);
    return retStr; 
  }

  private String performPostRequest(String requestUrlStr, String requestInputStreamStr, HttpMethodParams parameter) throws ApplicationException {
    String resultStr = null;
    try {
      String urlStr = protocol + "://" + host + ":" + port + requestUrlStr;
      PostMethod method = new PostMethod(urlStr);
      method.setRequestHeader("Cookie", "escidocCookie=" + eSciDocCookieId);
      method.setFollowRedirects(false); 
      if (requestInputStreamStr != null) {
        InputStream requestInputStream = new ByteArrayInputStream(requestInputStreamStr.getBytes("UTF-8"));
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(requestInputStream);
        method.setRequestEntity(inputStreamRequestEntity); 
      }
      if (parameter != null) {
        method.setParams(parameter);
      }
      httpClient.executeMethod(method); 
      resultStr = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      throw new ApplicationException(e);      
    } catch (IOException e) {
      throw new ApplicationException(e);      
    }
    return resultStr; 
  } 

  private String performPostRequest(String requestUrlStr, File requestFile, HttpMethodParams parameter) throws ApplicationException {
    String resultStr = null;
    try {
      String urlStr = protocol + "://" + host + ":" + port + requestUrlStr;
      PostMethod method = new PostMethod(urlStr);
      method.setRequestHeader("Cookie", "escidocCookie=" + eSciDocCookieId);
      method.setFollowRedirects(false); 
      if (requestFile != null) {
        /**
        FilePart requestFilePart = new FilePart(requestFile.getName(), requestFile);
        Part[] parts = { requestFilePart };
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams());
        method.setRequestEntity(multipartRequestEntity);
        **/
        FileInputStream requestFileInputStream = new FileInputStream(requestFile);
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(requestFileInputStream);
        method.setRequestEntity(inputStreamRequestEntity); 
      }
      if (parameter != null) {
        method.setParams(parameter);
      }
      httpClient.executeMethod(method); 
      resultStr = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      throw new ApplicationException(e);      
    } catch (IOException e) {
      throw new ApplicationException(e);      
    }
    return resultStr; 
  } 

  private String performPutRequestByBody(String requestName, String bodyContent) {
    String resultStr = null;
    try {
      String urlStr = protocol + "://" + host + ":" + port + requestName;
      PutMethod method = new PutMethod(urlStr);
      method.setRequestHeader("Cookie", "escidocCookie=" + eSciDocCookieId);
      if (bodyContent != null) {
        method.setRequestBody(bodyContent);
      }
      httpClient.executeMethod(method); 
      resultStr = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      e.printStackTrace();      
    } catch (IOException e) {
      e.printStackTrace();      
    }
    return resultStr; 
  } 

  private String performDeleteRequest(String requestName) {
    String resultStr = null;
    try {
      String urlStr = protocol + "://" + host + ":" + port + requestName;
      DeleteMethod method = new DeleteMethod(urlStr);
      method.setRequestHeader("Cookie", "escidocCookie=" + eSciDocCookieId);
      httpClient.executeMethod(method); 
      resultStr = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      e.printStackTrace();      
    } catch (IOException e) {
      e.printStackTrace();      
    }
    return resultStr;
  } 

  private String performGetRequest(String requestName) {
    String resultStr = null;
    try {
      String urlStr = protocol + "://" + host + ":" + port + requestName;
      GetMethod method = new GetMethod(urlStr);
      method.setRequestHeader("Cookie", "escidocCookie=" + eSciDocCookieId);
      httpClient.executeMethod(method); 
      resultStr = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      e.printStackTrace();      
    } catch (IOException e) {
      e.printStackTrace();      
    }
    return resultStr;
  } 

  private String performPostRequestByBody(String requestUrlStr, String bodyContent) throws ApplicationException {
    String resultStr = null;
    try {
      String urlStr = protocol + "://" + host + ":" + port + requestUrlStr;
      PostMethod method = new PostMethod(urlStr);
      method.setFollowRedirects(false); 
      if (bodyContent != null) {
        method.setRequestBody(bodyContent);
      }
      httpClient.executeMethod(method); 
      resultStr = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      throw new ApplicationException(e);      
    } catch (IOException e) {
      throw new ApplicationException(e);      
    }
    return resultStr; 
  } 
  
}