Currently only working with Intake (must be ported to CollectionObject and Acquisition).
This may benefit from some refactoring once I get the other ports done.
To test this work, refactored the base test (AbstractServiceTestImpl.java) so that it is easier to produce tests that do not focus on CRUD (these an inherit from a new BaseServiceTest class (yes, it could use a better name).
*/
package org.collectionspace.services.client.test;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-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.methods.StringRequestEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
-import org.collectionspace.services.client.TestServiceClient;
-import org.jboss.resteasy.client.ClientResponse;
-import org.jboss.resteasy.plugins.providers.multipart.InputPart;
-import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
-import org.testng.annotations.DataProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* AbstractServiceTest, abstract base class for the client tests to be performed
*
* For Javadoc descriptions of this class's methods, see the ServiceTest interface.
*/
-public abstract class AbstractServiceTestImpl implements ServiceTest {
-
- private final Logger logger =
- LoggerFactory.getLogger(AbstractServiceTestImpl.class);
- // A base-level client, used (only) to obtain the base service URL.
- protected static final TestServiceClient serviceClient =
- new TestServiceClient();
- // A resource identifier believed to be non-existent in actual use,
- // used when testing service calls that reference non-existent resources.
- protected final String NON_EXISTENT_ID = createNonExistentIdentifier();
- // The HTTP status code expected to be returned in the response,
- // from a request made to a service (where relevant).
- protected int EXPECTED_STATUS_CODE = 0;
- // The generic type of service request being tested
- // (e.g. CREATE, UPDATE, DELETE).
- //
- // This makes it possible to check behavior specific to that type of request,
- // such as the set of valid status codes that may be returned.
- //
- // Note that the default value is set to a guard value.
- protected ServiceRequestType REQUEST_TYPE = ServiceRequestType.NON_EXISTENT;
- // Static data to be submitted in various tests
- protected final static String XML_DECLARATION =
- "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
- // Note: this constant is intentionally missing its last angle bracket.
- protected final static String MALFORMED_XML_DATA =
- XML_DECLARATION
- + "<malformed_xml>wrong schema contents</malformed_xml";
- protected final String WRONG_XML_SCHEMA_DATA =
- XML_DECLARATION
- + "<wrong_schema>wrong schema contents</wrong_schema>";
- // A MIME media type character set designation for the entity bodies
- // of PUT and POST requests. Set this to null to avoid adding a character
- // set attribute to the MIME type in the "Content-Type:" HTTP header.
- final String NULL_CHARSET = null;
+public abstract class AbstractServiceTestImpl extends BaseServiceTest implements ServiceTest {
+
+ protected final Logger logger = LoggerFactory.getLogger(AbstractServiceTestImpl.class);
- // ---------------------------------------------------------------
- // CRUD tests : CREATE tests
- // ---------------------------------------------------------------
// Success outcomes
@Override
public void create(String testName) throws Exception {
}
protected void setupCreate(String label) {
- clearSetup();
- // Expected status code: 201 Created
- EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
- // Type of service request being tested
- REQUEST_TYPE = ServiceRequestType.CREATE;
- // Print a banner identifying the test that will be run.
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.CREATED.getStatusCode(), ServiceRequestType.CREATE, label);
}
@Override
}
protected void setupRead(String label) {
- clearSetup();
- // Expected status code: 200 OK
- EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.READ;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.OK.getStatusCode(), ServiceRequestType.READ, label);
}
// Failure outcomes
}
protected void setupReadNonExistent(String label) {
- clearSetup();
// Expected status code: 404 Not Found
- EXPECTED_STATUS_CODE = Response.Status.NOT_FOUND.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.READ;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.NOT_FOUND.getStatusCode(), ServiceRequestType.READ, label);
}
// ---------------------------------------------------------------
}
protected void setupReadList(String label) {
- clearSetup();
- // Expected status code: 200 OK
- EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.READ_LIST;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.OK.getStatusCode(), ServiceRequestType.READ_LIST, label);
}
// Failure outcomes
}
protected void setupUpdate(String label) {
- clearSetup();
// Expected status code: 200 OK
- EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.UPDATE;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.OK.getStatusCode(), ServiceRequestType.UPDATE, label);
}
// Failure outcomes
}
protected void setupUpdateWithEmptyEntityBody(String label) {
- clearSetup();
// Expected status code: 400 Bad Request
- EXPECTED_STATUS_CODE = Response.Status.BAD_REQUEST.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.UPDATE;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.BAD_REQUEST.getStatusCode(), ServiceRequestType.UPDATE, label);
}
@Override
}
protected void setupUpdateWithMalformedXml(String label) {
- clearSetup();
// Expected status code: 400 Bad Request
- EXPECTED_STATUS_CODE = Response.Status.BAD_REQUEST.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.UPDATE;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.BAD_REQUEST.getStatusCode(), ServiceRequestType.UPDATE, label);
}
@Override
}
protected void setupUpdateWithWrongXmlSchema(String label) {
- clearSetup();
// Expected status code: 400 Bad Request
- EXPECTED_STATUS_CODE = Response.Status.BAD_REQUEST.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.UPDATE;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.BAD_REQUEST.getStatusCode(), ServiceRequestType.UPDATE, label);
}
@Override
}
protected void setupUpdateNonExistent(String label) {
- clearSetup();
// Expected status code: 404 Not Found
- EXPECTED_STATUS_CODE = Response.Status.NOT_FOUND.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.UPDATE;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.NOT_FOUND.getStatusCode(), ServiceRequestType.UPDATE, label);
}
// ---------------------------------------------------------------
}
protected void setupDelete(String label) {
- clearSetup();
- // Expected status code: 200 OK
- EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
- REQUEST_TYPE = ServiceRequestType.DELETE;
- if (logger.isDebugEnabled()) {
- banner(label);
- }
+ testSetup(Response.Status.OK.getStatusCode(), ServiceRequestType.DELETE, label);
}
// Failure outcomes
banner(label);
}
}
-
- // ---------------------------------------------------------------
- // Abstract utility methods
- //
- // Must be implemented by classes that extend
- // this abstract base class.
- // ---------------------------------------------------------------
- /**
- * Returns the URL path component of the service.
- *
- * This component will follow directly after the
- * base path, if any.
- *
- * @return The URL path component of the service.
- */
- protected abstract String getServicePathComponent();
-
- /**
- * Returns the common part name for the service request.
- *
- * @return The common part name for the service request.
- */
- /*
- public String getCommonPartName();
- */
- // ---------------------------------------------------------------
- // Utility methods
- // ---------------------------------------------------------------
- /**
- * Reinitializes setup values, to help expose any unintended reuse
- * of those values between tests.
- */
- protected void clearSetup() {
- EXPECTED_STATUS_CODE = 0;
- REQUEST_TYPE = ServiceRequestType.NON_EXISTENT;
- }
-
- /**
- * Returns the name of the currently running test.
- *
- * Note: although the return type is listed as Object[][],
- * this method instead returns a String.
- *
- * @param m The currently running test method.
- *
- * @return The name of the currently running test method.
- */
- @DataProvider(name = "testName")
- public static Object[][] testName(Method m) {
- return new Object[][]{
- new Object[]{m.getName()}
- };
- }
-
- /**
- * Returns an error message indicating that the status code returned by a
- * specific call to a service does not fall within a set of valid status
- * codes for that service.
- *
- * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
- *
- * @param statusCode The invalid status code that was returned in the response,
- * from submitting that type of request to the service.
- *
- * @return An error message.
- */
- protected String invalidStatusCodeMessage(
- ServiceRequestType requestType, int statusCode) {
- return "Status code '" + statusCode
- + "' in response is NOT within the expected set: "
- + requestType.validStatusCodesAsString();
- }
-
- /**
- * Returns the root URL for a service.
- *
- * This URL consists of a base URL for all services, followed by
- * a path component (or components) for a service.
- *
- * @return The root URL for a service.
- */
- protected String getServiceRootURL() {
- return serviceClient.getBaseURL() + getServicePathComponent();
- }
-
- /**
- * Returns the URL of a specific resource managed by a service, and
- * designated by an identifier (such as a universally unique ID, or UUID).
- *
- * @param resourceIdentifier An identifier (such as a UUID) for a resource.
- *
- * @return The URL of a specific resource managed by a service.
- */
- protected String getResourceURL(String resourceIdentifier) {
- return getServiceRootURL() + "/" + resourceIdentifier;
- }
-
- /**
- * Submits an HTTP request to a specified URL, and returns the
- * status code of the response. Currently accepts GET and DELETE
- * requests.
- *
- * @param method An HTTP method.
- *
- * @param url A String representation of a URL.
- *
- * @return The status code received in the HTTP response.
- */
- protected int submitRequest(String method, String url) {
- int statusCode = 0;
- try {
- TestServiceClient client = new TestServiceClient();
- if (method.equals(javax.ws.rs.HttpMethod.DELETE)) {
- DeleteMethod deleteMethod = new DeleteMethod(url);
- statusCode = client.getHttpClient().executeMethod(deleteMethod);
- } else if (method.equals(javax.ws.rs.HttpMethod.GET)) {
- GetMethod getMethod = new GetMethod(url);
- statusCode = client.getHttpClient().executeMethod(getMethod);
- } else {
- // Do nothing - leave status code at default value.
- }
- } catch (Exception e) {
- logger.error(
- "Exception during HTTP " + method + " request to "
- + url + ":", e);
- }
- return statusCode;
- }
-
- /**
- * Submits an HTTP request to a specified URL, with the submitted
- * entity body, and returns the status code of the response.
- * Currently accepts POST and PUT requests.
- *
- * @param method An HTTP method.
- *
- * @param url A String representation of a URL.
- *
- * @param mediaType The media type of the entity body to be submitted.
- *
- * @param entity The contents of the entity body to be submitted.
- *
- * @return The status code received in the HTTP response.
- */
- protected int submitRequest(String method, String url,
- String mediaType, String entityStr) {
- int statusCode = 0;
- try {
- TestServiceClient client = new TestServiceClient();
- if (method.equals(javax.ws.rs.HttpMethod.POST)) {
- StringRequestEntity entityBody =
- new StringRequestEntity(mediaType, entityStr, NULL_CHARSET);
- PostMethod postMethod = new PostMethod(url);
- postMethod.setRequestEntity(entityBody);
- statusCode = client.getHttpClient().executeMethod(postMethod);
- } else if (method.equals(javax.ws.rs.HttpMethod.PUT)) {
- StringRequestEntity entityBody =
- new StringRequestEntity(mediaType, entityStr, NULL_CHARSET);
- PutMethod putMethod = new PutMethod(url);
- putMethod.setRequestEntity(entityBody);
- statusCode = client.getHttpClient().executeMethod(putMethod);
- } else {
- // Do nothing - leave status code at default value.
- }
- } catch (Exception e) {
- logger.error(
- "Exception during HTTP " + method + " request to "
- + url + ":", e);
- }
- return statusCode;
- }
-
- // @TODO Add Javadoc comments to all methods requiring them, below.
- protected String extractId(ClientResponse<Response> res) {
- MultivaluedMap mvm = res.getMetadata();
- String uri = (String) ((ArrayList) mvm.get("Location")).get(0);
- if (logger.isDebugEnabled()) {
- logger.debug("extractId:uri=" + uri);
- }
- String[] segments = uri.split("/");
- String id = segments[segments.length - 1];
- if (logger.isDebugEnabled()) {
- logger.debug("id=" + id);
- }
- return id;
- }
-
- protected String createIdentifier() {
- long identifier = System.currentTimeMillis();
- return Long.toString(identifier);
- }
-
- protected String createNonExistentIdentifier() {
- return Long.toString(Long.MAX_VALUE);
- }
-
- protected Object extractPart(MultipartInput input, String label,
- Class clazz) throws Exception {
- Object obj = null;
- String partLabel = "";
- List<InputPart> parts = input.getParts();
- if (parts.size() == 0) {
- logger.warn("No parts found in multipart body.");
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Parts:");
- for (InputPart part : parts) {
- partLabel = part.getHeaders().getFirst("label");
- logger.debug("part = " + partLabel);
- }
- }
- boolean partLabelMatched = false;
- for (InputPart part : parts) {
- partLabel = part.getHeaders().getFirst("label");
- if (label.equalsIgnoreCase(partLabel)) {
- partLabelMatched = true;
- if (logger.isDebugEnabled()) {
- logger.debug("found part" + partLabel);
- }
- String partStr = part.getBodyAsString();
- if (partStr == null || partStr.trim().isEmpty()) {
- logger.warn("Part '" + label + "' in multipart body is empty.");
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("extracted part as str=\n" + partStr);
- }
- obj = part.getBody(clazz, null);
- if (logger.isDebugEnabled()) {
- logger.debug("extracted part as obj=\n",
- objectAsXmlString(obj, clazz));
- }
- }
- break;
- }
- }
- if (!partLabelMatched) {
- logger.warn("Could not find part '" + label + "' in multipart body.");
- // In the event that getBodyAsString() or getBody(), above, do *not*
- // throw an IOException, but getBody() nonetheless retrieves a null object.
- // This *may* be unreachable.
- } else if (obj == null) {
- logger.warn("Could not extract part '" + label
- + "' in multipart body as an object.");
- }
- return obj;
- }
-
- protected Object getPartObject(String partStr, Class clazz)
- throws JAXBException {
- JAXBContext jc = JAXBContext.newInstance(clazz);
- ByteArrayInputStream bais = null;
- Object obj = null;
- try {
- bais = new ByteArrayInputStream(partStr.getBytes());
- Unmarshaller um = jc.createUnmarshaller();
- obj = um.unmarshal(bais);
- } finally {
- if (bais != null) {
- try {
- bais.close();
- } catch (Exception e) {
- }
- }
- }
- return obj;
- }
-
- // @TODO Some of the methods below may be candidates
- // to be moved to a utilities module, suitable for use
- // by both client-side and server-side code.
- protected String objectAsXmlString(Object o, Class clazz) {
- StringWriter sw = new StringWriter();
- try {
- JAXBContext jc = JAXBContext.newInstance(clazz);
- Marshaller m = jc.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
- Boolean.TRUE);
- m.marshal(o, sw);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return sw.toString();
- }
-
- /**
- * getObjectFromFile get object of given class from given file (in classpath)
- * @param jaxbClass
- * @param fileName of the file to read to construct the object
- * @return
- * @throws Exception
- */
- protected Object getObjectFromFile(Class jaxbClass, String fileName)
- throws Exception {
-
- JAXBContext context = JAXBContext.newInstance(jaxbClass);
- Unmarshaller unmarshaller = context.createUnmarshaller();
- //note: setting schema to null will turn validator off
- unmarshaller.setSchema(null);
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- InputStream is = tccl.getResourceAsStream(fileName);
- return getObjectFromStream(jaxbClass, is);
- }
-
- /**
- * getObjectFromStream get object of given class from given inputstream
- * @param jaxbClass
- * @param is stream to read to construct the object
- * @return
- * @throws Exception
- */
- protected Object getObjectFromStream(Class jaxbClass, InputStream is) throws Exception {
- JAXBContext context = JAXBContext.newInstance(jaxbClass);
- Unmarshaller unmarshaller = context.createUnmarshaller();
- //note: setting schema to null will turn validator off
- unmarshaller.setSchema(null);
- return jaxbClass.cast(unmarshaller.unmarshal(is));
- }
-
- protected String mapAsString(MultivaluedMap map) {
- StringBuffer sb = new StringBuffer();
- for (Object entry : map.entrySet()) {
- MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry;
- sb.append(" name=" + mentry.getKey());
- sb.append(" value=" + mentry.getValue() + "\n");
- }
- return sb.toString();
- }
-
- protected void banner(String label) {
- if (logger.isDebugEnabled()) {
- logger.debug("===================================================");
- logger.debug(" Test = " + label);
- logger.debug("===================================================");
- }
- }
}
--- /dev/null
+package org.collectionspace.services.client.test;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.File;\r
+import java.io.InputStream;\r
+import java.io.StringWriter;\r
+import java.lang.reflect.Method;\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import javax.ws.rs.core.MultivaluedMap;\r
+import javax.ws.rs.core.Response;\r
+import javax.xml.bind.JAXBContext;\r
+import javax.xml.bind.JAXBException;\r
+import javax.xml.bind.Marshaller;\r
+import javax.xml.bind.Unmarshaller;\r
+\r
+import org.apache.commons.httpclient.methods.DeleteMethod;\r
+import org.apache.commons.httpclient.methods.GetMethod;\r
+import org.apache.commons.httpclient.methods.PostMethod;\r
+import org.apache.commons.httpclient.methods.PutMethod;\r
+import org.apache.commons.httpclient.methods.StringRequestEntity;\r
+import org.collectionspace.services.client.TestServiceClient;\r
+import org.jboss.resteasy.client.ClientResponse;\r
+import org.jboss.resteasy.plugins.providers.multipart.InputPart;\r
+import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+import org.testng.annotations.DataProvider;\r
+\r
+public abstract class BaseServiceTest {\r
+\r
+ protected final Logger logger = LoggerFactory.getLogger(BaseServiceTest.class);\r
+ protected static final TestServiceClient serviceClient = new TestServiceClient();\r
+ protected final String NON_EXISTENT_ID = createNonExistentIdentifier();\r
+ protected int EXPECTED_STATUS_CODE = 0;\r
+ protected ServiceRequestType REQUEST_TYPE = ServiceRequestType.NON_EXISTENT;\r
+ protected static final String XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";\r
+ protected static final String MALFORMED_XML_DATA = XML_DECLARATION +\r
+ "<malformed_xml>wrong schema contents</malformed_xml";\r
+ protected final String WRONG_XML_SCHEMA_DATA = XML_DECLARATION +\r
+ "<wrong_schema>wrong schema contents</wrong_schema>";\r
+ final String NULL_CHARSET = null;\r
+\r
+ /**\r
+ * Returns the name of the currently running test.\r
+ *\r
+ * Note: although the return type is listed as Object[][],\r
+ * this method instead returns a String.\r
+ *\r
+ * @param m The currently running test method.\r
+ *\r
+ * @return The name of the currently running test method.\r
+ */\r
+ @DataProvider(name = "testName")\r
+ public static Object[][] testName(Method m) {\r
+ return new Object[][]{\r
+ new Object[] { m.getName() }\r
+ };\r
+ }\r
+\r
+ /**\r
+ * Returns the URL path component of the service.\r
+ *\r
+ * This component will follow directly after the\r
+ * base path, if any.\r
+ *\r
+ * @return The URL path component of the service.\r
+ */\r
+ protected abstract String getServicePathComponent();\r
+\r
+ /**\r
+ * Reinitializes setup values, to help expose any unintended reuse\r
+ * of those values between tests.\r
+ */\r
+ protected void clearSetup() {\r
+ EXPECTED_STATUS_CODE = 0;\r
+ REQUEST_TYPE = ServiceRequestType.NON_EXISTENT;\r
+ }\r
+ \r
+ /**\r
+ * Initializes setup valuesfor a given test.\r
+ */\r
+ protected void testSetup( \r
+ int expectedStatusCode, \r
+ ServiceRequestType reqType, \r
+ String bannerLabel ) {\r
+ clearSetup();\r
+ EXPECTED_STATUS_CODE = expectedStatusCode;\r
+ REQUEST_TYPE = reqType;\r
+ // Print a banner identifying the test that will be run.\r
+ if (logger.isDebugEnabled()) {\r
+ banner(bannerLabel);\r
+ }\r
+ }\r
+\r
+\r
+ public BaseServiceTest() {\r
+ super();\r
+ }\r
+\r
+ /**\r
+ * Returns an error message indicating that the status code returned by a\r
+ * specific call to a service does not fall within a set of valid status\r
+ * codes for that service.\r
+ *\r
+ * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).\r
+ *\r
+ * @param statusCode The invalid status code that was returned in the response,\r
+ * from submitting that type of request to the service.\r
+ *\r
+ * @return An error message.\r
+ */\r
+ protected String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
+ return "Status code '" + statusCode +\r
+ "' in response is NOT within the expected set: " +\r
+ requestType.validStatusCodesAsString();\r
+ }\r
+\r
+ /**\r
+ * Returns the root URL for a service.\r
+ *\r
+ * This URL consists of a base URL for all services, followed by\r
+ * a path component (or components) for a service.\r
+ *\r
+ * @return The root URL for a service.\r
+ */\r
+ protected String getServiceRootURL() {\r
+ return serviceClient.getBaseURL() + getServicePathComponent();\r
+ }\r
+\r
+ /**\r
+ * Returns the URL of a specific resource managed by a service, and\r
+ * designated by an identifier (such as a universally unique ID, or UUID).\r
+ *\r
+ * @param resourceIdentifier An identifier (such as a UUID) for a resource.\r
+ *\r
+ * @return The URL of a specific resource managed by a service.\r
+ */\r
+ protected String getResourceURL(String resourceIdentifier) {\r
+ return getServiceRootURL() + "/" + resourceIdentifier;\r
+ }\r
+\r
+ /**\r
+ * Submits an HTTP request to a specified URL, and returns the\r
+ * status code of the response. Currently accepts GET and DELETE\r
+ * requests.\r
+ *\r
+ * @param method An HTTP method.\r
+ *\r
+ * @param url A String representation of a URL.\r
+ *\r
+ * @return The status code received in the HTTP response.\r
+ */\r
+ protected int submitRequest(String method, String url) {\r
+ int statusCode = 0;\r
+ try{\r
+ TestServiceClient client = new TestServiceClient();\r
+ if(method.equals(javax.ws.rs.HttpMethod.DELETE)){\r
+ DeleteMethod deleteMethod = new DeleteMethod(url);\r
+ statusCode = client.getHttpClient().executeMethod(deleteMethod);\r
+ }else if(method.equals(javax.ws.rs.HttpMethod.GET)){\r
+ GetMethod getMethod = new GetMethod(url);\r
+ statusCode = client.getHttpClient().executeMethod(getMethod);\r
+ }else{\r
+ // Do nothing - leave status code at default value.\r
+ }\r
+ }catch(Exception e){\r
+ logger.error(\r
+ "Exception during HTTP " + method + " request to " +\r
+ url + ":", e);\r
+ }\r
+ return statusCode;\r
+ }\r
+\r
+ /**\r
+ * Submits an HTTP request to a specified URL, with the submitted\r
+ * entity body, and returns the status code of the response.\r
+ * Currently accepts POST and PUT requests.\r
+ *\r
+ * @param method An HTTP method.\r
+ *\r
+ * @param url A String representation of a URL.\r
+ *\r
+ * @param mediaType The media type of the entity body to be submitted.\r
+ *\r
+ * @param entity The contents of the entity body to be submitted.\r
+ *\r
+ * @return The status code received in the HTTP response.\r
+ */\r
+ protected int submitRequest(String method, String url, String mediaType,\r
+ String entityStr) {\r
+ int statusCode = 0;\r
+ try{\r
+ TestServiceClient client = new TestServiceClient();\r
+ if(method.equals(javax.ws.rs.HttpMethod.POST)){\r
+ StringRequestEntity entityBody =\r
+ new StringRequestEntity(mediaType, entityStr, NULL_CHARSET);\r
+ PostMethod postMethod = new PostMethod(url);\r
+ postMethod.setRequestEntity(entityBody);\r
+ statusCode = client.getHttpClient().executeMethod(postMethod);\r
+ }else if(method.equals(javax.ws.rs.HttpMethod.PUT)){\r
+ StringRequestEntity entityBody =\r
+ new StringRequestEntity(mediaType, entityStr, NULL_CHARSET);\r
+ PutMethod putMethod = new PutMethod(url);\r
+ putMethod.setRequestEntity(entityBody);\r
+ statusCode = client.getHttpClient().executeMethod(putMethod);\r
+ }else{\r
+ // Do nothing - leave status code at default value.\r
+ }\r
+ }catch(Exception e){\r
+ logger.error(\r
+ "Exception during HTTP " + method + " request to " +\r
+ url + ":", e);\r
+ }\r
+ return statusCode;\r
+ }\r
+\r
+ protected String extractId(ClientResponse<Response> res) {\r
+ MultivaluedMap mvm = res.getMetadata();\r
+ String uri = (String) ((ArrayList) mvm.get("Location")).get(0);\r
+ if(logger.isDebugEnabled()){\r
+ logger.debug("extractId:uri=" + uri);\r
+ }\r
+ String[] segments = uri.split("/");\r
+ String id = segments[segments.length - 1];\r
+ if(logger.isDebugEnabled()){\r
+ logger.debug("id=" + id);\r
+ }\r
+ return id;\r
+ }\r
+\r
+ protected String createIdentifier() {\r
+ long identifier = System.currentTimeMillis();\r
+ return Long.toString(identifier);\r
+ }\r
+\r
+ protected String createNonExistentIdentifier() {\r
+ return Long.toString(Long.MAX_VALUE);\r
+ }\r
+\r
+ protected Object extractPart(MultipartInput input, String label, Class clazz)\r
+ throws Exception {\r
+ Object obj = null;\r
+ String partLabel = "";\r
+ List<InputPart> parts = input.getParts();\r
+ if (parts.size() == 0) {\r
+ logger.warn("No parts found in multipart body.");\r
+ }\r
+ if(logger.isDebugEnabled()){\r
+ logger.debug("Parts:");\r
+ for(InputPart part : parts){\r
+ partLabel = part.getHeaders().getFirst("label");\r
+ logger.debug("part = " + partLabel);\r
+ }\r
+ }\r
+ boolean partLabelMatched = false;\r
+ for(InputPart part : parts){\r
+ partLabel = part.getHeaders().getFirst("label");\r
+ if(label.equalsIgnoreCase(partLabel)){\r
+ partLabelMatched = true;\r
+ if(logger.isDebugEnabled()){\r
+ logger.debug("found part" + partLabel);\r
+ }\r
+ String partStr = part.getBodyAsString();\r
+ if (partStr == null || partStr.trim().isEmpty()) {\r
+ logger.warn("Part '" + label + "' in multipart body is empty.");\r
+ } else {\r
+ if (logger.isDebugEnabled()){\r
+ logger.debug("extracted part as str=\n" + partStr);\r
+ }\r
+ obj = part.getBody(clazz, null);\r
+ if(logger.isDebugEnabled()){\r
+ logger.debug("extracted part as obj=\n",\r
+ objectAsXmlString(obj, clazz));\r
+ }\r
+ }\r
+ break;\r
+ }\r
+ }\r
+ if (! partLabelMatched) {\r
+ logger.warn("Could not find part '" + label + "' in multipart body.");\r
+ // In the event that getBodyAsString() or getBody(), above, do *not*\r
+ // throw an IOException, but getBody() nonetheless retrieves a null object.\r
+ // This *may* be unreachable.\r
+ } else if (obj == null) {\r
+ logger.warn("Could not extract part '" + label +\r
+ "' in multipart body as an object.");\r
+ }\r
+ return obj;\r
+ }\r
+\r
+ protected Object getPartObject(String partStr, Class clazz)\r
+ throws JAXBException {\r
+ JAXBContext jc = JAXBContext.newInstance(clazz);\r
+ ByteArrayInputStream bais = null;\r
+ Object obj = null;\r
+ try{\r
+ bais = new ByteArrayInputStream(partStr.getBytes());\r
+ Unmarshaller um = jc.createUnmarshaller();\r
+ obj = um.unmarshal(bais);\r
+ }finally{\r
+ if(bais != null){\r
+ try{\r
+ bais.close();\r
+ }catch(Exception e){\r
+ }\r
+ }\r
+ }\r
+ return obj;\r
+ }\r
+\r
+ protected String objectAsXmlString(Object o, Class clazz) {\r
+ StringWriter sw = new StringWriter();\r
+ try{\r
+ JAXBContext jc = JAXBContext.newInstance(clazz);\r
+ Marshaller m = jc.createMarshaller();\r
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,\r
+ Boolean.TRUE);\r
+ m.marshal(o, sw);\r
+ }catch(Exception e){\r
+ e.printStackTrace();\r
+ }\r
+ return sw.toString();\r
+ }\r
+\r
+ /**\r
+ * getObjectFromFile get object of given class from given file (in classpath)\r
+ * @param jaxbClass\r
+ * @param fileName of the file to read to construct the object\r
+ * @return\r
+ * @throws Exception\r
+ */\r
+ protected Object getObjectFromFile(Class jaxbClass, String fileName)\r
+ throws Exception {\r
+\r
+ JAXBContext context = JAXBContext.newInstance(jaxbClass);\r
+ Unmarshaller unmarshaller = context.createUnmarshaller();\r
+ //note: setting schema to null will turn validator off\r
+ unmarshaller.setSchema(null);\r
+ ClassLoader tccl = Thread.currentThread().getContextClassLoader();\r
+ InputStream is = tccl.getResourceAsStream(fileName);\r
+ return getObjectFromStream(jaxbClass, is);\r
+ }\r
+\r
+ /**\r
+ * getObjectFromStream get object of given class from given inputstream\r
+ * @param jaxbClass\r
+ * @param is stream to read to construct the object\r
+ * @return\r
+ * @throws Exception\r
+ */\r
+ protected Object getObjectFromStream(Class jaxbClass, InputStream is) throws Exception {\r
+ JAXBContext context = JAXBContext.newInstance(jaxbClass);\r
+ Unmarshaller unmarshaller = context.createUnmarshaller();\r
+ //note: setting schema to null will turn validator off\r
+ unmarshaller.setSchema(null);\r
+ return jaxbClass.cast(unmarshaller.unmarshal(is));\r
+ }\r
+ protected String mapAsString(MultivaluedMap map) {\r
+ StringBuffer sb = new StringBuffer();\r
+ for(Object entry : map.entrySet()){\r
+ MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry;\r
+ sb.append(" name=" + mentry.getKey());\r
+ sb.append(" value=" + mentry.getValue() + "\n");\r
+ }\r
+ return sb.toString();\r
+ }\r
+\r
+ protected void banner(String label) {\r
+ if(logger.isDebugEnabled()){\r
+ logger.debug("===================================================");\r
+ logger.debug(" Test = " + label);\r
+ logger.debug("===================================================");\r
+ }\r
+ }\r
+\r
+}
\ No newline at end of file
Created on : August 31, 2009, 10:52 AM
Description: tenant bindings
-->
-<tenant:TenantBindingConfig xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
- xmlns:tenant='http://collectionspace.org/services/common/tenant'
- xsi:schemaLocation='http://collectionspace.org/services/common/tenant http://collectionspace.org/services/common/tenant.xsd'
+<tenant:TenantBindingConfig
+ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
+ xmlns:tenant='http://collectionspace.org/services/common/tenant'
+ xmlns:types='http://collectionspace.org/services/common/types'
+ xsi:schemaLocation='http://collectionspace.org/services/common/tenant http://collectionspace.org/services/common/tenant.xsd'
>
<!-- begin movingimages.us tenant meta-data -->
<tenant:tenantBinding
<service:part id="1" control_group="Managed"
versionable="true" auditable="false"
label="intakes_common" updated="" order="1">
+ <service:properties>
+ <types:item><types:key>authRef</types:key><types:value>currentOwner</types:value></types:item>
+ <types:item><types:key>authRef</types:key><types:value>depositor</types:value></types:item>
+ <types:item><types:key>authRef</types:key><types:value>conditionCheckAssesor</types:value></types:item>
+ <types:item><types:key>authRef</types:key><types:value>insurer</types:value></types:item>
+ <types:item><types:key>authRef</types:key><types:value>fieldCollector</types:value></types:item>
+ <types:item><types:key>authRef</types:key><types:value>valuer</types:value></types:item>
+ </service:properties>
<service:content contentType="application/xml">
<service:xmlContent
namespaceURI="http://collectionspace.org/services/intake"
import org.collectionspace.services.common.service.ServiceBindingType;
import org.collectionspace.services.common.service.ServiceObjectType;
import org.collectionspace.services.common.tenant.TenantBindingType;
+import org.collectionspace.services.common.types.PropertyItemType;
+import org.collectionspace.services.common.types.PropertyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
return objectPartMap;
}
+
+ public List<PropertyType> getPropertiesForPart(String partLabel) {
+ Map<String, ObjectPartType> partMap = getPartsMetadata();
+ ObjectPartType part = partMap.get(partLabel);
+ if(part==null) {
+ throw new RuntimeException("No such part found: "+partLabel);
+ }
+ return part.getProperties();
+ }
+
+ public List<String> getPropertyValuesForPart(String partLabel, String propName) {
+ List<PropertyType> allProps = getPropertiesForPart(partLabel);
+ List<String> values = new ArrayList<String>();
+ if(allProps.size()>0) {
+ List<PropertyItemType> propItems = allProps.get(0).getItem();
+ for(PropertyItemType propItem:propItems) {
+ if(propName.equals(propItem.getKey())) {
+ String value = propItem.getValue();
+ if(value!=null) {
+ values.add(value);
+ }
+ }
+ }
+ }
+ return values;
+ }
+
+ public List<PropertyType> getCommonPartProperties() {
+ return getPropertiesForPart(getCommonPartLabel());
+ }
+
+ public List<String> getCommonPartPropertyValues(String propName) {
+ return getPropertyValuesForPart(getCommonPartLabel(), propName);
+ }
@Override
public String getQualifiedServiceName() {
*/
package org.collectionspace.services.common.repository;
+import org.collectionspace.services.common.context.ServiceContext;
+import org.collectionspace.services.common.document.DocumentException;
+import org.collectionspace.services.common.document.DocumentNotFoundException;
+import org.collectionspace.services.common.document.DocumentWrapper;
import org.collectionspace.services.common.storage.StorageClient;
+import org.nuxeo.ecm.core.api.DocumentModel;
/**
* RepositoryClient is a generic Document Repository client
* @throws java.lang.Exception
*/
public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception;
+
+ /**
+ * get wrapped documentModel from the Nuxeo repository
+ * @param ctx service context under which this method is invoked
+ * @param id
+ * of the document to retrieve
+ * @throws DocumentException
+ */
+ public DocumentWrapper<DocumentModel> getDoc(
+ ServiceContext ctx, String id)
+ throws DocumentNotFoundException, DocumentException;
+
}
--- /dev/null
+/**\r
+ * This document is a part of the source code and related artifacts\r
+ * for CollectionSpace, an open source collections management system\r
+ * for museums and related institutions:\r
+\r
+ * http://www.collectionspace.org\r
+ * http://wiki.collectionspace.org\r
+\r
+ * Copyright 2009 University of California at Berkeley\r
+\r
+ * Licensed under the Educational Community License (ECL), Version 2.0.\r
+ * You may not use this file except in compliance with this License.\r
+\r
+ * You may obtain a copy of the ECL 2.0 License at\r
+\r
+ * https://source.collectionspace.org/collection-space/LICENSE.txt\r
+\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.collectionspace.services.common.vocabulary;\r
+\r
+import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+\r
+/**\r
+ * RefNameUtils is a collection of utilities related to refName URN strings\r
+ * refNames are URNs that reference a document entity, often an authority or \r
+ * authority term. They are strings that take the form (for authorities):\r
+ * urn:cspace:org.collectionspace.demo:vocabulary:name(Entry Methods)'Entry Methods'\r
+ * or the form (for authority terms):\r
+ * urn:cspace:org.collectionspace.demo:vocabulary:name(Entry Methods):item:name(Loan)'Loan'\r
+ *\r
+ * $LastChangedRevision: $\r
+ * $LastChangedDate: $\r
+ */\r
+public class RefNameUtils {\r
+\r
+ private final Logger logger = LoggerFactory.getLogger(RefNameUtils.class);\r
+\r
+ private static final String URN_PREFIX = "urn:cspace:";\r
+ // FIXME Should not be hard-coded\r
+ private static final String ITEMS_REGEX = "item|person|organization";\r
+ // In a list of tokens, these are indices for each part\r
+ private static final int DOMAIN_TOKEN = 0; // e.g., 'org.collectionspace.demo'\r
+ private static final int RESOURCE_TOKEN = 1; // vocabulary, personauthority, etc.\r
+ private static final int AUTH_INSTANCE_TOKEN = 2; // name(Entry Methods)'Entry Methods'\r
+ private static final int ITEMS_TOKEN = 3; // 'item', 'person', etc.\r
+ private static final int ITEM_INSTANCE_TOKEN = 4; // name(Entry Methods)'Entry Methods'\r
+ // Tokenizing the INSTANCE, these are indices for each item-part\r
+ private static final int INSTANCE_SPEC_TYPE_TOKEN = 0; // 'name' or 'id' \r
+ private static final int INSTANCE_SPEC_TOKEN = 1; // name or id value\r
+ private static final int INSTANCE_DISPLAYNAME_TOKEN = 2;// optional displayName suffix\r
+ private static final int INSTANCE_TOKENS_MIN = 2;\r
+ private static final int INSTANCE_TOKENS_MAX = 3;\r
+ private static final int prefixLen = 11;\r
+ private static final String SEPARATOR = ":";\r
+\r
+ public static class AuthorityInfo {\r
+ private final Logger logger = LoggerFactory.getLogger(AuthorityInfo.class);\r
+ private static int MIN_TOKENS = 3;\r
+ public String domain;\r
+ public String resource;\r
+ public String csid;\r
+ public String name;\r
+ public String displayName;\r
+ \r
+ public AuthorityInfo(String refNameTokens[]) throws Exception {\r
+ try {\r
+ if(refNameTokens.length < MIN_TOKENS) {\r
+ throw new IllegalArgumentException("Malformed refName for Authority (too few tokens)");\r
+ }\r
+ this.domain = refNameTokens[DOMAIN_TOKEN]; \r
+ this.resource = refNameTokens[RESOURCE_TOKEN];\r
+ String idTokens[] = refNameTokens[AUTH_INSTANCE_TOKEN].split("[()]", INSTANCE_TOKENS_MAX);\r
+ if(idTokens.length<INSTANCE_TOKENS_MIN) {\r
+ throw new IllegalArgumentException("Missing/malformed identifier");\r
+ }\r
+ if(idTokens[INSTANCE_SPEC_TYPE_TOKEN].equals("name")) {\r
+ this.name = idTokens[INSTANCE_SPEC_TOKEN];\r
+ this.csid = null;\r
+ } else if(idTokens[INSTANCE_SPEC_TYPE_TOKEN].startsWith("id")) {\r
+ this.csid = idTokens[INSTANCE_SPEC_TOKEN];\r
+ this.name = null;\r
+ } else {\r
+ throw new IllegalArgumentException("Identifier type must be 'name' or 'id'");\r
+ }\r
+ // displayName is always in quotes, so must have at least 3 chars\r
+ this.displayName = \r
+ ((idTokens.length<INSTANCE_TOKENS_MAX)||(idTokens[INSTANCE_DISPLAYNAME_TOKEN].length()<3))? null:\r
+ idTokens[INSTANCE_DISPLAYNAME_TOKEN].substring(1, idTokens[INSTANCE_DISPLAYNAME_TOKEN].length()-1);\r
+ } catch (Exception e) {\r
+ if (logger.isDebugEnabled()) {\r
+ logger.debug("Problem Building AuthorityInfo from tokens: " \r
+ + RefNameUtils.implodeStringArray(refNameTokens, ", "));\r
+ }\r
+ throw e;\r
+ }\r
+ }\r
+ \r
+ public String getRelativeUri() {\r
+ StringBuilder uri = new StringBuilder();\r
+ // FIXME This should not be hard-coded.\r
+ if(resource.equals("vocabulary")) {\r
+ uri.append("/vocabularies/");\r
+ } else if(resource.equals("personauthority")) {\r
+ uri.append("/personauthorities/");\r
+ } else if(resource.equals("orgauthority")) {\r
+ uri.append("/orgauthorities/");\r
+ } else {\r
+ throw new RuntimeException("Illegal Authority Type: " + resource);\r
+ }\r
+ if(csid!=null) {\r
+ uri.append(csid);\r
+ } else if(name!=null) {\r
+ uri.append("urn:cspace:name("+name+")");\r
+ } else {\r
+ throw new RuntimeException("Missing id/name specifier");\r
+ }\r
+ return uri.toString();\r
+ }\r
+ };\r
+\r
+ public static class AuthorityTermInfo {\r
+ private final Logger logger = LoggerFactory.getLogger(AuthorityTermInfo.class);\r
+ private static int MIN_TOKENS = 5;\r
+ public AuthorityInfo inAuthority;\r
+ public String csid;\r
+ public String name;\r
+ public String displayName;\r
+ \r
+ public AuthorityTermInfo(String refNameTokens[]) throws Exception {\r
+ try {\r
+ if(refNameTokens.length < MIN_TOKENS) {\r
+ throw new IllegalArgumentException("Malformed refName for AuthorityTerm (too few tokens)");\r
+ }\r
+ this.inAuthority = new AuthorityInfo(refNameTokens); \r
+ if(!refNameTokens[ITEMS_TOKEN].matches(ITEMS_REGEX)) {\r
+ throw new IllegalArgumentException("Item spec must be one of: "+ITEMS_REGEX);\r
+ }\r
+ String idTokens[] = refNameTokens[ITEM_INSTANCE_TOKEN].split("[\\(\\)]", 3);\r
+ if(idTokens.length<INSTANCE_TOKENS_MIN) {\r
+ throw new IllegalArgumentException("Missing/malformed identifier");\r
+ }\r
+ if(idTokens[INSTANCE_SPEC_TYPE_TOKEN].equals("name")) {\r
+ this.name = idTokens[INSTANCE_SPEC_TOKEN];\r
+ this.csid = null;\r
+ } else if(idTokens[INSTANCE_SPEC_TYPE_TOKEN].startsWith("id")) {\r
+ this.csid = idTokens[INSTANCE_SPEC_TOKEN];\r
+ this.name = null;\r
+ } else {\r
+ throw new IllegalArgumentException("Identifier type must be 'name' or 'id'");\r
+ }\r
+ // displayName is always in quotes, so must have at least 3 chars\r
+ this.displayName = \r
+ ((idTokens.length<INSTANCE_TOKENS_MAX)||(idTokens[INSTANCE_DISPLAYNAME_TOKEN].length()<3))? null:\r
+ idTokens[INSTANCE_DISPLAYNAME_TOKEN].substring(1, idTokens[INSTANCE_DISPLAYNAME_TOKEN].length()-1);\r
+ } catch (Exception e) {\r
+ if (logger.isDebugEnabled()) {\r
+ logger.debug("Problem Building AuthorityTermInfo from tokens: " \r
+ + RefNameUtils.implodeStringArray(refNameTokens, ", "));\r
+ }\r
+ throw e;\r
+ }\r
+ }\r
+ \r
+ public String getRelativeUri() {\r
+ StringBuilder uri = new StringBuilder(inAuthority.getRelativeUri()+"/items/");\r
+ if(csid!=null) {\r
+ uri.append(csid);\r
+ } else if(name!=null) {\r
+ uri.append("urn:cspace:name("+name+")");\r
+ } else {\r
+ throw new RuntimeException("Missing id/name specifier");\r
+ }\r
+ return uri.toString();\r
+ }\r
+ };\r
+\r
+ public static AuthorityInfo parseAuthorityInfo(String refName)\r
+ throws Exception {\r
+ if(refName==null || !refName.startsWith(URN_PREFIX))\r
+ throw new RuntimeException( "Null or invalid refName syntax");\r
+ return new AuthorityInfo(refName.substring(prefixLen).split(SEPARATOR));\r
+ }\r
+\r
+ public static AuthorityTermInfo parseAuthorityTermInfo(String refName)\r
+ throws Exception {\r
+ if(refName==null || !refName.startsWith(URN_PREFIX))\r
+ throw new RuntimeException( "Null or invalid refName syntax");\r
+ return new AuthorityTermInfo(refName.substring(prefixLen).split(SEPARATOR));\r
+ }\r
+\r
+ public static String implodeStringArray(String tokens[], String separator) {\r
+ if (tokens.length==0) {\r
+ return "";\r
+ } else {\r
+ StringBuffer sb = new StringBuffer();\r
+ sb.append(tokens[0]);\r
+ for (int i=1;i<tokens.length;i++) {\r
+ sb.append(separator);\r
+ sb.append(tokens[i]);\r
+ }\r
+ return sb.toString();\r
+ }\r
+ }\r
+ \r
+}\r
+\r
}
}
+ /**
+ * get wrapped documentModel from the Nuxeo repository
+ * @param ctx service context under which this method is invoked
+ * @param id
+ * of the document to retrieve
+ * @throws DocumentException
+ */
+ @Override
+ public DocumentWrapper<DocumentModel> getDoc(
+ ServiceContext ctx, String id)
+ throws DocumentNotFoundException, DocumentException {
+ RepositoryInstance repoSession = null;
+ DocumentWrapper<DocumentModel> wrapDoc = null;
+
+ try {
+ repoSession = getRepositorySession();
+ DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
+ DocumentModel doc = null;
+ try {
+ doc = repoSession.getDocument(docRef);
+ } catch (ClientException ce) {
+ String msg = "could not find document with id=" + id;
+ logger.error(msg, ce);
+ throw new DocumentNotFoundException(msg, ce);
+ }
+ wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
+ } catch (IllegalArgumentException iae) {
+ throw iae;
+ } catch (DocumentException de) {
+ throw de;
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Caught exception ", e);
+ }
+ throw new DocumentException(e);
+ } finally {
+ if (repoSession != null) {
+ releaseRepositorySession(repoSession);
+ }
+ }
+ return wrapDoc;
+ }
+
@Override
public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
throws DocumentNotFoundException, DocumentException {
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Copyright 2009 University of California at Berkeley
+ Licensed under the Educational Community License (ECL), Version 2.0.
+ You may not use this file except in compliance with this License.
+
+ You may obtain a copy of the ECL 2.0 License at
+ https://source.collectionspace.org/collection-space/LICENSE.txt
+
+ Document : authorityref.xsd
+ Revision : $LastChangedRevision: 1292 $
+ Created on : $LastChangedDate: 2010-01-29 14:55:28 -0800 (Fri, 29 Jan 2010) $
+ Author : $LastChangedBy: $
+ Description: AuthorityRef describes a list of values that describe
+ references to authorities (Person, Org, etc.) within some
+ context object (e.g., a CollectionObject or Intake instance).
+-->
+<xs:schema
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns="http://collectionspace.org/services/common/authorityref"
+ targetNamespace="http://collectionspace.org/services/common/authorityref"
+ version="0.1"
+ >
+
+ <xs:element name="authority-ref-list">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="authority-ref-item" maxOccurs="unbounded">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="sourceField" type="xs:string" minOccurs="1" />
+ <xs:element name="refName" type="xs:string" minOccurs="1" />
+ <xs:element name="authDisplayName" type="xs:string" minOccurs="1" />
+ <xs:element name="itemDisplayName" type="xs:string" minOccurs="1" />
+ <xs:element name="uri" type="xs:anyURI" minOccurs="1" />
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+
+</xs:schema>
<artifactId>org.collectionspace.services.client</artifactId>\r
<version>${cspace.services.client.version}</version>\r
</dependency>\r
+ <dependency>\r
+ <groupId>org.collectionspace.services</groupId>\r
+ <artifactId>org.collectionspace.services.person.client</artifactId>\r
+ <version>${cspace.services.client.version}</version>\r
+ </dependency>\r
\r
<dependency>\r
<groupId>org.testng</groupId>\r
*/
package org.collectionspace.services.client;
+import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
+import org.collectionspace.services.common.authorityref.AuthorityRefList;
+import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.intake.IntakesCommonList;
import org.jboss.resteasy.client.ProxyFactory;
/**
* @return
- * @see org.collectionspace.hello.client.IntakeProxy#getIntake()
+ * @see org.collectionspace.services.client.IntakeProxy#getIntake()
*/
public ClientResponse<IntakesCommonList> readList() {
return intakeProxy.readList();
}
+
+ /**
+ * @param csid
+ * @return
+ * @see org.collectionspace.services.client.IntakeProxy#getAuthorityRefs(java.lang.String)
+ */
+ public ClientResponse<AuthorityRefList> getAuthorityRefs(String csid) {
+ return intakeProxy.getAuthorityRefs(csid);
+ }
+
/**
* @param csid
* @return
- * @see org.collectionspace.hello.client.IntakeProxy#getIntake(java.lang.String)
+ * @see org.collectionspace.services.client.IntakeProxy#getIntake(java.lang.String)
*/
public ClientResponse<MultipartInput> read(String csid) {
return intakeProxy.read(csid);
/**
* @param intake
* @return
- * @see org.collectionspace.hello.client.IntakeProxy#createIntake(org.collectionspace.hello.Intake)
+ * @see org.collectionspace.services.client.IntakeProxy#createIntake(org.collectionspace.hello.Intake)
*/
public ClientResponse<Response> create(MultipartOutput multipart) {
return intakeProxy.create(multipart);
* @param csid
* @param intake
* @return
- * @see org.collectionspace.hello.client.IntakeProxy#updateIntake(java.lang.Long, org.collectionspace.hello.Intake)
+ * @see org.collectionspace.services.client.IntakeProxy#updateIntake(java.lang.Long, org.collectionspace.hello.Intake)
*/
public ClientResponse<MultipartInput> update(String csid, MultipartOutput multipart) {
return intakeProxy.update(csid, multipart);
/**
* @param csid
* @return
- * @see org.collectionspace.hello.client.IntakeProxy#deleteIntake(java.lang.Long)
+ * @see org.collectionspace.services.client.IntakeProxy#deleteIntake(java.lang.Long)
*/
public ClientResponse<Response> delete(String csid) {
return intakeProxy.delete(csid);
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
+import org.collectionspace.services.common.authorityref.AuthorityRefList;
import org.collectionspace.services.intake.IntakesCommonList;
+import org.collectionspace.services.person.PersonsCommonList;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
@DELETE
@Path("/{csid}")
ClientResponse<Response> delete(@PathParam("csid") String csid);
+
+ // List Items
+ @GET
+ @Produces({"application/xml"})
+ @Path("/{csid}/authorityrefs/")
+ ClientResponse<AuthorityRefList> getAuthorityRefs(@PathParam("csid") String csid);
+
}
--- /dev/null
+/**
+ * This document is a part of the source code and related artifacts
+ * for CollectionSpace, an open source collections management system
+ * for museums and related institutions:
+ *
+ * http://www.collectionspace.org
+ * http://wiki.collectionspace.org
+ *
+ * Copyright © 2009 Regents of the University of California
+ *
+ * Licensed under the Educational Community License (ECL), Version 2.0.
+ * You may not use this file except in compliance with this License.
+ *
+ * You may obtain a copy of the ECL 2.0 License at
+ * https://source.collectionspace.org/collection-space/LICENSE.txt
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.collectionspace.services.client.test;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.collectionspace.services.PersonJAXBSchema;
+import org.collectionspace.services.client.IntakeClient;
+import org.collectionspace.services.client.PersonAuthorityClient;
+import org.collectionspace.services.client.PersonAuthorityClientUtils;
+import org.collectionspace.services.common.authorityref.AuthorityRefList;
+import org.collectionspace.services.intake.IntakesCommon;
+import org.collectionspace.services.intake.IntakesCommonList;
+
+import org.jboss.resteasy.client.ClientResponse;
+
+import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
+import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
+import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.Test;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * IntakeAuthRefsTest, carries out tests against a
+ * deployed and running Intake Service.
+ *
+ * $LastChangedRevision: 1327 $
+ * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
+ */
+public class IntakeAuthRefsTest extends BaseServiceTest {
+
+ private final Logger logger =
+ LoggerFactory.getLogger(IntakeAuthRefsTest.class);
+
+ // Instance variables specific to this test.
+ private IntakeClient intakeClient = new IntakeClient();
+ private PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
+ final String SERVICE_PATH_COMPONENT = "intakes";
+ final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
+ private String knownResourceId = null;
+ private List<String> intakeIdsCreated = new ArrayList();
+ private List<String> personIdsCreated = new ArrayList();
+ private int CREATED_STATUS = Response.Status.CREATED.getStatusCode();
+ private int OK_STATUS = Response.Status.OK.getStatusCode();
+ private String personAuthCSID = null;
+ private String currentOwnerRefName = null;
+ private String depositorRefName = null;
+ private String conditionCheckAssesorRefName = null;
+ private String insurerRefName = null;
+ private String fieldCollectorRefName = null;
+ private String valuerRefName = null;
+ private final int NUM_AUTH_REFS_EXPECTED = 6;
+
+ // ---------------------------------------------------------------
+ // CRUD tests : CREATE tests
+ // ---------------------------------------------------------------
+ // Success outcomes
+ @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
+ public void createWithAuthRefs(String testName) throws Exception {
+
+ testSetup(CREATED_STATUS, ServiceRequestType.CREATE,testName);
+
+ // Submit the request to the service and store the response.
+ String identifier = createIdentifier();
+
+ // Create all the person refs and entities
+ createPersonRefs();
+
+ MultipartOutput multipart = createIntakeInstance(
+ "entryNumber-" + identifier,
+ "entryDate-" + identifier,
+ currentOwnerRefName,
+ depositorRefName,
+ conditionCheckAssesorRefName,
+ insurerRefName,
+ fieldCollectorRefName,
+ valuerRefName );
+
+ ClientResponse<Response> res = intakeClient.create(multipart);
+
+ int statusCode = res.getStatus();
+
+ // Check the status code of the response: does it match
+ // the expected response(s)?
+ //
+ // Specifically:
+ // Does it fall within the set of valid status codes?
+ // Does it exactly match the expected status code?
+ if(logger.isDebugEnabled()){
+ logger.debug(testName + ": status = " + statusCode);
+ }
+ Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
+ Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
+
+ // Store the ID returned from the first resource created
+ // for additional tests below.
+ if (knownResourceId == null){
+ knownResourceId = extractId(res);
+ if (logger.isDebugEnabled()) {
+ logger.debug(testName + ": knownResourceId=" + knownResourceId);
+ }
+ }
+
+ // Store the IDs from every resource created by tests,
+ // so they can be deleted after tests have been run.
+ intakeIdsCreated.add(extractId(res));
+ }
+
+ protected void createPersonRefs(){
+ String authRefName =
+ PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
+ MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
+ PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
+ ClientResponse<Response> res = personAuthClient.create(multipart);
+ int statusCode = res.getStatus();
+
+ Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
+ Assert.assertEquals(statusCode, CREATED_STATUS);
+ personAuthCSID = extractId(res);
+
+ currentOwnerRefName = PersonAuthorityClientUtils.createPersonRefName(
+ authRefName, "Olivier Owner", true);
+ personIdsCreated.add(createPerson("Olivier", "Owner", currentOwnerRefName));
+
+ depositorRefName = PersonAuthorityClientUtils.createPersonRefName(
+ authRefName, "Debbie Depositor", true);
+ personIdsCreated.add(createPerson("Debbie", "Depositor", depositorRefName));
+
+ conditionCheckAssesorRefName = PersonAuthorityClientUtils.createPersonRefName(
+ authRefName, "Andrew Assessor", true);
+ personIdsCreated.add(createPerson("Andrew", "Assessor", conditionCheckAssesorRefName));
+
+ insurerRefName = PersonAuthorityClientUtils.createPersonRefName(
+ authRefName, "Ingrid Insurer", true);
+ personIdsCreated.add(createPerson("Ingrid", "Insurer", insurerRefName));
+
+ fieldCollectorRefName = PersonAuthorityClientUtils.createPersonRefName(
+ authRefName, "Connie Collector", true);
+ personIdsCreated.add(createPerson("Connie", "Collector", fieldCollectorRefName));
+
+ valuerRefName = PersonAuthorityClientUtils.createPersonRefName(
+ authRefName, "Vince Valuer", true);
+ personIdsCreated.add(createPerson("Vince", "Valuer", valuerRefName));
+
+
+ }
+
+ protected String createPerson(String firstName, String surName, String refName ) {
+ Map<String, String> personInfo = new HashMap<String,String>();
+ personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
+ personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
+ MultipartOutput multipart =
+ PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
+ refName, personInfo, personAuthClient.getItemCommonPartName());
+ ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
+ int statusCode = res.getStatus();
+
+ Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
+ Assert.assertEquals(statusCode, CREATED_STATUS);
+ return extractId(res);
+ }
+
+ // Success outcomes
+ @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
+ dependsOnMethods = {"createWithAuthRefs"})
+ public void readAndCheckAuthRefs(String testName) throws Exception {
+
+ // Perform setup.
+ testSetup(OK_STATUS, ServiceRequestType.READ,testName);
+
+ // Submit the request to the service and store the response.
+ ClientResponse<MultipartInput> res = intakeClient.read(knownResourceId);
+ int statusCode = res.getStatus();
+
+ // Check the status code of the response: does it match
+ // the expected response(s)?
+ if(logger.isDebugEnabled()){
+ logger.debug(testName + ".read: status = " + statusCode);
+ }
+ Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
+ Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
+
+ MultipartInput input = (MultipartInput) res.getEntity();
+ IntakesCommon intake = (IntakesCommon) extractPart(input,
+ intakeClient.getCommonPartName(), IntakesCommon.class);
+ Assert.assertNotNull(intake);
+ // Check a couple of fields
+ Assert.assertEquals(intake.getCurrentOwner(), currentOwnerRefName);
+ Assert.assertEquals(intake.getInsurer(), insurerRefName);
+
+ // Get the auth refs and check them
+ ClientResponse<AuthorityRefList> res2 = intakeClient.getAuthorityRefs(knownResourceId);
+ statusCode = res2.getStatus();
+
+ if(logger.isDebugEnabled()){
+ logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
+ }
+ Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
+ Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
+ AuthorityRefList list = res2.getEntity();
+
+ // Optionally output additional data about list members for debugging.
+ boolean iterateThroughList = true;
+ if(iterateThroughList && logger.isDebugEnabled()){
+ List<AuthorityRefList.AuthorityRefItem> items =
+ list.getAuthorityRefItem();
+ int i = 0;
+ for(AuthorityRefList.AuthorityRefItem item : items){
+ logger.debug(testName + ": list-item[" + i + "] Field:" +
+ item.getSourceField() + "= " +
+ item.getAuthDisplayName() +
+ item.getItemDisplayName());
+ logger.debug(testName + ": list-item[" + i + "] refName=" +
+ item.getRefName());
+ logger.debug(testName + ": list-item[" + i + "] URI=" +
+ item.getUri());
+ i++;
+ }
+ Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
+ }
+ }
+
+
+ // ---------------------------------------------------------------
+ // Cleanup of resources created during testing
+ // ---------------------------------------------------------------
+
+ /**
+ * Deletes all resources created by tests, after all tests have been run.
+ *
+ * This cleanup method will always be run, even if one or more tests fail.
+ * For this reason, it attempts to remove all resources created
+ * at any point during testing, even if some of those resources
+ * may be expected to be deleted by certain tests.
+ */
+ // @AfterClass(alwaysRun=true)
+ public void cleanUp() {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Cleaning up temporary resources created for testing ...");
+ }
+ // Note: Any non-success responses are ignored and not reported.
+ for (String resourceId : intakeIdsCreated) {
+ ClientResponse<Response> res = intakeClient.delete(resourceId);
+ }
+ // Delete persons before PersonAuth
+ for (String resourceId : personIdsCreated) {
+ ClientResponse<Response> res = personAuthClient.deleteItem(personAuthCSID, resourceId);
+ }
+ ClientResponse<Response> res = personAuthClient.delete(personAuthCSID);
+ }
+
+ // ---------------------------------------------------------------
+ // Utility methods used by tests above
+ // ---------------------------------------------------------------
+ @Override
+ public String getServicePathComponent() {
+ return SERVICE_PATH_COMPONENT;
+ }
+
+ private MultipartOutput createIntakeInstance(String entryNumber,
+ String entryDate,
+ String currentOwner,
+ String depositor,
+ String conditionCheckAssesor,
+ String insurer,
+ String fieldCollector,
+ String Valuer ) {
+ IntakesCommon intake = new IntakesCommon();
+ intake.setEntryNumber(entryNumber);
+ intake.setEntryDate(entryDate);
+ intake.setCurrentOwner(currentOwner);
+ intake.setDepositor(depositor);
+ intake.setConditionCheckAssesor(conditionCheckAssesor);
+ intake.setInsurer(insurer);
+ intake.setFieldCollector(fieldCollector);
+ intake.setValuer(Valuer);
+ MultipartOutput multipart = new MultipartOutput();
+ OutputPart commonPart =
+ multipart.addPart(intake, MediaType.APPLICATION_XML_TYPE);
+ commonPart.getHeaders().add("label", intakeClient.getCommonPartName());
+
+ if(logger.isDebugEnabled()){
+ logger.debug("to be created, intake common");
+ logger.debug(objectAsXmlString(intake, IntakesCommon.class));
+ }
+
+ return multipart;
+ }
+}
*/
package org.collectionspace.services.intake;
+import java.util.Iterator;
import java.util.List;
+import java.util.Map;
+
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
+import org.collectionspace.services.IntakeJAXBSchema;
import org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl;
+import org.collectionspace.services.common.authorityref.AuthorityRefList;
import org.collectionspace.services.common.ClientType;
import org.collectionspace.services.common.ServiceMain;
import org.collectionspace.services.common.context.MultipartServiceContext;
import org.collectionspace.services.common.context.MultipartServiceContextFactory;
+import org.collectionspace.services.common.context.MultipartServiceContextImpl;
import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.document.DocumentFilter;
import org.collectionspace.services.common.document.DocumentNotFoundException;
import org.collectionspace.services.common.document.DocumentHandler;
+import org.collectionspace.services.common.document.DocumentWrapper;
import org.collectionspace.services.common.query.IQueryManager;
import org.collectionspace.services.common.query.QueryManager;
import org.collectionspace.services.common.security.UnauthorizedException;
+import org.collectionspace.services.common.service.ObjectPartType;
+import org.collectionspace.services.common.vocabulary.RefNameUtils;
+import org.collectionspace.services.intake.IntakesCommonList.IntakeListItem;
+import org.collectionspace.services.intake.nuxeo.IntakeDocumentModelHandler;
+import org.collectionspace.services.nuxeo.util.NuxeoUtils;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.util.HttpResponseCodes;
+import org.nuxeo.ecm.core.api.DocumentModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return intakeObjectList;
}
+ @GET
+ @Path("{csid}/authorityrefs")
+ @Produces("application/xml")
+ public AuthorityRefList getAuthorityRefs(
+ @PathParam("csid") String csid,
+ @Context UriInfo ui) {
+ AuthorityRefList authRefList = null;
+ try {
+ ServiceContext ctx = MultipartServiceContextFactory.get().createServiceContext(null, getServiceName());
+ DocumentWrapper<DocumentModel> docWrapper =
+ getRepositoryClient(ctx).getDoc(ctx, csid);
+ IntakeDocumentModelHandler handler = (IntakeDocumentModelHandler)createDocumentHandler(ctx);
+ List<String> authRefFields = ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues("authRef");
+ String prefix = ctx.getCommonPartLabel()+":";
+ authRefList = handler.getAuthorityRefs(docWrapper, prefix, authRefFields);
+ } catch (UnauthorizedException ue) {
+ Response response = Response.status(
+ Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
+ throw new WebApplicationException(response);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Caught exception in getAuthorityRefs", e);
+ }
+ Response response = Response.status(
+ Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
+ throw new WebApplicationException(response);
+ }
+ return authRefList;
+ }
+
/**
* Gets the intake list.
*
import java.util.Iterator;
import java.util.List;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
import org.collectionspace.services.IntakeJAXBSchema;
+import org.collectionspace.services.common.authorityref.AuthorityRefList;
+import org.collectionspace.services.common.context.MultipartServiceContextFactory;
+import org.collectionspace.services.common.context.MultipartServiceContextImpl;
+import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.document.DocumentHandler.Action;
import org.collectionspace.services.common.document.DocumentWrapper;
+import org.collectionspace.services.common.security.UnauthorizedException;
+import org.collectionspace.services.common.vocabulary.RefNameUtils;
import org.collectionspace.services.intake.IntakesCommon;
import org.collectionspace.services.intake.IntakesCommonList;
import org.collectionspace.services.intake.IntakesCommonList.IntakeListItem;
public String getQProperty(String prop) {
return IntakeConstants.NUXEO_SCHEMA_NAME + ":" + prop;
}
+
+ public AuthorityRefList getAuthorityRefs(
+ DocumentWrapper<DocumentModel> docWrapper,
+ String pathPrefix,
+ List<String> authRefFields) {
+ AuthorityRefList authRefList = new AuthorityRefList();
+ try {
+ DocumentModel docModel = docWrapper.getWrappedObject();
+ List<AuthorityRefList.AuthorityRefItem> list =
+ authRefList.getAuthorityRefItem();
+
+ for(String field:authRefFields){
+ String refName = (String)docModel.getPropertyValue(pathPrefix+field);
+ if(refName==null)
+ continue;
+ try{
+ RefNameUtils.AuthorityTermInfo termInfo =
+ RefNameUtils.parseAuthorityTermInfo(refName);
+ AuthorityRefList.AuthorityRefItem ilistItem =
+ new AuthorityRefList.AuthorityRefItem();
+ ilistItem.setRefName(refName);
+ ilistItem.setAuthDisplayName(termInfo.inAuthority.displayName);
+ ilistItem.setItemDisplayName(termInfo.displayName);
+ ilistItem.setSourceField(field);
+ ilistItem.setUri(termInfo.getRelativeUri());
+ list.add(ilistItem);
+ } catch( Exception e ) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Caught exception in getAuthorityRefs", e);
+ }
+ }
+ }
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Caught exception in getIntakeList", e);
+ }
+ Response response = Response.status(
+ Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
+ throw new WebApplicationException(response);
+ }
+ return authRefList;
+ }
+
}