import javax.ws.rs.core.Response;
import org.collectionspace.services.client.AuthorityClient;
+import org.collectionspace.services.client.CollectionSpaceClient;
import org.collectionspace.services.client.PoxPayloadIn;
import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;
import org.collectionspace.services.common.context.MultipartServiceContextImpl;
public static final Boolean NO_CHANGE = null;
+ /**
+ * Make a request to the SAS Server for an authority payload.
+ *
+ * @param ctx
+ * @param specifier
+ * @param responseType
+ * @return
+ * @throws Exception
+ */
static public PoxPayloadIn requestPayloadIn(ServiceContext ctx, Specifier specifier, Class responseType) throws Exception {
PoxPayloadIn result = null;
- AuthorityClient client = (AuthorityClient) ctx.getClient();
+ AuthorityClient client = (AuthorityClient) ctx.getClient(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME);
Response res = client.read(specifier.getURNValue());
try {
int statusCode = res.getStatus();
PoxPayloadIn result = null;
ServiceContext parentCtx = new MultipartServiceContextImpl(serviceName);
- AuthorityClient client = (AuthorityClient) parentCtx.getClient();
+ AuthorityClient client = (AuthorityClient) parentCtx.getClient(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME);
Response res = client.readItem(specifier.getParentSpecifier().getURNValue(), specifier.getItemSpecifier().getURNValue());
try {
int statusCode = res.getStatus();
*/
}
-
+
+ /**
+ * Request an authority item list payload from the SAS server.
+ *
+ * @param ctx
+ * @param specifier
+ * @return
+ * @throws Exception
+ */
private PoxPayloadIn requestPayloadInItemList(ServiceContext ctx, Specifier specifier) throws Exception {
PoxPayloadIn result = null;
* @throws Exception
*/
public AbstractServiceClientImpl(String propertiesFileName) {
- readClientProperties(propertiesFileName);
- init();
+ setClientProperties(propertiesFileName);
}
/**
*/
public AbstractServiceClientImpl(Properties properties) {
setClientProperties(properties);
- init();
}
/**
if (this.properties.isEmpty() == true) {
throw new RuntimeException("Client connection properties are empty. Cannot proceed.");
}
- setupHttpClient();
- setupHttpClient4(); // temp fix for CSPACE-6281
+
+ try {
+ setupHttpClient();
+ setupHttpClient4(); // temp fix for CSPACE-6281
+ } catch (Exception e) {
+ throw new RuntimeException(e.getMessage());
+ }
+
ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
RegisterBuiltin.register(factory);
setProxy();
*
* @exception RuntimeException
*/
- protected void readClientProperties(String clientPropertiesFilename) {
+ @Override
+ public void setClientProperties(String clientPropertiesFilename) {
Properties inProperties = new Properties();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = null;
* @throws Exception
*/
protected void setClientProperties(Properties inProperties) {
- properties.putAll(inProperties);
+ properties = inProperties;
if (logger.isDebugEnabled()) {
System.getenv();
if (logger.isDebugEnabled()) {
printProperties();
}
+ //
+ // How use the properties to initialize the HTTP client
+ //
+ init();
}
/**
* setupHttpClient sets up HTTP client for the service client the setup
* process relies on the following properties URL_PROPERTY USER_PROPERTY
* PASSWORD_PROPERTY AUTH_PROPERTY SSL_PROPERTY
+ *
+ * @throws Exception
*/
@Override
- public void setupHttpClient() {
+ public void setupHttpClient() throws Exception {
try {
this.httpClient = new HttpClient();
if (useAuth()) {
}
}
} catch (Throwable e) {
- e.printStackTrace();
+ throw new Exception("Could not setup an HTTP client as requested with ", e);
}
}
* This is a temp fix for RESTEasy upgrade in CSPACE-6281. The long-term solution will be to use
* the non-deprecated approach per the RESTEasy documentation.
*/
- public void setupHttpClient4() {
+ public void setupHttpClient4() throws Exception {
try {
this.httpClient4 = new DefaultHttpClient();
if (useAuth()) {
}
}
} catch (Throwable e) {
- e.printStackTrace();
+ throw new Exception("Could not setup an HTTP client as requested with ", e);
}
}
} else {
removeProperty(CollectionSpaceClient.AUTH_PROPERTY);
}
- setupHttpClient();
- setupHttpClient(); // temp fix for CSPACE-6281
+
+ try {
+ setupHttpClient();
+ setupHttpClient(); // temp fix for CSPACE-6281
+ } catch (Exception e) {
+ throw new RuntimeException(e.getMessage());
+ }
+
setProxy();
}
package org.collectionspace.services.client;
+import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
-import org.jboss.resteasy.client.ClientResponse;
+import org.jboss.resteasy.client.ClientResponse;
import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
import org.collectionspace.services.common.authorityref.AuthorityRefList;
import org.collectionspace.services.jaxb.AbstractCommonList;
public Response getItemAuthorityRefs(String parentcsid, String itemcsid);
/*
- *
+ * Synchronization methods
+ */
+ Response syncByName(String name);
+
+
+ /*
+ * READ/GET by name method
*/
Response readByName(String name);
package org.collectionspace.services.client;
+import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.ClientResponse;
return getProxy().getItemAuthorityRefs(parentcsid, csid);
}
+ /*
+ * Synchronization method
+ */
+ public Response syncByName(String name) {
+ return getProxy().syncByName(name);
+ }
+
/*
*
*/
@PathParam("itemcsid") String itemcsid);
/*
- *
+ * Synchronization methods
+ */
+
+ // Sync by name
+ @GET
+ @Path("/urn:cspace:name({name})/sync")
+ Response syncByName(@PathParam("name") String name);
+
+ /*
+ * READ/GET Methods
*/
//(R)ead by name
package org.collectionspace.services.client;
import javax.ws.rs.core.Response;
+
import org.apache.commons.httpclient.HttpClient;
import org.jboss.resteasy.client.ClientResponse;
import org.collectionspace.services.common.authorityref.AuthorityRefList;
* PASSWORD_PROPERTY
* AUTH_PROPERTY
* SSL_PROPERTY
+ * @throws Exception
*/
- void setupHttpClient();
+ void setupHttpClient() throws Exception;
/**
* setProxy for the client
* @return the client response
*/
public Response delete(String csid);
+
+ /**
+ * Uses a properties files to set the url and credentials for an HTTP connection.
+ *
+ * @param clientPropertiesFilename
+ */
+ public void setClientProperties(String clientPropertiesFilename);
}
package org.collectionspace.services.client.test;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import javax.ws.rs.core.Response;
import org.collectionspace.services.client.CollectionSpaceClient;
import org.collectionspace.services.client.PayloadInputPart;
import org.collectionspace.services.client.PayloadOutputPart;
+import org.collectionspace.services.client.PersonAuthorityClient;
import org.collectionspace.services.client.PoxPayloadOut;
import org.collectionspace.services.jaxb.AbstractCommonList;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
protected static final String READITEMS_SHORT_IDENTIFIER = "resourceWithItems";
protected String knownAuthorityWithItems = null;
+ protected static final String SAS_IDENTIFIER = "SAS";
+ protected String knownSASAuthorityResourceId = null;
+ protected String knownSASItemResourceId = null;
+ protected HashMap<String, String> allSASResourceItemIdsCreated = new HashMap<String, String>(); /* itemURN, parentURN */;
+
protected String knownResourceRefName = null;
protected String knownItemResourceId = null;
protected String knownItemResourceShortIdentifer = null;
knownResourceRefName = refName;
}
+ protected String getSASAuthorityIdentifier() {
+ // TODO Auto-generated method stub
+ return this.getKnowResourceIdentifier() + this.SAS_IDENTIFIER;
+ }
+
+ protected String getUrnIdentifier(String shortId) {
+ return String.format("urn:cspace:name:(%s)", shortId);
+ }
+
+ /**
+ * Sets up create tests.
+ */
+ protected void setupSync() {
+ testExpectedStatusCode = this.STATUS_OK;
+ testRequestType = ServiceRequestType.SYNC;
+ testSetup(testExpectedStatusCode, testRequestType);
+ }
+
/**
* Gets a client to the SAS (Shared Authority Server)
*
}
}
- @Test(dataProvider = "testName",
- dependsOnMethods = {"CRUDTests"})
+ @Test(dataProvider = "testName", dependsOnMethods = {"CRUDTests"})
public void createItem(String testName) {
// Perform setup.
setupCreate();
}
/**
- * SAS - Create an item on the SAS server.
+ * Sync the local with the SAS
+ */
+ @Test(dataProvider = "testName", dependsOnMethods = {"createSASItem", "CRUDTests"})
+ public void syncWithSAS(String testName) {
+ setupSync();
+ AuthorityClient client = (AuthorityClient) this.getClientInstance();
+
+ //
+ // First create an empty instance of the authority, so we can sync items with it. We're
+ // using the short ID of the SAS authority. The short ID of the local and the SAS will (must) be the same.
+ //
+ String localAuthorityId = null;
+ try {
+ localAuthorityId = createResource(client, testName, getSASAuthorityIdentifier());
+ } catch (Exception e) {
+ Assert.assertNotNull(localAuthorityId);
+ }
+
+ //
+ // Now we can try to sync the SAS authority with the local one we just created.
+ //
+ Response response = client.syncByName(getSASAuthorityIdentifier()); // Notice we're using the Short ID (short ID is the same on the local and SAS)
+ try {
+ int statusCode = response.getStatus();
+ if (logger.isDebugEnabled()) {
+ logger.debug(testName + ": HTTP status = " + statusCode);
+ }
+ Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
+ invalidStatusCodeMessage(testRequestType, statusCode));
+ Assert.assertEquals(statusCode, testExpectedStatusCode);
+ } finally {
+ response.close();
+ }
+ }
+
+ /**
+ * SAS - Create a new authority on the SAS server.
+ * @param testName
+ */
+ @Test(dataProvider = "testName", dependsOnMethods = {"createItem", "CRUDTests"})
+ public void createSASAuthority(String testName) {
+ // Perform setup.
+ setupCreate();
+
+ try {
+ String newID = createResource(getSASClientInstance(), testName, getSASAuthorityIdentifier());
+ knownSASAuthorityResourceId = newID;
+ if (logger.isDebugEnabled()) {
+ String.format("Created SAS authority '%s' with CSID=%s.", getSASAuthorityIdentifier(), newID);
+ }
+ } catch (Exception e) {
+ logger.info(String.format("Failed to create SAS authority '%s'.", getSASAuthorityIdentifier()));
+ }
+ }
+
+
+ /**
+ * SAS - Create an item in the SAS authority on the SAS server.
* @param testName
*/
- @Test(dataProvider = "testName",
- dependsOnMethods = {"CRUDTests"})
+ @Test(dataProvider = "testName", dependsOnMethods = {"createSASAuthority", "CRUDTests"})
public void createSASItem(String testName) {
// Perform setup.
setupCreate();
- String newID = createItemInAuthority(getSASClientInstance(), knownResourceId);
+ String newID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceId);
- // Store the ID returned from the first item resource created
+ // Store the ID returned from the first item resource created
// for additional tests below.
- if (knownItemResourceId == null) {
- knownItemResourceId = newID;
+ if (knownSASItemResourceId == null) {
+ knownSASItemResourceId = newID;
if (null != testName && logger.isDebugEnabled()) {
- logger.debug(testName + ": knownItemResourceId=" + knownItemResourceId);
+ logger.debug(testName + ": knownSASItemResourceId=" + knownSASItemResourceId);
}
}
}
setupRead();
// Submit the request to the service and store the response.
- AuthorityClientImpl<AUTHORITY_ITEM_TYPE, AuthorityProxy> client =
- (AuthorityClientImpl<AUTHORITY_ITEM_TYPE, AuthorityProxy>)this.getClientInstance();
+ AuthorityClient client = (AuthorityClient) this.getClientInstance();
Response res = client.readByName(getKnowResourceIdentifier());
try {
int statusCode = res.getStatus();
public void CRUDTests(String testName) {
// TODO Auto-generated method stub
}
-
+
+ @Override
+ public void cleanUp() {
+ String noTest = System.getProperty("noTestCleanup");
+ if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Skipping Cleanup phase ...");
+ }
+ return;
+ }
+
+ AuthorityClient client = (AuthorityClient) this.getClientInstance();
+ String parentResourceId;
+ String itemResourceId;
+ //
+ // Clean up all authority item resources.
+ //
+ for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
+ itemResourceId = entry.getKey();
+ parentResourceId = entry.getValue();
+ Response response = client.deleteItem(parentResourceId, itemResourceId);
+ try {
+ int status = response.getStatus();
+ if (status != Response.Status.OK.getStatusCode()) {
+ logger.debug(String.format("Could not deleted authority item '%s' in authority '%s'.",
+ itemResourceId, parentResourceId));
+ }
+ } finally {
+ response.close();
+ }
+ }
+ //
+ // Clean up authority items using the SAS client.
+ //
+ client = (AuthorityClient) this.getSASClientInstance();
+ for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
+ itemResourceId = entry.getKey();
+ parentResourceId = entry.getValue();
+ // Note: Any non-success responses from the delete operation
+ // below are ignored and not reported.
+ client.deleteItem(parentResourceId, itemResourceId).close();
+ }
+ //
+ // Call out superclass's cleanUp method to delete the SAS authorities
+ //
+ super.cleanUp(client);
+ //
+ // Finally, call out superclass's cleanUp method to deleted the local authorities
+ //
+ super.cleanUp();
+ }
}
protected String createResource(String testName, String identifier) throws Exception {
String result = null;
- setupCreate();
CollectionSpaceClient client = this.getClientInstance();
+ result = createResource(client, testName, identifier);
+
+ return result;
+ }
+
+ protected String createResource(CollectionSpaceClient client, String testName, String identifier) throws Exception {
+ String result = null;
+
+ setupCreate();
REQUEST_TYPE payload = createInstance(client.getCommonPartName(), identifier);
Response res = client.create(payload);
try {
}
return result;
- }
+ }
abstract public Class<RESPONSE_TYPE> getEntityResponseType();
}
return;
}
-
- if (logger.isDebugEnabled()) {
- logger.debug("Cleaning up temporary resources created for testing ...");
- }
- CollectionSpaceClient client = this.getClientInstance();
- //
- // First, check to see if we need to cleanup any authority items
- //
- if (this.isAuthorityClient(client) == true) {
- AuthorityClient authorityClient = (AuthorityClient) client;
- for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
- String itemResourceId = entry.getKey();
- String authorityResourceId = entry.getValue();
- // Note: Any non-success responses are ignored and not reported.
- authorityClient.deleteItem(authorityResourceId, itemResourceId).close();
- }
- }
- //
- // Next, delete all other entities include possible authorities.
- //
+ cleanUp(this.getClientInstance());
+ }
+
+ public void cleanUp(CollectionSpaceClient client) {
for (String resourceId : allResourceIdsCreated) {
// Note: Any non-success responses are ignored and not reported.
client.delete(resourceId).close();
return javax.ws.rs.HttpMethod.GET;
}
},
+
READ_LIST {
@Override
return javax.ws.rs.HttpMethod.GET;
}
},
+
UPDATE {
@Override
return javax.ws.rs.HttpMethod.PUT;
}
},
+
DELETE {
@Override
return javax.ws.rs.HttpMethod.DELETE;
}
},
+
SEARCH {
@Override
return javax.ws.rs.HttpMethod.GET;
}
},
+
+ SYNC {
+
+ @Override
+ public int[] validStatusCodes() {
+ final int[] STATUS_CODES = {
+ Response.Status.OK.getStatusCode(),
+ Response.Status.BAD_REQUEST.getStatusCode(),
+ Response.Status.UNAUTHORIZED.getStatusCode(),
+ Response.Status.FORBIDDEN.getStatusCode(),
+ Response.Status.NOT_FOUND.getStatusCode(),
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
+ };
+ Arrays.sort(STATUS_CODES);
+ return STATUS_CODES;
+ }
+
+ @Override
+ public boolean isValidStatusCode(int statusCode) {
+ if (Arrays.binarySearch(SYNC.validStatusCodes(), statusCode) >= 0) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public String validStatusCodesAsString() {
+ return Arrays.toString(SYNC.validStatusCodes());
+ }
+
+ @Override
+ public String httpMethodName() {
+ return javax.ws.rs.HttpMethod.GET; // Should be POST
+ }
+ },
// Used by guard code.
NON_EXISTENT {
import org.collectionspace.authentication.spi.AuthNContext;
import org.collectionspace.services.client.AuthorityClient;
+import org.collectionspace.services.client.CollectionSpaceClient;
import org.collectionspace.services.client.IClientQueryParams;
import org.collectionspace.services.client.IQueryManager;
import org.collectionspace.services.client.workflow.WorkflowClient;
return valHandlers;
}
+ /**
+ * If one doesn't already exist, use the default properties filename to load a set of properties that
+ * will be used to create an HTTP client to a CollectionSpace instance.
+ */
@Override
public AuthorityClient getClient() throws Exception {
AuthorityClient result = authorityClient;
-
+
if (authorityClient == null) {
- String authorityClientClazz = getServiceBinding().getClientHandler();
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- authorityClientClazz = authorityClientClazz.trim();
- try {
- Class<?> c = tccl.loadClass(authorityClientClazz);
- if (AuthorityClient.class.isAssignableFrom(c)) {
- result = authorityClient = ((AuthorityClient) c.newInstance());
- } else {
- logger.error(String.format("The service binding clientHandler class '%s' for '%s' service was not of type AuthorityClient.",
- authorityClientClazz, this.getServiceName()));
- }
- } catch (ClassNotFoundException e) {
- String msg = String.format("Missing document validation handler: '%s'.", authorityClientClazz);
- logger.warn(msg);
- logger.trace(msg, e);
- }
+ result = authorityClient = getClient(CollectionSpaceClient.DEFAULT_CLIENT_PROPERTIES_FILENAME);
+ }
+
+ return result;
+ }
+
+ /*
+ * Use the properties filename passed in to load the URL and credentials that will be used
+ * to create a new HTTP client.
+ *
+ * Never uses or resets the this.authorityClient member. Always creates a new HTTP client using
+ * the loaded properties.
+ *
+ * (non-Javadoc)
+ * @see org.collectionspace.services.common.context.ServiceContext#getClient(java.lang.String)
+ */
+ @Override
+ public AuthorityClient getClient(String clientPropertiesFilename) throws Exception {
+ AuthorityClient result = null;
+
+ String authorityClientClazz = getServiceBinding().getClientHandler();
+ ClassLoader tccl = Thread.currentThread().getContextClassLoader();
+ authorityClientClazz = authorityClientClazz.trim();
+ try {
+ Class<?> c = tccl.loadClass(authorityClientClazz);
+ if (AuthorityClient.class.isAssignableFrom(c)) {
+ result = authorityClient = ((AuthorityClient) c.newInstance());
+ result.setClientProperties(clientPropertiesFilename);
+ } else {
+ logger.error(String.format("The service binding clientHandler class '%s' for '%s' service was not of type AuthorityClient.",
+ authorityClientClazz, this.getServiceName()));
+ }
+ } catch (ClassNotFoundException e) {
+ String msg = String.format("Missing document validation handler: '%s'.", authorityClientClazz);
+ logger.warn(msg);
+ logger.trace(msg, e);
}
return result;
public void setRepositoryDomain(RepositoryDomainType repositoryDomain);
public CollectionSpaceClient getClient() throws Exception;
+
+ public CollectionSpaceClient getClient(String clientProperitesFilename) throws Exception;
/**
* @return the JAX-RS resource of service for the current context.
import org.collectionspace.services.person.PersonTermGroup;
import org.collectionspace.services.person.PersonTermGroupList;
import org.collectionspace.services.person.PersonsCommon;
-import org.jboss.resteasy.client.ClientResponse;
-//import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
}
return;
}
+
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up temporary resources created for testing ...");
}
+
String parentResourceId;
String itemResourceId;
String contactResourceId;
contactResourceId);
res.close();
}
- // Clean up item resources.
- for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
- itemResourceId = entry.getKey();
- parentResourceId = entry.getValue();
- // Note: Any non-success responses from the delete operation
- // below are ignored and not reported.
- Response response = client.deleteItem(parentResourceId, itemResourceId);
- try {
- int status = response.getStatus();
- if (status != Response.Status.OK.getStatusCode()) {
- logger.debug(String.format("Could not deleted authority item '%s' in authority '%s'.",
- itemResourceId, parentResourceId));
- }
- } finally {
- response.close();
- }
- }
- // Clean up item using the SAS client resources.
- client = (PersonAuthorityClient) this.getSASClientInstance();
- for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
- itemResourceId = entry.getKey();
- parentResourceId = entry.getValue();
- // Note: Any non-success responses from the delete operation
- // below are ignored and not reported.
- client.deleteItem(parentResourceId, itemResourceId).close();
- }
//
- // Finally, clean up parent resources.
+ // Finally, clean call our superclass' cleanUp method.
//
super.cleanUp();
}
return result;
}
- @Override
+ @Override
protected PersonauthoritiesCommon updateInstance(PersonauthoritiesCommon personauthoritiesCommon) {
PersonauthoritiesCommon result = new PersonauthoritiesCommon();
@Override
protected void verifyReadItemInstance(PersonsCommon item) throws Exception {
// Do nothing for now. Add more 'read' validation checks here if applicable.
- }
-
+ }
}