* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
* limitations under the License.
*/
-// @TODO: When auto expanding, we'll need to allow setting of a maximum length to
-// which the generated IDs can grow, likely as an additional parameter to be
+// @TODO: When auto expanding, we'll need to allow setting of a maximum length
+// to which the generated IDs can grow, likely as an additional parameter to be
// passed to a constructor, with a default value hard-coded in the class.
-// If that length is exceeded, nextID() should throw an IllegalStateException.
+// If that length is exceeded, nextID() should throw an Exception.
-// @TODO: Consider handling escaped characters or sequences which represent Unicode
-// code points, both in the start and end characters of the sequence, and in the initial value.
+// @TODO: Consider handling escaped characters or sequences which represent
+// Unicode code points, both in the start and end characters of the sequence,
+// and in the initial value.
// (Example: '\u0072' for the USASCII 'r' character; see
// http://www.fileformat.info/info/unicode/char/0072/index.htm)
//
//
// Some initial research on this:
// http://www.velocityreviews.com/forums/t367758-unescaping-unicode-code-points-in-a-java-string.html
-// We might also look into the (protected) source code for java.util.Properties.load()
-// which reads escaped Unicode values.
+// We might also look into the (protected) source code for
+// java.util.Properties.load() which reads escaped Unicode values.
//
-// Note also that, if the goal is to cycle through a sequence of alphabetic identifiers,
-// such as the sequence of characters used in a particular human language, it may or may not
-// be the case that any contiguous Unicode code point sequence reflects such a character sequence.
+// Note also that, if the goal is to cycle through a sequence of alphabetic
+// identifiers, such as the sequence of characters used in a particular
+// human language, it may or may not be the case that any contiguous Unicode
+// code point sequence reflects such a character sequence.
// NOTE: This class currently hard-codes the assumption that the values in
// alphabetic identifiers are ordered in significance from left-to-right;
* Constructor using defaults for character sequence and initial value.
*
* If no start and end characters are provided for the alphabetic character
- * sequence, default to an 'a-z' sequence, representing the lowercase alphabetic
- * characters in the USASCII character set (within Java's internal
+ * sequence, defaults to an 'a-z' sequence, representing the lowercase
+ * alphabetic characters in the USASCII character set (within Java's internal
* Unicode UTF-16 representation).
*
* Additionally defaults to an initial value of "a".
* Constructor using defaults for character sequence and initial value.
*
* If no start and end characters are provided for the alphabetic character
- * sequence, default to an 'a-z' sequence, representing the lowercase alphabetic
- * characters in the USASCII character set (within Java's internal
+ * sequence, default to an 'a-z' sequence, representing the lowercase
+ * alphabetic characters in the USASCII character set (within Java's internal
* Unicode UTF-16 representation).
*
* @param initial The initial value of the alphabetic ID. Must be a
- * member of the valid aphabetic sequence.
+ * member of the valid alphabetic sequence.
*/
public AlphabeticIDGeneratorPart(String initial)
throws IllegalArgumentException {
if (sequenceStart == null || sequenceStart.equals("")) {
throw new IllegalArgumentException(
- "Start character in the character sequence must not be null or empty");
+ "Start character in the character sequence must not be " +
+ "null or empty");
}
if (sequenceStart.length() == 1) {
if (sequenceEnd == null || sequenceEnd.equals("")) {
throw new IllegalArgumentException(
- "End character in the character sequence must not be null or empty");
+ "End character in the character sequence must not be " +
+ "null or empty");
}
if (sequenceEnd.length() == 1) {
if (this.endChar <= this.startChar) {
throw new IllegalArgumentException(
- "End (last) character in the character sequence must be greater than the start character");
+ "End (last) character in the character sequence must be " +
+ "greater than the start character");
}
// Validate and store the initial value of this identifier.
if (initial == null || initial.equals("")) {
- throw new IllegalArgumentException("Initial value must not be null or empty");
+ throw new IllegalArgumentException("Initial value must not be " +
+ "null or empty");
}
// @TODO: Add a check for maximum length of the initial value here.
@Override
public String getInitialID() {
- return getIDString(this.initialValue);
+ return toIDString(this.initialValue);
}
@Override
// and may be ripe for refactoring.
if (value == null || value.equals("")) {
- throw new IllegalArgumentException("Initial value must not be null or empty");
+ throw new IllegalArgumentException("Initial value must not be " +
+ "null or empty");
}
// @TODO: Add a check for maximum length of the value here.
@Override
public String getCurrentID() {
if (this.currentValue == null || this.currentValue.size() == 0) {
- return getIDString(this.initialValue);
+ return toIDString(this.initialValue);
} else {
- return getIDString(this.currentValue);
+ return toIDString(this.currentValue);
}
}
// set a flag to later expand the size of the identifier.
//
// @TODO: Set another flag to enable or disable this behavior,
- // as well as a mechanism for setting the maximum expansion permitted.
+ // as well as a mechanism for setting the maximum expansion
+ // permitted.
if (i == 0) {
expandIdentifier = true;
}
this.currentValue.add(0, Character.valueOf(this.startChar));
}
- return getIDString(this.currentValue);
+ return toIDString(this.currentValue);
}
// and set the current value to the initial value.
if (this.currentValue == null || this.currentValue.size() == 0) {
this.currentValue = this.initialValue;
- return getIDString(this.currentValue);
+ return toIDString(this.currentValue);
// Otherwise, return a new value.
} else {
return nextID();
}
/**
- * Returns a String representation of the ID, by concatenating
+ * Returns a String representation of a provided ID, by concatenating
* the String values of each alphabetic character constituting the ID.
*
* @param characters The alphabetic characters constituting the ID.
*
* @return A String representation of the ID.
*/
- public String getIDString(Vector<Character> characters) {
+ public String toIDString(Vector<Character> characters) {
StringBuffer sb = new StringBuffer();
for ( Character ch : characters ) {
sb.append(ch.toString());
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
*/
public class BaseIDGenerator implements IDGenerator {
- protected String csid = "";
- protected String uri = "";
- protected String description = "";
protected Vector<IDGeneratorPart> parts = new Vector<IDGeneratorPart>();
final static int MAX_ID_LENGTH = 50;
/**
- * Constructor.
- *
- * @param csid A CollectionSpace ID (CSID) identifying this ID generator.
- *
- */
- public BaseIDGenerator(String csid) {
- if (csid != null && ! csid.equals("")) {
- this.csid = csid;
- }
+ * Constructor (no argument)
+ */
+ public BaseIDGenerator() {
}
/**
* Constructor.
*
- * @param csid A CollectionSpace ID (CSID) identifying this ID generator.
- *
* @param parts A collection of ID generator parts.
- *
*/
- public BaseIDGenerator(String csid, Vector<IDGeneratorPart> parts) {
- if (csid != null && ! csid.equals("")) {
- this.csid = csid;
- }
+ public BaseIDGenerator(Vector<IDGeneratorPart> parts) {
if (parts != null) {
this.parts = parts;
}
}
- /**
- * Returns the CollectionSpace ID (CSID) identifying this ID generator.
- *
- * @return A CollectionSpace ID (CSID) identifying this ID generator.
- */
- public String getCsid() {
- return this.csid;
- }
-
- /**
- * Sets a URI as a second type of identifier for this ID generator,
- * in addition to its CollectionSpace ID (CSID).
- *
- * @param uriStr A String representation of a URI.
- */
- public void setURI(String uriStr) {
- if (uriStr == null || uriStr.equals("")) {
- return;
- }
- // Validate that this is a legal URI.
- try {
- URI tempUri = new URI(uriStr);
- } catch (URISyntaxException e) {
- // Fail silently without setting the URI.
- return;
- }
- this.uri = uriStr;
- }
-
- /**
- * Returns a String representation of the URI, if any,
- * that is used as a second type of identifier for this
- * ID generator, in addition to its CollectionSpace ID (CSID).
- *
- * @return A String representation of the URI identifying this
- * ID generator.
- */
- public String getURI() {
- return this.uri;
- }
-
- /**
- * Sets an optional, human-readable description of this ID generator.
- *
- * @param description A human-readable description of this ID generator.
- */
- public void setDescription(String description) {
- if (description != null) {
- this.description = description;
- }
- }
-
- /**
- * Returns the human-readable description of this ID generator, if any.
- *
- * @return description A human-readable description of this ID generator.
- */
- public String getDescription() {
- return this.description;
- }
-
/**
* Adds a single ID generator part.
*
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
*/
package org.collectionspace.services.id;
-import java.util.List;
+import java.io.StringWriter;
+import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
// May at some point instead use
// org.jboss.resteasy.spi.NotFoundException
import org.collectionspace.services.common.repository.BadRequestException;
import org.collectionspace.services.common.repository.DocumentNotFoundException;
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.DocumentHelper;
+import org.dom4j.Element;
+import org.dom4j.Namespace;
+import org.dom4j.io.OutputFormat;
+import org.dom4j.io.XMLWriter;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final Logger logger = LoggerFactory.getLogger(IDResource.class);
final static IDService service = new IDServiceJdbcImpl();
+
+ // XML namespace for the ID Service.
+ final static String ID_SERVICE_NAMESPACE =
+ "http://collectionspace.org/services/id";
+ final static String ID_SERVICE_NAMESPACE_PREFIX = "ns2";
+
+ // Names of elements for ID generator lists and list items.
+ final static String ID_GENERATOR_LIST_NAME = "idgenerator-list";
+ final static String ID_GENERATOR_LIST_ITEM_NAME = "idgenerator-list-item";
+
+ // Base URL path for REST-based requests to the ID Service.
+ //
+ // @TODO Investigate whether this can be obtained from the
+ // value used in the class-level @PATH annotation, above.
final static String BASE_URL_PATH = "/idgenerators";
//////////////////////////////////////////////////////////////////////
// there is a requirement to return an XML representation, and/or any
// other representations.
- // Unless the 'response' variable is explicitly initialized here,
- // the compiler gives the error: "variable response might not have
- // been initialized."
- Response response = null;
- response = response.ok().build();
- String newId = "";
+ ResponseBuilder builder = Response.ok();
+ Response response = builder.build();
+ String newId = "";
try {
// Obtain a new ID from the specified ID generator,
// and return it in the entity body of the response.
newId = service.createID(csid);
- if (newId == null || newId.equals("")) {
+ if (newId == null || newId.trim().isEmpty()) {
response =
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("ID Service returned null or empty ID")
logger.debug("> in readIDGenerator(String)");
- Response response = null;
- response = response.ok().build();
- String resourceRepresentation = "";
+ ResponseBuilder builder = Response.ok();
+ Response response = builder.build();
+ String resourceRepresentation = "";
try {
resourceRepresentation = service.readIDGenerator(csid);
if (
resourceRepresentation == null ||
- resourceRepresentation.equals("")
+ resourceRepresentation.trim().isEmpty()
) {
response =
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
//////////////////////////////////////////////////////////////////////
/**
- * Placeholder for retrieving a list of available ID Generator
- * instance resources.
+ * Retrieve a list of available ID Generator instance resources.
*
- * Required to facilitate a HEAD method test in ServiceLayerTest.
+ * Note: This REST method is required by a HEAD method test
+ * in org.collectionspace.services.client.test.ServiceLayerTest.
*
* @param format A representation ("format") in which to return list items,
* such as a "full" or "summary" format.
logger.debug("> in readIDGeneratorsList()");
- // @TODO The names of the query parameters above ("format"
- // and "role") are arbitrary, as are the format of the
+ // @TODO The names and values of the query parameters above
+ // ("format"and "role") are arbitrary, as are the format of the
// results returned. These should be standardized and
// referenced project-wide.
- Response response = null;
- response = response.ok().build();
- String resourceRepresentation = "";
+ ResponseBuilder builder = Response.ok();
+ Response response = builder.build();
- // @TODO Replace these placeholders/expedients
- // with a schema-defined list format.
- final String LIST_ROOT_START = "<list>";
- final String LIST_ROOT_END = "</list>";
- final String LIST_ITEM_START = "<item>";
- final String LIST_ITEM_END = "</item>";
+ String resourceRepresentation = "";
- final String LIST_FORMAT_FULL = "full";
final String LIST_FORMAT_SUMMARY = "summary";
+ final String LIST_FORMAT_FULL = "full";
// @TODO We're currently overloading the String items in
// the 'generators' list with distinctly different types of
// or may not be a good idea.
try {
- List<String> generators = null;
- if (format == null || format.equals("")) {
- generators = service.readIDGeneratorsSummaryList();
+ Map<String,String> generators = service.readIDGeneratorsList();
+
+ // @TODO Filtering by role will likely take place here ...
+
+ // Default to summary list if no list format is specified.
+ if (format == null || format.trim().isEmpty()) {
+ resourceRepresentation = formattedSummaryList(generators);
} else if (format.equalsIgnoreCase(LIST_FORMAT_SUMMARY)) {
- generators = service.readIDGeneratorsSummaryList();
+ resourceRepresentation = formattedSummaryList(generators);
} else if (format.equalsIgnoreCase(LIST_FORMAT_FULL)) {
- generators = service.readIDGeneratorsList();
+ resourceRepresentation = formattedFullList(generators);
+ // Return an error if the value of the query parameter
+ // is unrecognized.
} else {
// @TODO Return an appropriate XML-based entity body upon error.
String msg = "Query parameter '" + format + "' was not recognized.";
.build();
}
- // @TODO Replace this placeholder/expedient, as per above
- StringBuffer sb = new StringBuffer("");
- sb.append(LIST_ROOT_START);
-
// Filter list by role
//
// @TODO Checking for roles here is a short-term expedient;
// If the request didn't filter by role, return all
// ID generator instances.
- if (role == null || role.equals("")) {
+ if (role == null || role.trim().isEmpty()) {
if (generators != null) {
- for (String generator : generators) {
- sb.append(LIST_ITEM_START);
- sb.append(generator);
- sb.append(LIST_ITEM_END);
- }
+ // Do nothing
}
// Otherwise, return only ID generator instances
// matching the requested role.
} else {
- if (generators != null) {
- for (String generator : generators) {
- if (generatorInRole(generator, role)) {
- sb.append(LIST_ITEM_START);
- sb.append(generator);
- sb.append(LIST_ITEM_END);
- }
- }
- }
-
- }
-
- sb.append(LIST_ROOT_END);
-
- resourceRepresentation = sb.toString();
+ // @TODO Implement this stubbed code.
+ }
response =
Response.status(Response.Status.OK)
.type(MediaType.APPLICATION_XML)
.build();
- // @TODO Return an XML-based error results format with the
- // responses below.
-
+ // @TODO Return an XML-based error results format with the
+ // responses below.
} catch (IllegalStateException ise) {
response =
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN)
.build();
- // This is guard code that should never be reached.
+ // This is guard code that should never be reached.
} catch (Exception e) {
response =
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
return response;
}
- private boolean generatorInRole(String generator, String role) {
+ //////////////////////////////////////////////////////////////////////
+ /**
+ * Identifies whether the specified ID generator instance can
+ * generate and validate IDs in a specified role (aka type or context).
+ *
+ * Example: Can a particular ID generator instance generate IDs for
+ * accession numbers? For intake numbers?
+ *
+ * @param csid A CollectionSpace ID (CSID) identifying an
+ * ID generator instance.
+ *
+ * @param role A role (aka type or context) in which that
+ * ID generator instance can generate and
+ * validate IDs.
+ *
+ * @return True if the specified ID generator can generate and validate
+ * IDs in the specified role; false if it cannot.
+ */
+ private boolean generatorHasRole(String csid, String role) {
+
+ // @TODO Implement this stubbed method, replacing
+ // this with a lookup of associations of ID generator
+ // instances to ID generator roles; perhaps in the
+ // short term with an external configuration file
+ // and ultimately in a database table.
+
+ return true;
- // @TODO Short term expedient, relying on the incidental
- // and transient fact that as of 2009-10-08, CSIDs for
- // ID generator instances are identical to role names.
+ // Pseudocode (with static string examples) of what we might
+ // want to do instead:
+ //
+ // getCSID(), below, would retrieve the value of the <csid> element,
+ // present in all list formats for ID generator instances,
+ // via xpath or similar.
//
- // This will work only for summary lists; in full lists,
- // the CSID is not currently returned, and so any filtering
- // by role will cause zero (0) items to be returned in the list.
-
- // @TODO Replace this with a lookup of associations of
- // ID generator instances to ID generator roles;
- // perhaps in the short term with an external configuration
- // file and ultimately in a database table.
-
- if (generator.equalsIgnoreCase(role)) {
- return true;
- } else {
- return false;
+ // if (csid.equals("1a67470b-19b1-4ae3-88d4-2a0aa936270e")
+ // && role.equalsIgnoreCase("ID_ROLE_ACCESSION_NUMBER")) {
+ // // Return true if the ID generator instance identified by
+ // // the provided CSID is associated with the provided role.
+ // return true;
+ // } else {
+ // return false;
+ // }
+
+ }
+
+ //////////////////////////////////////////////////////////////////////
+ /**
+ * Returns a summary list of ID generator instances.
+ *
+ * This is an XML-based list format that returns only
+ * basic data about each ID generator instance, along
+ * with relative URIs that may be used to retrieve more
+ * data about each instance.
+ *
+ * @param generators A list of ID generator instances, each
+ * containing a CollectionSpace ID (CSID).
+ *
+ * @return A summary list of ID generator instances.
+ */
+ private String formattedSummaryList(Map<String,String> generators) {
+
+ Document doc = DocumentHelper.createDocument();
+ Element root = doc.addElement(ID_GENERATOR_LIST_NAME);
+ Namespace namespace =
+ new Namespace(ID_SERVICE_NAMESPACE_PREFIX, ID_SERVICE_NAMESPACE);
+ doc.getRootElement().add(namespace);
+
+ Element listitem = null;
+ Element csid = null;
+ Element uri = null;
+ for (String csidValue : generators.keySet() )
+ {
+ listitem = root.addElement(ID_GENERATOR_LIST_ITEM_NAME);
+ csid = listitem.addElement("csid");
+ csid.addText(csidValue);
+ uri = listitem.addElement("uri");
+ uri.addText(getRelativePath(csidValue));
+ }
+
+ String summaryList = "";
+ try {
+ summaryList = prettyPrintXML(doc);
+ } catch(Exception e) {
+ logger.debug("Error pretty-printing XML: " + e.getMessage());
+ summaryList = doc.asXML();
+ }
+
+ return summaryList;
+ }
+
+ //////////////////////////////////////////////////////////////////////
+ /**
+ * Returns a full list of ID generator instances.
+ *
+ * This is an XML-based list format that returns
+ * full data about each ID generator instance.
+ *
+ * @param generators A list of ID generator instances, each
+ * containing a CollectionSpace ID (CSID).
+ *
+ * @return A full list of ID generator instances.
+ */
+ private String formattedFullList(Map<String,String> generators) {
+
+ Document doc = DocumentHelper.createDocument();
+ Element root = doc.addElement(ID_GENERATOR_LIST_NAME);
+ Namespace namespace =
+ new Namespace(ID_SERVICE_NAMESPACE_PREFIX, ID_SERVICE_NAMESPACE);
+ doc.getRootElement().add(namespace);
+
+ Element listitem = null;
+ Element csid = null;
+ Element uri = null;
+ Element generator = null;
+ Element generatorRoot = null;
+ String generatorStr = "";
+ Document generatorDoc = null;
+ for (String csidValue : generators.keySet() )
+ {
+ listitem = root.addElement(ID_GENERATOR_LIST_ITEM_NAME);
+ csid = listitem.addElement("csid");
+ csid.addText(csidValue);
+ uri = listitem.addElement("uri");
+ uri.addText(getRelativePath(csidValue));
+ generator = listitem.addElement("idgenerator");
+ // Using the CSID as a key, get the XML string
+ // representation of the ID generator.
+ generatorStr = generators.get(csidValue);
+ // Convert the XML string representation of the
+ // ID generator to a new XML document, copy its
+ // root element, and append it to the relevant location
+ // in the current list item.
+ try {
+ generatorDoc = textToXMLDocument(generatorStr);
+ generatorRoot = generatorDoc.getRootElement();
+ generator.add(generatorRoot.createCopy());
+ // If an error occurs parsing the XML string representation,
+ // the text of the ID generator element will remain empty.
+ } catch (Exception e) {
+ logger.warn("Error parsing XML text: " + generatorStr);
+ }
+
+ }
+
+ String summaryList = "";
+ try {
+ summaryList = prettyPrintXML(doc);
+ } catch(Exception e) {
+ logger.debug("Error pretty-printing XML: " + e.getMessage());
+ summaryList = doc.asXML();
+ }
+
+ return summaryList;
+ }
+
+ // @TODO Refactoring opportunity: the utility methods below
+ // might be moved into the 'common' module.
+
+ //////////////////////////////////////////////////////////////////////
+ /**
+ * Returns a 'pretty printed' String representation of
+ * an XML document.
+ *
+ * Uses the default settings for indentation, whitespace, etc.
+ * of a pre-defined dom4j output format.
+ *
+ * @param doc A dom4j XML Document.
+ *
+ * @return A pretty-printed String representation of that document.
+ */
+ private String prettyPrintXML(Document doc)
+ throws Exception {
+
+ StringWriter sw = new StringWriter();
+ try {
+ final OutputFormat PRETTY_PRINT_FORMAT =
+ OutputFormat.createPrettyPrint();
+ final XMLWriter writer =
+ new XMLWriter(sw, PRETTY_PRINT_FORMAT);
+ // Print the document to the current writer.
+ writer.write(doc);
}
+ catch (Exception e) {
+ throw e;
+ }
+ return sw.toString();
+ }
+ //////////////////////////////////////////////////////////////////////
+ /**
+ * Returns an XML document, when provided with a String
+ * representation of that XML document.
+ *
+ * @param xmlStr A String representation of an XML document.
+ *
+ * @return A dom4j XML document.
+ */
+ private Document textToXMLDocument(String xmlStr) throws Exception {
+
+ Document doc = null;
+ try {
+ doc = DocumentHelper.parseText(xmlStr);
+ } catch (DocumentException e) {
+ throw e;
+ }
+ return doc;
}
+
+ //////////////////////////////////////////////////////////////////////
+ /**
+ * Returns a relative URI path to a resource
+ * that represents an instance of an ID generator.
+ *
+ * @param csid A CollectionSpace ID (CSID).
+ *
+ * @return A relative URI path to a resource that
+ * represents an ID generator instance.
+ */
+ private String getRelativePath(String csid) {
+ if (csid !=null && ! csid.trim().isEmpty()) {
+ return BASE_URL_PATH + "/" + csid;
+ } else {
+ return BASE_URL_PATH;
+ }
+ }
+
}
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
// May at some point instead use
// org.jboss.resteasy.spi.NotFoundException
-import java.util.List;
+import java.util.Map;
import org.collectionspace.services.common.repository.DocumentNotFoundException;
import org.collectionspace.services.common.repository.BadRequestException;
IllegalArgumentException, IllegalStateException;
// Read a list of objects (aka read multiple)
- // and return in a full list format.
- public List<String> readIDGeneratorsList() throws IllegalStateException;
+ // and return a list (map) of those objects and their identifiers.
+ public Map<String,String> readIDGeneratorsList() throws IllegalStateException;
- // Read a list of objects (aka read multiple)
- // and return in a summary list format.
- public List<String> readIDGeneratorsSummaryList() throws BadRequestException,
- IllegalStateException;
-
- // Update (may need to check for changes in the ID generator structure)
- public void updateIDGenerator(String csid, String serializedIDGenerator)
+ // Update
+ public void updateIDGenerator(String csid, String serializedIDGenerator)
throws DocumentNotFoundException, BadRequestException,
IllegalArgumentException, IllegalStateException;
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
// May at some point instead use
// org.jboss.resteasy.spi.NotFoundException
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import org.collectionspace.services.common.repository.BadRequestException;
import org.collectionspace.services.common.repository.DocumentNotFoundException;
int rowsUpdated = stmt.executeUpdate(
"UPDATE id_generators SET last_generated_id='" + lastId +
- "' WHERE id_generator_csid='" + csid + "'");
+ "' WHERE csid='" + csid + "'");
if (rowsUpdated != 1) {
throw new IllegalStateException(
ResultSet rs = stmt.executeQuery(
"SELECT last_generated_id FROM id_generators " +
- "WHERE id_generator_csid='" + csid + "'");
+ "WHERE csid='" + csid + "'");
boolean moreRows = rs.next();
if (! moreRows) {
// of the generator, such as its URI, if any, and its structure,
// so we avoid duplication based on content as well as identifier.
ResultSet rs = stmt.executeQuery(
- "SELECT id_generator_csid FROM id_generators " +
- "WHERE id_generator_csid='" + csid + "'");
+ "SELECT csid FROM id_generators " +
+ "WHERE csid='" + csid + "'");
boolean moreRows = rs.next();
final String SQL_STATEMENT_STRING =
"INSERT INTO id_generators " +
"(" +
- "id_generator_csid, " +
+ "csid, " +
"id_generator_state, " +
"last_generated_id" +
")" +
ResultSet rs = stmt.executeQuery(
"SELECT id_generator_state FROM id_generators " +
- "WHERE id_generator_csid='" + csid + "'");
+ "WHERE csid='" + csid + "'");
boolean moreRows = rs.next();
if (! moreRows) {
* @throws IllegalStateException if a storage-related error occurred.
*/
@Override
- public List readIDGeneratorsList() throws IllegalStateException {
+ public Map<String,String> readIDGeneratorsList() throws IllegalStateException {
logger.debug("> in readIDGeneratorsList");
- List<String> generators = new ArrayList<String>();
+ Map<String,String> generators = new HashMap<String,String>();
Connection conn = null;
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
- "SELECT id_generator_state FROM id_generators");
+ "SELECT csid, id_generator_state FROM id_generators");
boolean moreRows = rs.next();
if (! moreRows) {
}
while (moreRows = rs.next()) {
- generators.add(rs.getString(1));
+ generators.put(rs.getString(1), rs.getString(2));
}
rs.close();
}
}
- logger.debug("> retrieved list: ");
- for (String generator : generators) {
- logger.debug("generator=\n" + generator);
- }
-
- return generators;
- }
-
- //////////////////////////////////////////////////////////////////////
- /**
- * Returns a list of ID generator instances from persistent storage.
- *
- * @return A list of ID generator instances, with each list item
- * constituting a serialized representation of an
- * ID generator instance.
- *
- * @throws IllegalStateException if a storage-related error occurred.
- */
- @Override
- public List readIDGeneratorsSummaryList() throws IllegalStateException {
-
- logger.debug("> in readIDGeneratorsSummaryList");
-
- List<String> generators = new ArrayList<String>();
-
- Connection conn = null;
- try {
-
- conn = getJdbcConnection();
- Statement stmt = conn.createStatement();
-
- ResultSet rs = stmt.executeQuery(
- "SELECT id_generator_csid FROM id_generators");
-
- boolean moreRows = rs.next();
- if (! moreRows) {
- return generators;
- }
-
- while (moreRows = rs.next()) {
- generators.add(rs.getString(1));
- }
-
- rs.close();
-
- } catch (SQLException e) {
- throw new IllegalStateException(
- "Error retrieving ID generators " +
- " from database: " + e.getMessage());
- } finally {
- try {
- if (conn != null) {
- conn.close();
- }
- } catch(SQLException e) {
- // Do nothing here
- }
- }
-
- logger.debug("> retrieved list: ");
- for (String generator : generators) {
- logger.debug("generator=\n" + generator);
- }
-
return generators;
}
// Test whether this ID generator already exists in the database.
ResultSet rs = stmt.executeQuery(
- "SELECT id_generator_csid FROM id_generators " +
- "WHERE id_generator_csid='" +
+ "SELECT csid FROM id_generators " +
+ "WHERE csid='" +
csid + "'");
boolean moreRows = rs.next();
"UPDATE id_generators SET " +
"id_generator_state = ?, " +
"last_generated_id = ? " +
- "WHERE id_generator_csid = ?";
+ "WHERE csid = ?";
SettableIDGenerator generator;
try {
// Test whether this ID generator already exists in the database.
ResultSet rs = stmt.executeQuery(
- "SELECT id_generator_csid FROM id_generators " +
- "WHERE id_generator_csid='" +
+ "SELECT csid FROM id_generators " +
+ "WHERE csid='" +
csid + "'");
boolean moreRows = rs.next();
if (idGeneratorFound) {
final String SQL_STATEMENT_STRING =
- "DELETE FROM id_generators WHERE id_generator_csid = ?";
+ "DELETE FROM id_generators WHERE csid = ?";
PreparedStatement ps = conn.prepareStatement(SQL_STATEMENT_STRING);
ps.setString(1, csid);
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
*/
// @TODO Need to handle Exceptions as described in comments below.
+
+// @TODO Need to add optional capability to pad with leading zeros.
package org.collectionspace.services.id;
*/
public class NumericIDGeneratorPart implements SequenceIDGeneratorPart {
- final static private int DEFAULT_MAX_LENGTH = 6;
- private int maxLength = DEFAULT_MAX_LENGTH;
+ final static private long DEFAULT_MAX_LENGTH = 6;
+ private long maxLength = DEFAULT_MAX_LENGTH;
- final static private int DEFAULT_INITIAL_VALUE = 1;
+ final static private long DEFAULT_INITIAL_VALUE = 1;
final static private long CURRENT_VALUE_NOT_SET = -1;
private long initialValue = DEFAULT_INITIAL_VALUE;
private long currentValue = CURRENT_VALUE_NOT_SET;
* Constructor using defaults for initial value and maximum length.
*/
public NumericIDGeneratorPart() throws IllegalArgumentException {
- this(Integer.toString(DEFAULT_INITIAL_VALUE),
- Integer.toString(DEFAULT_MAX_LENGTH));
+ this(Long.toString(DEFAULT_INITIAL_VALUE),
+ Long.toString(DEFAULT_MAX_LENGTH));
}
/**
*/
public NumericIDGeneratorPart(String initialValue)
throws IllegalArgumentException {
- this(initialValue, Integer.toString(DEFAULT_MAX_LENGTH));
+ this(initialValue, Long.toString(DEFAULT_MAX_LENGTH));
}
/**
"Initial ID value must not be null or empty");
}
try {
- this.maxLength = Integer.parseInt(maxLength);
+ this.maxLength = Long.parseLong(maxLength);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Maximum ID length must be parseable as a number");
@Override
public String getRegex() {
String regex =
- "(" + "\\d" + "{1," + Integer.toString(this.maxLength) + "}" + ")";
+ "(" + "\\d" + "{1," + Long.toString(this.maxLength) + "}" + ")";
return regex;
}
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
public class SettableIDGenerator extends BaseIDGenerator {
/**
- * Constructor.
- *
- * @param csid A CollectionSpace ID (CSID) identifying this ID generator.
- *
+ * Constructor (no argument)
*/
- public SettableIDGenerator(String csid) {
- super(csid);
+ public SettableIDGenerator() {
+ super();
}
/**
* Constructor.
*
- * @param csid A CollectionSpace ID (CSID) identifying this ID generator.
- *
* @param parts A collection of ID generator parts.
*
*/
- public SettableIDGenerator(String csid, Vector<IDGeneratorPart> parts) {
- super(csid, parts);
+ public SettableIDGenerator(Vector<IDGeneratorPart> parts) {
+ super(parts);
}
/**
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
/*
- * create_id_generators_table.sql
- *
- * Creates the "id_generators" table, which stores ID patterns and their state.
- * Also sets the access permissions of that table.
- *
* 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:
*
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
+ */
+
+/*
+ * create_id_generators_table.sql
+ *
+ * Creates the "id_generators" table, used by the ID Service,
+ * and sets the access permissions of that table.
*
- * $LastChangedBy: aron $
* $LastChangedRevision: 302 $
* $LastChangedDate: 2009-07-15 17:42:23 -0700 (Wed, 15 Jul 2009) $
*/
+/*
+ * Note: due to the use of the FLUSH PRIVILEGES command, below,
+ * this script must be executed by a database user (such as
+ * the root user) who has RELOAD privileges.
+*/
+
CREATE DATABASE IF NOT EXISTS `cspace`;
USE `cspace`;
DROP TABLE IF EXISTS `id_generators`;
CREATE TABLE `id_generators` (
- `id_generator_csid` varchar(80) PRIMARY KEY,
- -- `id_generator_uri` varchar(200),
- `id_generator_state` varchar(8000),
- `last_generated_id` varchar(255),
- `modified` timestamp NOT NULL
- default CURRENT_TIMESTAMP
- on update CURRENT_TIMESTAMP,
- INDEX `id_generator_csid_index` (`id_generator_csid`)
- -- INDEX `id_generator_uri_index` (`id_generator_uri`)
+ `csid` varchar(80) PRIMARY KEY,
+ `displayname` varchar(80),
+ `description` varchar(500),
+ `id_generator_state` varchar(8000),
+ `last_generated_id` varchar(255),
+ `modified` timestamp NOT NULL
+ default CURRENT_TIMESTAMP
+ on update CURRENT_TIMESTAMP,
+ INDEX `csid_index` (`csid`)
) ENGINE=InnoDB;
GRANT SELECT, INSERT, UPDATE, DELETE
/*
- * load_id_generators_table.sql
- *
- * Loads an initial set of ID patterns into the "id_generators" table.
- *
* 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:
*
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
+ */
+
+/*
+ * load_id_generators_table.sql
+ *
+ * Loads a default set of data into the "id_generators" table,
+ * used by the ID Service.
*
- * $LastChangedBy: aron $
* $LastChangedRevision: 302 $
* $LastChangedDate: 2009-09-25 15:51:39 -0700 (Fri, 25 Sep 2009) $
*/
+/*
+ * NOTE: For numeric sequence parts whose first generated
+ * value is expected to start at the initial value (such as '1'),
+ * enter '-1' for the current value.
+ *
+ * Otherwise, the first generated value will be the next value
+ * in the sequence after the initial value (e.g. '2', if the
+ * initial value is '1').
+ */
+
USE `cspace`;
-- ACCESSION_LOT_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('ACCESSION_LOT_NUMBER',
+ ('1a67470b-19b1-4ae3-88d4-2a0aa936270e',
+ 'Accession Activity Number',
+ 'Generates accession lot or activity numbers, to identify accession
+activities in which a lot of one or more collection objects is
+acquired by the institution.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>ACCESSION_LOT_NUMBER</csid>
- <uri></uri>
- <description>Generates accession numbers, identifying accession
-events in which a lot of one or more collection objects are
-acquired by the museum.</description>
<parts>
<org.collectionspace.services.id.YearIDGeneratorPart>
<currentValue></currentValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- ACCESSION_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('ACCESSION_NUMBER',
+ ('9dd92952-c384-44dc-a736-95e435c1759c',
+ 'Accession Number',
+ 'Generates accession numbers, to identify individual
+collection objects individually acquired by the museum. This
+generator is used for collection objects without parts.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>ACCESSION_NUMBER</csid>
- <uri></uri>
- <description>Generates accession numbers, to identify individual
-collection objects individually acquired by the museum. This
-generator is used for collection objects without parts.</description>
<parts>
<org.collectionspace.services.id.YearIDGeneratorPart>
<currentValue></currentValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>.</initialValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- ARCHIVES_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('ARCHIVES_NUMBER',
+ ('70586d30-9dca-4a07-a3a2-1976fe898028',
+ 'Archives Number',
+ 'Generates archives numbers, to identify accession activities
+in which a lot of one or more collection objects is formally
+acquired for the archives.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>ARCHIVES_NUMBER</csid>
- <uri></uri>
- <description>Generates archives numbers.</description>
<parts>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>AR</initialValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- EVALUATION_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('EVALUATION_NUMBER',
+ ('d2d80822-25c7-4c7c-a105-fc40cdb0c50f',
+ 'Evaluation Number',
+ 'Generates evaluation numbers, to identify intake activities
+in which a lot of one or more collection objects is formally
+acquired for evaluation.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>EVALUATION_NUMBER</csid>
- <uri></uri>
- <description>Generates evaluation numbers.</description>
<parts>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>EV</initialValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- INTAKE_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('INTAKE_NUMBER',
+ ('8088cfa5-c743-4824-bb4d-fb11b12847f7',
+ 'Intake Number',
+ 'Generates intake activity numbers, to identify intake activities
+in which a lot of one or more collection objects enters
+the institution for evaluation.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>INTAKE_NUMBER</csid>
- <uri></uri>
- <description>Generates intake numbers.</description>
- <parts>
+ <parts>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>IN</initialValue>
<currentValue>IN</currentValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- INTAKE_OBJECT_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('INTAKE_OBJECT_NUMBER',
+ ('a91db555-5c53-4996-9918-6712351397a0',
+ 'Intake Object Number',
+ 'Generates intake numbers, to identify individual
+collection objects that enter the institution through
+intake activities, before they are either returned to
+their owner or formally acquired by the institution.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>INTAKE_OBJECT_NUMBER</csid>
- <uri></uri>
- <description>Generates intake numbers.</description>
<parts>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>IN</initialValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>.</initialValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- LIBRARY_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('LIBRARY_NUMBER',
+ ('80fedaf6-1647-4f30-9f53-a75a3cac2ffd',
+ 'Library Number',
+ 'Generates library numbers, in which a lot of one or more
+collection objects is formally acquired for the library.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>LIBRARY_NUMBER</csid>
- <uri></uri>
- <description>Generates library numbers.</description>
- <parts>
+ <parts>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>LIB</initialValue>
<currentValue>LIB</currentValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- LOANS_IN_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('LOANS_IN_NUMBER',
+ ('ed87e7c6-0678-4f42-9d33-f671835586ef',
+ 'Loans-in Number',
+ 'Generates loans-in numbers, to identify individual
+collection objects that are received on loan.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>LOANS_IN_NUMBER</csid>
- <uri></uri>
- <description>Generates loans-in numbers.</description>
<parts>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>LI</initialValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>.</initialValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- STUDY_NUMBER
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('STUDY_NUMBER',
+ ('0518132e-dd8c-4773-8fa9-07c9af4444ee',
+ 'Study Number',
+ 'Generates study numbers, to identify intake activities
+in which a lot of one or more collection objects is formally
+acquired for study.',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>STUDY_NUMBER</csid>
- <uri></uri>
- <description>Generates study numbers.</description>
- <parts>
+ <parts>
<org.collectionspace.services.id.StringIDGeneratorPart>
<initialValue>ST</initialValue>
<currentValue>ST</currentValue>
<org.collectionspace.services.id.NumericIDGeneratorPart>
<maxLength>6</maxLength>
<initialValue>1</initialValue>
- <currentValue>1</currentValue>
+ <currentValue>-1</currentValue>
</org.collectionspace.services.id.NumericIDGeneratorPart>
</parts>
</org.collectionspace.services.id.SettableIDGenerator>');
-- UUID
INSERT INTO `id_generators`
- (id_generator_csid, last_generated_id, id_generator_state)
+ (csid, displayname, description, last_generated_id, id_generator_state)
VALUES
- ('UUID',
+ ('1fa40353-05b8-4ae6-82a6-44a18b4f3c12',
+ 'UUID',
+ 'Generates universally unique identifiers (UUIDs), which may be
+used for CollectionSpace IDs (CSIDs) and other purposes. (These are
+Type 4 UUIDs, whose generation is based on random and pseudo-random parts.)',
'',
'<org.collectionspace.services.id.SettableIDGenerator>
- <csid>UUID</csid>
- <uri></uri>
- <description>Generates universally unique identifiers (UUIDs),
-as used for CollectionSpace IDs (CSIDs). These are Type 4 UUIDs,
-based on random and pseudo-random parts.</description>
<parts>
<org.collectionspace.services.id.UUIDGeneratorPart>
</org.collectionspace.services.id.UUIDGeneratorPart>
*/
public class BaseIDGeneratorTest extends TestCase {
- BaseIDGenerator generator = new BaseIDGenerator(DEFAULT_CSID);
+ BaseIDGenerator generator = new BaseIDGenerator();
IDGeneratorPart part;
final static String CURRENT_YEAR = YearIDGeneratorPart.getCurrentYear();
- final static String DEFAULT_CSID = "1";
// Note: tests may fail with IllegalArgumentException
// if any initialization of new IDParts fails
parts.clear();
parts.add(new AlphabeticIDGeneratorPart("a"));
- gen = new BaseIDGenerator(DEFAULT_CSID, parts);
+ gen = new BaseIDGenerator(parts);
assertEquals("a", gen.getCurrentID());
parts.clear();
parts.add(new NumericIDGeneratorPart("1"));
- gen = new BaseIDGenerator(DEFAULT_CSID, parts);
+ gen = new BaseIDGenerator(parts);
assertEquals("1", gen.getCurrentID());
parts.clear();
parts.add(new StringIDGeneratorPart("PREFIX"));
parts.add(new StringIDGeneratorPart("-"));
parts.add(new StringIDGeneratorPart("SUFFIX"));
- gen = new BaseIDGenerator(DEFAULT_CSID, parts);
+ gen = new BaseIDGenerator(parts);
assertEquals("PREFIX-SUFFIX", gen.getCurrentID());
parts.clear();
parts.add(new YearIDGeneratorPart());
- gen = new BaseIDGenerator(DEFAULT_CSID, parts);
+ gen = new BaseIDGenerator(parts);
assertEquals(CURRENT_YEAR, gen.getCurrentID());
parts.clear();
parts.add(new UUIDGeneratorPart());
- gen = new BaseIDGenerator(DEFAULT_CSID, parts);
+ gen = new BaseIDGenerator(parts);
assertTrue(gen.getCurrentID().length() ==
UUIDGeneratorPart.UUID_LENGTH);
parts.add(new NumericIDGeneratorPart("1"));
parts.add(new StringIDGeneratorPart("-"));
parts.add(new AlphabeticIDGeneratorPart("a"));
- gen = new BaseIDGenerator(DEFAULT_CSID, parts);
+ gen = new BaseIDGenerator(parts);
assertEquals("2009.1-a", gen.getCurrentID());
}
generator.add(new NumericIDGeneratorPart("1"));
assertEquals("(\\d{4})(\\.)(\\d{1,6})", generator.getRegex());
}
-
- // @TODO: Add more tests of boundary conditions, exceptions ...
}
final static String DEFAULT_SERIALIZED_ID_GENERATOR =
"<org.collectionspace.services.id.SettableIDGenerator>\n" +
- " <csid>" + DEFAULT_CSID + "</csid>\n" +
- " <uri></uri>\n" +
- " <description></description>\n" +
" <parts/>\n" +
"</org.collectionspace.services.id.SettableIDGenerator>";
// expected and actual XML in these tests, to avoid failures resulting
// from differences in whitespace, etc.
public void testSerializeIDGenerator() {
- SettableIDGenerator tempGenerator = new SettableIDGenerator(DEFAULT_CSID);
+ SettableIDGenerator tempGenerator = new SettableIDGenerator();
assertEquals(DEFAULT_SERIALIZED_ID_GENERATOR,
IDGeneratorSerializer.serialize(tempGenerator));
}
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
- * Copyright (c)) 2009 Regents of the University of California
+ * 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.
package org.collectionspace.services.id.test;
import java.util.List;
+import java.util.Map;
import org.collectionspace.services.common.repository.BadRequestException;
import org.collectionspace.services.common.repository.DocumentNotFoundException;
IllegalArgumentException, IllegalStateException {
serializedGenerator = jdbc.readIDGenerator(DEFAULT_CSID);
+ Assert.assertTrue(serializedGenerator != null);
+ Assert.assertTrue(! serializedGenerator.equals(""));
generator = IDGeneratorSerializer.deserialize(serializedGenerator);
- Assert.assertEquals(generator.getCsid(), DEFAULT_CSID);
- }
+ }
@Test(dependsOnMethods =
{"hasRequiredDatabaseTable", "createIDGenerator", "readIDGenerator"})
public void readIDGeneratorsList() throws IllegalStateException {
- List generators = jdbc.readIDGeneratorsList();
+ Map<String,String> generators = jdbc.readIDGeneratorsList();
// @TODO Replace this placeholder test, which just
// verifies that no error occurred while retrieving the list,
// with a more meaningful test.
+ Assert.assertTrue(generators != null);
Assert.assertTrue(generators.size() > 0);
}
@Test(dependsOnMethods =
"readIDGeneratorsList"})
public void readIDGeneratorsSummaryList() throws IllegalStateException {
- List generators = jdbc.readIDGeneratorsList();
+ Map<String,String> generators = jdbc.readIDGeneratorsList();
// @TODO Replace this placeholder test, which just
// verifies that no error occurred while retrieving the list,
Assert.assertTrue(generators.size() > 0);
}
+/*
@Test(dependsOnMethods = {"hasRequiredDatabaseTable", "createIDGenerator",
"readIDGenerator"})
public void updateIDGenerator() throws DocumentNotFoundException,
Assert.assertEquals(generator.getDescription(), NEW_DESCRIPTION);
}
+*/
@Test(dependsOnMethods = {"hasRequiredDatabaseTable", "createIDGenerator",
"readIDGenerator", "readIDGeneratorsList",
- "readIDGeneratorsSummaryList", "updateIDGenerator"})
+ "readIDGeneratorsSummaryList"})
public void deleteIDGenerator() throws DocumentNotFoundException {
jdbc.deleteIDGenerator(DEFAULT_CSID);
}
@Test(dependsOnMethods = {"hasRequiredDatabaseTable", "createIDGenerator",
- "readIDGenerator", "updateIDGenerator", "deleteIDGenerator"})
+ "readIDGenerator", "deleteIDGenerator"})
public void createID() throws DocumentNotFoundException,
BadRequestException, IllegalArgumentException,
IllegalStateException {
public String getSpectrumEntryNumberGenerator() {
- generator = new SettableIDGenerator(DEFAULT_CSID);
- generator.setDescription(
- "SPECTRUM entry number generator");
- generator.setURI(
- "urn:collectionspace:idpattern:spectrum-entry-number");
+ generator = new SettableIDGenerator();
generator.add(new StringIDGeneratorPart("E"));
generator.add(new NumericIDGeneratorPart("1"));
public String getChinAccessionNumberGenerator() {
- generator = new SettableIDGenerator(DEFAULT_CSID);
- generator.setDescription(
- "CHIN accession number generator, for items without parts");
- generator.setURI(
- "urn:collectionspace:idpattern:chin-accession-number-no-parts");
+ generator = new SettableIDGenerator();
generator.add(new YearIDGeneratorPart());
generator.add(new StringIDGeneratorPart("."));
generator.add(new NumericIDGeneratorPart("1"));
*/
public class SettableIDGeneratorTest extends TestCase {
- SettableIDGenerator generator = new SettableIDGenerator(DEFAULT_CSID);
+ SettableIDGenerator generator = new SettableIDGenerator();
IDGeneratorPart part;
final static String CURRENT_YEAR = YearIDGeneratorPart.getCurrentYear();
- final static String DEFAULT_CSID = "1";
// Note: tests may fail with IllegalArgumentException
// if any initialization of new IDParts fails