Mercurial > hg > mpdl-group
view software/eXist/mpdl-modules/src/de/mpg/mpiwg/berlin/mpdl/escidoc/ESciDocRestSession.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.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.namespace.NamespaceContext; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; 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.general.MpdlConstants; import de.mpg.mpiwg.berlin.mpdl.util.FileUtil; import de.mpg.mpiwg.berlin.mpdl.util.XmlUtil; public class ESciDocRestSession { private static String CONTENT_ENCODING = "utf-8"; private static String STAGE_PATH = "/st/staging-file"; private static String LINE_SEPARATOR = System.getProperty("line.separator"); private static Pattern PATTERN_XML_BASE_ATTRIBUTE = Pattern.compile("xml:base=\"([^\"]*)\""); private static Pattern PATTERN_XLINK_HREF_ATTRIBUTE = Pattern.compile("xlink:href=\"([^\"]*)\""); private String protocol = "http"; private String host = "escidoc-dev.mpiwg-berlin.mpg.de"; private int port = 8080; private String contentModelId; private String contextId; private HttpClient httpClient; private String cookieId; public static ESciDocRestSession getInstance(String cookieId) throws ApplicationException { ESciDocRestSession instance = new ESciDocRestSession(); instance.protocol = "http"; instance.host = MpdlConstants.MPDL_ESCIDOC_HOST_NAME; instance.port = MpdlConstants.MPDL_ESCIDOC_PORT; instance.contentModelId = MpdlConstants.MPDL_ESCIDOC_CMM_ID; instance.contextId = MpdlConstants.MPDL_ESCIDOC_CONTEXT_ID; instance.cookieId = cookieId; instance.httpClient = new HttpClient(); return instance; } public static String login(String userName, String pw) throws ApplicationException { String protocol = "http"; String host = MpdlConstants.MPDL_ESCIDOC_HOST_NAME; int port = MpdlConstants.MPDL_ESCIDOC_PORT; String cookieId = null; try { String frameworkUrl = protocol + "://" + host + ":" + port; HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(host, port, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod( frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userName); login.addParameter("j_password", pw); client.executeMethod(login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod("/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); client.executeMethod(postMethod); Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); Base64 base64 = new Base64(); String locationTemp = location.substring(index + 1, location.length()); cookieId = new String(base64.decode(locationTemp.getBytes())); } } // if login is possible but the grants are not enough if (cookieId != null) { ESciDocRestSession session = getInstance(cookieId); String grantAdminHref = session.getGrantHrefByUserNameAndRoleName(userName, "escidoc:role-system-administrator"); if (grantAdminHref == null) cookieId = "-10"; } postMethod.releaseConnection(); } catch (Exception e) { throw new ApplicationException(e); } return cookieId; } // validation service of eSciDoc // TODO not implemented yet public void validate(String pid, MetadataRecord mdRecord, String srcUrl) throws ApplicationException { Component component = new Component("valid", "public", "any fulltext", "text/xml", srcUrl, "internal-managed"); ArrayList<Component> components = new ArrayList<Component>(); components.add(component); Item xmlTemplate = new Item(contextId, pid, mdRecord, contentModelId, components); String itemXmlStr = xmlTemplate.toXmlString(); String uri = "/validation/rest/validateItemXmlBySchema"; HttpMethodParams parameter = new HttpMethodParams(); parameter.setParameter("validation-point", ""); // None (Pick the validation schema from the context provided with the item) parameter.setParameter("validation-schema", ""); // None (Default) String valAnswer = performPostRequest(uri, itemXmlStr, parameter); } public String getCookieId() { return cookieId; } public void openContext(String contextId) throws ApplicationException { String contextXmlStr = getContextById(contextId); Date lastModificationDate = getLastModificationDate(contextXmlStr); String lastModificationDateStr = XmlUtil.getInstance().toXsDate(lastModificationDate); String bodyContentStr = "<param last-modification-date=\"" + lastModificationDateStr + "\"/>"; String uri = "/ir/context/" + contextId + "/open"; performPostRequestByBody(uri, bodyContentStr); } public String createContext(String organizationalUnit, String name, String description, String type) throws ApplicationException { Context xmlTemplate = new Context(organizationalUnit, name, description, type); String bodyContentXmlStr = xmlTemplate.toXmlString(); String contextXmlStr = performPutRequestByBody("/ir/context", bodyContentXmlStr); String contextId = getFirstContextId(contextXmlStr); return contextId; } public String getContextById(String contextId) throws ApplicationException { String bodyContent = "<param><filter><id>" + contextId + "</id></filter></param>"; String requestUrlStr = "/ir/contexts/filter"; String resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); return resultXmlStr; } public void grant(String userName, String roleName) throws ApplicationException { String grantXmlStr = null; String userId = null; String internalRoleName = null; if (roleName != null && roleName.equals("admin")) { internalRoleName = "escidoc:role-system-administrator"; userId = getUserId(userName); Grant grant = new Grant(userName, userId, "System-Administrator", "/aa/role/" + internalRoleName); grantXmlStr = grant.toXmlString(); } String grantHref = getGrantHrefByUserNameAndRoleName(userName, internalRoleName); if (grantHref == null || grantHref.equals("")) performPutRequestByBody(userId + "/resources/grants/grant", grantXmlStr); } public String getGrantHrefByUserNameAndRoleName(String userName, String roleName) throws ApplicationException { String resultXmlStr = null; String fullUserId = getUserId(userName); // // e.g. userId=/aa/user-account/escidoc:22650 if (fullUserId != null) { int userIdIndex = fullUserId.lastIndexOf("/"); if (userIdIndex != -1) { String userId = fullUserId.substring(userIdIndex + 1); String filterUserName = "<filter name=\"http://escidoc.de/core/01/properties/user\">" + userId + "</filter>"; // e.g. userId=escidoc:22650 String filterRoleName = "<filter name=\"http://escidoc.de/core/01/properties/role\">" + roleName + "</filter>"; // e.g. roleName=escidoc:role-system-administrator String bodyContent = "<param>" + filterUserName + filterRoleName + "</param>"; String requestUrlStr = "/aa/grants/filter"; resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); resultXmlStr = getFirstGrantId(resultXmlStr); } } return resultXmlStr; } public String getGrantsByUserName(String userName) throws ApplicationException { String resultXmlStr = null; String fullUserId = getUserId(userName); // // e.g. userId=/aa/user-account/escidoc:22650 if (fullUserId != null) { int userIdIndex = fullUserId.lastIndexOf("/"); if (userIdIndex != -1) { String userId = fullUserId.substring(userIdIndex + 1); String filterUserName = "<filter name=\"http://escidoc.de/core/01/properties/user\">" + userId + "</filter>"; // e.g. userId=escidoc:22650 String bodyContent = "<param>" + filterUserName + "</param>"; String requestUrlStr = "/aa/grants/filter"; resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); } } return resultXmlStr; } public String createContainer(String pid, MetadataRecord mdRecord) throws ApplicationException { Container xmlTemplate = new Container(contentModelId, contextId, pid, mdRecord); String bodyContentXmlStr = xmlTemplate.toXmlString(); String containerXmlStr = performPutRequestByBody("/ir/container", bodyContentXmlStr); String containerId = getFirstContainerId(containerXmlStr); return containerId; } public Container createContainerInContainer(String pid, MetadataRecord mdRecord, String containerId) throws ApplicationException { Container xmlTemplate = new Container(contentModelId, contextId, pid, mdRecord); String bodyContentXmlStr = xmlTemplate.toXmlString(); String uri = containerId + "/create-container"; String containerXmlStr = performPostRequestByBody(uri, bodyContentXmlStr); String retContainerId = getFirstContainerId(containerXmlStr); Date lastModificationDate = getLastModificationDate(containerXmlStr); Container container = new Container(retContainerId, lastModificationDate); return container; } public Item createItemInContainer(String containerId, String pid, MetadataRecord mdRecord, ArrayList<Component> components) throws ApplicationException { Item xmlTemplate = new Item(contextId, pid, mdRecord, contentModelId, components); String bodyContentXmlStr = xmlTemplate.toXmlString(); String uri = containerId + "/create-item"; String itemXmlStr = performPostRequestByBody(uri, bodyContentXmlStr); String itemId = getFirstItemId(itemXmlStr); Date lastModificationDate = getLastModificationDate(itemXmlStr); Item item = new Item(itemId, lastModificationDate); return item; } public Item createItemInContainer(String containerId, String itemXmlStr) throws ApplicationException { String uri = containerId + "/create-item"; String retItemXmlStr = performPostRequestByBody(uri, itemXmlStr); String itemId = getFirstItemId(retItemXmlStr); Date lastModificationDate = getLastModificationDate(retItemXmlStr); String validStatus = ""; // TODO String visibility = ""; // TODO String contentCategory = ""; // TODO String mimeType = ""; // TODO String url = getFirstComponentId(retItemXmlStr); String storage = ""; // TODO Component component = new Component(validStatus, visibility, contentCategory, mimeType, url, storage); Item item = new Item(itemId, lastModificationDate); item.addComponent(component); return item; } public void submitContainer(String containerId, Date lastModificationDate, String comment) throws ApplicationException { String uri = containerId + "/submit"; String dateStr = XmlUtil.getInstance().toXsDate(lastModificationDate); String xmlStr = "<param last-modification-date=\"" + dateStr + "\"><comment>" + comment + "</comment></param>"; performPostRequestByBody(uri, xmlStr); } public void submitItem(String itemId, Date lastModificationDate, String comment) throws ApplicationException { String uri = itemId + "/submit"; String dateStr = XmlUtil.getInstance().toXsDate(lastModificationDate); String xmlStr = "<param last-modification-date=\"" + dateStr + "\"><comment>" + comment + "</comment></param>"; performPostRequestByBody(uri, xmlStr); } public Date addMembers(String containerId, Date lastModificationDate, ArrayList<String> memberIds) throws ApplicationException { if (containerId == null || lastModificationDate == null || memberIds == null) return null; String dateStr = XmlUtil.getInstance().toXsDate(lastModificationDate); String membersXmlStr = "<param last-modification-date=\"" + dateStr + "\">"; for (int i=0; i< memberIds.size(); i++) { String memberId = memberIds.get(i); membersXmlStr = membersXmlStr + "<id>" + "escidoc:" + memberId +"</id>"; } membersXmlStr += "</param>"; String lastModDateXmlStr = performPostRequestByBody(containerId + "/members/add", membersXmlStr); Date lastModDate = getLastModificationDate(lastModDateXmlStr); return lastModDate; } public Date removeMembers(String containerId, Date lastModificationDate, ArrayList<String> memberIds) throws ApplicationException { if (containerId == null || lastModificationDate == null || memberIds == null) return null; String dateStr = XmlUtil.getInstance().toXsDate(lastModificationDate); String membersXmlStr = "<param last-modification-date=\"" + dateStr + "\">"; for (int i=0; i< memberIds.size(); i++) { String memberId = memberIds.get(i); // if memberId is a full id and contains non digits they will be removed: e.g. /ir/item/escidoc:4711 will be replaced by 4711 if (! memberId.matches("[0-9]+")) { memberId = memberId.replaceAll("[^0-9]+", ""); } membersXmlStr = membersXmlStr + "<id>" + "escidoc:" + memberId +"</id>"; } membersXmlStr += "</param>"; String lastModDateXmlStr = performPostRequestByBody(containerId + "/members/remove", membersXmlStr); Date lastModDate = getLastModificationDate(lastModDateXmlStr); return lastModDate; } public Item createItem(String pid, MetadataRecord mdRecord, ArrayList<Component> components) throws ApplicationException { Item xmlTemplate = new Item(contextId, pid, mdRecord, contentModelId, components); String xmlStr = xmlTemplate.toXmlString(); String itemXmlStr = performPutRequestByBody("/ir/item", xmlStr); String itemId = getFirstItemId(itemXmlStr); Date lastModificationDate = getLastModificationDate(itemXmlStr); Item item = new Item(itemId, lastModificationDate); return item; } public Date updateItem(String itemId, Date lastModificationDate, String pid, MetadataRecord mdRecord, ArrayList<Component> components) throws ApplicationException { if (itemId == null || lastModificationDate == null) return null; Item xmlTemplate = new Item(contextId, pid, mdRecord, contentModelId, components); xmlTemplate.setLastModificationDate(lastModificationDate); String xmlStr = xmlTemplate.toXmlString(); String itemXmlStr = performPutRequestByBody(itemId, xmlStr); Date newVersionDate = getVersionDate(itemXmlStr); return newVersionDate; } public void deleteItem(String itemId) { if (itemId != null) { performDeleteRequest(itemId); } } public void deleteContainer(String containerId) { if (containerId != null) { performDeleteRequest(containerId); } } public Date getContainerLastModificationDate(String containerId) throws ApplicationException { Date lastModificationDate = null; String resultXmlStr = getContainer(containerId); if (resultXmlStr != null) { lastModificationDate = getLastModificationDate(resultXmlStr); } return lastModificationDate; } public String getContainer(String containerId) throws ApplicationException { String resultXmlStr = null; if (containerId != null) { resultXmlStr = performGetRequest(containerId); } return resultXmlStr; } public String getItem(String itemId) throws ApplicationException { String resultXmlStr = null; if (itemId != null) { resultXmlStr = performGetRequest(itemId); } return resultXmlStr; } public void saveComponentContentToLocalFile(String componentContentId, String localFileName) throws ApplicationException { if (componentContentId != null) { performGetRequestToLocalFile(componentContentId, localFileName); } } public String getUserId(String userName) throws ApplicationException { String userId = null; if (userName != null) { String userNameAccessStr = userName + ",uid=" + userName + ",ou=users,dc=wisges,dc=rz-berlin,dc=mpg,dc=de"; String resultXmlStr = performGetRequest("/aa/user-account/" + userNameAccessStr); userId = getFirstUserId(resultXmlStr); } return userId; } public String getUser(String userName) throws ApplicationException { String resultXmlStr = null; if (userName != null) { String userNameAccessStr = userName + ",uid=" + userName + ",ou=users,dc=wisges,dc=rz-berlin,dc=mpg,dc=de"; resultXmlStr = performGetRequest("/aa/user-account/" + userNameAccessStr); } return resultXmlStr; } public String getAllUsers() throws ApplicationException { String bodyContent = "<param><filter></filter></param>"; String requestUrlStr = "/aa/user-accounts/filter"; String resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); return resultXmlStr; } public String getMembersByContainerIdAndFilter(String containerId, String filter) throws ApplicationException { String bodyContent = "<param><filter></filter></param>"; if (filter != null) bodyContent = "<param>" + filter + "</param>"; String requestUrlStr = containerId + "/members/filter"; String resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); return resultXmlStr; } public String getAllItems() throws ApplicationException { String bodyContent = "<param><filter></filter></param>"; String requestUrlStr = "/ir/items/filter"; String resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); return resultXmlStr; } private String getContainerByEXistId(String existId) throws ApplicationException { String bodyContent = "<param><filter name=\"/md-records/md-record/metadata/exist-identifier\">" + existId + "</filter></param>"; // e.g. existId = /echo/la/alvarus_1509_lat_V40_10.xml String requestUrlStr = "/ir/containers/filter"; String resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); return resultXmlStr; } public String getContainerIdByEXistId(String existId) throws ApplicationException { String containerXmlStr = getContainerByEXistId(existId); String eScidDocContainerId = null; if (containerXmlStr != null && containerXmlStr != "") { eScidDocContainerId = getFirstContainerId(containerXmlStr); } return eScidDocContainerId; } public String getItemByPid(String pid) throws ApplicationException { String bodyContent = "<param><filter name=\"/properties/pid\">" + pid + "</filter></param>"; String requestUrlStr = "/ir/items/filter"; String resultXmlStr = performPostRequestByBody(requestUrlStr, bodyContent); return resultXmlStr; } public String uploadFileToESciDocStageArea(String filePath) throws ApplicationException { StringBuffer result = new StringBuffer(); try { URL createUrl = new URL(protocol + "://" + host + ":" + port + STAGE_PATH); HttpURLConnection uploadConnection = (HttpURLConnection) createUrl.openConnection(); uploadConnection.setRequestProperty("Cookie", "escidocCookie=" + cookieId); uploadConnection.setRequestMethod("PUT"); uploadConnection.setDoOutput(true); // open POST Request OutputStream out = uploadConnection.getOutputStream(); // access binary content InputStream in = new FileInputStream(filePath); // write template to POST Request byte[] bytes = new byte[4096]; int l = in.read(bytes); while (l > -1) { out.write(bytes, 0, l); l = in.read(bytes); } in.close(); out.close(); uploadConnection.connect(); // connect response reader BufferedReader createdReader = null; String contentEncoding = uploadConnection.getContentEncoding(); if (contentEncoding == null) { contentEncoding = CONTENT_ENCODING; } createdReader = new BufferedReader(new InputStreamReader(uploadConnection.getInputStream(), contentEncoding)); // read response String line = createdReader.readLine(); while (line != null) { result.append(line); result.append(LINE_SEPARATOR); line = createdReader.readLine(); } createdReader.close(); } catch (IOException e) { throw new ApplicationException(e); } String stageUrl = obtainResourceHref(result.toString()); return stageUrl; } public String getPid() throws ApplicationException { return "mpiwg:47114711"; // TODO /* try { XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); XmlRpcClient client = new XmlRpcClient(); String zopeUrlStr = "http://xserve07.mpiwg-berlin.mpg.de:18080"; config.setServerURL(new URL(zopeUrlStr + "/idGenerator")); client.setConfig(config); Object[] params = new Object[]{}; String pid = (String) client.execute("generateId", params); return pid; } catch (MalformedURLException e) { throw new ApplicationException(e); } catch (XmlRpcException e) { throw new ApplicationException(e); } */ } public ArrayList<String> getContainerIds(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); ArrayList<String> containerIds = xmlUtil.evaluateToStringArray(xmlStr, "//srel:container/@xlink:href", nsContext); return containerIds; } public ArrayList<String> getContainerTitles(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); ArrayList<String> containerTitles = xmlUtil.evaluateToStringArray(xmlStr, "//srel:container/@xlink:title", nsContext); return containerTitles; } public String getLatestVersionId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String id = xmlUtil.evaluateToString(xmlStr, "//prop:latest-version/@xlink:href", nsContext); return id; } public String getFirstUserId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String id = xmlUtil.evaluateToString(xmlStr, "//user-account:user-account/@xlink:href", nsContext); return id; } public String getFirstGrantId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String g = xmlUtil.evaluateToString(xmlStr, "//grants:grant/@xlink:href", nsContext); return g; } public String getFirstContextId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String id = xmlUtil.evaluateToString(xmlStr, "//context:context/@xlink:href", nsContext); return id; } public String getFirstContainerId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String id = xmlUtil.evaluateToString(xmlStr, "//container:container/@xlink:href", nsContext); return id; } public String getFirstItemId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String id = xmlUtil.evaluateToString(xmlStr, "//escidocItem:item/@xlink:href", nsContext); return id; } public String getFirstStageAreaURL(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String eSciDocStageAreaUrl = xmlUtil.evaluateToString(xmlStr, "//escidocComponents:content/@xlink:href", nsContext); return eSciDocStageAreaUrl; } public String getFirstComponentId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String componentId = xmlUtil.evaluateToString(xmlStr, "//escidocComponents:content/@xlink:href", nsContext); return componentId; } public String getFirstEXistId(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String id = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/mpiwg:exist-identifier", nsContext); return id; } public MetadataRecord getFirstMdRecord(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String id = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/dc:identifier", nsContext); String language = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/dc:language", nsContext); String creator = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/dc:creator", nsContext); String title = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/dc:title", nsContext); String type = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/dc:type", nsContext); String rights = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/dc:rights", nsContext); String dateStr = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/dc:date", nsContext); Date date = new Date(dateStr); String license = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/mpiwg:license", nsContext); String accessRights = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/mpiwg:accessRights", nsContext); String mediaType = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/mpiwg:mediaType", nsContext); String existId = xmlUtil.evaluateToString(xmlStr, "/escidocItem:item/escidocMetadataRecords:md-records/escidocMetadataRecords:md-record/metadata/mpiwg:exist-identifier", nsContext); MetadataRecord mdRecord = new MetadataRecord(id, language, creator, title, null, null, type, rights, date); // TODO vervollständigen, testen mdRecord.setLicense(license); mdRecord.setAccessRights(accessRights); mdRecord.setMediaType(mediaType); mdRecord.setEXistIdentifier(existId); return mdRecord; } public Date getVersionDate(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String dateStr = xmlUtil.evaluateToString(xmlStr, "//version:date", nsContext); Date lastModificationDate = xmlUtil.toDate(dateStr); return lastModificationDate; } public Date getLastModificationDate(String xmlStr) throws ApplicationException { NamespaceContext nsContext = getNsContext(); XmlUtil xmlUtil = XmlUtil.getInstance(); String dateStr = xmlUtil.evaluateToString(xmlStr, "//*/@last-modification-date", nsContext); Date lastModificationDate = xmlUtil.toDate(dateStr); return lastModificationDate; } private String obtainResourceHref(String xml) { // base String base = ""; Matcher baseMatcher = PATTERN_XML_BASE_ATTRIBUTE.matcher(xml); if (baseMatcher.find()) { base = baseMatcher.group(1); } // href String href = null; Matcher hrefMatcher = PATTERN_XLINK_HREF_ATTRIBUTE.matcher(xml); if (hrefMatcher.find()) { href = hrefMatcher.group(1); } else { throw new UnsupportedOperationException("Can not obtain href for resources without xlink:href attribute."); } return base + href; } 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); method.setRequestHeader("Cookie", "escidocCookie=" + cookieId); if (bodyContent != null) { method.setRequestBody(bodyContent); } httpClient.executeMethod(method); byte[] responseBody = method.getResponseBody(); resultStr = new String(responseBody, "utf-8"); method.releaseConnection(); } catch (HttpException e) { throw new ApplicationException(e); } catch (IOException e) { throw new ApplicationException(e); } return resultStr; } // TODO private String performPostRequest(String requestUrlStr, String bodyContent, HttpMethodParams parameter) throws ApplicationException { String resultStr = null; try { String urlStr = protocol + "://" + host + ":" + port + requestUrlStr; PostMethod method = new PostMethod(urlStr); method.setFollowRedirects(false); method.setRequestHeader("Cookie", "escidocCookie=" + cookieId); if (bodyContent != null) { method.setRequestBody(bodyContent); } if (parameter != null) { method.setParams(parameter); } httpClient.executeMethod(method); byte[] responseBody = method.getResponseBody(); resultStr = new String(responseBody, "utf-8"); 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=" + cookieId); if (bodyContent != null) { method.setRequestBody(bodyContent); } httpClient.executeMethod(method); byte[] responseBody = method.getResponseBody(); resultStr = new String(responseBody, "utf-8"); method.releaseConnection(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return resultStr; } private void performDeleteRequest(String requestName) { try { String urlStr = protocol + "://" + host + ":" + port + requestName; DeleteMethod method = new DeleteMethod(urlStr); method.setRequestHeader("Cookie", "escidocCookie=" + cookieId); httpClient.executeMethod(method); method.releaseConnection(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private String performGetRequest(String requestName) { String resultStr = null; try { String urlStr = protocol + "://" + host + ":" + port + requestName; GetMethod method = new GetMethod(urlStr); method.setRequestHeader("Cookie", "escidocCookie=" + cookieId); httpClient.executeMethod(method); byte[] responseBody = method.getResponseBody(); resultStr = new String(responseBody, "utf-8"); method.releaseConnection(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return resultStr; } private void performGetRequestToLocalFile(String requestName, String localFileName) throws ApplicationException { try { String urlStr = protocol + "://" + host + ":" + port + requestName; GetMethod method = new GetMethod(urlStr); method.setRequestHeader("Cookie", "escidocCookie=" + cookieId); httpClient.executeMethod(method); InputStream responseBodyInputStream = method.getResponseBodyAsStream(); FileUtil.getInstance().saveInputStreamToLocalFile(responseBodyInputStream, localFileName); method.releaseConnection(); } catch (HttpException e) { throw new ApplicationException(e); } catch (IOException e) { throw new ApplicationException(e); } } public static NamespaceContext getNsContext() { NamespaceContext nsContext = new NamespaceContext() { public String getNamespaceURI(String prefix) { String uri; if (prefix.equals("xlink")) uri = "http://www.w3.org/1999/xlink"; else if (prefix.equals("escidocItem")) uri = "http://www.escidoc.de/schemas/item/0.9"; else if (prefix.equals("user-account")) uri = "http://www.escidoc.de/schemas/useraccount/0.7"; else if (prefix.equals("grants")) uri = "http://www.escidoc.de/schemas/grants/0.5"; else if (prefix.equals("context")) uri = "http://www.escidoc.de/schemas/context/0.7"; else if (prefix.equals("container")) uri = "http://www.escidoc.de/schemas/container/0.8"; else if (prefix.equals("escidocMetadataRecords")) uri = "http://www.escidoc.de/schemas/metadatarecords/0.5"; else if (prefix.equals("escidocComponents")) uri = "http://www.escidoc.de/schemas/components/0.9"; else if (prefix.equals("prop")) uri = "http://escidoc.de/core/01/properties"; else if (prefix.equals("struct-map")) uri = "http://www.escidoc.de/schemas/structmap/0.4"; else if (prefix.equals("version")) uri = "http://escidoc.de/core/01/properties/version/"; else if (prefix.equals("srel")) uri = "http://escidoc.de/core/01/structural-relations/"; else if (prefix.equals("xml")) uri = "http://www.w3.org/XML/1998/namespace"; else if (prefix.equals("dc")) uri = "http://purl.org/dc/elements/1.1/"; else if (prefix.equals("mpiwg")) uri = "http://www.mpiwg-berlin.mpg.de/ns/mpiwg"; else uri = null; return uri; } public String getPrefix(String uri) { if (uri.equals("http://www.w3.org/1999/xlink")) return "xlink"; else if (uri.equals("http://www.escidoc.de/schemas/item/0.9")) return "escidocItem"; else if (uri.equals("http://www.escidoc.de/schemas/useraccount/0.7")) return "user-account"; else if (uri.equals("http://www.escidoc.de/schemas/grants/0.5")) return "grants"; else if (uri.equals("http://www.escidoc.de/schemas/context/0.7")) return "context"; else if (uri.equals("http://www.escidoc.de/schemas/container/0.8")) return "container"; else if (uri.equals("http://www.escidoc.de/schemas/metadatarecords/0.5")) return "escidocMetadataRecords"; else if (uri.equals("http://www.escidoc.de/schemas/components/0.9")) return "escidocComponents"; else if (uri.equals("http://escidoc.de/core/01/properties")) return "prop"; else if (uri.equals("http://www.escidoc.de/schemas/structmap/0.4")) return "struct-map"; else if (uri.equals("http://escidoc.de/core/01/properties/version/")) return "version"; else if (uri.equals("http://escidoc.de/core/01/structural-relations/")) return "srel"; else if (uri.equals("http://www.w3.org/XML/1998/namespace")) return "xml"; else if (uri.equals("http://purl.org/dc/elements/1.1/")) return "dc"; else if (uri.equals("http://www.mpiwg-berlin.mpg.de/ns/mpiwg")) return "mpiwg"; else return null; } public Iterator getPrefixes(String namespace) { return null; } }; return nsContext; } }