code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; import org.apache.log4j.Logger; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class SwordContentPackageTypes { private static Logger log = Logger.getLogger(SwordContentPackageTypes.class); private static Properties types; static { // static constructor to attempt to load the properties file try { types = new Properties(); InputStream stream = SwordContentPackageTypes.class.getClassLoader().getResourceAsStream("swordContentPackageTypes.properties"); if( stream != null ) { types.loadFromXML(stream); } } catch(Exception ex) { log.error("Unable to load sword types property file: " + ex.getMessage()); } } public SwordContentPackageTypes() { } private static SwordContentPackageTypes instance; public static SwordContentPackageTypes instance() { if( instance == null ) { instance = new SwordContentPackageTypes(); } return instance; } public boolean isValidType(String uri) { return types.containsKey(uri); } public boolean isEmpty() { return types.isEmpty(); } /** * * @return */ public Enumeration elements() { return types.elements(); } public Enumeration keys() { return types.keys(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import org.apache.log4j.Logger; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; /** * Represents a deposit. * * @author Stuart Lewis */ public class Deposit { private static final Logger log = Logger.getLogger(Deposit.class); /** The File deposited */ private File file; /** The content type */ private String contentType; /** The content length */ private int contentLength; /** The username */ private String username; /** The password */ private String password; /** The onBehalfOf value */ private String onBehalfOf; /** The slug string */ private String slug; /** MD5 hash */ private String md5; /** True if verbose should be used */ private boolean verbose; /** True if this is a no-operation command */ private boolean noOp; /** The packaging format */ private String packaging; /** Deposit ID */ private String depositID; /** The IP Address */ private String IPAddress; /** The location */ private String location; /** The content disposition */ private String contentDisposition; /** * Submission created */ public static final int CREATED = HttpServletResponse.SC_CREATED; /** * Submission accepted. */ public static final int ACCEPTED = HttpServletResponse.SC_ACCEPTED; /** * @return the authenticatedUserName */ public String getUsername() { return username; } /** * @param username the authenticated UserName to set */ public void setUsername(String username) { this.username = username; } /** * @return the authenticatedUserPassword */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the contentLength */ public int getContentLength() { return contentLength; } /** * @param contentLength the contentLength to set */ public void setContentLength(int contentLength) { this.contentLength = contentLength; } /** * @return the contentType */ public String getContentType() { return contentType; } /** * @param contentType the contentType to set */ public void setContentType(String contentType) { this.contentType = contentType; } /** * @return the depositID */ public String getDepositID() { return depositID; } /** * @param depositID the depositID to set */ public void setDepositID(String depositID) { this.depositID = depositID; } /** * @return the file */ public File getFile() { return file; } /** * @param file the file to set */ public void setFile(File file) { this.file = file; } /** * @return the packaging */ public String getPackaging() { return packaging; } /** * @param packaging the packaging to set */ public void setPackaging(String packaging) { this.packaging = packaging; } /** * @return the md5 */ public String getMd5() { return md5; } /** * @param md5 the md5 to set */ public void setMd5(String md5) { this.md5 = md5; } /** * @return the noOp */ public boolean isNoOp() { return noOp; } /** * @param noOp the noOp to set */ public void setNoOp(boolean noOp) { this.noOp = noOp; } /** * @return the onBehalfOf */ public String getOnBehalfOf() { return onBehalfOf; } /** * @param onBehalfOf the onBehalfOf to set */ public void setOnBehalfOf(String onBehalfOf) { this.onBehalfOf = onBehalfOf; } /** * @return the slug */ public String getSlug() { return slug; } /** * @param slug the slug to set */ public void setSlug(String slug) { this.slug = slug; } /** * @return the verbose */ public boolean isVerbose() { return verbose; } /** * @param verbose the verbose to set */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Get the IP address of the user * * @return the IP address */ public String getIPAddress() { return IPAddress; } /** * Set the IP address of the user * * @param IPAddress the IP address */ public void setIPAddress(String IPAddress) { this.IPAddress = IPAddress; } /** * Get the location of the deposit * * @return the location of the deposit */ public String getLocation() { return location; } /** * Set the location of the deposit * * @param location the location */ public void setLocation(String location) { this.location = location; } /** * Retrieve the filename that is associated with this deposit. This * is extracted from the content disposition value. * * @return The filename. */ public String getFilename() { String filename = null; // default return value if( contentDisposition != null ) { try { String filePattern = ".*filename=(.*?)((; *.*)|( +)){0,1}"; Pattern p = Pattern.compile(filePattern); Matcher m = p.matcher(contentDisposition); if( m.matches() && m.groupCount() > 2 ) { filename = m.group(1); } } catch( Exception ex ) { log.error("Unable to extract filename", ex); } } return filename; } /** * Set the content disposition that is to be used for this deposit. * This will include the filename, if specified. * * @param disposition The content disposition value. */ public void setContentDisposition(String disposition) { this.contentDisposition = disposition; } /** * Return the content disposition value. * * @return The value. */ public String getContentDisposition() { return this.contentDisposition; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Element; import org.apache.log4j.Logger; import org.purl.sword.base.XmlName; /** * Represents a text construct in the ATOM elements. This is a superclass of * several elements within this implementation. * * @author Neil Taylor */ public abstract class BasicContentElement extends XmlElement implements SwordElementInterface { /** * The log. */ private static Logger log = Logger.getLogger(BasicContentElement.class); public BasicContentElement(String prefix, String name, String namespaceUri) { super(prefix, name, namespaceUri); } public BasicContentElement(XmlName name) { super(name); } /** * Marshal the data in this object to an Element object. * * @return The data expressed in an Element. */ public Element marshall() { Element element = new Element(getQualifiedName(), xmlName.getNamespace()); marshallContent(element); return element; } protected abstract void marshallContent(Element element); /** * Unmarshal the text element into this object. * * This unmarshaller only handles plain text content, although it can * recognise the three different type elements of text, html and xhtml. This * is an area that can be improved in a future implementation, if necessary. * * @param element The text element. * @param validationProperties * * @throws UnmarshallException If the specified element is not of * the correct type, where the localname is used * to specify the valid name. Also thrown * if there is an issue accessing the data. */ public SwordValidationInfo unmarshall(Element element, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf(element, xmlName) ) { return handleIncorrectElement(element, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>(); try { processUnexpectedAttributes(element, attributeItems); int length = element.getChildCount(); if( length > 0 ) { try { unmarshallContent(element); } catch( UnmarshallException ume ) { log.error("Error accessing the content of the " + xmlName.getQualifiedName() + " element"); if( validationProperties == null ) { throw ume; } else { SwordValidationInfo info = new SwordValidationInfo(xmlName, SwordValidationInfo.ERROR_WITH_CONTENT, SwordValidationInfoType.ERROR); info.setContentDescription(element.getValue()); validationItems.add(info); } } } } catch( Exception ex ) { log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); if( validationProperties == null ) { throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); } } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeItems, validationProperties); } return result; } public void unmarshall(Element element) throws UnmarshallException { } @Override public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } /** * * @param existing * @param attributeItems * @return */ protected SwordValidationInfo validate(List<SwordValidationInfo> existing, List<SwordValidationInfo> attributeItems, Properties validationContext) { SwordValidationInfo result = new SwordValidationInfo(xmlName); result.setContentDescription(getContentAsString()); SwordValidationInfo contentResult = validateContent(validationContext); if( contentResult != null ) { result.addValidationInfo(contentResult); } result.addUnmarshallValidationInfo(existing, attributeItems); return result; } protected abstract void unmarshallContent(Element element) throws UnmarshallException; protected abstract SwordValidationInfo validateContent(Properties validationContext); protected abstract String getContentAsString(); }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Attribute; import nu.xom.Element; import org.apache.log4j.Logger; /** * Represents a text construct in the ATOM elements. This is a superclass of * several elements within this implementation. * * @author Neil Taylor */ public class SwordAcceptPackaging extends XmlElement implements SwordElementInterface { /** * The content in the element. */ private String content; /** * The type of the element. */ private QualityValue qualityValue; /** * The log. */ private static Logger log = Logger.getLogger(SwordAcceptPackaging.class); /** */ public static final String ELEMENT_NAME = "acceptPackaging"; protected static final XmlName ATTRIBUTE_Q_NAME = new XmlName(Namespaces.PREFIX_SWORD, "q", Namespaces.NS_SWORD); private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_SWORD, ELEMENT_NAME, Namespaces.NS_SWORD); public SwordAcceptPackaging() { this(null, new QualityValue()); } public SwordAcceptPackaging(String name, float value) { this(name, new QualityValue(value)); } public SwordAcceptPackaging(String name, QualityValue value) { super(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace()); initialise(); setContent(name); setQualityValue(value); } public static XmlName elementName() { return XML_NAME; } protected final void initialise() { qualityValue = null; content = null; } /** * Marshal the data in this object to an Element object. * * @return The data expressed in an Element. */ public Element marshall() { Element element = new Element(getQualifiedName(), xmlName.getNamespace()); if( qualityValue != null ) { Attribute qualityValueAttribute = new Attribute(ATTRIBUTE_Q_NAME.getLocalName(), qualityValue.toString()); element.addAttribute(qualityValueAttribute); } if( content != null ) { element.appendChild(content); } return element; } /** * Unmarshal the text element into this object. * * This unmarshaller only handles plain text content, although it can * recognise the three different type elements of text, html and xhtml. This * is an area that can be improved in a future implementation, if necessary. * * @param acceptPackaging The text element. * @param validationProperties * * @throws UnmarshallException If the specified element is not of * the correct type, where the localname is used * to specify the valid name. Also thrown * if there is an issue accessing the data. */ public SwordValidationInfo unmarshall(Element acceptPackaging, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf(acceptPackaging, xmlName) ) { handleIncorrectElement(acceptPackaging, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>(); try { // get the attributes int attributeCount = acceptPackaging.getAttributeCount(); Attribute attribute = null; float qv = -1; for( int i = 0; i < attributeCount; i++ ) { attribute = acceptPackaging.getAttribute(i); if( ATTRIBUTE_Q_NAME.getLocalName().equals(attribute.getQualifiedName())) { try { qv = Float.parseFloat(attribute.getValue()); qualityValue = new QualityValue(qv); SwordValidationInfo attr = new SwordValidationInfo(xmlName, ATTRIBUTE_Q_NAME); attr.setContentDescription("" + qv); attributeItems.add(attr); } catch(NumberFormatException nfe ) { SwordValidationInfo attr = new SwordValidationInfo(xmlName, ATTRIBUTE_Q_NAME, nfe.getMessage(), SwordValidationInfoType.ERROR); attr.setContentDescription(attribute.getValue()); attributeItems.add(attr); } } else { SwordValidationInfo attr = new SwordValidationInfo(xmlName, new XmlName(attribute), SwordValidationInfo.UNKNOWN_ATTRIBUTE, SwordValidationInfoType.INFO ); attr.setContentDescription(attribute.getValue()); attributeItems.add(attr); } } int length = acceptPackaging.getChildCount(); if( length > 0 ) { try { content = unmarshallString(acceptPackaging); } catch( UnmarshallException ume ) { log.error("Error accessing the content of the acceptPackaging element"); validationItems.add(new SwordValidationInfo(xmlName, "Error unmarshalling element: " + ume.getMessage(), SwordValidationInfoType.ERROR)); } } } catch( Exception ex ) { log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeItems, validationProperties); } return result; } public void unmarshall(Element element) throws UnmarshallException { unmarshall(element, null); } @Override public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } /** * * @param existing * @param attributeItems * @return */ protected SwordValidationInfo validate(List<SwordValidationInfo> existing, List<SwordValidationInfo> attributeItems, Properties validationContext) { SwordValidationInfo result = new SwordValidationInfo(xmlName); result.setContentDescription(content); // item specific rules if( content == null ) { result.addValidationInfo( new SwordValidationInfo(xmlName, SwordValidationInfo.MISSING_CONTENT, SwordValidationInfoType.WARNING)); } else { // check that the content is one of the Sword types if( ! SwordContentPackageTypes.instance().isValidType(content) ) { result.addValidationInfo(new SwordValidationInfo(xmlName, "The URI is not one of the types specified in http://purl.org/NET/sword-types", SwordValidationInfoType.WARNING)); } } result.addUnmarshallValidationInfo(existing, attributeItems); return result; } /** * Get the content in this TextConstruct. * * @return The content, expressed as a string. */ public final String getContent() { return content; } /** * Set the content. This only supports text content. * * @param content The content. */ public final void setContent(String content) { this.content = content; } /** * Get the type. * * @return The type. */ public final QualityValue getQualityValue() { return qualityValue; } /** * Set the type. * * @param value The type. */ public final void setQualityValue(QualityValue value) { this.qualityValue = value; } /** * Get a string representation. * * @return The string. */ @Override public String toString() { return "Summary - content: " + getContent() + " value: " + getQualityValue(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; import nu.xom.Builder; import nu.xom.Document; import nu.xom.Element; import nu.xom.ParsingException; import nu.xom.Serializer; /** * Represents a deposit response. This holds the SWORD Entry element. * * @author Stuart Lewis * @author Neil Taylor * */ public class DepositResponse { /** The entry returned in the response */ private SWORDEntry entry; /** The HTTP Response code */ private int httpResponse; /** The value to set in the Location header (typically the atom edit link) */ private String location; /** Logger */ private static Logger log = Logger.getLogger(DepositResponse.class); /** * Create a new response with the specified http code. * * @param httpResponse Response code. */ public DepositResponse( int httpResponse ) { entry = new SWORDEntry(); this.httpResponse = httpResponse; location = null; } /** * Set the entry element for this response. * * @param entry The SWORD Entry. */ public void setEntry( SWORDEntry entry ) { this.entry = entry; } /** * Get the SWORD Entry * * @return The entry */ public SWORDEntry getEntry( ) { return entry; } /** * Get the SWORD Entry as an error document * * @return The error document * @throws SWORDException If this DespositResponse does not contain a * SWORDErrorDocumentTest. If this is thrown, then * the document stores an Entry. */ public SWORDErrorDocument getErrorDocument( ) throws SWORDException { if( entry instanceof SWORDErrorDocument) { return (SWORDErrorDocument)entry; } throw new SWORDException("Requested document is not an Error Document."); } /** * Retrieve the HTTP Response code. * * @return The response code. */ public int getHttpResponse() { return httpResponse; } /** * Set the HTTP Response code. * * @param httpResponse The code. */ public void setHttpResponse(int httpResponse) { this.httpResponse = httpResponse; } /** * Retrieve the Location header. * * @return The Location header */ public String getLocation() { return location; } /** * Set the HTTP Location header. * * @param location The Location header. */ public void setLocation(String location) { this.location = location; } /** * Marshall the data in the enclosed SWORD Entry. * * @return The string representation. Null if there was an error. */ public String marshall( ) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Serializer serializer = new Serializer(stream, "UTF-8"); serializer.setIndent(3); if( entry != null ) { Document doc = new Document(entry.marshall()); serializer.write(doc); log.info(stream.toString()); return stream.toString(); } } catch (IOException ex) { log.error(ex.getMessage()); } return null; // default return value. } /** * Unmarshall the specified XML data into a SWORD Entry. * * @param xml The XML data as a string. * @throws UnmarshallException If there was an error unmarshalling the data. */ public void unmarshall(String xml) throws UnmarshallException { unmarshall(xml, null); } public SwordValidationInfo unmarshall(String xml, Properties validationContext) throws UnmarshallException { try { Builder builder = new Builder(); Document doc = builder.build(xml, Namespaces.NS_ATOM); Element root = doc.getRootElement(); entry = new SWORDEntry( ); return entry.unmarshall(root, validationContext); } catch( ParsingException ex ) { throw new UnmarshallException("Unable to parse the XML", ex ); } catch( IOException ex ) { throw new UnmarshallException("Error acessing the file?", ex); } } public void unmarshallErrorDocument(String xml) throws UnmarshallException { unmarshallErrorDocument(xml, null); } /** * Unmarshall the specified XML data into a SWORD error document. * * @param xml The XML data as a string. * @throws UnmarshallException If there was an error unmarshalling the data. */ public SwordValidationInfo unmarshallErrorDocument(String xml, Properties validationContext ) throws UnmarshallException { try { Builder builder = new Builder(); Document doc = builder.build(xml, Namespaces.NS_SWORD); Element root = doc.getRootElement(); SWORDErrorDocument sed = new SWORDErrorDocument(); SwordValidationInfo info = sed.unmarshall(root, validationContext); entry = sed; return info; } catch( ParsingException ex ) { throw new UnmarshallException("Unable to parse the XML", ex ); } catch( IOException ex ) { throw new UnmarshallException("Error acessing the file?", ex); } } /** * Retrieve a string representation of this data. This is equivalent to * calling unmarshall(). * * @return The marshalled data. */ public String toString() { return marshall(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * Represents a generic SWORD exception. If this thrown by a repository, * it would result in a SWORD Error Document being thrown. * * @author Stuart Lewis */ public class SWORDErrorException extends Exception { /** The error URI (defined in ErrorCodes class) */ private String errorURI; /** The HTTP error code (defined in HTTPServletResponse class) */ private int status; /** The error message given by the repository */ private String description; /** * Create a new instance and store the specified data. * * @param errorURI The errorURI of the exception being thrown * @param description A description of the error thrown. */ public SWORDErrorException(String errorURI, String description) { super(description); this.errorURI = errorURI; this.description = description; if (errorURI.equals(ErrorCodes.ERROR_BAD_REQUEST)) { status = 400; } else if (errorURI.equals(ErrorCodes.ERROR_CHECKSUM_MISMATCH)) { status = 412; } else if (errorURI.equals(ErrorCodes.ERROR_CONTENT)) { status = 415; } else if (errorURI.equals(ErrorCodes.MAX_UPLOAD_SIZE_EXCEEDED)) { status = 413; } else if (errorURI.equals(ErrorCodes.MEDIATION_NOT_ALLOWED)) { status = 412; } else if (errorURI.equals(ErrorCodes.TARGET_OWNER_UKNOWN)) { status = 401; } else { status = 400; } } /** * @return the errorURI */ public String getErrorURI() { return errorURI; } /** * @return the status */ public int getStatus() { return status; } /** * Set the status * * @param status The HTTP status code */ public void setStatus(int status) { this.status = status; } /** * @return the description */ public String getDescription() { return description; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class SwordCollectionPolicy extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_SWORD, "collectionPolicy", Namespaces.NS_SWORD); public SwordCollectionPolicy() { super(XML_NAME); } public SwordCollectionPolicy(String version) { this(); setContent(version); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class SwordVersion extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_SWORD, "version", Namespaces.NS_SWORD); public SwordVersion() { super(XML_NAME); } public SwordVersion(String version) { this(); setContent(version); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * Represents a ServiceDocumentRequest. * * @author Stuart Lewis * */ public class ServiceDocumentRequest { /** The username */ private String username; /** The password */ private String password; /** The onBehalf of name */ private String onBehalfOf; /** The IP Address */ private String IPAddress; /** The location */ private String location; /** * Retrieve the username. * * @return the authenticatedUserName */ public String getUsername() { return username; } /** * Set the username. * * @param username the authenticated UserName to set */ public void setUsername(String username) { this.username = username; } /** * Get the password. * * @return the authenticatedUserPassword */ public String getPassword() { return password; } /** * Set the password. * * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * Get the onBehalfOf name. * * @return the onBehalfOf */ public String getOnBehalfOf() { return onBehalfOf; } /** * Set the onBehalfOf name. * * @param onBehalfOf the onBehalfOf to set */ public void setOnBehalfOf(String onBehalfOf) { this.onBehalfOf = onBehalfOf; } /** * Get the IP address of the user * * @return the the IP address */ public String getIPAddress() { return IPAddress; } /** * Set the IP address of the user * * @param IPAddress the IP address */ public void setIPAddress(String IPAddress) { this.IPAddress = IPAddress; } /** * Get the location of the service document * * @return the location of the service document */ public String getLocation() { return location; } /** * Set the location of the service document * * @param location the location */ public void setLocation(String location) { this.location = location; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import nu.xom.Attribute; import nu.xom.Element; import nu.xom.Elements; import org.apache.log4j.Logger; import org.purl.sword.atom.ContentType; import org.purl.sword.atom.Title; import org.purl.sword.atom.Accept; /** * A representation of a SWORD Collection. * * @author Stuart Lewis * @author Neil Taylor */ public class Collection extends XmlElement implements SwordElementInterface { /** * Collection location, expressed as a URL. */ private String location; /** * Holds the ATOM Title for the collection. */ private Title title; /** * List of the APP:Accept elements. */ private List<Accept> accepts; /** * Holds the SWORD Collection policy. */ //private String collectionPolicy; /** * The SWORD mediation value. Indicates if mediation is allowed. */ //private boolean mediation; private SwordMediation swordMediation; private SwordService swordService; private DcAbstract dcTermsAbstract; private SwordTreatment swordTreatment; private SwordCollectionPolicy swordCollectionPolicy; /** * The SWORD acceptsPackaging details. */ private List<SwordAcceptPackaging> acceptPackaging; /** * The logger. */ private static Logger log = Logger.getLogger(Collection.class); /** * Label for the Href attribute. */ public static final String ATTRIBUTE_HREF = "href"; /** * Label for the local part of this element. */ @Deprecated public static final String ELEMENT_NAME = "collection"; private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_APP, "collection", Namespaces.NS_APP); /** * Create a new instance. */ public Collection() { super(XML_NAME); initialise(); } public static XmlName elementName() { return XML_NAME; } protected final void initialise() { location = null; title = null; accepts = new ArrayList<Accept>(); acceptPackaging = new ArrayList<SwordAcceptPackaging>(); swordCollectionPolicy = null; swordMediation = null; swordService = null; dcTermsAbstract = null; swordTreatment = null; } /** * Create a new instance and set the initial location for the collection. * * @param location The initial location, expressed as a URL. */ public Collection(String location) { this(); this.location = location; } /** * Retrieve an array that holds all of the Accept details. * * @return An array of strings. Each string represents an * individual accept element. The array will have a length * of 0 if no accepts elements are stored in this collection. */ public String[] getAccepts() { String[] values = new String[this.accepts.size()]; Iterator<Accept> iterator = accepts.iterator(); for(int i = 0; iterator.hasNext(); i++ ) { Accept accept = iterator.next(); values[i] = accept.getContent(); } return values; } /** * Retrieve an array that holds all of the Accept details. * * @return An array of strings. Each string represents an * individual accept element. The array will have a length * of 0 if no accepts elements are stored in this collection. */ @Deprecated public List<String> getAcceptsList() { ArrayList<String> items = new ArrayList<String>(); for(Accept item : accepts ) { items.add(item.getContent()); } return items; } /** * * @return */ public List<Accept> getAcceptList() { return accepts; } /** * Add an accepts entry. * * @param accepts The accepts value. */ public void addAccepts(String accepts) { this.accepts.add(new Accept(accepts)); } /** * Remove all of the accepts associated with this Collection. */ public void clearAccepts( ) { this.accepts.clear(); } /** * Retrieve a hashtable that holds all the acceptsPackaging details. * * @return A hashtable. The keys are accepted packaging formats, * and the values the quality values (stored as QualityValue objects) */ public List<SwordAcceptPackaging> getAcceptPackaging() { return acceptPackaging; } /** * Add an acceptPackaging format. * * @param acceptPackaging the packaging format. * @param qualityValue the quality value of accepted packaging format. */ public void addAcceptPackaging(String acceptPackaging, float qualityValue) { this.acceptPackaging.add(new SwordAcceptPackaging(acceptPackaging, qualityValue)); } /** * Add an acceptPackaging format. A default quality vale is given. * * @param acceptPackaging the packaging format. */ public void addAcceptPackaging(String acceptPackaging) { this.acceptPackaging.add(new SwordAcceptPackaging(acceptPackaging, new QualityValue())); } /** * Remove all of the accepted packaging formats associated with this Collection. */ public void clearAcceptPackaging( ) { this.acceptPackaging.clear(); } /** * Get the collection policy. * * @return The SWORD collectionPolicy. */ public String getCollectionPolicy() { if( swordCollectionPolicy == null ) { return null; } return swordCollectionPolicy.getContent(); } /** * Set the collection policy. * * @param collectionPolicy The collection policy. */ public void setCollectionPolicy(String collectionPolicy) { swordCollectionPolicy = new SwordCollectionPolicy(collectionPolicy); } /** * Get the location. * * @return TShe location */ public String getLocation() { return location; } /** * Set the location. * * @param location The location. */ public void setLocation(String location) { this.location = location; } /** * Get the mediation value. * * @return The mediation */ public boolean getMediation() { if( swordMediation == null ) { return false; } return swordMediation.getContent(); } public boolean isMediationSet() { if( swordMediation == null ) { return false; } return swordMediation.isSet(); } /** * Set the mediation value. * * @param mediation The mediation value. */ public void setMediation(boolean mediation) { swordMediation = new SwordMediation(mediation); } /** * Get the DC Term abstract. * * @return The abstract. */ public String getAbstract() { if( dcTermsAbstract == null ) { return null; } return dcTermsAbstract.getContent(); } /** * Set the abstract. * * @param abstractString The abstract. */ public void setAbstract(String abstractString) { dcTermsAbstract = new DcAbstract(abstractString); } /** * Get the sword service. * * @return The service. */ public String getService() { if( swordService == null ) { return null; } return swordService.getContent(); } /** * Set the sword service. * * @param serviceString The service. */ public void setService(String serviceString) { swordService = new SwordService(serviceString); } /** * Set the title. This will set the title type to ContentType.TEXT. * * @param title The title. */ public void setTitle( String title ) { if( this.title == null) { this.title = new Title(); } this.title.setContent(title); this.title.setType(ContentType.TEXT); } /** * Get the title. * * @return The title, or <code>null</code> if no title has been set. */ public String getTitle( ) { if( title == null ) { return null; } return title.getContent(); } /** * Get the treatment value. * * @return The treatment. */ public String getTreatment() { if( swordTreatment == null ) { return null; } return swordTreatment.getContent(); } /** * Set the treatment. * * @param treatment The treatment. */ public void setTreatment(String treatment) { swordTreatment = new SwordTreatment(treatment); } /** * Get a string representation of this object. This is * equivalent to calling marshall().toString(). */ @Override public String toString() { Element element = marshall(); return element.toString(); } /** * Marshall the data in this object to an Element object. * * @return A XOM Element that holds the data for this Content element. */ public Element marshall( ) { // convert data into XOM elements and return the 'root', i.e. the one // that represents the collection. Element collection = new Element(getQualifiedName(), Namespaces.NS_APP); Attribute href = new Attribute(ATTRIBUTE_HREF, location); collection.addAttribute(href); if (title == null) { title = new Title(); title.setContent("Untitled"); } collection.appendChild(title.marshall()); for (Accept item:accepts) { collection.appendChild(item.marshall()); } Iterator<SwordAcceptPackaging> apIterator = acceptPackaging.iterator(); while( apIterator.hasNext() ) { collection.appendChild(apIterator.next().marshall()); } if (swordCollectionPolicy != null) { collection.appendChild(swordCollectionPolicy.marshall()); } if (dcTermsAbstract != null) { collection.appendChild(dcTermsAbstract.marshall()); } if (swordService != null) { collection.appendChild(swordService.marshall()); } if (swordMediation != null ) { collection.appendChild(swordMediation.marshall()); } if (swordTreatment != null) { collection.appendChild(swordTreatment.marshall()); } return collection; } /** * Unmarshall the content element into the data in this object. * * @throws UnmarshallException If the element does not contain a * content element or if there are problems * accessing the data. */ public void unmarshall(Element collection) throws UnmarshallException { unmarshall(collection, null); } public SwordValidationInfo unmarshall(Element collection, Properties validationProperties) throws UnmarshallException { if (!isInstanceOf(collection, xmlName)) { return handleIncorrectElement(collection, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeValidationItems = new ArrayList<SwordValidationInfo>(); try { initialise(); // retrieve the attributes int count = collection.getAttributeCount(); Attribute a = null; for( int i = 0; i < count; i++ ) { a = collection.getAttribute(i); if (ATTRIBUTE_HREF.equals(a.getQualifiedName())) { location = a.getValue(); SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(a)); info.setContentDescription(location); attributeValidationItems.add(info); } else { SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(a), SwordValidationInfo.UNKNOWN_ATTRIBUTE, SwordValidationInfoType.INFO ); info.setContentDescription(a.getValue()); attributeValidationItems.add(info); } } // retrieve all of the sub-elements Elements elements = collection.getChildElements(); Element element = null; int length = elements.size(); for (int i = 0; i < length; i++) { element = elements.get(i); if (isInstanceOf(element, Title.elementName())) { if( title == null ) { title = new Title(); validationItems.add(title.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo( Title.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } else if (isInstanceOf(element, Accept.elementName()) ) { Accept accept = new Accept(); SwordValidationInfo info = accept.unmarshall(element, validationProperties); accepts.add(accept); validationItems.add(info); } else if (isInstanceOf(element, SwordAcceptPackaging.elementName())) { SwordAcceptPackaging packaging = new SwordAcceptPackaging(); validationItems.add(packaging.unmarshall(element, validationProperties)); acceptPackaging.add(packaging); } else if (isInstanceOf(element, SwordCollectionPolicy.elementName())) { if (swordCollectionPolicy == null) { swordCollectionPolicy = new SwordCollectionPolicy(); validationItems.add(swordCollectionPolicy.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo( SwordCollectionPolicy.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } else if (isInstanceOf(element, DcAbstract.elementName())) { if( dcTermsAbstract == null ) { dcTermsAbstract = new DcAbstract(); validationItems.add(dcTermsAbstract.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(DcAbstract.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } else if (isInstanceOf(element, SwordService.elementName())) { if( swordService == null ) { swordService = new SwordService(); validationItems.add(swordService.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordService.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } else if (isInstanceOf(element, SwordMediation.elementName())) { if( swordMediation == null ) { swordMediation = new SwordMediation(); validationItems.add(swordMediation.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordMediation.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); validationItems.add(info); } } else if (isInstanceOf(element, SwordTreatment.elementName())) { if( swordTreatment == null ) { swordTreatment = new SwordTreatment(); validationItems.add(swordTreatment.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordTreatment.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); validationItems.add(info); } } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), SwordValidationInfo.UNKNOWN_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } } catch (Exception ex) { log.error("Unable to parse an element in collection: " + ex.getMessage()); throw new UnmarshallException("Unable to parse an element in Collection", ex); } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeValidationItems, validationProperties); } return result; } /** * * @return */ @Override public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } /** * * @param existing * @return */ protected SwordValidationInfo validate(List<SwordValidationInfo> existing, List<SwordValidationInfo> attributes, Properties validationContext) { boolean validateAll = (existing == null); SwordValidationInfo result = new SwordValidationInfo(xmlName); if( accepts == null || accepts.size() == 0 ) { result.addValidationInfo(new SwordValidationInfo(Accept.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR, SwordValidationInfoType.WARNING )); } if( location == null ) { XmlName attribute = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_HREF, Namespaces.NS_ATOM); result.addAttributeValidationInfo(new SwordValidationInfo(xmlName, attribute, SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, SwordValidationInfoType.WARNING )); } if( swordMediation == null ) { result.addValidationInfo(new SwordValidationInfo(SwordMediation.elementName(), SwordValidationInfo.MISSING_ELEMENT_WARNING, SwordValidationInfoType.WARNING)); } if( validateAll ) { if( accepts.size() > 0 ) { Iterator<Accept> acceptIterator = accepts.iterator(); while( acceptIterator.hasNext() ) { result.addValidationInfo(acceptIterator.next().validate(validationContext)); } } if( acceptPackaging.size() > 0 ) { Iterator<SwordAcceptPackaging> apIterator = acceptPackaging.iterator(); while( apIterator.hasNext() ) { result.addValidationInfo(apIterator.next().validate(validationContext)); } } if( location != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF, location)); } if( title != null ) { result.addValidationInfo(title.validate(validationContext)); } if( swordMediation != null ) { result.addValidationInfo(swordMediation.validate(validationContext)); } if( swordService != null ) { result.addValidationInfo(swordService.validate(validationContext)); } if( swordTreatment != null ) { result.addValidationInfo(swordTreatment.validate(validationContext)); } if( swordCollectionPolicy != null ) { result.addValidationInfo(swordCollectionPolicy.validate(validationContext)); } if( dcTermsAbstract != null ) { result.addValidationInfo(dcTermsAbstract.validate(validationContext)); } } result.addUnmarshallValidationInfo(existing, attributes); return result; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import javax.servlet.http.HttpServletResponse; /** * Definition of the additional HTTP Header tags that will be used in * the SWORD protocol. * * @author Neil Taylor * @author Stuart Lewis * */ public interface HttpHeaders { /** * The HTTP Header label that specifies the MD5 label. */ public static final String CONTENT_MD5 = "Content-MD5"; /** * The HTTP Header label that specifies the MD5 label. */ public static final String CONTENT_LENGTH = "Content-Length"; /** * The HTTP Header label that specifies the On Behalf Of information. */ public static final String X_ON_BEHALF_OF = "X-On-Behalf-Of"; /** * The HTTP Header label that specifies the Packaging information. */ public static final String X_PACKAGING = "X-Packaging"; /** * The HTTP Header label that specifies the desired Verbose status. */ public static final String X_VERBOSE = "X-Verbose"; /** * The HTTP Header label that specifies the desired NoOp status. */ public static final String X_NO_OP = "X-No-Op"; /** * An HTTP Header label that the server should not epect, and thus * created a corrupt header. */ public static final String X_CORRUPT = "X-wibble"; /** * The HTTP Header that specifies the error code information. */ public static final String X_ERROR_CODE = "X-Error-Code"; /** * The user agent. */ public static final String USER_AGENT = "User-Agent"; /** * The Slug header. */ public static final String SLUG = "Slug"; /** * Submission created */ public static final int CREATED = HttpServletResponse.SC_CREATED; /** * Submission accepted. */ public static final int ACCEPTED = HttpServletResponse.SC_ACCEPTED; /** * The HTTP Header that specifies the content disposition item. This is * used by the SWORD profile to identify the name for the deposit. */ public static final String CONTENT_DISPOSITION = "Content-Disposition"; }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.purl.sword.base; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class SwordMaxUploadSize extends BasicIntegerContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_SWORD, "maxUploadSize", Namespaces.NS_SWORD); public SwordMaxUploadSize() { super(XML_NAME); } public SwordMaxUploadSize(int value) { this(); setContent(value); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class SwordPackaging extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_SWORD, "packaging", Namespaces.NS_SWORD); public SwordPackaging() { super(XML_NAME); } public SwordPackaging(String version) { this(); setContent(version); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Represents an validation information item about * the elements/attributes. * * @author Neil Taylor (nst@aber.ac.uk) */ public class SwordValidationInfo { /** * Name of the element. */ private XmlName elementName; /** * Name of the attribute for the specified element. This will * only be used when the information relates to an attribute. */ private XmlName attributeName; /** * Optional description of the content of the element or attribute. */ private String contentDescription; /** The information message. This holds the actual error/warning message */ private String message; /** The type of validation information */ private SwordValidationInfoType type; /** List of nested validation info items */ private List<SwordValidationInfo> elementInfo; private List<SwordValidationInfo> attributeInfo; /** * List of validation info notes that were generated during * an unmarshal stage. */ private List<SwordValidationInfo> unmarshallElementInfo; /** * List of validation info notes that were generated during an * unmarshal stage. */ private List<SwordValidationInfo> unmarshallAttributeInfo; public static final String UNKNOWN_ELEMENT = "This element is present, but it is not used as part of the SWORD profile"; public static final String UNKNOWN_ATTRIBUTE = "This attribute is present, but it is not used as part of the SWORD profile"; public static final String MISSING_ELEMENT_WARNING = "This element is not present, but it SHOULD be included."; public static final String MISSING_ATTRIBUTE_WARNING = "This attribute is not present, but it SHOULD be included."; public static final String DUPLICATE_ELEMENT = "This element has already been included earlier in this document. This element is ignored."; public static final String MISSING_CONTENT = "No content is defined. This element should have content."; public static final String MISSING_ELEMENT_ERROR = "This element is not present, but at least one MUST be included."; public static final String ERROR_WITH_CONTENT = "There is an error with the value."; /** * Create a new information object for the specified element. Sets the * default type to be VALID. * * @param element The element. */ public SwordValidationInfo(XmlName element) { this(element, null, "", SwordValidationInfoType.VALID); } /** * Create a new information object for the specified element's * attribute. Sets the default type to be VALID. * * @param element the element. * @param attribute the attribute. */ public SwordValidationInfo(XmlName element, XmlName attribute) { this(element, attribute, "", SwordValidationInfoType.VALID); } /** * Create a new instance of a validation information object that * reports on an element. * * @param element The element. * @param theMessage The information message. * @param theType The type of message. */ public SwordValidationInfo(XmlName element, String theMessage, SwordValidationInfoType theType) { this(element, null, theMessage, theType); } /** * Create a new instance of a validation information object that * reports on an attribute in the specified element. * * @param element The local name for the element. * @param attribute The attribute. * @param theMessage The information message. * @param theType The type of message. */ public SwordValidationInfo(XmlName element, XmlName attribute, String theMessage, SwordValidationInfoType theType) { this.elementName = element; this.attributeName = attribute; message = theMessage; type = theType; elementInfo = new ArrayList<SwordValidationInfo>(); attributeInfo = new ArrayList<SwordValidationInfo>(); unmarshallElementInfo = new ArrayList<SwordValidationInfo>(); unmarshallAttributeInfo = new ArrayList<SwordValidationInfo>(); } /** * Return the information message. * * @return the message */ public String getMessage() { return message; } /** * Set the information message. * * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * Return the type of information. * * @return the type */ public SwordValidationInfoType getType() { return type; } /** * Set the type of information * * @param type the type to set */ public void setType(SwordValidationInfoType type) { this.type = type; } /** * Return the element that this information describes. * * @return the element */ public XmlName getElement() { return elementName; } /** * Set the element that this information describes. * * @param element the element to set */ public void setElement(XmlName element) { this.elementName = element; } /** * Return the attribute that this information describes. * * @return the attribute */ public XmlName getAttribute() { return attributeName; } /** * Set the attribute that this information describes. * * @param attribute the attribute to set */ public void setAttribute(XmlName attribute) { this.attributeName = attribute; } /** * Add a related information item to this resource. * * @param item The information item to store. */ public void addValidationInfo(SwordValidationInfo item) { if( type.compareTo(item.getType()) < 0 ) { type = item.getType(); } elementInfo.add(item); } public void addAttributeValidationInfo(SwordValidationInfo attribute) { if( type.compareTo(attribute.getType()) < 0 ) { type = attribute.getType(); } attributeInfo.add(attribute); } public void addUnmarshallElementInfo(SwordValidationInfo unmarshallElement) { if( unmarshallElement == null ) { // not part of the validation process - end here return; } if( type.compareTo(unmarshallElement.getType()) < 0 ) { type = unmarshallElement.getType(); } unmarshallElementInfo.add(unmarshallElement); } public void addUnmarshallAttributeInfo(SwordValidationInfo unmarshallAttribute) { if( type.compareTo(unmarshallAttribute.getType()) < 0 ) { type = unmarshallAttribute.getType(); } unmarshallAttributeInfo.add(unmarshallAttribute); } /** * Clear the list of validation info items. */ public void clearValidationItems() { elementInfo.clear(); attributeInfo.clear(); resetType(); } /** * Clear the list of unmarshalled info items. */ public void clearUnmarshallItems() { unmarshallElementInfo.clear(); unmarshallAttributeInfo.clear(); resetType(); } protected void resetType() { type = SwordValidationInfoType.VALID; resetType(getValidationElementInfoIterator()); resetType(getValidationAttributeInfoIterator()); resetType(getUnmarshallElementInfoIterator()); resetType(getUnmarshallAttributeInfoIterator()); } protected void resetType(Iterator<SwordValidationInfo> iterator) { SwordValidationInfo item = null; while( iterator.hasNext() ) { item = iterator.next(); if( item != null && type.compareTo(item.getType()) < 0 ) { type = item.getType(); } } } /** * Return an iterator to view the nested validation info objects. * * @return Iterator for the nested objects. */ public Iterator<SwordValidationInfo> getValidationElementInfoIterator() { return elementInfo.iterator(); } /** * * @return */ public Iterator<SwordValidationInfo> getValidationAttributeInfoIterator() { return attributeInfo.iterator(); } /** * * @return */ public Iterator<SwordValidationInfo> getUnmarshallElementInfoIterator() { return unmarshallElementInfo.iterator(); } /** * * @return */ public Iterator<SwordValidationInfo> getUnmarshallAttributeInfoIterator() { return unmarshallAttributeInfo.iterator(); } /** * @return the contentDescription */ public String getContentDescription() { return contentDescription; } /** * @param contentDescription the contentDescription to set */ public void setContentDescription(String contentDescription) { this.contentDescription = contentDescription; } /** * * @param elementItems * @param attributeItems */ public void addUnmarshallValidationInfo( List<SwordValidationInfo> elementItems, List<SwordValidationInfo> attributeItems) { if( elementItems != null ) { Iterator<SwordValidationInfo> items = elementItems.iterator(); while( items.hasNext() ) { addUnmarshallElementInfo(items.next()); } } if( attributeItems != null ) { Iterator<SwordValidationInfo> attributes = attributeItems.iterator(); while( attributes.hasNext() ) { addUnmarshallAttributeInfo(attributes.next()); } } } public void addUnmarshallValidationInfo(SwordValidationInfo other) { addUnmarshallValidationInfo(other.elementInfo, other.attributeInfo); } @Override public String toString() { return "" + getType(); } /** * Utility method that will recursively print out the list of items * for the specified validation info object. * * @param info The validation info object to display. * @param indent The level of indent, expressed as a number of space characters. */ public void createString(SwordValidationInfo info, StringBuffer buffer, String indent) { String prefix = info.getElement().getPrefix(); buffer.append(indent); buffer.append("["); buffer.append(info.getType()); buffer.append("]"); if( prefix != null && prefix.trim().length() > 0 ) { buffer.append(prefix); buffer.append(":"); } buffer.append(info.getElement().getLocalName()); buffer.append(" "); if (info.getAttribute() != null) { buffer.append(info.getAttribute().getLocalName()); buffer.append("=\""); if( info.getContentDescription() != null ) { buffer.append(info.getContentDescription()); } buffer.append("\""); } else { if( info.getContentDescription() != null ) { buffer.append(" Value: '"); buffer.append(info.getContentDescription()); buffer.append("'"); } } buffer.append("\n" + indent + "message: " ); buffer.append(info.getMessage()); buffer.append("\n"); // process the list of attributes first Iterator<SwordValidationInfo> iterator = info.getValidationAttributeInfoIterator(); while( iterator.hasNext()) { createString(iterator.next(), buffer, " " + indent); } iterator = info.getUnmarshallAttributeInfoIterator(); while( iterator.hasNext()) { createString(iterator.next(), buffer, " " + indent); } // next, process the element messages iterator = info.getValidationElementInfoIterator(); while( iterator.hasNext()) { createString(iterator.next(), buffer, " " + indent); } iterator = info.getUnmarshallElementInfoIterator(); while( iterator.hasNext()) { createString(iterator.next(), buffer, " " + indent); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.log4j.Logger; /** * Utility class that holds Checksum related methods. * * @author Neil Taylor, Stuart Lewis */ public class ChecksumUtils { /** Logger */ private static Logger log = Logger.getLogger(ChecksumUtils.class); /** * Generate an MD5 hash for the file that is specified in the * filepath. The hash is returned as a String representation. * * @param filepath The path to the file to load. * @return A string hash of the file. * @throws NoSuchAlgorithmException If the MD5 algorithm is * not supported by the installed virtual machine. * * @throws IOException If there is an error accessing the file. */ public static String generateMD5(String filepath) throws NoSuchAlgorithmException, IOException { return generateMD5(new FileInputStream(filepath)); } /** * Generate an MD5 hash for the file that is specified in the * filepath. The hash is returned as a String representation. * * @param md5Stream The InputStream to checksum. * @return A string hash of the file. * @throws NoSuchAlgorithmException If the MD5 algorithm is * not supported by the installed virtual machine. * * @throws IOException If there is an error accessing the file. */ public static String generateMD5(InputStream md5Stream) throws NoSuchAlgorithmException, IOException { String md5 = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); byte[] bytes = new byte[1024]; int count = 0; while( (count = md5Stream.read(bytes)) != -1 ) { md.update(bytes, 0, count); } byte[] md5Digest = md.digest(); StringBuffer buffer = new StringBuffer(); for( byte b : md5Digest ) { // 0xFF is used to handle the issue of negative numbers in the bytes String hex = Integer.toHexString(b & 0xFF); if( hex.length() == 1 ) { buffer.append("0"); } buffer.append(hex); } md5 = buffer.toString(); } catch(NoSuchAlgorithmException ex ) { log.error("MD5 Algorithm Not found"); throw ex; } finally { if( md5Stream != null ) { md5Stream.close(); } } return md5; } /** * Generate an MD5 hash for the file that is specified in the * filepath. The hash is returned as a String representation. * * @param bytes The byte array to checksum. * @return A string hash of the file. * @throws NoSuchAlgorithmException If the MD5 algorithm is * not supported by the installed virtual machine. * * @throws IOException If there is an error accessing the file. */ public static String generateMD5(byte[] bytes) throws NoSuchAlgorithmException, IOException { String md5 = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(bytes); byte[] md5Digest = md.digest(); StringBuffer buffer = new StringBuffer(); for( byte b : md5Digest ) { // 0xFF is used to handle the issue of negative numbers in the bytes String hex = Integer.toHexString(b & 0xFF); if( hex.length() == 1 ) { buffer.append("0"); } buffer.append(hex); } md5 = buffer.toString(); } catch(NoSuchAlgorithmException ex ) { log.error("MD5 Algorithm Not found"); throw ex; // rethrow } return md5; } /** * Run a simple test to process the file. * * @param args The command line arguments. * @throws NoSuchAlgorithmException If there was an error generating the MD5. * @throws IOException If there is an error accessing the file. */ public static void main(String[] args) throws NoSuchAlgorithmException, IOException { System.out.println(ChecksumUtils.generateMD5(args[0])); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class DcAbstract extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_DC_TERMS, "abstract", Namespaces.NS_DC_TERMS); public DcAbstract() { super(XML_NAME); } public DcAbstract(String version) { this(); setContent(version); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import java.util.Properties; import nu.xom.Element; import nu.xom.Elements; import org.purl.sword.atom.Entry; /** * Extension of the ATOM Entry class. This adds support for the additional * SWORD elements. These elements reside inside the ATOM Entry object, * created in org.w3.atom.Entry class. * * @author Neil Taylor */ public class SWORDEntry extends Entry { /** * Specifies whether the document was run in noOp mode, i.e. * if the document records that no operation was taken for * the deposit other than to generate a response. */ protected SwordNoOp swordNoOp; /** * Use to supply a verbose description. */ protected SwordVerboseDescription swordVerboseDescription; /** * Used for a human readable statement about what treatment * the deposited resource has received. Include either a * text description or a URI. */ protected SwordTreatment swordTreatment; /** * The user agent */ protected SwordUserAgent swordUserAgent; /** * The packaging infomation */ private SwordPackaging swordPackaging; /** * Create a new SWORDEntry with the given namespace and element. This method is * not normally used, instead the default constructor should be used as this will * set the namespace and element correctly. * * @param namespace The namespace of the element * @param element The element name */ public SWORDEntry(String namespace, String element, String namespaceUri) { super(namespace, element, namespaceUri); } /** * A default constructor. */ public SWORDEntry() { super(); } public SWORDEntry(XmlName name) { super(name); } protected void initialise() { super.initialise(); swordNoOp = null; swordPackaging = null; swordVerboseDescription = null; swordTreatment = null; swordUserAgent = null; } /** * Get the current value of NoOp. * * @return True if the value is set, false otherwise. */ public boolean isNoOp() { if( swordNoOp == null ) { return false; } return swordNoOp.getContent(); } /** * Call this method to set noOp. It should be called even by internal * methods so that the object can determine if the value has been set * or whether it just holds the default value. * * @param noOp */ public void setNoOp(boolean noOp) { swordNoOp = new SwordNoOp(noOp); } /** * Determine if the noOp value has been set. This should be called * if you want to know whether false for noOp means that it is the * default value (i.e. no code has set it) or it is a value that * has been actively set. * * @return True if the value has been set. Otherwise, false. */ public boolean isNoOpSet() { if( swordNoOp == null ) { return false; } return swordNoOp.isSet(); } /** * Get the Verbose Description for this entry. * * @return The description. */ public String getVerboseDescription() { if( swordVerboseDescription == null ) { return null; } return swordVerboseDescription.getContent(); } /** * Set the verbose description. * * @param verboseDescription The description. */ public void setVerboseDescription(String verboseDescription) { swordVerboseDescription = new SwordVerboseDescription(verboseDescription); } /** * Get the treatment value. * * @return The treatment. */ public String getTreatment() { if( swordTreatment == null ) { return null; } return swordTreatment.getContent(); } /** * Set the treatment value. * * @param treatment The treatment. */ public void setTreatment(String treatment) { swordTreatment = new SwordTreatment(treatment); } /** * Get the user agent * * @return the user agent */ public String getUserAgent() { if( swordUserAgent == null ) { return null; } return swordUserAgent.getContent(); } /** * Set the user agent * * @param userAgent the user agent */ public void setUserAgent(String userAgent) { swordUserAgent = new SwordUserAgent(userAgent); } /** * Get the packaging format * * @return the packaging format */ public String getPackaging() { if( swordPackaging == null ) { return null; } return swordPackaging.getContent(); } /** * Set the packaging format * * @param packaging the packaging format */ public void setPackaging(String packaging) { this.swordPackaging = new SwordPackaging(packaging); } protected void marshallElements(Element entry) { super.marshallElements(entry); if( swordTreatment != null ) { entry.appendChild(swordTreatment.marshall()); } if( swordVerboseDescription != null ) { entry.appendChild(swordVerboseDescription.marshall()); } if (swordNoOp != null) { entry.appendChild(swordNoOp.marshall()); } if( swordUserAgent != null ) { entry.appendChild(swordUserAgent.marshall()); } if( swordPackaging != null ) { entry.appendChild(swordPackaging.marshall()); } } /** * Overrides the unmarshall method in the parent Entry. This will * call the parent method to parse the general Atom elements and * attributes. This method will then parse the remaining sword * extensions that exist in the element. * * @param entry The entry to parse. * * @throws UnmarshallException If the entry is not an atom:entry * or if there is an exception extracting the data. */ public SwordValidationInfo unmarshallWithValidation(Element entry, Properties validationProperties) throws UnmarshallException { SwordValidationInfo result = super.unmarshallWithoutValidate(entry, validationProperties); processUnexpectedAttributes(entry, result); // retrieve all of the sub-elements Elements elements = entry.getChildElements(); Element element = null; int length = elements.size(); for(int i = 0; i < length; i++ ) { element = elements.get(i); if (isInstanceOf(element, SwordTreatment.elementName())) { if( swordTreatment == null ) { swordTreatment = new SwordTreatment(); result.addUnmarshallElementInfo( swordTreatment.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordTreatment.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, SwordNoOp.elementName())) { if( swordNoOp == null ) { swordNoOp = new SwordNoOp(); result.addUnmarshallElementInfo(swordNoOp.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, SwordVerboseDescription.elementName())) { if( swordVerboseDescription == null ) { swordVerboseDescription = new SwordVerboseDescription(); result.addUnmarshallElementInfo(swordVerboseDescription.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordVerboseDescription.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, SwordUserAgent.elementName())) { if( swordUserAgent == null ) { swordUserAgent = new SwordUserAgent(); result.addUnmarshallElementInfo(swordUserAgent.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordUserAgent.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, SwordPackaging.elementName())) { if( swordPackaging == null ) { swordPackaging = new SwordPackaging(); result.addUnmarshallElementInfo(swordPackaging.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(SwordPackaging.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (validationProperties != null ) { XmlName name = new XmlName(element); if( ! isElementChecked(name) ) { SwordValidationInfo info = new SwordValidationInfo(name, SwordValidationInfo.UNKNOWN_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } } // for return result; } public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) throws UnmarshallException { SwordValidationInfo result = unmarshallWithValidation(entry, validationProperties); if( validationProperties != null ) { result = validate(result, validationProperties); } return result; } /** * * @param elementName * @return */ protected boolean isElementChecked(XmlName elementName) { if( elementName == null ) { return false; } return elementName.equals(SwordNoOp.elementName()) | elementName.equals(SwordUserAgent.elementName()) | elementName.equals(SwordTreatment.elementName()) | elementName.equals(SwordVerboseDescription.elementName()) | elementName.equals(SwordPackaging.elementName()) | super.isElementChecked(elementName); } public SwordValidationInfo validate(Properties validationContext) { return validate(null, validationContext); } protected SwordValidationInfo validate(SwordValidationInfo info, Properties validationContext) { boolean validateAll = (info == null); SwordValidationInfo swordEntry = super.validate(info, validationContext); if( swordUserAgent == null ) { String agent = validationContext.getProperty(HttpHeaders.USER_AGENT); if( agent != null ) { swordEntry.addValidationInfo(new SwordValidationInfo(SwordUserAgent.elementName(), SwordValidationInfo.MISSING_ELEMENT_WARNING + " Clients SHOULD provide a User-Agent request-header (as described in [HTTP1.1] section 14.43). If provided, servers SHOULD store the value in the sword:userAgent element.", SwordValidationInfoType.WARNING)); } } else if( swordUserAgent != null && validateAll ) { info.addValidationInfo(swordUserAgent.validate(validationContext)); } // additional rules for sword elements if( swordTreatment == null ) { swordEntry.addValidationInfo(new SwordValidationInfo(SwordTreatment.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR + " MUST be present and contain either a human-readable statement describing treatment the deposited resource has received or a URI that dereferences to such a description.", SwordValidationInfoType.ERROR)); } else if( swordTreatment != null && validateAll ) { info.addValidationInfo(swordTreatment.validate(validationContext)); } // additional rules for sword elements if( swordVerboseDescription == null ) { String verbose = validationContext.getProperty(HttpHeaders.X_VERBOSE); if( verbose != null ) { swordEntry.addValidationInfo(new SwordValidationInfo(SwordVerboseDescription.elementName(), SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the client made the POST request with an X-Verbose:true header, the server SHOULD supply a verbose description of the deposit process.", SwordValidationInfoType.WARNING)); } } else if( swordVerboseDescription != null && validateAll ) { info.addValidationInfo(swordVerboseDescription.validate(validationContext)); } if( swordNoOp == null ) { String noOp = validationContext.getProperty(HttpHeaders.X_NO_OP); if( noOp != null ) { swordEntry.addValidationInfo(new SwordValidationInfo(SwordNoOp.elementName(), SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the client made the POST request with an X-No-Op:true header, the server SHOULD reflect this by including a sword:noOp element with a value of 'true' in the response. See Part A Section 3.1. Servers MAY use a value of 'false' to indicate that the deposit proceeded but MUST NOT use this element to signify an error.", SwordValidationInfoType.WARNING)); } } else if( swordNoOp != null && validateAll ) { info.addValidationInfo(swordNoOp.validate(validationContext)); } if( swordPackaging == null ) { swordEntry.addValidationInfo(new SwordValidationInfo(SwordPackaging.elementName(), SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the POST request results in the creation of packaged resource, the server MAY use this element to declare the packaging type. If used it SHOULD take a value from [SWORD-TYPES].", SwordValidationInfoType.INFO)); } else if( swordPackaging != null && validateAll ) { info.addValidationInfo(swordPackaging.validate(validationContext)); } return swordEntry; } /** * Overrides the unmarshall method in the parent Entry. This will * call the parent method to parse the general Atom elements and * attributes. This method will then parse the remaining sword * extensions that exist in the element. * * @param entry The entry to parse. * * @throws UnmarshallException If the entry is not an atom:entry * or if there is an exception extracting the data. */ @Override public void unmarshall(Element entry) throws UnmarshallException { unmarshall(entry, null); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * A representation of a quality value. * * The quality value must be between 0 and 1, with no more than three digits * after the decimal place. * * @author Stuart Lewis */ public class QualityValue { /** The quality value. */ private float quality; /** * Create a quality value defaulting to 1 * * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification */ public QualityValue() throws NumberFormatException { // As per the spec, default to value 1 setQualityValue(1f); } /** * Create a quality value * * @param q The quality value * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification */ public QualityValue(float q) throws NumberFormatException { setQualityValue(q); } /** * Set the quality value. * * @param q The quality value * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification */ public final void setQualityValue(float q) throws NumberFormatException { // Check the float is in range if ((q < 0) || (q > 1)) { throw new NumberFormatException("Invalid value - must be between 0 and 1"); } // Check there are no more than three digits after the decimal point String qStr = "" + q; int pos = qStr.indexOf('.'); if (qStr.substring(pos + 1).length() > 3) { throw new NumberFormatException("Invalid value - no more than three digits after the decimal point: " + qStr); } quality = q; } /** * Get the quality value * * @return the quality value */ public final float getQualityValue() { return quality; } /** * Get a String representation of this quality value * * @return The String representation of the quality value */ public String toString() { return Float.toString(quality); } /** * A main method with rudimentary tests to check the class */ /*public static void main(String[] args) { // Test the class // Fail - under 0 try { QualityValue qv1 = new QualityValue(-0.01f); System.out.println("1) Fail: -0.01 passed unexpectedly"); } catch (NumberFormatException nfe) { System.out.print("1) Pass: -0.01 failed as expected "); System.out.println(nfe); } // Fail - over 1 try { QualityValue qv2 = new QualityValue(1.01f); System.out.println("2) Fail: 1.01 passed unexpectedly"); } catch (NumberFormatException nfe) { System.out.print("2) Pass: 1.01 failed as expected "); System.out.println(nfe); } // Fail - to many decimal points try { QualityValue qv3 = new QualityValue(0.1234f); System.out.println("3) Fail: 0.1234 passed unexpectedly"); } catch (NumberFormatException nfe) { System.out.print("3) Pass: 0.1234 failed as expected "); System.out.println(nfe); } // Pass - no decimal places 0 try { QualityValue qv4 = new QualityValue(0f); System.out.println("4) Pass: 0 passed as expected"); } catch (NumberFormatException nfe) { System.out.println("4) Fail: 0 failed unexpectedly"); } // Pass - no decimal places 1 try { QualityValue qv5 = new QualityValue(1f); System.out.println("5) Pass: 1 passed as expected"); } catch (NumberFormatException nfe) { System.out.println("5) Fail: 1 failed unexpectedly"); } // Pass - 3 decimal places try { QualityValue qv6 = new QualityValue(0.123f); System.out.print("6) Pass: 0.123 passed as expected - "); System.out.println(qv6); } catch (NumberFormatException nfe) { System.out.println("6) Fail: 0.123 failed unexpectedly"); } // Pass - No value given try { QualityValue qv6 = new QualityValue(); System.out.print("7) Pass: no value passed as expected - "); System.out.println(qv6); } catch (NumberFormatException nfe) { System.out.println("7) Fail: no value failed unexpectedly"); } } */ }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; import nu.xom.Attribute; import nu.xom.Element; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.HashCodeBuilder; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class XmlName { /** Prefix for the name */ private String prefix; /** Local name */ private String localName; /** The namespace for the element */ private String namespace; /** * Create a new instance with the specified prefix and local name. * @param prefix The namespace prefix. * @param localName The element's local name. */ public XmlName(String prefix, String localName, String namespace ) { this.prefix = prefix; this.localName = localName; this.namespace = namespace; } public XmlName(Element element) { this.prefix = element.getNamespacePrefix(); this.localName = element.getLocalName(); this.namespace = element.getNamespaceURI(); } public XmlName(Attribute attribute) { this.prefix = attribute.getNamespacePrefix(); this.localName = attribute.getLocalName(); this.namespace = attribute.getNamespaceURI(); } /** * Get the prefix. * * @return the prefix */ public String getPrefix() { return prefix; } /** * Set the prefix. * * @param prefix the prefix to set */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Get the local name. * * @return the localName */ public String getLocalName() { return localName; } /** * Set the local name. * * @param localName the localName to set */ public void setLocalName(String localName) { this.localName = localName; } /** * Get the current namespace value. * * @return the namespace */ public String getNamespace() { return namespace; } /** * Set the namespace value. * * @param namespace the namespace to set */ public void setNamespace(String namespace) { this.namespace = namespace; } public String getQualifiedName() { String qName = ""; if( prefix != null && prefix.trim().length() > 0 ) { qName = prefix + ":"; } qName += localName; return qName; } @Override public boolean equals(Object other) { if( other instanceof XmlName ) { XmlName otherName = (XmlName) other; return StringUtils.equals(this.namespace, otherName.namespace) && StringUtils.equals(this.localName, otherName.localName); } return false; } @Override public int hashCode() { return new HashCodeBuilder().append(namespace).append(localName).hashCode(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.base; /** * Represents a SWORD exception to be thrown if bad authentication credentials * are passed to a repository. * * @author Stuart Lewis * @author Neil Taylor */ public class SWORDAuthenticationException extends Exception { /** * Create a new instance and store the specified message and source data. * * @param message The message for the exception. * @param source The original exception that lead to this exception. This * can be <code>null</code>. */ public SWORDAuthenticationException(String message, Exception source) { super(message, source); } /** * Create a new instance and store the specified message. * * @param message The message for the exception. */ public SWORDAuthenticationException(String message) { super(message); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import java.io.IOException; import java.io.OutputStream; /** * A stream that will write any output to the specified panel. * * @author Neil Taylor */ public class DebugOutputStream extends OutputStream { /** * Panel that will display the messages. */ private MessageOutputPanel panel; /** * Create a new instance and specify the panel that will receive the output. * * @param panel The panel. */ public DebugOutputStream(MessageOutputPanel panel) { this.panel = panel; } /** * Override the write method from OutputStream. Capture the char and * send it to the panel. * * @param arg0 The output character, expressed as an integer. * * @see java.io.OutputStream#write(int) */ public void write(int arg0) throws IOException { panel.addCharacter(Character.valueOf((char)arg0)); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /** * Copyright (c) 2007, Aberystwyth University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of the Centre for Advanced Software and * Intelligent Systems (CASIS) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package org.purl.sword.client; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * Panel to display output messages. Text or characters can be sent to the * panel for display. The panel also includes a button to clear any * text that is currently displayed. * * @author Neil Taylor */ public class MessageOutputPanel extends JPanel implements ActionListener { /** * The text area that displays the messages. */ private JTextArea messages = null; /** * Create a new instance and initialise the panel. */ public MessageOutputPanel() { super(); setLayout(new GridBagLayout()); messages = new JTextArea(); JScrollPane detailsPane = new JScrollPane(messages, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); JButton clearButton = new JButton("Clear"); clearButton.addActionListener(this); //add components and set constraints //dpc = details pane constraint GridBagConstraints dpc = new GridBagConstraints(); dpc.gridx = 0; dpc.gridy = 0; dpc.fill = GridBagConstraints.BOTH; dpc.weightx = 0.75; dpc.weighty = 0.45; dpc.gridwidth = 2; dpc.insets = new Insets(5,5,5,5); add(detailsPane,dpc); //cbc = clear button constraint GridBagConstraints cbc = new GridBagConstraints(); cbc.gridx = 1; cbc.gridy = 1; cbc.insets = new Insets(0,0,5,5); cbc.anchor = GridBagConstraints.LINE_END; add(clearButton,cbc); } /** * Add a message to the text area. The message will be added with a carriage return. * * @param message The message. */ public void addMessage(String message) { messages.insert(message + "\n", messages.getDocument().getLength()); } /** * Add a single character to the text area. * * @param character The character. */ public void addCharacter(Character character) { messages.insert(character.toString(), messages.getDocument().getLength()); } /** * Clear the text from the display. * * @param arg0 The action event. * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { messages.setText(""); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.util.Properties; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.FileRequestEntity; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.log4j.Logger; import org.purl.sword.base.ChecksumUtils; import org.purl.sword.base.DepositResponse; import org.purl.sword.base.HttpHeaders; import org.purl.sword.base.ServiceDocument; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.UnmarshallException; /** * This is an example Client implementation to demonstrate how to connect to a * SWORD server. The client supports BASIC HTTP Authentication. This can be * initialised by setting a username and password. * * @author Neil Taylor */ public class Client implements SWORDClient { /** * The status field for the response code from the recent network access. */ private Status status; /** * The name of the server to contact. */ private String server; /** * The port number for the server. */ private int port; /** * Specifies if the network access should use HTTP authentication. */ private boolean doAuthentication; /** * The username to use for Basic Authentication. */ private String username; /** * User password that is to be used. */ private String password; /** * The userAgent to identify this application. */ private String userAgent; /** * The client that is used to send data to the specified server. */ private HttpClient client; /** * The default connection timeout. This can be modified by using the * setSocketTimeout method. */ public static final int DEFAULT_TIMEOUT = 20000; /** * Logger. */ private static Logger log = Logger.getLogger(Client.class); /** * Create a new Client. The client will not use authentication by default. */ public Client() { client = new HttpClient(); client.getParams().setParameter("http.socket.timeout", Integer.valueOf(DEFAULT_TIMEOUT)); log.debug("proxy host: " + client.getHostConfiguration().getProxyHost()); log.debug("proxy port: " + client.getHostConfiguration().getProxyPort()); doAuthentication = false; } /** * Initialise the server that will be used to send the network access. * * @param server * @param port */ public void setServer(String server, int port) { this.server = server; this.port = port; } /** * Set the user credentials that will be used when making the access to the * server. * * @param username * The username. * @param password * The password. */ public void setCredentials(String username, String password) { this.username = username; this.password = password; doAuthentication = true; } /** * Set the basic credentials. You must have previously set the server and * port using setServer. * * @param username * @param password */ private void setBasicCredentials(String username, String password) { log.debug("server: " + server + " port: " + port + " u: '" + username + "' p '" + password + "'"); client.getState().setCredentials(new AuthScope(server, port), new UsernamePasswordCredentials(username, password)); } /** * Set a proxy that should be used by the client when trying to access the * server. If this is not set, the client will attempt to make a direct * direct connection to the server. The port is set to 80. * * @param host * The hostname. */ public void setProxy(String host) { setProxy(host, 80); } /** * Set a proxy that should be used by the client when trying to access the * server. If this is not set, the client will attempt to make a direct * direct connection to the server. * * @param host * The name of the host. * @param port * The port. */ public void setProxy(String host, int port) { client.getHostConfiguration().setProxy(host, port); } /** * Clear the proxy setting. */ public void clearProxy() { client.getHostConfiguration().setProxyHost(null); } /** * Clear any user credentials that have been set for this client. */ public void clearCredentials() { client.getState().clearProxyCredentials(); doAuthentication = false; } public void setUserAgent(String userAgent){ this.userAgent = userAgent; } /** * Set the connection timeout for the socket. * * @param milliseconds * The time, expressed as a number of milliseconds. */ public void setSocketTimeout(int milliseconds) { client.getParams().setParameter("http.socket.timeout", Integer.valueOf(milliseconds)); } /** * Retrieve the service document. The service document is located at the * specified URL. This calls getServiceDocument(url,onBehalfOf). * * @param url * The location of the service document. * @return The ServiceDocument, or <code>null</code> if there was a * problem accessing the document. e.g. invalid access. * * @throws SWORDClientException * If there is an error accessing the resource. */ public ServiceDocument getServiceDocument(String url) throws SWORDClientException { return getServiceDocument(url, null); } /** * Retrieve the service document. The service document is located at the * specified URL. This calls getServiceDocument(url,onBehalfOf). * * @param url * The location of the service document. * @return The ServiceDocument, or <code>null</code> if there was a * problem accessing the document. e.g. invalid access. * * @throws SWORDClientException * If there is an error accessing the resource. */ public ServiceDocument getServiceDocument(String url, String onBehalfOf) throws SWORDClientException { URL serviceDocURL = null; try { serviceDocURL = new URL(url); } catch (MalformedURLException e) { // Try relative URL URL baseURL = null; try { baseURL = new URL("http", server, Integer.valueOf(port), "/"); serviceDocURL = new URL(baseURL, (url == null) ? "" : url); } catch (MalformedURLException e1) { // No dice, can't even form base URL... throw new SWORDClientException(url + " is not a valid URL (" + e1.getMessage() + "), and could not form a relative one from: " + baseURL + " / " + url, e1); } } GetMethod httpget = new GetMethod(serviceDocURL.toExternalForm()); if (doAuthentication) { // this does not perform any check on the username password. It // relies on the server to determine if the values are correct. setBasicCredentials(username, password); httpget.setDoAuthentication(true); } Properties properties = new Properties(); if (containsValue(onBehalfOf)) { log.debug("Setting on-behalf-of: " + onBehalfOf); httpget.addRequestHeader(new Header(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf)); properties.put(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf); } if (containsValue(userAgent)) { log.debug("Setting userAgent: " + userAgent); httpget.addRequestHeader(new Header(HttpHeaders.USER_AGENT, userAgent)); properties.put(HttpHeaders.USER_AGENT, userAgent); } ServiceDocument doc = null; try { client.executeMethod(httpget); // store the status code status = new Status(httpget.getStatusCode(), httpget .getStatusText()); if (status.getCode() == HttpStatus.SC_OK) { String message = readResponse(httpget.getResponseBodyAsStream()); log.debug("returned message is: " + message); doc = new ServiceDocument(); lastUnmarshallInfo = doc.unmarshall(message, properties); } else { throw new SWORDClientException( "Received error from service document request: " + status); } } catch (HttpException ex) { throw new SWORDClientException(ex.getMessage(), ex); } catch (IOException ioex) { throw new SWORDClientException(ioex.getMessage(), ioex); } catch (UnmarshallException uex) { throw new SWORDClientException(uex.getMessage(), uex); } finally { httpget.releaseConnection(); } return doc; } private SwordValidationInfo lastUnmarshallInfo; /** * * @return */ public SwordValidationInfo getLastUnmarshallInfo() { return lastUnmarshallInfo; } /** * Post a file to the server. The different elements of the post are encoded * in the specified message. * * @param message * The message that contains the post information. * * @throws SWORDClientException * if there is an error during the post operation. */ public DepositResponse postFile(PostMessage message) throws SWORDClientException { if (message == null) { throw new SWORDClientException("Message cannot be null."); } PostMethod httppost = new PostMethod(message.getDestination()); if (doAuthentication) { setBasicCredentials(username, password); httppost.setDoAuthentication(true); } DepositResponse response = null; String messageBody = ""; try { if (message.isUseMD5()) { String md5 = ChecksumUtils.generateMD5(message.getFilepath()); if (message.getChecksumError()) { md5 = "1234567890"; } log.debug("checksum error is: " + md5); if (md5 != null) { httppost.addRequestHeader(new Header( HttpHeaders.CONTENT_MD5, md5)); } } String filename = message.getFilename(); if (! "".equals(filename)) { httppost.addRequestHeader(new Header( HttpHeaders.CONTENT_DISPOSITION, " filename=" + filename)); } if (containsValue(message.getSlug())) { httppost.addRequestHeader(new Header(HttpHeaders.SLUG, message .getSlug())); } if(message.getCorruptRequest()) { // insert a header with an invalid boolean value httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, "Wibble")); }else{ httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, Boolean .toString(message.isNoOp()))); } httppost.addRequestHeader(new Header(HttpHeaders.X_VERBOSE, Boolean .toString(message.isVerbose()))); String packaging = message.getPackaging(); if (packaging != null && packaging.length() > 0) { httppost.addRequestHeader(new Header( HttpHeaders.X_PACKAGING, packaging)); } String onBehalfOf = message.getOnBehalfOf(); if (containsValue(onBehalfOf)) { httppost.addRequestHeader(new Header( HttpHeaders.X_ON_BEHALF_OF, onBehalfOf)); } String userAgent = message.getUserAgent(); if (containsValue(userAgent)) { httppost.addRequestHeader(new Header( HttpHeaders.USER_AGENT, userAgent)); } FileRequestEntity requestEntity = new FileRequestEntity( new File(message.getFilepath()), message.getFiletype()); httppost.setRequestEntity(requestEntity); client.executeMethod(httppost); status = new Status(httppost.getStatusCode(), httppost .getStatusText()); log.info("Checking the status code: " + status.getCode()); if (status.getCode() == HttpStatus.SC_ACCEPTED || status.getCode() == HttpStatus.SC_CREATED) { messageBody = readResponse(httppost .getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.setLocation(httppost.getResponseHeader("Location").getValue()); // added call for the status code. lastUnmarshallInfo = response.unmarshall(messageBody, new Properties()); } else { messageBody = readResponse(httppost .getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.unmarshallErrorDocument(messageBody); } return response; } catch (NoSuchAlgorithmException nex) { throw new SWORDClientException("Unable to use MD5. " + nex.getMessage(), nex); } catch (HttpException ex) { throw new SWORDClientException(ex.getMessage(), ex); } catch (IOException ioex) { throw new SWORDClientException(ioex.getMessage(), ioex); } catch (UnmarshallException uex) { throw new SWORDClientException(uex.getMessage() + "(<pre>" + messageBody + "</pre>)", uex); } finally { httppost.releaseConnection(); } } /** * Read a response from the stream and return it as a string. * * @param stream * The stream that contains the response. * @return The string extracted from the screen. * * @throws UnsupportedEncodingException * @throws IOException */ private String readResponse(InputStream stream) throws UnsupportedEncodingException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( stream, "UTF-8")); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); buffer.append("\n"); } return buffer.toString(); } /** * Return the status information that was returned from the most recent * request sent to the server. * * @return The status code returned from the most recent access. */ public Status getStatus() { return status; } /** * Check to see if the specified item contains a non-empty string. * * @param item * The string to check. * @return True if the string is not null and has a length greater than 0 * after any whitespace is trimmed from the start and end. * Otherwise, false. */ private boolean containsValue(String item) { return ((item != null) && (item.trim().length() > 0)); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; /** * Represents an exception thrown by the SWORD Client. * * @author Neil Taylor */ public class SWORDClientException extends Exception { /** * Create a new exception, without a message. */ public SWORDClientException() { super(); } /** * Create a new exception with the specified message. * * @param message The message. */ public SWORDClientException( String message) { super(message); } /** * Create a new exception with the specified message and set * the exception that generated this error. * * @param message The message. * @param cause The original exception. */ public SWORDClientException( String message, Exception cause) { super(message, cause); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /** * Copyright (c) 2007, Aberystwyth University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of the Centre for Advanced Software and * Intelligent Systems (CASIS) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package org.purl.sword.client; import java.awt.BorderLayout; import java.awt.Component; import java.util.*; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.ToolTipManager; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.purl.sword.atom.Author; import org.purl.sword.atom.Content; import org.purl.sword.atom.Contributor; import org.purl.sword.atom.Generator; import org.purl.sword.atom.Link; import org.purl.sword.atom.TextConstruct; import org.purl.sword.base.Collection; import org.purl.sword.base.DepositResponse; import org.purl.sword.base.SWORDEntry; import org.purl.sword.base.Service; import org.purl.sword.base.ServiceDocument; import org.purl.sword.base.Workspace; import org.purl.sword.base.SwordAcceptPackaging; /** * The main panel for the GUI client. This contains the top-two sub-panels: the * tree and the text area to show the details of the selected node. * * @author Neil Taylor */ public class ServicePanel extends JPanel implements TreeSelectionListener { /** * The top level item in the tree that lists services. */ DefaultMutableTreeNode top; /** * The tree model used to display the items. */ DefaultTreeModel treeModel = null; /** * Tree that holds the list of services. */ private JTree services; /** * The panel that shows an HTML table with any details for the selected * node in the services tree. */ private JEditorPane details; /** * A registered listener. This listener will be notified when there is a * different node selected in the service tree. */ private ServiceSelectedListener listener; /** * Create a new instance of the panel. */ public ServicePanel() { super(); setLayout(new BorderLayout()); top = new DefaultMutableTreeNode("Services & Posted Files"); treeModel = new DefaultTreeModel(top); services = new JTree(treeModel); services.setCellRenderer(new ServicePostTreeRenderer()); JScrollPane servicesPane = new JScrollPane(services, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); details = new JEditorPane("text/html", "<html><body><h1>Details</h1><p>This panel will show the details for the currently selected item in the tree.</p></body></html>"); JScrollPane detailsPane = new JScrollPane(details, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, servicesPane, detailsPane); splitPane.setOneTouchExpandable(true); splitPane.setResizeWeight(0.5); splitPane.setDividerLocation(200); services.addTreeSelectionListener(this); ToolTipManager.sharedInstance().registerComponent(services); add(splitPane, BorderLayout.CENTER); } /** * Renderer that displays the icons for the tree nodes. * * @author Neil Taylor */ static class ServicePostTreeRenderer extends DefaultTreeCellRenderer { Icon workspaceIcon; Icon serviceIcon; Icon collectionIcon; Icon fileIcon; /** * Initialise the renderer. Load the icons. */ public ServicePostTreeRenderer() { ClassLoader loader = this.getClass().getClassLoader(); workspaceIcon = new ImageIcon(loader.getResource("images/WorkspaceNodeImage.gif")); serviceIcon = new ImageIcon(loader.getResource("images/ServiceNodeImage.gif")); collectionIcon = new ImageIcon(loader.getResource("images/CollectionNodeImage.gif")); fileIcon = new ImageIcon(loader.getResource("images/ServiceNodeImage.gif")); } /** * Return the cell renderer. This will be the default tree cell renderer * with a different icon depending upon the type of data in the node. * * @param tree The JTree control. * @param value The value to display. * @param sel True if the node is selected. * @param expanded True if the node is expanded. * @param leaf True if the node is a leaf. * @param row The row. * @param hasFocus True if the node has focus. */ public Component getTreeCellRendererComponent( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { JComponent comp = (JComponent)super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; Object o = node.getUserObject(); if( o instanceof TreeNodeWrapper ) { TreeNodeWrapper wrapper = (TreeNodeWrapper)o; comp.setToolTipText(wrapper.toString()); Object data = wrapper.getData(); if( data instanceof Service ) { setIcon(serviceIcon); } else if( data instanceof Workspace ) { setIcon(workspaceIcon); } else if( data instanceof Collection ) { setIcon(collectionIcon); } else if( data instanceof SWORDEntry ) { setIcon(fileIcon); } } else { comp.setToolTipText(null); } return comp; } } /** * Set the service selected listener. This listener will be notified when * there is a selection change in the tree. * * @param listener The listener. */ public void setServiceSelectedListener(ServiceSelectedListener listener) { this.listener = listener; } /** * Process the specified service document. Add the details as a new child of the * root of the tree. * * @param url The url used to access the service document. * @param doc The service document. */ public void processServiceDocument(String url, ServiceDocument doc) { TreeNodeWrapper wrapper = null; Service service = doc.getService(); wrapper = new TreeNodeWrapper(url, service); DefaultMutableTreeNode serviceNode = new DefaultMutableTreeNode(wrapper); treeModel.insertNodeInto(serviceNode, top, top.getChildCount()); services.scrollPathToVisible(new TreePath(serviceNode.getPath())); // process the workspaces DefaultMutableTreeNode workspaceNode = null; Iterator<Workspace> workspaces = service.getWorkspaces(); for (; workspaces.hasNext();) { Workspace workspace = workspaces.next(); wrapper = new TreeNodeWrapper(workspace.getTitle(), workspace); workspaceNode = new DefaultMutableTreeNode(wrapper); treeModel.insertNodeInto(workspaceNode, serviceNode, serviceNode.getChildCount()); services.scrollPathToVisible(new TreePath(workspaceNode.getPath())); DefaultMutableTreeNode collectionNode = null; Iterator<Collection> collections = workspace.collectionIterator(); for (; collections.hasNext();) { Collection collection = collections.next(); wrapper = new TreeNodeWrapper(collection.getTitle(), collection); collectionNode = new DefaultMutableTreeNode(wrapper); treeModel.insertNodeInto(collectionNode, workspaceNode, workspaceNode.getChildCount()); services.scrollPathToVisible(new TreePath(collectionNode.getPath())); } } // for } /** * Holds the data for a tree node. It specifies the name that will be displayed * in the node, and stores associated data. * * @author Neil Taylor */ static class TreeNodeWrapper { /** * The node name. */ private String name; /** * The user data. */ private Object userObject; /** * Create a new instance. * * @param name The name of the node. * @param data The data in the node. */ public TreeNodeWrapper(String name, Object data) { this.name = name; this.userObject = data; } /** * Retrieve the data that is stored in this node. * * @return The data. */ public Object getData() { return userObject; } /** * Get a string description for this node. */ public String toString() { if( name == null || name.trim().equals("") ) { return "Unspecified"; } return name; } } /** * Respond to a changed tree selection event. Update the details panel to * show an appropriate message for the newly selected node. Also, * alert the selection listener for this panel. The listener will receive * a path, if a collection has been selected. Otherwise, the listener * will receive <code>null</code>. */ public void valueChanged(TreeSelectionEvent evt) { // Get all nodes whose selection status has changed TreePath[] paths = evt.getPaths(); for (int i=0; i<paths.length; i++) { if (evt.isAddedPath(i)) { // process new selections DefaultMutableTreeNode node; node = (DefaultMutableTreeNode)(paths[i].getLastPathComponent()); Object o = node.getUserObject(); if( o instanceof TreeNodeWrapper ) { try { TreeNodeWrapper wrapper = (TreeNodeWrapper)o; Object data = wrapper.getData(); if( data instanceof Service ) { showService((Service)data); alertListener(null); } else if( data instanceof Workspace ) { showWorkspace((Workspace)data); if( listener != null ) { alertListener(null); } } else if( data instanceof Collection ) { Collection c = (Collection)data; showCollection(c); alertListener(c.getLocation()); } else if( data instanceof SWORDEntry ) { showEntry((SWORDEntry)data); alertListener(null); } else { details.setText("<html><body>unknown</body></html>"); alertListener(null); } } catch( Exception e ) { details.setText("<html><body>An error occurred. The message was: " + e.getMessage() + "</body></html>"); alertListener(null); e.printStackTrace(); } } else { details.setText("<html><body>please select one of the other nodes</body></html>"); alertListener(null); } } } } /** * Notify the listener that there has been a change to the currently selected * item in the tree. * * @param value The value to send to the listener. */ private void alertListener(String value) { if( listener != null ) { listener.selected(value); } } /** * Add a new HTML table row to the specified StringBuffer. The label is displayed in * the left column and the value is displayed in the right column. * * @param buffer The destination string buffer. * @param label The label to add. * @param value The corresponding value to add. */ private void addTableRow(StringBuffer buffer, String label, Object value) { buffer.append("<tr bgcolor=\"#ffffff;\"><td>"); buffer.append(label); buffer.append("</td><td>"); buffer.append(displayableValue(value)); buffer.append("</td></tr>"); } /** * Show the specified service data in the details panel. * * @param service The service node to display. */ private void showService(Service service) { StringBuffer buffer = new StringBuffer(); buffer.append("<html>"); buffer.append("<body>"); buffer.append("<table border=\"1\" width=\"100%\">"); buffer.append("<tr bgcolor=\"#69a5c8;\"><td colspan=\"2\"><font size=\"+2\">Service Summary</font></td></tr>"); addTableRow(buffer, "SWORD Version", service.getVersion()); addTableRow(buffer, "NoOp Support ", service.isNoOp()); addTableRow(buffer, "Verbose Support ", service.isVerbose()); String maxSize = ""; // Commented out the following code as the client code is out of step with the // Sword 'base' library and wont compile. - Robin Taylor. //if( service.maxUploadIsDefined() ) //{ // maxSize = "" + service.getMaxUploadSize() + "kB"; //} //else //{ maxSize = "undefined"; //} addTableRow(buffer, "Max File Upload Size ", maxSize); buffer.append("</table>"); buffer.append("</body>"); buffer.append("</html>"); details.setText(buffer.toString()); } /** * Display the workspace data in the details panel. * * @param workspace The workspace. */ private void showWorkspace(Workspace workspace) { StringBuffer buffer = new StringBuffer(); buffer.append("<html>"); buffer.append("<body>"); buffer.append("<table border=\"1\" width=\"100%\">"); buffer.append("<tr bgcolor=\"#69a5c8;\"><td colspan=\"2\"><font size=\"+2\">Workspace Summary</font></td></tr>"); addTableRow(buffer, "Workspace Title", workspace.getTitle()); buffer.append("</table>"); buffer.append("</body>"); buffer.append("</html>"); details.setText(buffer.toString()); } /** * Return the parameter unmodified if set, or the not defined text if null * @param s * @return s or ClientConstants.NOT_DEFINED_TEXT */ private Object displayableValue(Object s) { if (null == s) { return ClientConstants.NOT_DEFINED_TEXT; }else{ return s; } } /** * Add a string within paragraph tags. * * @param buffer The buffer to add the message to. * @param message The message to add. */ private void addPara(StringBuffer buffer, String message) { buffer.append("<p>" + message + "</p>"); } /** * Show the specified collection data in the details panel. * * @param collection The collection data. */ private void showCollection(Collection collection) { StringBuffer buffer = new StringBuffer(); buffer.append("<html>"); buffer.append("<body>"); if( collection == null ) { addPara(buffer, "Invalid Collection object. Unable to display details."); } else { buffer.append("<table border=\"1\" width=\"100%\">"); buffer.append("<tr bgcolor=\"#69a5c8;\"><td colspan=\"2\"><font size=\"+2\">Collection Summary</font></td></tr>"); addTableRow(buffer, "Collection location", collection.getLocation()); addTableRow(buffer, "Collection title", collection.getTitle()); addTableRow(buffer, "Abstract", collection.getAbstract()); addTableRow(buffer, "Collection Policy", collection.getCollectionPolicy()); addTableRow(buffer, "Treatment", collection.getTreatment()); addTableRow(buffer, "Mediation", collection.getMediation()); addTableRow(buffer, "Nested Service Document", collection.getService()); String[] accepts = collection.getAccepts(); StringBuilder acceptList = new StringBuilder(); if( accepts != null && accepts.length == 0 ) { acceptList.append("None specified"); } else { for (String s : accepts) { acceptList.append(s).append("<br>"); } } addTableRow(buffer, "Accepts", acceptList.toString()); List<SwordAcceptPackaging> acceptsPackaging = collection.getAcceptPackaging(); StringBuilder acceptPackagingList = new StringBuilder(); for (Iterator i = acceptsPackaging.iterator(); i.hasNext();) { SwordAcceptPackaging accept = (SwordAcceptPackaging) i.next(); acceptPackagingList.append(accept.getContent()).append(" (").append(accept.getQualityValue()).append(")"); // add a , separator if there are any more items in the list if( i.hasNext() ) { acceptPackagingList.append(", "); } } addTableRow(buffer, "Accepts Packaging", acceptPackagingList.toString()); buffer.append("</table>"); } buffer.append("</body>"); buffer.append("</html>"); details.setText(buffer.toString()); } /** * Display the contents of a Post entry in the display panel. * * @param entry The entry to display. */ private void showEntry(SWORDEntry entry) { StringBuffer buffer = new StringBuffer(); buffer.append("<html>"); buffer.append("<body>"); if( entry == null ) { addPara(buffer, "Invalid Entry object. Unable to display details."); } else { buffer.append("<table border=\"1\" width=\"100%\">"); buffer.append("<tr bgcolor=\"#69a5c8;\"><td colspan=\"2\"><font size=\"+2\">Entry Summary</font></td></tr>"); // process atom:title String titleString = getTextConstructDetails(entry.getSummary()); addTableRow(buffer, "Title", titleString); // process id addTableRow(buffer, "ID", entry.getId()); // process updated addTableRow(buffer, "Date Updated", entry.getUpdated()); String authorString = getAuthorDetails(entry.getAuthors()); addTableRow(buffer, "Authors", authorString); // process summary String summaryString = getTextConstructDetails(entry.getSummary()); addTableRow(buffer, "Summary", summaryString); // process content Content content = entry.getContent(); String contentString = ""; if( content == null ) { contentString = "Not defined."; } else { contentString += "Source: '" + content.getSource() + "', Type: '" + content.getType() + "'"; } addTableRow(buffer, "Content", contentString); // process links Iterator<Link> links = entry.getLinks(); StringBuffer linkBuffer = new StringBuffer(); for( ; links.hasNext(); ) { Link link = links.next(); linkBuffer.append("href: '"); linkBuffer.append(link.getHref()); linkBuffer.append("', href lang: '"); linkBuffer.append(link.getHreflang()); linkBuffer.append("', rel: '"); linkBuffer.append(link.getRel()); linkBuffer.append("')<br>"); } if( linkBuffer.length() == 0 ) { linkBuffer.append("Not defined"); } addTableRow(buffer, "Links", linkBuffer.toString()); // process contributors String contributorString = getContributorDetails(entry.getContributors()); addTableRow(buffer, "Contributors", contributorString); // process source String sourceString=""; Generator generator = entry.getGenerator(); if( generator != null ) { sourceString += "Content: '" + generator.getContent() + "' <br>'"; sourceString += "Version: '" + generator.getVersion() + "' <br>'"; sourceString += "Uri: '" + generator.getUri() + "'"; } else { sourceString += "No generator defined."; } addTableRow(buffer, "Generator", sourceString); // process treatment addTableRow(buffer, "Treatment", entry.getTreatment()); // process verboseDescription addTableRow(buffer, "Verbose Description", entry.getVerboseDescription()); // process noOp addTableRow(buffer, "NoOp", entry.isNoOp()); // process formatNamespace addTableRow(buffer, "Packaging", entry.getPackaging()); // process userAgent addTableRow(buffer, "User Agent", entry.getUserAgent()); buffer.append("</table>"); } buffer.append("</body>"); buffer.append("</html>"); details.setText(buffer.toString()); } /** * Retrieve the details for a TextConstruct object. * * @param data The text construct object to display. * * @return Either 'Not defined' if the data is <code>null</code>, or * details of the text content element. */ private String getTextConstructDetails(TextConstruct data) { String summaryStr = ""; if( data == null ) { summaryStr = "Not defined"; } else { summaryStr = "Content: '" + data.getContent() + "', Type: "; if( data.getType() != null ) { summaryStr += "'" + data.getType().toString() + "'"; } else { summaryStr += "undefined."; } } return summaryStr; } /** * Get the author details and insert them into a string. * * @param authors the list of authors to process. * * @return A string containing the list of authors. */ private String getAuthorDetails(Iterator<Author> authors) { // process author StringBuffer authorBuffer = new StringBuffer(); for( ; authors.hasNext(); ) { Author a = authors.next(); authorBuffer.append(getAuthorDetails(a)); } if( authorBuffer.length() == 0 ) { authorBuffer.append("Not defined"); } return authorBuffer.toString(); } /** * Get the contributor details and insert them into a string. * * @param contributors The contributors. * * @return The string that lists the details of the contributors. */ private String getContributorDetails(Iterator<Contributor> contributors) { // process author StringBuffer authorBuffer = new StringBuffer(); for( ; contributors.hasNext(); ) { Contributor c = contributors.next(); authorBuffer.append(getAuthorDetails(c)); } if( authorBuffer.length() == 0 ) { authorBuffer.append("Not defined"); } return authorBuffer.toString(); } /** * Build a string that describes the specified author. * * @param author The author. * * @return The string description. */ private String getAuthorDetails(Author author) { // process author StringBuffer authorBuffer = new StringBuffer(); authorBuffer.append(author.getName()); authorBuffer.append(" (email: '"); authorBuffer.append(author.getEmail()); authorBuffer.append("', uri: '"); authorBuffer.append(author.getUri()); authorBuffer.append("')<br>"); return authorBuffer.toString(); } /** * Process the deposit response and insert the details into the tree. If the url * matches one of the collections in the tree, the deposit is added as a child * node. Otherwise, the node is added as a child of the root. * * @param url The url of the collection that the file was posted to. * * @param response The details of the deposit. */ public void processDepositResponse(String url, DepositResponse response) { SWORDEntry entry = response.getEntry(); Object title = entry.getTitle(); if( title == null ) { title = "Undefined"; } else { title = entry.getTitle().getContent(); } TreeNodeWrapper wrapper = new TreeNodeWrapper(title.toString(), entry); DefaultMutableTreeNode entryNode = new DefaultMutableTreeNode(wrapper); DefaultMutableTreeNode newParentNode = top; List<DefaultMutableTreeNode> nodes = getCollectionNodes(); for( DefaultMutableTreeNode node : nodes ) { Object o = node.getUserObject(); if( o instanceof TreeNodeWrapper ) { TreeNodeWrapper collectionWrapper = (TreeNodeWrapper)o; Object data = collectionWrapper.getData(); if( data instanceof Collection ) { Collection col = (Collection)data; String location = col.getLocation(); if( location != null && location.equals(url)) { newParentNode = node; break; } } } } treeModel.insertNodeInto(entryNode, newParentNode, newParentNode.getChildCount()); services.scrollPathToVisible(new TreePath(entryNode.getPath())); } /** * Get a list of all current collections displayed in the tree. * * @return An array of the URLs for the collections. */ public String[] getCollectionLocations() { List<DefaultMutableTreeNode> nodes = getCollectionNodes(); String[] locations = new String[nodes.size()]; DefaultMutableTreeNode node; for( int i = 0; i < nodes.size(); i++ ) { node = nodes.get(i); Object o = node.getUserObject(); if( o instanceof TreeNodeWrapper ) { TreeNodeWrapper collectionWrapper = (TreeNodeWrapper)o; Object data = collectionWrapper.getData(); if( data instanceof Collection ) { Collection col = (Collection)data; String location = col.getLocation(); if( location != null ) { locations[i] = location; } } } } return locations; } /** * Get a list of nodes that contain collections. * * @return A vector of the collection nodes. */ private List<DefaultMutableTreeNode> getCollectionNodes() { List<DefaultMutableTreeNode> nodes = new ArrayList<DefaultMutableTreeNode>(); DefaultMutableTreeNode node; Enumeration treeNodes = top.depthFirstEnumeration(); while( treeNodes.hasMoreElements() ) { node = (DefaultMutableTreeNode)treeNodes.nextElement(); Object o = node.getUserObject(); if( o instanceof TreeNodeWrapper ) { TreeNodeWrapper wrapper = (TreeNodeWrapper)o; Object data = wrapper.getData(); if( data instanceof Collection ) { nodes.add(node); } } } return nodes; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /** * Copyright (c) 2007, Aberystwyth University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of the Centre for Advanced Software and * Intelligent Systems (CASIS) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package org.purl.sword.client; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * Dialog for users to enter details of post destinations. * * @author Neil Taylor */ public class PostDialog implements ActionListener, ChangeListener { /** * label for the browse command. */ protected static final String BROWSE = "browse"; /** * label for the add command. */ protected static final String ADD = "add"; /** * label for the edit command. */ protected static final String EDIT = "edit"; /** * label for the delete command. */ protected static final String DELETE = "delete"; /** * label for the clear command. */ protected static final String CLEAR = "clear"; /** * Username combo box. */ private SWORDComboBox username; /** * Post Location combo box. */ private SWORDComboBox postLocation; /** * Password field. */ private JPasswordField password; /** * The file combo box. */ private SWORDComboBox file; /** * The filetype combo box. */ private SWORDComboBox fileType; /** * The onBehalfOf combo box. */ private SWORDComboBox onBehalfOf; /** * The md5 checkbox. */ private JCheckBox useMD5; /** * The corruptMD5 checkbox. */ private JCheckBox corruptMD5; /** * The corruptRequest checkbox. */ private JCheckBox corruptRequest; /** * The useNoOp checkbox. */ private JCheckBox useNoOp; /** * The verbose checkbox. */ private JCheckBox useVerbose; /** * The format namespace combo box. */ private SWORDComboBox formatNamespace; /** * The list of post destinations. */ private JList list; /** * The parent frame for the dialog that is displayed. */ private JFrame parentFrame = null; /** * Array that lists the labels for the buttons on the panel. */ private static Object[] options = {"Post File", "Cancel" }; /** * The panel that holds the controls to show. */ private JPanel controls = null; /** * * @param parentFrame */ public PostDialog(JFrame parentFrame) { this.parentFrame = parentFrame; controls = createControls(); } /** * Show the dialog with ok and cancel options. * @return The return value from displaying JOptionPane. Either * JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION. */ public int show( ) { int result = JOptionPane.showOptionDialog(parentFrame, controls, "Post Document", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, null); if( result == JOptionPane.OK_OPTION ) { // update the combo boxes with the values username.updateList(); file.updateList(); fileType.updateList(); onBehalfOf.updateList(); formatNamespace.updateList(); } return result; } /** * Create the controls for the main panel. * * @return The panel. */ protected final JPanel createControls( ) { file = new SWORDComboBox(); JPanel filePanel = new JPanel(new BorderLayout()); filePanel.add(file, BorderLayout.CENTER); JButton browse = new JButton("Browse..."); browse.setActionCommand(BROWSE); browse.addActionListener(this); filePanel.add(browse, BorderLayout.SOUTH); fileType = new SWORDComboBox(); String type = "application/zip"; fileType.addItem(type); fileType.setSelectedItem(type); // controls that will be used in the second dialog postLocation = new SWORDComboBox(); username = new SWORDComboBox(); password = new JPasswordField(); onBehalfOf = new SWORDComboBox(); useMD5 = new JCheckBox(); useMD5.addChangeListener(this); corruptMD5 = new JCheckBox(); corruptRequest = new JCheckBox(); useNoOp = new JCheckBox(); useVerbose = new JCheckBox(); formatNamespace = new SWORDComboBox(); JLabel fileLabel = new JLabel("File:", JLabel.TRAILING); JLabel fileTypeLabel = new JLabel("File Type:", JLabel.TRAILING); JLabel useMD5Label = new JLabel("Use MD5:", JLabel.TRAILING); JLabel corruptMD5Label = new JLabel("Corrupt MD5:", JLabel.TRAILING); JLabel corruptRequestLabel = new JLabel("Corrupt Request:", JLabel.TRAILING); //JLabel corruptMD5Label = new JLabel("Corrupt MD5:", JLabel.TRAILING); JLabel useNoOpLabel = new JLabel("Use noOp:", JLabel.TRAILING); JLabel useVerboseLabel = new JLabel("Use verbose:", JLabel.TRAILING); JLabel formatNamespaceLabel = new JLabel("X-Packaging:", JLabel.TRAILING); JLabel userAgentLabel = new JLabel("User Agent:", JLabel.TRAILING); JLabel userAgentNameLabel = new JLabel(ClientConstants.SERVICE_NAME, JLabel.LEADING); SWORDFormPanel panel = new SWORDFormPanel(); panel.addFirstRow(new JLabel("Please enter the details for the post operation")); JPanel destinations = createDestinationsPanel(); panel.addRow(new JLabel("Destinations:"), destinations); panel.addRow(fileLabel, filePanel); panel.addRow(fileTypeLabel, fileType); panel.addRow(useMD5Label, useMD5); panel.addRow(corruptMD5Label, corruptMD5); panel.addRow(corruptRequestLabel, corruptRequest); panel.addRow(useNoOpLabel, useNoOp); panel.addRow(useVerboseLabel, useVerbose); panel.addRow(formatNamespaceLabel, formatNamespace); panel.addRow(userAgentLabel, userAgentNameLabel); return panel; } /** * Create the destinations panel. This contains a list and four buttons * to operate on values in the list. * * @return The panel containing the controls. */ protected JPanel createDestinationsPanel() { DefaultListModel model = new DefaultListModel(); list = new JList(model); JScrollPane jsp = new JScrollPane(list); JPanel destinations = new JPanel(new BorderLayout()); destinations.add(jsp, BorderLayout.CENTER); JPanel destinationButtons = new JPanel(); JButton addButton = new JButton("Add"); addButton.setActionCommand(ADD); addButton.addActionListener(this); JButton editButton = new JButton("Edit"); editButton.setActionCommand(EDIT); editButton.addActionListener(this); JButton deleteButton = new JButton("Delete"); deleteButton.setActionCommand(DELETE); deleteButton.addActionListener(this); JButton clearButton = new JButton("Clear"); clearButton.setActionCommand(CLEAR); clearButton.addActionListener(this); destinationButtons.add(addButton); destinationButtons.add(editButton); destinationButtons.add(deleteButton); destinationButtons.add(clearButton); destinations.add(destinationButtons, BorderLayout.SOUTH); return destinations; } /** * Handle the button click to select a file to upload. */ public void actionPerformed(ActionEvent evt) { String cmd = evt.getActionCommand(); if( BROWSE.equals(cmd) ) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); int returnVal = chooser.showOpenDialog(parentFrame); if(returnVal == JFileChooser.APPROVE_OPTION) { file.setSelectedItem(chooser.getSelectedFile().getAbsolutePath()); } } else if( ADD.equals(cmd)) { PostDestination dest = showDestinationDialog(null); if( dest != null ) { ((DefaultListModel)list.getModel()).addElement(dest); } } else if( EDIT.equals(cmd)) { PostDestination dest = (PostDestination)list.getSelectedValue(); if( dest != null ) { showDestinationDialog(dest); list.repaint(); } } else if( DELETE.equals(cmd)) { if( list.getSelectedIndex() != -1 ) { ((DefaultListModel)list.getModel()).removeElementAt(list.getSelectedIndex()); } } else if( CLEAR.equals(cmd)) { ((DefaultListModel)list.getModel()).clear(); } } /** * Show the destination dialog. This is used to enter the URL, * username, password and onBehalfOf name for a destination. * * @param destination The post destination. If this is not null, the values * in the object are used to set the current values * in the dialog controls. * @return The post destination value. */ public PostDestination showDestinationDialog( PostDestination destination ) { SWORDFormPanel panel = new SWORDFormPanel(); panel.addFirstRow(new JLabel("Please enter the details for the post operation")); JLabel postLabel = new JLabel("Post Location:", JLabel.TRAILING); JLabel userLabel = new JLabel("Username:", JLabel.TRAILING); JLabel passwordLabel = new JLabel("Password:", JLabel.TRAILING); JLabel onBehalfOfLabel = new JLabel("On Behalf Of:", JLabel.TRAILING); panel.addRow(postLabel, postLocation); panel.addRow(userLabel, username); panel.addRow(passwordLabel, password); panel.addRow(onBehalfOfLabel, onBehalfOf); if( destination != null ) { postLocation.insertItem(destination.getUrl()); username.insertItem(destination.getUsername()); password.setText(destination.getPassword()); onBehalfOf.insertItem(destination.getOnBehalfOf()); } else { String s = ""; postLocation.insertItem(s); //postLocation.setSelectedItem(s); username.insertItem(s); username.setSelectedItem(s); password.setText(s); onBehalfOf.insertItem(s); onBehalfOf.setSelectedItem(s); } int result = JOptionPane.showOptionDialog(null, panel, "Destination", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[] { "OK", "Cancel" }, null); if( result == JOptionPane.OK_OPTION ) { postLocation.updateList(); username.updateList(); onBehalfOf.updateList(); if( destination == null ) { destination = new PostDestination(); } destination.setUrl(postLocation.getText()); destination.setUsername(username.getText()); String pass = new String(password.getPassword()); if( pass.length() > 0 ) { destination.setPassword(pass); } else { destination.setPassword(null); } String obo = onBehalfOf.getText(); if( obo.length() > 0 ) { destination.setOnBehalfOf(onBehalfOf.getText()); } else { destination.setOnBehalfOf(null); } } return destination; } /** * Get the list of Post Destinations. * @return The destinations. */ public PostDestination[] getDestinations() { DefaultListModel model = (DefaultListModel)list.getModel(); PostDestination[] destinations = new PostDestination[model.size()]; for( int i = 0; i < model.size(); i++) { destinations[i] = (PostDestination)model.get(i); } return destinations; } /** * Get the file details. * @return The value. */ public String getFile( ) { return file.getText(); } /** * Get the filetype value. * @return The value. */ public String getFileType() { return fileType.getText(); } /** * Get the onBehalfOf value. * @return The value. */ public String getOnBehalfOf() { return onBehalfOf.getText(); } /** * Get the format namespace value. * @return The value. */ public String getFormatNamespace() { return formatNamespace.getText(); } /** * Determine if the MD5 checkbox is selected. * * @return True if the MD5 checkbox is selected. */ public boolean useMd5() { return useMD5.isSelected(); } /** * Determine if the noOp checkbox is selected. * * @return True if the checkbox is selected. */ public boolean useNoOp() { return useNoOp.isSelected(); } /** * Determine if the verbose checkbox is selected. * * @return True if the checkbox is selected. */ public boolean useVerbose() { return useVerbose.isSelected(); } /** * Get the post location. * @return The post location. */ public String getPostLocation() { return postLocation.getText(); } /** * Determine if the MD5 hash should be corrupted. * @return True if the corrupt MD5 checkbox is selected. The MD5 checkbox * must also be selected. */ public boolean corruptMD5() { return (corruptMD5.isEnabled() && corruptMD5.isSelected()); } /** * Determine if the POST request should be corrupted. * @return True if the corrupt request checkbox is selected. */ public boolean corruptRequest() { return (corruptRequest.isSelected()); } /** * Detect a state change event for the checkbox. * * @param evt The event. */ public void stateChanged(ChangeEvent evt) { corruptMD5.setEnabled(useMD5.isSelected()); } /** * Add a list of user ids. * * @param users The user ids. */ public void addUserIds(String[] users) { username.insertItems(users); } /** * Add a list of deposit URLs. * * @param deposits The URLs. */ public void addDepositUrls(String[] deposits) { postLocation.insertItems(deposits); } /** * Add a list of onBehalfOf names. * * @param users The names. */ public void addOnBehalfOf(String[] users) { onBehalfOf.insertItems(users); } /** * Add the list of formatNamespace strings. * * @param namespaces list of strings. */ public void addFormatNamespaces(String[] namespaces) { formatNamespace.insertItems(namespaces); } /** * Add a list of file types. * * @param types The file types. */ public void addFileTypes(String[] types) { fileType.insertItems(types); } /** * Add a list of file names. * @param files The list of files. */ public void addFiles(String[] files) { file.insertItems(files); } /** * Set the deposit location. * * @param location The location. */ public void setDepositLocation(String location) { postLocation.insertItem(location); postLocation.setSelectedItem(location); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; /** * Representation of the status code and message. * * @author Neil Taylor */ public class Status { /** * The status code. */ private int code; /** * The status message. */ private String message; /** * Create a new status message. * * @param code The code. * @param message The message. */ public Status( int code, String message) { this.code = code; this.message = message; } /** * Retrieve the code. * * @return The code. */ public int getCode( ) { return code; } /** * Get the message. * * @return The message. */ public String getMessage() { return message; } /** * Get a string representation of the status. */ public String toString() { return "Code: " + code + ", Message: '" + message + "'"; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; /** * Details for a destination. This is used to represent a destination. If * expressed as a string, the destination looks like: * <pre> * <user>[<onBehalfOf>]:<password>@<url> * </pre> * * @author Neil Taylor */ public class PostDestination { /** * URL for the post destination. */ private String url; /** * The username. */ private String username; /** * The password. */ private String password; /** * The onBehalfOf ID. */ private String onBehalfOf; /** * Create a new instance. */ public PostDestination() { // No-Op } /** * Create a new instance. * * @param url The url. * @param username The username. * @param password The password. * @param onBehalfOf The onBehalfOf id. */ public PostDestination(String url, String username, String password, String onBehalfOf) { this.url = url; this.username = username; this.password = password; this.onBehalfOf = onBehalfOf; } /** * @return the url */ public String getUrl() { return url; } /** * @param url the url to set */ public void setUrl(String url) { this.url = url; } /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the onBehalfOf */ public String getOnBehalfOf() { return onBehalfOf; } /** * @param onBehalfOf the onBehalfOf to set */ public void setOnBehalfOf(String onBehalfOf) { this.onBehalfOf = onBehalfOf; } /** * Create a string representation of this object. * * @return The string. */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(username); if( onBehalfOf != null ) { buffer.append("["); buffer.append(onBehalfOf); buffer.append("]"); } if( password != null ) { buffer.append(":******"); } buffer.append("@"); buffer.append(url); return buffer.toString(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; /** * List of options that are parsed from the command line. * @author Neil Taylor */ public class ClientOptions { /** * Label for the service operation. */ public static final String TYPE_SERVICE = "service"; /** * Label for the post operation. */ public static final String TYPE_POST = "post"; /** * Label for the multipost operation. */ public static final String TYPE_MULTI_POST = "multipost"; /** * The access type. */ private String accessType = null; /** * Proxy host name. */ private String proxyHost = null; /** * Proxy host port. */ private int proxyPort = 8080; /** * Username to access the service/post server. */ private String username = null; /** * Password to access the service/post server. */ private String password = null; /** * HREF of the server to access. */ private String href = null; /** * Filename to post. */ private String filename = null; /** * Filetype. */ private String filetype = null; /** * Specifies that the output streams are not to be captured by the GUI client. */ private boolean noCapture = false; /** * SLUG Header field. */ private String slug = null; /** * NoOp, used to indicate an operation on the server that does not * require the file to be stored. */ private boolean noOp = false; /** * Request verbose output from the server. */ private boolean verbose = false; /** * OnBehalfOf user id. */ private String onBehalfOf = null; /** * Format namespace to be used for the posted file. */ private String formatNamespace = null; /** * Introduce a checksum error. This is used to simualte an error with the * MD5 value. */ private boolean checksumError = false; /** * Logger. */ private static Logger log = Logger.getLogger(ClientOptions.class); /** * List of multiple destination items. Used if the mode is set to multipost. */ private List<PostDestination> multiPost = new ArrayList<PostDestination>(); /** * Pattern string to extract the data from a destination parameter in multipost mode. */ private static final Pattern multiPattern = Pattern.compile("(.*?)(\\[(.*?)\\]){0,1}(:(.*)){0,1}@(http://.*)"); /** * Flag that indicates if the gui mode has been set. This is * true by default. */ private boolean guiMode = true; /** * Flat that indicates if the MD5 option has been selected. This * is true by default. */ private boolean md5 = false; /** * Parse the list of options contained in the specified array. * * @param args The array of options. * * @return True if the options were parsed successfully. */ public boolean parseOptions( String[] args ) { try { // iterate over the args for( int i = 0; i < args.length; i++ ) { if( "-md5".equals(args[i])) { md5 = true; } if( "-noOp".equals(args[i])) { noOp = true; } if( "-verbose".equals(args[i])) { verbose = true; } if( "-cmd".equals(args[i]) ) { guiMode = false; } if( "-gui".equals(args[i]) ) { guiMode = true; } if( "-host".equals(args[i]) ) { i++; proxyHost = args[i]; } if( "-port".equals(args[i]) ) { i++; proxyPort = Integer.parseInt(args[i]); } if( "-u".equals(args[i]) ) { i++; username = args[i]; } if( "-p".equals(args[i])) { i++; password = args[i]; } if( "-href".equals(args[i])) { i++; href = args[i]; } if( "-help".equals(args[i]) ) { // force the calling code to display the usage information return false; } if( "-t".equals(args[i])) { i++; accessType = args[i]; } if( "-file".equals(args[i])) { i++; filename = args[i]; } if( "-filetype".equals(args[i])) { i++; filetype = args[i]; } if( "-slug".equals(args[i])) { i++; slug = args[i]; } if( "-onBehalfOf".equals(args[i])) { i++; onBehalfOf = args[i]; } if( "-formatNamespace".equals(args[i])) { i++; formatNamespace = args[i]; } if( "-checksumError".equals(args[i])) { i++; checksumError = true; } if( "-dest".equals(args[i])) { i++; Matcher m = multiPattern.matcher(args[i]); if( ! m.matches() ) { log.debug("Error with dest parameter. Ignoring value: " + args[i]); } else { int numGroups = m.groupCount(); for( int g = 0; g <= numGroups; g++ ) { log.debug("Group (" + g + ") is: " + m.group(g)); } String username = m.group(1); String onBehalfOf = m.group(3); String password = m.group(5); String url = m.group(6); PostDestination destination = new PostDestination(url, username, password, onBehalfOf); multiPost.add(destination); } } if( "-nocapture".equals(args[i]) ) { i++; noCapture = true; } } // apply any settings if( href == null && "service".equals(accessType) ) { log.error( "No href specified."); return false; } if( multiPost.size() == 0 && "multipost".equals(accessType)) { log.error("No destinations specified"); return false; } if( accessType == null && ! guiMode ) { log.error("No access type specified"); return false; } if( ( username == null && password != null ) || (username != null && password == null)) { log.error("The username and/or password are not specified. If one is specified, the other must also be specified."); return false; } } catch( ArrayIndexOutOfBoundsException ex ) { log.error("Error with parameters."); return false; } return true; } /** * Get the access type. * @return The value, or <code>null</code> if the value is not set. */ public String getAccessType() { return accessType; } /** * Set the access type. * @param accessType The value, or <code>null</code> to clear the value. */ public void setAccessType(String accessType) { this.accessType = accessType; } /** * Get the proxy host. * @return The value, or <code>null</code> if the value is not set. */ public String getProxyHost() { return proxyHost; } /** * Set the proxy host. * @param proxyHost The value, or <code>null</code> to clear the value. */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } /** * Get the proxy port. * @return The proxy port. Default value is 80. */ public int getProxyPort() { return proxyPort; } /** * Set the proxy port. * @param proxyPort The proxy port. */ public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } /** * Get the username. * @return The value, or <code>null</code> if the value is not set. */ public String getUsername() { return username; } /** * Set the username. * @param username The value, or <code>null</code> to clear the value. */ public void setUsername(String username) { this.username = username; } /** * Get the password. * @return The value, or <code>null</code> if the value is not set. */ public String getPassword() { return password; } /** * Set the password. * @param password The value, or <code>null</code> to clear the value. */ public void setPassword(String password) { this.password = password; } /** * Get the HREF of the service to access. * @return The value, or <code>null</code> if the value is not set. */ public String getHref() { return href; } /** * Set the HREF of the service to access. * @param href The value, or <code>null</code> to clear the value. */ public void setHref(String href) { this.href = href; } /** * Get the name of the file to post. * @return The value, or <code>null</code> if the value is not set. */ public String getFilename() { return filename; } /** * Set the name of the file to post. * @param filename The value, or <code>null</code> to clear the value. */ public void setFilename(String filename) { this.filename = filename; } /** * Get the type of the file to post. * @return The filetype, or <code>null</code> if the value is not set. */ public String getFiletype() { return filetype; } /** * Set the type of the file to post. * @param filetype The value, or <code>null</code> to clear the value. */ public void setFiletype(String filetype) { this.filetype = filetype; } /** * Determine if the tool is to be run in GUI mode. * @return True if the tool is set for GUI mode. */ public boolean isGuiMode() { return guiMode; } /** * Set the tool to run in GUI mode. * @param guiMode True if the tool is to run in gui mode. */ public void setGuiMode(boolean guiMode) { this.guiMode = guiMode; } /** * Get the MD5 setting. True if the tool is to use MD5 for post operations. * @return The MD5 setting. */ public boolean isMd5() { return md5; } /** * Set the MD5 setting. * @param md5 True if the tool should use MD5 for post operations. */ public void setMd5(boolean md5) { this.md5 = md5; } /** * Determine if the NoOp header should be sent. * @return True if the header should be sent. */ public boolean isNoOp() { return noOp; } /** * Set the NoOp setting. * @param noOp True if the NoOp header should be used. */ public void setNoOp(boolean noOp) { this.noOp = noOp; } /** * Determine if the verbose option is set. * @return True if verbose option is set. */ public boolean isVerbose() { return verbose; } /** * Set the verbose option. * @param verbose True if verbose should be set. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Get the onBehalfOf value. * @return The value, or <code>null</code> to clear the value. */ public String getOnBehalfOf() { return onBehalfOf; } /** * Set the onBehalf of Value. * @param onBehalfOf The value, or <code>null</code> to clear the value. */ public void setOnBehalfOf(String onBehalfOf) { this.onBehalfOf = onBehalfOf; } /** * Get the format namespace value. * @return The value, or <code>null</code> if the value is not set. */ public String getFormatNamespace() { return formatNamespace; } /** * Set the format namespace value. * @param formatNamespace The value, or <code>null</code> to clear the value. */ public void setFormatNamespace(String formatNamespace) { this.formatNamespace = formatNamespace; } /** * Get the checksum error value. * @return True if an error should be introduced into the checksum. */ public boolean getChecksumError() { return checksumError; } /** * Set the checksum error value. * @param checksumError True if the error should be introduced. */ public void setChecksumError(boolean checksumError) { this.checksumError = checksumError; } /** * Get the current slug header. * @return The slug value, or <code>null</code> if the value is not set. */ public String getSlug( ) { return this.slug; } /** * Set the text that is to be used for the slug header. * @param slug The value, or <code>null</code> to clear the value. */ public void setSlug(String slug) { this.slug = slug; } /** * Get the list of post destinations. * @return An iterator over the list of PostDestination objects. */ public Iterator<PostDestination> getMultiPost() { return multiPost.iterator(); } /** * Determine if the noCapture option is set. This indicates that the code * should not attempt to redirect stdout and stderr to a different output * destination. Intended for use in a GUI client. * * @return The noCapture setting. True if set. */ public boolean isNoCapture() { return noCapture; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import org.apache.log4j.PropertyConfigurator; /** * Entry point for the SWORD Demonstration Client. This will parse the list of * command line options and load either a Command Line client or a GUI client. * * @author Neil Taylor */ public class ClientFactory { /** * Create a new instance. */ public ClientFactory() { // configure the logger from the property file. The GUI client will // reload these properties if it is set to capture the output and // display it in a panel. PropertyConfigurator.configure(this.getClass().getClassLoader() .getResource(ClientConstants.LOGGING_PROPERTY_FILE)); } /** * Generate a string that specifies the command line options for this * program. * * @return A list of the options for this program. */ public static String usage() { StringBuffer buffer = new StringBuffer(); buffer.append("swordclient: version "); buffer.append(ClientConstants.CLIENT_VERSION); buffer.append("\n"); buffer.append("GUI Mode: "); buffer.append("swordclient [-gui] [-nocapture]"); buffer.append("\n\n"); buffer.append("Command Mode: Service - Request a Service Document\n"); buffer .append("swordclient -cmd -t service [user-options] [proxy-options] -href url [-onBehalfOf name] "); buffer.append("\n\n"); buffer .append("Command Mode: Post - Post a file to a remote service.\n"); buffer .append("swordclient -cmd -t post [user-options] [proxy-options] [post-options] \n"); buffer .append(" [-file file] [-filetype type] [-onBehalfOf name]"); buffer.append("\n\n"); buffer .append("Command Mode: MultiPost - Post a file to multiple remote services.\n"); buffer .append("swordclient -cmd -t multipost [user-options] [proxy-options] [post-options] \n"); buffer.append(" [-dest dest]"); buffer.append("\n\n"); buffer.append("User options: \n"); buffer .append(" -u username Specify a username to access the remote service.\n"); buffer .append(" -p password Specify a password to access the remote service.\n"); buffer.append(" Required if -u option is used."); buffer.append("\n\n"); buffer.append("Proxy options: \n"); buffer .append(" -host host Hostname of a proxy, wwwproxy.aber.ac.uk.\n"); buffer .append(" -port port Proxy port number, e.g. 8080.\n"); buffer.append("\n\n"); buffer.append("Post options: \n"); buffer .append(" -noOp Specified to indicate that the post is a test operation.\n"); buffer .append(" -md5 Use an MD5 checksum in the message header.\n"); buffer .append(" -checksumError Mis-calculate the file checksum for server test purposes.\n"); buffer.append(" -formatNamespace ns The format namespace value.\n"); buffer.append(" -slug name The slug value.\n"); buffer .append(" -verbose Request a verbose response from the server.\n"); buffer.append("\n\n"); buffer.append("Other options: \n"); buffer.append(" -help Show this message.\n"); buffer .append(" -t type The type of operation: service, post or multipost.\n"); buffer .append(" -href url The URL for the service or post document.\n"); buffer .append(" Required for service. The post and multipost operations \n"); buffer .append(" will prompt you if the value is not provided.\n"); buffer .append(" -filetype type The filetype, e.g. application/zip. The post and multipost\n"); buffer .append(" will prompt you for the value if it is not provided.\n"); buffer .append(" -onBehalfOf name Specify this parameter to set the On Behalf Of value.\n"); buffer .append(" -dest dest Specify the destination for a deposit. This can be repeated\n"); buffer .append(" multiple times. The format is: \n"); buffer .append(" <username>[<onbehalfof>]:<password>@<href>\n"); buffer .append(" e.g. sword[nst]:swordpass@http://sword.aber.ac.uk/post/\n"); buffer .append(" nst:pass@http://sword.aber.ac.uk/post\n"); buffer .append(" -nocapture Do not capture System.out and System.err to a debug panel\n"); buffer.append(" in the GUI panel."); return buffer.toString(); } /** * Create a client. If GUI mode is set, a GUI client is created. Otherwise, * a command line client is created. * * @param options * The list of options extracted from the command line. * * @return A new client. */ public ClientType createClient(ClientOptions options) { return new CmdClient(); } /** * Start the application and determine which client should be loaded. The * application currently has two modes: GUI and client. The GUI mode is the * default option. * * @param args * The command line arguments. */ public static void main(String[] args) { ClientFactory factory = new ClientFactory(); ClientOptions options = new ClientOptions(); if (options.parseOptions(args)) { ClientType client = factory.createClient(options); client.run(options); } else { System.out.println(usage()); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JPanel; /** * Utility class. Creates a two column form. The left column is used to show * the label for the row. The right column is used to show the control, e.g. * text box, combo box or checkbox, for the row. * * @author Neil Taylor */ public class SWORDFormPanel extends JPanel { /** * Constraints used to control the layout on the panel. */ private GridBagConstraints labelConstraints; /** * Constraints used to control the layout of the input controls on the panel. */ private GridBagConstraints controlConstraints; /** * Index to the next row. */ private int rowIndex = 0; /** * Insets for the top row of the label column. */ private Insets labelTop = new Insets(10, 10, 0, 0); /** * Insets for the top row of the control column. */ private Insets controlTop = new Insets(10, 4, 0, 10); /** * Insets for a general row in the label column. */ private Insets labelGeneral = new Insets(3, 10, 0, 0); /** * Insets for a general row in the control column. */ private Insets controlGeneral = new Insets(3, 4, 0, 10); /** * Create a new instance of the class. */ public SWORDFormPanel() { super(); setLayout(new GridBagLayout()); labelConstraints = new GridBagConstraints(); labelConstraints.fill = GridBagConstraints.NONE; labelConstraints.anchor = GridBagConstraints.LINE_END; labelConstraints.weightx = 0.1; controlConstraints = new GridBagConstraints(); controlConstraints.fill = GridBagConstraints.HORIZONTAL; controlConstraints.weightx = 0.9; } /** * Add the specified component as the first row. It will occupy two * columns. * * @param one The control to add. */ public void addFirstRow(Component one) { addRow(one, null, labelTop, controlTop); } /** * Add the specified components as the first row in the form. * @param one The label component. * @param two The control component. */ public void addFirstRow(Component one, Component two) { addRow(one, two, labelTop, controlTop); } /** * Add a component to the general row. This will be added in the label column. * @param one The component. */ public void addRow(Component one) { addRow(one, null); } /** * Add a component to the general row. * @param one The component to add to the label column. * @param two The component to add to the control column. */ public void addRow(Component one, Component two) { addRow(one, two, labelGeneral, controlGeneral); } /** * Add a row to the table. * * @param one The component to display in the label column. * @param two The component to display in the control column. * @param labels The insets for the label column. * @param controls The insets for the controls column. */ protected void addRow(Component one, Component two, Insets labels, Insets controls ) { labelConstraints.insets = labels; labelConstraints.gridx = 0; labelConstraints.gridy = rowIndex; if( two == null ) { labelConstraints.gridwidth = 2; } else { labelConstraints.gridwidth = 1; } add(one, labelConstraints); if( two != null ) { controlConstraints.insets = controls; controlConstraints.gridx = 1; controlConstraints.gridy = rowIndex; add(two, controlConstraints); } rowIndex++; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /** * Copyright (c) 2007, Aberystwyth University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of the Centre for Advanced Software and * Intelligent Systems (CASIS) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package org.purl.sword.client; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; /** * Dialog that prompts the user to enter the details for a service * document location. * * @author Neil Taylor */ public class ServiceDialog { /** * The username. */ private SWORDComboBox username; /** * The password. */ private JPasswordField password; /** * Holds the URL for the collection. */ private SWORDComboBox location; /** * The combo box that shows the list of onBehalfOf items. */ private SWORDComboBox onBehalfOf; /** * Parent frame for the dialog. */ private JFrame parentFrame = null; /** * The panel that holds the controls. */ private JPanel controls = null; /** * List of buttons. */ private static Object[] options = {"Get Service Document", "Cancel" }; /** * Create a new instance. * * @param parentFrame The parent frame. The dialog will be shown over the * centre of this frame. */ public ServiceDialog(JFrame parentFrame) { this.parentFrame = parentFrame; controls = createControls(); } /** * Show the dialog. * * @return The close option. This is one of the dialog options from * JOptionPane. */ public int show( ) { int result = JOptionPane.showOptionDialog(parentFrame, controls, "Get Service Document", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]); if( result == JOptionPane.OK_OPTION ) { // update the combo boxes with the values username.updateList(); location.updateList(); onBehalfOf.updateList(); } return result; } /** * Create the controls that are displayed in the dialog. * * @return The panel that contains the controls. */ protected final JPanel createControls( ) { username = new SWORDComboBox(); username.setEditable(true); password = new JPasswordField(); location = new SWORDComboBox(); location.setEditable(true); onBehalfOf = new SWORDComboBox(); onBehalfOf.setEditable(true); JLabel userLabel = new JLabel("Username:", JLabel.TRAILING); JLabel passwordLabel = new JLabel("Password:", JLabel.TRAILING); JLabel locationLabel = new JLabel("Location:", JLabel.TRAILING); JLabel onBehalfOfLabel = new JLabel("On Behalf Of:", JLabel.TRAILING); SWORDFormPanel panel = new SWORDFormPanel(); panel.addFirstRow(userLabel, username); panel.addRow(passwordLabel, password); panel.addRow(locationLabel, location); panel.addRow(onBehalfOfLabel, onBehalfOf); return panel; } /** * Get the username from the controls on the dialog. * * @return The username. */ public String getUsername() { return username.getText(); } /** * Get the password from the dialog. * * @return The password. */ public String getPassword() { return new String(password.getPassword()); } /** * The location from the dialog. * * @return The location. */ public String getLocation() { return location.getText(); } /** * The onBehalfOf value from the dialog. * * @return The onBehalfOf value. */ public String getOnBehalfOf() { String text = onBehalfOf.getText().trim(); if( text.length() == 0 ) { return null; } return text; } /** * Add the list of user ids to the dialog. * * @param users The list of user ids. */ public void addUserIds(String[] users) { username.insertItems(users); } /** * Add the list of service URLs. * * @param services The service URLs. */ public void addServiceUrls(String[] services) { location.insertItems(services); } /** * Add a list of onBehalfOf names. * * @param users The list of onBehalfOf items. */ public void addOnBehalfOf(String[] users) { onBehalfOf.insertItems(users); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; /** * Interface for a client. This contains a single method that allows the factory * to pass a set of command line options to the client. * * @author Neil Taylor */ public interface ClientType { /** * Run the client, processing the specified options. * * @param options The options extracted from the command line. */ public void run( ClientOptions options ); }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; /** * Listener for any objects that want to be notified when a collection has been selected in the * ServicePanel. * * @author Neil Taylor * */ public interface ServiceSelectedListener { /** * Called to provide an update on whether the selected node is a Collection. * * @param collection The location of the collection. <code>null</code>, otherwise. */ public void selected(String collection); }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /** * Copyright (c) 2007, Aberystwyth University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of the Centre for Advanced Software and * Intelligent Systems (CASIS) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package org.purl.sword.client; import javax.swing.JComboBox; /** * An extension of the JComboBox class. This adds a method that * can update the list of items with the item. The update will only * work on combo boxes that are set to editable. * * @author Neil Taylor */ public class SWORDComboBox extends JComboBox { /** * Create an instance of the SWORD Combo box. */ public SWORDComboBox() { super(); setEditable(true); } /** * Update the list for the Combo box with the currently selected * item. This will only add an item to the list if: i) the control * is editable, ii) the selected item is not empty and iii) the * item is not already in the list. */ public void updateList() { Object s = getSelectedItem(); if( ! isEditable() || s == null || (s != null && ((String)s).trim().length() == 0 ) ) { // don't update with an empty item or if the combo box is not editable. return; } insertItem(s); } /** * Insert an item into the combo box. This will only be added * if the item is not already present in the combo box. * * @param newItem The item to insert. */ public void insertItem(Object newItem) { int count = getItemCount(); boolean found = false; for( int i = 0; i < count && ! found; i++ ) { Object item = getItemAt(i); if( item != null && item.equals(newItem) ) { found = true; } } if( ! found ) { addItem(newItem); } } /** * Insert multiple items into the combo box. * * @param items The array of items. */ public void insertItems(String[] items) { for( String item : items ) { insertItem(item); } } /** * Get the text of the currently selected item in the combo box. * @return The text. <code>null</code> is returned if no item * is selected. */ public String getText() { Object o = getSelectedItem(); if( o != null ) { return o.toString().trim(); } return null; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import java.awt.BorderLayout; import java.util.Enumeration; import java.util.Properties; import javax.swing.DefaultCellEditor; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; /** * Dialog that is used to edit the collection of properties. * * @author Neil Taylor, Suzana Barreto */ public class PropertiesDialog { /** * The parent frame for the dialog that is displayed. */ private JFrame parentFrame = null; /** * Array that lists the labels for the buttons on the panel. */ private static Object[] options = {"OK", "Cancel" }; /** * The panel that holds the controls to show. */ private JPanel controls = null; /** * The configuration properties */ private Properties properties = null; /** * Table that is used to display the list of properties. */ private JTable propertiesTable; /** * Create a new instance. * * @param parentFrame The parent frame for the dialog. * @param props The properties lisst to display */ public PropertiesDialog(JFrame parentFrame, Properties props) { this.parentFrame = parentFrame; properties = props; controls = createControls(); } /** * Create the controls that are to be displayed in the system. * * @return A panel that contains the controls. */ protected final JPanel createControls( ) { JPanel panel = new JPanel(new BorderLayout()); propertiesTable = new JTable(new PropertiesModel()); ((DefaultCellEditor)propertiesTable.getDefaultEditor(String.class)).setClickCountToStart(1); JScrollPane scrollpane = new JScrollPane(propertiesTable,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); panel.add(scrollpane, BorderLayout.CENTER); return panel; } /** * Show the dialog and return the status code. * * @return The status code returned from the dialog. */ public int show( ) { int result = JOptionPane.showOptionDialog(parentFrame, controls, "Edit Properties", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, null); // cancel any edit in the table. If there is a cell editing, the getEditingColumn will // return a non-negative column number. This can be used to retreive the cell editor. // The code then gets the default editor and calls the stopCellEditing. If custom // editors are used, an additional check must be made to get the cell editor // for a specific cell. int column = propertiesTable.getEditingColumn(); if( column > -1 ) { TableCellEditor editor = propertiesTable.getDefaultEditor( propertiesTable.getColumnClass(column)); if( editor != null ) { editor.stopCellEditing(); } } return result; } /** * A table model that is used to show the properties. The model links directly * to the underlying properties object. As changes are made in the table, the * corresponding changes are made in the properties object. The user can only * edit the value column in the table. */ public class PropertiesModel extends AbstractTableModel { /** * Column names. */ private String columns[] = {"Property Name","Value"}; /** * Create a new instance of the model. If no properties object exists, * a default model is created. Note, this will allow the table to * continue editing, although this value will not be passed back to * the calling window. */ public PropertiesModel() { super(); if(properties == null) { properties = new Properties(); } } /** * Get the number of columns. * * @return The number of columns. */ public int getColumnCount() { return columns.length; } /** * Get the number of rows. * * @return The number of rows. */ public int getRowCount() { return properties.size(); } /** * Get the value that is at the specified cell. * * @param row The row for the cell. * @param col The column for the cell. * * @return The data value from the properties. */ public Object getValueAt(int row, int col) { if(col == 0) { return getKeyValue(row); } else { String key = getKeyValue(row); return properties.get(key); } } /** * Retrieve the column name for the specified column. * * @param col The column number. * * @return The column name. */ public String getColumnName(int col){ return columns[col]; } /** * Retrieve the column class. * * @param col The column number. * * @return The class for the object found at the column position. */ public Class getColumnClass(int col) { return getValueAt(0, col).getClass(); } /** * Determine if the cell can be edited. This model will only * allow the second column to be edited. * * @param row The cell row. * @param col The cell column. * * @param True if the cell can be edited. Otherwise, false. */ public boolean isCellEditable(int row, int col) { if(col == 1) { return true; } return false; } /** * Set the value for the specified cell. * * @param value The value to set. * @param row The row for the cell. * @param col The column. */ public void setValueAt(Object value, int row, int col) { String key = getKeyValue(row); properties.setProperty(key, ((String) value)); fireTableCellUpdated(row, col); } /** * Get the Key value for the specified row. * @param row The row. * @return A string that shows the key value. */ public String getKeyValue(int row) { int count = 0; Enumeration<Object> k = properties.keys(); while (k.hasMoreElements()) { String key = (String) k.nextElement(); if(count == row){ return key; } count++; } return null; } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import org.purl.sword.base.DepositResponse; import org.purl.sword.base.ServiceDocument; /** * Interface for any SWORD client implementation. */ public interface SWORDClient { /** * Set the server that is to be contacted on the next access. * * @param server The name of the server, e.g. www.aber.ac.uk * @param port The port number, e.g. 80. */ public void setServer( String server, int port ); /** * Set the user credentials that are to be used for subsequent accesses. * * @param username The username. * @param password The password. */ public void setCredentials( String username, String password ); /** * Clear the credentials settings on the client. */ public void clearCredentials(); /** * Set the proxy that is to be used for subsequent accesses. * * @param host The host name, e.g. cache.host.com. * @param port The port, e.g. 8080. */ public void setProxy( String host, int port ); /** * Get the status result returned from the most recent network test. * * @return An the status code and message. */ public Status getStatus( ); /** * Get a service document, specified in the URL. * * @param url The URL to connect to. * @return A ServiceDocument that contains the Service details that were * obained from the specified URL. * * @throws SWORDClientException If there is an error accessing the * URL. */ public ServiceDocument getServiceDocument( String url ) throws SWORDClientException; /** * Get a service document, specified in the URL. The document is accessed on * behalf of the specified user. * * @param url The URL to connect to. * @param onBehalfOf The username for the onBehalfOf access. * @return A ServiceDocument that contains the Service details that were * obained from the specified URL. * * @throws SWORDClientException If there is an error accessing the * URL. */ public ServiceDocument getServiceDocument(String url, String onBehalfOf ) throws SWORDClientException; /** * Post a file to the specified destination URL. * * @param message The message that defines the requirements for the operation. * * @return A DespoitResponse if the response is successful. If there was an error, * <code>null</code> should be returned. * * @throws SWORDClientException If there is an error accessing the URL. */ public DepositResponse postFile( PostMessage message ) throws SWORDClientException; }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.purl.sword.atom.Author; import org.purl.sword.atom.Content; import org.purl.sword.atom.Contributor; import org.purl.sword.atom.Generator; import org.purl.sword.atom.Link; import org.purl.sword.atom.Rights; import org.purl.sword.atom.Summary; import org.purl.sword.atom.Title; import org.purl.sword.base.Collection; import org.purl.sword.base.DepositResponse; import org.purl.sword.base.SWORDEntry; import org.purl.sword.base.ServiceDocument; import org.purl.sword.base.Workspace; import org.purl.sword.base.SwordAcceptPackaging; /** * Example implementation of a command line client. This can send out service * document requests and print out the results and process posting a file to * either a single or multiple destinations. The command line options are * initialised prior to calling the class. The options are passed into the * run(ClientOptions) method. * * @author Neil Taylor */ public class CmdClient implements ClientType { /** * The client that is used to process the service and post requests. */ private SWORDClient client; /** * List of the options that can be specified on the command line. */ private ClientOptions options; /** * The logger. */ private static Logger log = Logger.getLogger(CmdClient.class); /** * Create a new instance of the class and create an instance of the * client. */ public CmdClient( ) { client = new Client( ); } /** * Process the options that have been initialised from the command line. * This will call one of service(), post() or multiPost(). */ public void process() { if (options.getProxyHost() != null) { client.setProxy(options.getProxyHost(), options.getProxyPort()); } try { String accessType = options.getAccessType(); if (ClientOptions.TYPE_SERVICE.equals(accessType)) { service(); } else if (ClientOptions.TYPE_POST.equals(accessType)) { post(); } else if (ClientOptions.TYPE_MULTI_POST.equals(accessType) ) { System.out.println("checking multi-post"); multiPost(); } else { System.out.println("Access type not recognised."); } } catch ( MalformedURLException mex ) { System.out.println("The specified href was not valid: " + options.getHref() + " message: " + mex.getMessage()); } catch (SWORDClientException ex) { System.out.println("Exception: " + ex.getMessage()); log.error("Unable to process request", ex); } } /** * Process the service operation. Output the results of the service request. * * @throws SWORDClientException if there is an error processing the service request. * @throws MalformedURLException if there is an error with the URL for the service request. */ private void service() throws SWORDClientException, MalformedURLException { String href = options.getHref(); initialiseServer(href, options.getUsername(), options.getPassword()); ServiceDocument document = client.getServiceDocument(href, options.getOnBehalfOf()); Status status = client.getStatus(); System.out.println("The status is: " + status); if (status.getCode() == 200) { log.debug("message is: " + document.marshall()); System.out.println("\nThe following Details were retrieved: "); System.out.println("SWORD Version: " + document.getService().getVersion()); System.out.println("Supports NoOp? " + document.getService().isNoOp()); System.out.println("Supports Verbose? " + document.getService().isVerbose()); System.out.println("Max Upload File Size " + document.getService().getMaxUploadSize() +" kB"); Iterator<Workspace> workspaces = document.getService().getWorkspaces(); for (; workspaces.hasNext();) { Workspace workspace = workspaces.next(); System.out.println("\nWorkspace Title: '" + workspace.getTitle() + "'"); System.out.println("\n+ Collections ---"); // process the collections Iterator<Collection> collections = workspace .collectionIterator(); for (; collections.hasNext();) { Collection collection = collections.next(); System.out.println("\nCollection location: " + collection.getLocation()); System.out.println("Collection title: " + collection.getTitle()); System.out .println("Abstract: " + collection.getAbstract()); System.out.println("Collection Policy: " + collection.getCollectionPolicy()); System.out.println("Treatment: " + collection.getTreatment()); System.out.println("Mediation: " + collection.getMediation()); String[] accepts = collection.getAccepts(); if( accepts != null && accepts.length == 0 ) { System.out.println("Accepts: none specified"); } else { for (String s : accepts) { System.out.println("Accepts: " + s); } } List<SwordAcceptPackaging> acceptsPackaging = collection.getAcceptPackaging(); StringBuilder acceptPackagingList = new StringBuilder(); for(Iterator i = acceptsPackaging.iterator();i.hasNext();) { SwordAcceptPackaging accept = (SwordAcceptPackaging) i.next(); acceptPackagingList.append(accept.getContent()).append(" (").append(accept.getQualityValue()).append("), ").toString(); } System.out.println("Accepts Packaging: "+ acceptPackagingList.toString()); } System.out.println("+ End of Collections ---"); } } } /** * Perform a post. If any of the destination URL, the filename and the * filetype are missing, the user will be prompted to enter the values. * * @throws SWORDClientException if there is an error processing the post for a requested * destination. * @throws MalformedURLException if there is an error with the URL for the post. */ private void post() throws SWORDClientException, MalformedURLException { String url = options.getHref(); if( url == null ) { url = readLine("Please enter the URL for the deposit: "); } initialiseServer(url, options.getUsername(), options.getPassword()); String file = options.getFilename(); if( file == null ) { file = readLine("Please enter the filename to deposit: "); } String type = options.getFiletype(); if( type == null ) { type = readLine("Please enter the file type, e.g. application/zip: "); } PostMessage message = new PostMessage(); message.setFilepath(file); message.setDestination(url); message.setFiletype(type); message.setUseMD5(options.isMd5()); message.setVerbose(options.isVerbose()); message.setNoOp(options.isNoOp()); message.setFormatNamespace(options.getFormatNamespace()); message.setOnBehalfOf(options.getOnBehalfOf()); message.setChecksumError(options.getChecksumError()); message.setUserAgent(ClientConstants.SERVICE_NAME); processPost(message); } /** * Perform a multi-post. Iterate over the list of -dest arguments in the command line * options. For each -dest argument, attempt to post the file to the server. * * @throws SWORDClientException if there is an error processing the post for a requested * destination. * @throws MalformedURLException if there is an error with the URL for the post. */ private void multiPost() throws SWORDClientException, MalformedURLException { // request the common information String file = options.getFilename(); if( file == null ) { file = readLine("Please enter the filename to deposit: "); } String type = options.getFiletype(); if( type == null ) { type = readLine("Please enter the file type, e.g. application/zip: "); } // process this information for each of the specified destinations PostDestination destination; String url = null; Iterator<PostDestination> iterator = options.getMultiPost(); while( iterator.hasNext() ) { destination = iterator.next(); url = destination.getUrl(); initialiseServer(url, destination.getUsername(), destination.getPassword()); String onBehalfOf = destination.getOnBehalfOf(); if( onBehalfOf == null ) { onBehalfOf = ""; } else { onBehalfOf = " on behalf of: " + onBehalfOf; } System.out.println("Sending file to: " + url + " for: " + destination.getUsername() + onBehalfOf ); PostMessage message = new PostMessage(); message.setFilepath(file); message.setDestination(url); message.setFiletype(type); message.setUseMD5(options.isMd5()); message.setVerbose(options.isVerbose()); message.setNoOp(options.isNoOp()); message.setFormatNamespace(options.getFormatNamespace()); message.setOnBehalfOf(destination.getOnBehalfOf()); message.setChecksumError(options.getChecksumError()); message.setUserAgent(ClientConstants.SERVICE_NAME); processPost(message); } } /** * Process the post response. The message contains the list of arguments * for the post. The method will then print out the details of the * response. * * @parma message The post options. * * @exception SWORDClientException if there is an error accessing the * post response. */ protected void processPost(PostMessage message) throws SWORDClientException { DepositResponse response = client.postFile(message); System.out.println("The status is: " + client.getStatus()); if( response != null) { log.debug("message is: " + response.marshall()); // iterate over the data and output it SWORDEntry entry = response.getEntry(); System.out.println("Id: " + entry.getId()); Title title = entry.getTitle(); if( title != null ) { System.out.print("Title: " + title.getContent() + " type: " ); if( title.getType() != null ) { System.out.println(title.getType().toString()); } else { System.out.println("Not specified."); } } // process the authors Iterator<Author> authors = entry.getAuthors(); while( authors.hasNext() ) { Author author = authors.next(); System.out.println("Author - " + author.toString() ); } Iterator<String> categories = entry.getCategories(); while( categories.hasNext() ) { System.out.println("Category: " + categories.next()); } Iterator<Contributor> contributors = entry.getContributors(); while( contributors.hasNext() ) { Contributor contributor = contributors.next(); System.out.println("Contributor - " + contributor.toString()); } Iterator<Link> links = entry.getLinks(); while( links.hasNext() ) { Link link = links.next(); System.out.println(link.toString()); } Generator generator = entry.getGenerator(); if( generator != null ) { System.out.println("Generator - " + generator.toString()); } else { System.out.println("There is no generator"); } System.out.println( "Published: " + entry.getPublished()); Content content = entry.getContent(); if( content != null ) { System.out.println(content.toString()); } else { System.out.println("There is no content element."); } Rights right = entry.getRights(); if( right != null ) { System.out.println(right.toString()); } else { System.out.println("There is no right element."); } Summary summary = entry.getSummary(); if( summary != null ) { System.out.println(summary.toString()); } else { System.out.println("There is no summary element."); } System.out.println("Update: " + entry.getUpdated() ); System.out.println("Published: " + entry.getPublished()); System.out.println("Verbose Description: " + entry.getVerboseDescription()); System.out.println("Treatment: " + entry.getTreatment()); System.out.println("Packaging: " + entry.getPackaging()); if( entry.isNoOpSet() ) { System.out.println("NoOp: " + entry.isNoOp()); } } else { System.out.println("No valid Entry document was received from the server"); } } /** * Initialise the server. Set the server that will be connected to and * initialise any username and password. If the username and password are * either null or contain empty strings, the user credentials will be cleared. * * @param location The location to connect to. This is a URL, of the format, * http://a.host.com:port/. The host name and port number will * be extracted. If the port is not specified, a default port of * 80 will be used. * @param username The username. If this is null or an empty string, the basic * credentials will be cleared. * @param password The password. If this is null or an empty string, the basic * credentials will be cleared. * * @throws MalformedURLException if there is an error processing the URL. */ private void initialiseServer(String location, String username, String password) throws MalformedURLException { URL url = new URL(location); int port = url.getPort(); if( port == -1 ) { port = 80; } client.setServer(url.getHost(), port); if (username != null && username.length() > 0 && password != null && password.length() > 0 ) { log.info("Setting the username/password: " + username + " " + password); client.setCredentials(username, password); } else { client.clearCredentials(); } } /** * Read a line of text from System.in. If there is an error reading * from the input, the prompt will be redisplayed and the user asked * to try again. * * @param prompt The prompt to display before the prompt. * @return The string that is read from the line. */ private String readLine( String prompt ) { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); String result = null; boolean ok = false; while (!ok) { try { System.out.print(prompt); System.out.flush(); result = reader.readLine(); ok = true; } catch (IOException ex) { System.out.println("There was an error with your input. Please try again."); } } return result; } /** * Run the client and process the specified options. * * @param options The command line options. */ public void run( ClientOptions options ) { this.options = options; process( ); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.client; /** * Hold general constants for the client. * * @author Neil Taylor */ public class ClientConstants { /** * Current software version. */ public static final String CLIENT_VERSION = "1.1"; /** * the name of this application */ public static final String SERVICE_NAME = "CASIS Test Client"; /** * the name of this application */ public static final String NOT_DEFINED_TEXT = "Not defined"; /** * The logging property file. */ public static final String LOGGING_PROPERTY_FILE = "log4j.properties"; }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /** * Copyright (c) 2007, Aberystwyth University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of the Centre for Advanced Software and * Intelligent Systems (CASIS) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package org.purl.sword.client; import java.io.File; /** * Represents the details of a post to a server. The message holds all of the possible values * that are to be sent from the client to the server. Not all elements of the message * must be filled in. Any required fields are defined in the current SWORD specification. * * @author Neil Taylor */ public class PostMessage { /** * The local filepath for the file to upload/deposit. */ private String filepath; /** * The URL of the destination server. */ private String destination; /** * The filetype of the package that is to be uploaded. */ private String filetype; /** * The string with the username if the deposit is on behalf of another user. */ private String onBehalfOf; /** * True if an MD5 checksum should be sent with the deposit. */ private boolean useMD5; /** * True if the deposit is a test and should not result in an actual deposit. */ private boolean noOp; /** * True if the verbose operation is requested. */ private boolean verbose; /** * The packaging format for the deposit. */ private String packaging; /** * True if the deposit should simualte a checksum error. The client should check this * field to determine if a correct MD5 checksum should be sent or whether the checksum should * be modified so that it generates an error at the server. */ private boolean checksumError; /** * True if the deposit should corrupt the POST header. The client should check this * field to determine if a correct header should be sent or whether the header should * be modified so that it generates an error at the server. */ private boolean corruptRequest; /** * The Slug header value. */ private String slug; /** * The user agent name */ private String userAgent; /** * Get the filepath. * * @return The filepath. */ public String getFilepath() { return filepath; } /** * Get the filename. This is the last element of the filepath * that has been set in this class. */ public String getFilename() { File file = new File(filepath); return file.getName(); } /** * Set the filepath. * * @param filepath The filepath. */ public void setFilepath(String filepath) { this.filepath = filepath; } /** * Get the destination collection. * * @return The collection. */ public String getDestination() { return destination; } /** * Set the destination collection. * * @param destination The destination. */ public void setDestination(String destination) { this.destination = destination; } /** * Get the filetype. * @return The filetype. */ public String getFiletype() { return filetype; } /** * Set the filetype. * * @param filetype The filetype. */ public void setFiletype(String filetype) { this.filetype = filetype; } /** * Get the onBehalfOf value. * * @return The value. */ public String getOnBehalfOf() { return onBehalfOf; } /** * Set the onBehalfOf value. * * @param onBehalfOf The value. */ public void setOnBehalfOf(String onBehalfOf) { this.onBehalfOf = onBehalfOf; } /** * Get the MD5 status. * @return The value. */ public boolean isUseMD5() { return useMD5; } /** * Set the md5 state. * * @param useMD5 True if the message should use an MD5 checksum. */ public void setUseMD5(boolean useMD5) { this.useMD5 = useMD5; } /** * Get the no-op state. * * @return The value. */ public boolean isNoOp() { return noOp; } /** * Set the no-op state. * * @param noOp The no-op. */ public void setNoOp(boolean noOp) { this.noOp = noOp; } /** * Get the verbose value. * * @return The value. */ public boolean isVerbose() { return verbose; } /** * Set the verbose state. * * @param verbose True if the post message should send a * verbose header. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Get the packaging format. * * @return The value. */ public String getPackaging() { return packaging; } /** * Set the packaging format. * * @param formatNamespace The packaging format. */ public void setFormatNamespace(String packaging) { this.packaging = packaging; } /** * Get the status of the checksum error. * * @return True if the client should simulate a checksum error. */ public boolean getChecksumError() { return checksumError; } /** * Set the state of the checksum error. * * @param checksumError True if the item should include a checksum error. */ public void setChecksumError(boolean checksumError) { this.checksumError = checksumError; } /** * Get the status of the corrupt request flag. * * @return True if the client should corrupt the POST header. */ public boolean getCorruptRequest() { return corruptRequest; } /** * Set the state of the corrupt request flag. * * @param checksumError True if the item should corrupt the POST header. */ public void setCorruptRequest(boolean corruptRequest) { this.corruptRequest = corruptRequest; } /** * Set the Slug value. * * @param slug The value. */ public void setSlug(String slug) { this.slug = slug; } /** * Get the Slug value. * * @return The Slug. */ public String getSlug() { return this.slug; } /** * @return the userAgent */ public String getUserAgent() { return userAgent; } /** * Set the user agent * * @param userAgent the userAgent to set */ public void setUserAgent(String userAgent) { this.userAgent = userAgent; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; /** * An invalid media type has been detected during parsing. * * @author Neil Taylor */ public class InvalidMediaTypeException extends Exception { /** * Create a new instance and store the message. * * @param message The exception's message. */ public InvalidMediaTypeException( String message ) { super(message); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Updated extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "updated", Namespaces.NS_ATOM); public Updated() { super(XML_NAME); } public Updated(String uri) { this(); setContent(uri); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Category extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "category", Namespaces.NS_ATOM); public Category() { super(XML_NAME); } public Category(String uri) { this(); setContent(uri); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Attribute; import nu.xom.Element; import org.purl.sword.base.Namespaces; import org.purl.sword.base.SwordElementInterface; import org.purl.sword.base.UnmarshallException; import org.purl.sword.base.XmlElement; import org.apache.log4j.Logger; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.SwordValidationInfoType; import org.purl.sword.base.XmlName; /** * Represents an ATOM Generator element. * * @author Neil Taylor */ public class Generator extends XmlElement implements SwordElementInterface { /** * Label for the URI attribute. */ public static final String ATTRIBUTE_URI = "uri"; /** * Label for the version attribute. */ public static final String ATTRIBUTE_VERSION = "version"; /** * Local name for the element. */ @Deprecated public static final String ELEMENT_NAME = "generator"; /** * The content for the element. */ private String content; /** * The URI attribute. */ private String uri; /** * The version attribute. */ private String version; /** * The logger. */ private static Logger log = Logger.getLogger(Generator.class); /** * The Xml name details for the element. */ private static final XmlName XML_NAME = new XmlName( Namespaces.PREFIX_ATOM, "generator", Namespaces.NS_ATOM); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'generator'. */ public Generator() { super(XML_NAME); initialise(); } public static XmlName elementName() { return XML_NAME; } protected final void initialise() { content = null; version = null; uri = null; } /** * Marshal the data in the object to an Element object. * * @return The element. */ public Element marshall() { Element element = new Element(getQualifiedName(), xmlName.getNamespace()); if( content != null ) { element.appendChild(content); } if( uri != null ) { Attribute uriAttribute = new Attribute(ATTRIBUTE_URI, uri); element.addAttribute(uriAttribute); } if( version != null ) { Attribute versionAttribute = new Attribute(ATTRIBUTE_VERSION, version); element.addAttribute(versionAttribute); } return element; } /** * Unmarshal the specified Generator element into the data in this object. * * @param generator The generator element. * * @throws UnmarshallException If the specified element is not an atom:generator * element, or if there is an error accessing the data. */ public void unmarshall(Element generator) throws UnmarshallException { unmarshall(generator, null); } public SwordValidationInfo unmarshall(Element generator, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf(generator, xmlName)) { return handleIncorrectElement(generator, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeValidationItems = new ArrayList<SwordValidationInfo>(); try { initialise(); // get the attributes int attributeCount = generator.getAttributeCount(); Attribute attribute = null; for( int i = 0; i < attributeCount; i++ ) { attribute = generator.getAttribute(i); if( ATTRIBUTE_URI.equals(attribute.getQualifiedName())) { uri = attribute.getValue(); XmlName uriName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_URI, Namespaces.NS_ATOM); SwordValidationInfo info = new SwordValidationInfo(xmlName, uriName); info.setContentDescription(uri); attributeValidationItems.add(info); } else if( ATTRIBUTE_VERSION.equals(attribute.getQualifiedName())) { version = attribute.getValue(); XmlName versionName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_VERSION, Namespaces.NS_ATOM); SwordValidationInfo info = new SwordValidationInfo(xmlName, versionName); info.setContentDescription(version); attributeValidationItems.add(info); } else { XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), attribute.getLocalName(), attribute.getNamespaceURI()); SwordValidationInfo info = new SwordValidationInfo(xmlName, attributeName, SwordValidationInfo.UNKNOWN_ATTRIBUTE, SwordValidationInfoType.INFO); info.setContentDescription(attribute.getValue()); validationItems.add(info); } } int length = generator.getChildCount(); if( length > 0 ) { content = unmarshallString(generator); } } catch( Exception ex ) { log.error("Unable to parse an element in Generator: " + ex.getMessage()); throw new UnmarshallException("Unable to parse element in Generator", ex); } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeValidationItems, validationProperties); } return result; } /** * * @return */ public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } /** * * @param existing * @param attributeItems * @return */ public SwordValidationInfo validate(List<SwordValidationInfo> existing, List<SwordValidationInfo> attributeItems, Properties validationContext) { boolean validateAll = (existing == null); SwordValidationInfo result = new SwordValidationInfo(xmlName); result.setContentDescription(content); XmlName attributeName; if( content == null ) { result.addValidationInfo( new SwordValidationInfo(xmlName, SwordValidationInfo.MISSING_CONTENT, SwordValidationInfoType.WARNING)); } if( uri == null ) { attributeName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_URI, Namespaces.NS_ATOM); result.addAttributeValidationInfo( new SwordValidationInfo(xmlName, attributeName, SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, SwordValidationInfoType.WARNING)); } else if( validateAll && uri != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_URI, uri)); } if( version == null ) { attributeName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_VERSION, Namespaces.NS_ATOM); result.addAttributeValidationInfo( new SwordValidationInfo(xmlName, attributeName, SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, SwordValidationInfoType.WARNING)); } else if( validateAll && version != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_VERSION, version)); } result.addUnmarshallValidationInfo(existing, attributeItems); return result; } /** * Get the content. * * @return The content. */ public String getContent() { return content; } /** * Set the content. * * @param content The content. */ public void setContent(String content) { this.content = content; } /** * Get the URI. * * @return The URI. */ public String getUri() { return uri; } /** * Set the URI. * * @param uri The URI. */ public void setUri(String uri) { this.uri = uri; } /** * Get the version. * * @return The version. */ public String getVersion() { return version; } /** * Set the version. * * @param version The version. */ public void setVersion(String version) { this.version = version; } /** * Get a string representation. */ public String toString() { return "Generator - content: " + getContent() + " version: " + getVersion() + " uri: " + getUri(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Attribute; import nu.xom.Element; import org.apache.log4j.Logger; import org.purl.sword.base.Namespaces; import org.purl.sword.base.SwordElementInterface; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.SwordValidationInfoType; import org.purl.sword.base.UnmarshallException; import org.purl.sword.base.XmlElement; import org.purl.sword.base.XmlName; /** * Represents an ATOM Link element. * * @author Neil Taylor */ public class Link extends XmlElement implements SwordElementInterface { /** * Label for the href attribute. */ public static final String ATTRIBUTE_HREF = "href"; /** * Label for the rel attribute. */ public static final String ATTRIBUTE_REL = "rel"; /** * Label for the type attribute. */ public static final String ATTRIBUTE_TYPE = "type"; /** * Label for the hreflang attribute. */ public static final String ATTRIBUTE_HREF_LANG = "hreflang"; /** * Label for the title attribute. */ public static final String ATTRIBUTE_TITLE = "title"; /** * Label for the length attribute. */ public static final String ATTRIBUTE_LENGTH = "length"; /** * Local name for the element. */ @Deprecated public static final String ELEMENT_NAME = "link"; /** * Stores the href. */ private String href; /** * Stores the Rel attribute. */ private String rel; /** * Stores the type. */ private String type; /** * Stores the HREF lang. */ private String hreflang; /** * Stores the title. */ private String title; /** * Stores the length. */ private String length; /** * Stores the content. */ private String content; /** * The logger. */ private static Logger log = Logger.getLogger(Link.class); private static final XmlName XML_NAME = new XmlName( Namespaces.PREFIX_ATOM, "link", Namespaces.NS_ATOM); /** * Create a new instance and set prefix and local name to 'atom' and 'link', * respectively. */ public Link() { super(XML_NAME); } public static XmlName elementName() { return XML_NAME; } /** * Mashall the data stored in this object into Element objects. * * @return An element that holds the data associated with this object. */ public Element marshall() { Element element = new Element(getQualifiedName(), xmlName.getNamespace()); if( content != null ) { element.appendChild(content); } if( href != null ) { Attribute hrefAttribute = new Attribute(ATTRIBUTE_HREF, href); element.addAttribute(hrefAttribute); } if( rel != null ) { Attribute relAttribute = new Attribute(ATTRIBUTE_REL, rel); element.addAttribute(relAttribute); } if( type != null ) { Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type); element.addAttribute(typeAttribute); } if( hreflang != null ) { Attribute hreflangAttribute = new Attribute(ATTRIBUTE_HREF_LANG, hreflang); element.addAttribute(hreflangAttribute); } if( title != null ) { Attribute titleAttribute = new Attribute(ATTRIBUTE_TITLE, title); element.addAttribute(titleAttribute); } if( length != null ) { Attribute lengthAttribute = new Attribute(ATTRIBUTE_LENGTH, length); element.addAttribute(lengthAttribute); } return element; } /** * Unmarshall the contents of the Link element into the internal data objects * in this object. * * @param link The Link element to process. * * @throws UnmarshallException If the element does not contain an ATOM link * element, or if there is a problem processing the element or any * subelements. */ public void unmarshall(Element link) throws UnmarshallException { unmarshall(link, null); } public SwordValidationInfo unmarshall(Element link, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf(link, xmlName) ) { return handleIncorrectElement(link, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>(); try { // get the attributes int attributeCount = link.getAttributeCount(); Attribute attribute = null; for( int i = 0; i < attributeCount; i++ ) { attribute = link.getAttribute(i); if( ATTRIBUTE_HREF.equals(attribute.getQualifiedName())) { href = attribute.getValue(); if( validationProperties != null) { attributeItems.add(createValidAttributeInfo(ATTRIBUTE_HREF, href)); } } else if( ATTRIBUTE_REL.equals(attribute.getQualifiedName())) { rel = attribute.getValue(); if( validationProperties != null) { attributeItems.add(createValidAttributeInfo(ATTRIBUTE_REL, rel)); } } else if( ATTRIBUTE_TYPE.equals(attribute.getQualifiedName())) { type = attribute.getValue(); if( validationProperties != null) { attributeItems.add(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); } } else if( ATTRIBUTE_HREF_LANG.equals(attribute.getQualifiedName())) { hreflang = attribute.getValue(); if( validationProperties != null) { attributeItems.add(createValidAttributeInfo(ATTRIBUTE_HREF_LANG, hreflang)); } } else if( ATTRIBUTE_TITLE.equals(attribute.getQualifiedName())) { title = attribute.getValue(); if( validationProperties != null) { attributeItems.add(createValidAttributeInfo(ATTRIBUTE_TITLE, title)); } } else if( ATTRIBUTE_LENGTH.equals(attribute.getQualifiedName())) { length = attribute.getValue(); if( validationProperties != null) { attributeItems.add(createValidAttributeInfo(ATTRIBUTE_LENGTH, length)); } } else { XmlName attributeName = new XmlName(attribute); SwordValidationInfo unknown = new SwordValidationInfo(xmlName, attributeName, SwordValidationInfo.UNKNOWN_ATTRIBUTE, SwordValidationInfoType.INFO); unknown.setContentDescription(attribute.getValue()); attributeItems.add(unknown); } } if( link.getChildCount() > 0 ) { SwordValidationInfo content = new SwordValidationInfo(xmlName, "This element has content, but it is not used by SWORD", SwordValidationInfoType.INFO); validationItems.add(content); } } catch( Exception ex ) { log.error("Unable to parse an element in Link: " + ex.getMessage()); throw new UnmarshallException("Unable to parse element in link", ex); } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeItems, validationProperties); } return result; } public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } public SwordValidationInfo validate(List<SwordValidationInfo> elements, List<SwordValidationInfo> attributes, Properties validationContext) { boolean validateAll = (elements == null); SwordValidationInfo result = new SwordValidationInfo(xmlName); if( href == null ) { XmlName attributeName = new XmlName(xmlName.getPrefix(), ATTRIBUTE_HREF, xmlName.getNamespace()); SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, SwordValidationInfoType.ERROR); result.addAttributeValidationInfo(item); } if( validateAll ) { if( href != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF, href)); } if( rel != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_REL, rel)); } if( type != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); } if( hreflang != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF_LANG, hreflang)); } if( title != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_TITLE, title)); } if( length != null ) { result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_LENGTH, length)); } } result.addUnmarshallValidationInfo(elements, attributes); return result; } /** * Get the HREF attribute. * * @return The HREF. */ public String getHref() { return href; } /** * Set the HREF attribute. * * @param href The href. */ public void setHref(String href) { this.href = href; } /** * Get the Rel attribute. * * @return The Rel. */ public String getRel() { return rel; } /** * Set the Rel attribute. * * @param rel The Rel. */ public void setRel(String rel) { this.rel = rel; } /** * Get the type. * * @return The type. */ public String getType() { return type; } /** * Set the type. * @param type The type. */ public void setType(String type) { this.type = type; } /** * Get the HREF Lang attribute. * * @return The HREF Lang. */ public String getHreflang() { return hreflang; } /** * Set the HREF Lang attribute. * * @param hreflang The HREF Lang. */ public void setHreflang(String hreflang) { this.hreflang = hreflang; } /** * Get the title. * * @return The title. */ public String getTitle() { return title; } /** * Set the title. * * @param title The title. */ public void setTitle(String title) { this.title = title; } /** * Get the length. * * @return The length. */ public String getLength() { return length; } /** * Set the length. * * @param length The length. */ public void setLength(String length) { this.length = length; } /** * Get the content. * * @return The content. */ public String getContent() { return content; } /** * Set the content. * * @param content The content. */ public void setContent(String content) { this.content = content; } public String toString() { return "Link -" + " href: " + getHref() + " hreflang: " + getHreflang() + " title: " + getTitle() + " rel: " + getRel() + " content: " + getContent() + " type: " + getType() + " length: " + getLength(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.Namespaces; import org.purl.sword.base.XmlName; /** * Represents an ATOM Contributor. * * @author Neil Taylor */ public class Contributor extends Author { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "contributor", Namespaces.NS_ATOM); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'contributor'. */ public Contributor() { super(XML_NAME); } /** * Get the element name for this Xml Element. * * @return The details of prefix, localname and namespace. */ public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Email extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "email", Namespaces.NS_ATOM); public Email() { super(XML_NAME); } public Email(String email) { this(); setContent(email); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Attribute; import nu.xom.Element; import org.purl.sword.base.Namespaces; import org.purl.sword.base.SwordElementInterface; import org.purl.sword.base.UnmarshallException; import org.purl.sword.base.XmlElement; import org.apache.log4j.Logger; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.SwordValidationInfoType; import org.purl.sword.base.XmlName; /** * Represents an ATOM Content element. * * @author Neil Taylor */ public class Content extends XmlElement implements SwordElementInterface { /** * The identifier for the src attribute. */ public static final String ATTRIBUTE_SRC = "src"; /** * The identifier for the type attribute. */ public static final String ATTRIBUTE_TYPE = "type"; /** * The data for the type attribute. */ private String type; /** * The data for the source attribute. */ private String source; /** * The log. */ private static Logger log = Logger.getLogger(Content.class); /** * */ private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "content", Namespaces.NS_ATOM); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'content'. */ public Content() { super(XML_NAME); } public static XmlName elementName() { return XML_NAME; } /** * Get the Source. * * @return The Source. */ public String getSource() { return source; } /** * Set the Source. * * @param source The source. */ public void setSource(String source) { this.source = source; } /** * Get the type. * * @return The type. */ public String getType() { return type; } /** * Set the type for the content. This should match the pattern * ".* /.*" [Note, there is no space before the /, this has been added * to allow this text to be written in a Java comment.]. * * An example of the type is <code>application/zip</code>. * * @param type The specified type. * @throws InvalidMediaTypeException If the specified type is null or * it does not match the specified pattern. */ public void setType(String type) throws InvalidMediaTypeException { if( type == null || ! type.matches(".*/.*") ) { throw new InvalidMediaTypeException("Type: '" + type + "' does not match .*/.*"); } this.type = type; } /** * Marshall the data in this object to an Element object. * * @return A XOM Element that holds the data for this Content element. */ public Element marshall() { Element content = new Element(getQualifiedName(), Namespaces.NS_ATOM); if( type != null ) { Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type); content.addAttribute(typeAttribute); } if( source != null ) { Attribute typeAttribute = new Attribute(ATTRIBUTE_SRC, source); content.addAttribute(typeAttribute); } return content; } public void unmarshall(Element content) throws UnmarshallException { unmarshall(content, null); } /** * Unmarshall the content element into the data in this object. * * @throws UnmarshallException If the element does not contain a * content element or if there are problems * accessing the data. */ public SwordValidationInfo unmarshall(Element content, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf( content, xmlName.getLocalName(), Namespaces.NS_ATOM)) { return handleIncorrectElement(content, validationProperties); } ArrayList<SwordValidationInfo> elements = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributes = new ArrayList<SwordValidationInfo>(); try { // get the attributes int attributeCount = content.getAttributeCount(); Attribute attribute = null; for( int i = 0; i < attributeCount; i++ ) { attribute = content.getAttribute(i); String name = attribute.getQualifiedName(); if( ATTRIBUTE_TYPE.equals(name)) { type = attribute.getValue(); if( validationProperties != null ) { attributes.add(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); } } else if( ATTRIBUTE_SRC.equals(name) ) { source = attribute.getValue(); if( validationProperties != null ) { attributes.add(createValidAttributeInfo(ATTRIBUTE_SRC, source)); } } else { SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(attribute), SwordValidationInfo.UNKNOWN_ATTRIBUTE, SwordValidationInfoType.INFO ); info.setContentDescription(attribute.getValue()); attributes.add(info); } } // check if there is any content. If there is, add a simple message to // say that there are sub elements that are not used in this profile if( content.getChildCount() > 0 ) { elements.add(new SwordValidationInfo(xmlName, "This element has child elements. These are not expected as part of the SWORD profile", SwordValidationInfoType.INFO)); } } catch( Exception ex ) { log.error("Unable to parse an element in Content: " + ex.getMessage()); throw new UnmarshallException("Error parsing Content", ex); } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(elements, attributes, validationProperties); } return result; } public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } /** * * @param elements * @param attributes * @return */ protected SwordValidationInfo validate(List<SwordValidationInfo> elements, List<SwordValidationInfo> attributes, Properties validationContext) { SwordValidationInfo info = new SwordValidationInfo(xmlName); if( source == null ) { XmlName attributeName = new XmlName(xmlName.getPrefix(), ATTRIBUTE_SRC, xmlName.getNamespace()); SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, SwordValidationInfoType.ERROR); info.addValidationInfo(item); } info.addUnmarshallValidationInfo(elements, attributes); return info; } /** * Get a string representation. * * @return String */ @Override public String toString() { return "Content - source: " + getSource() + " type: " + getType(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Element; import nu.xom.Elements; import org.purl.sword.base.Namespaces; import org.purl.sword.base.SwordElementInterface; import org.purl.sword.base.UnmarshallException; import org.purl.sword.base.XmlElement; import org.purl.sword.base.XmlName; import org.apache.log4j.Logger; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.SwordValidationInfoType; /** * Represents an ATOM Generator element. * * @author Neil Taylor */ public class Source extends XmlElement implements SwordElementInterface { /** * Local name for the element. */ private static final XmlName XML_NAME = new XmlName( Namespaces.PREFIX_ATOM, "source", Namespaces.NS_ATOM); /** * The generator data for this object. */ private Generator generator; /** * The log. */ private static Logger log = Logger.getLogger(Source.class); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'source'. */ public Source() { super(XML_NAME); } public static XmlName elementName() { return XML_NAME; } /** * Marshal the data stored in this object into Element objects. * * @return An element that holds the data associated with this object. */ public Element marshall() { Element source = new Element(getQualifiedName(), xmlName.getNamespace()); if( generator != null ) { source.appendChild(generator.marshall()); } return source; } /** * Unmarshal the contents of the source element into the internal data objects * in this object. * * @param source The Source element to process. * * @throws UnmarshallException If the element does not contain an ATOM Source * element, or if there is a problem processing the element or any * sub-elements. */ public void unmarshall(Element source) throws UnmarshallException { unmarshall(source, null); } /** * * @param source * @param validationProperties * @return * @throws org.purl.sword.base.UnmarshallException */ public SwordValidationInfo unmarshall(Element source, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf(source, xmlName.getLocalName(), Namespaces.NS_ATOM)) { //throw new UnmarshallException( "Not an atom:source element" ); return handleIncorrectElement(source, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>(); try { processUnexpectedAttributes(source, attributeItems); // retrieve all of the sub-elements Elements elements = source.getChildElements(); Element element = null; int length = elements.size(); for(int i = 0; i < length; i++ ) { element = elements.get(i); if( isInstanceOf(element, Generator.elementName()) ) { generator = new Generator(); generator.unmarshall(element); } else { SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), SwordValidationInfo.UNKNOWN_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } } catch( Exception ex ) { log.error("Unable to parse an element in Source: " + ex.getMessage()); throw new UnmarshallException("Unable to parse an element in Source", ex); } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeItems, validationProperties); } return result; } public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } public SwordValidationInfo validate(List<SwordValidationInfo> elements, List<SwordValidationInfo> attributes, Properties validationContext) { SwordValidationInfo result = new SwordValidationInfo(xmlName); result.addUnmarshallValidationInfo(elements, attributes); return result; } /** * Get the generator. * * @return The generator. */ public Generator getGenerator() { return generator; } /** * Set the generator. * * @param generator The generator. */ public void setGenerator(Generator generator) { this.generator = generator; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Attribute; import nu.xom.Element; import org.purl.sword.base.Namespaces; import org.purl.sword.base.SwordElementInterface; import org.purl.sword.base.UnmarshallException; import org.purl.sword.base.XmlElement; import org.apache.log4j.Logger; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.SwordValidationInfoType; import org.purl.sword.base.XmlName; /** * Represents a text construct in the ATOM elements. This is a superclass of * several elements within this implementation. * * @author Neil Taylor */ public class TextConstruct extends XmlElement implements SwordElementInterface { /** * The content in the element. */ private String content; /** * The type of the element. */ private ContentType type; /** * The log. */ private static Logger log = Logger.getLogger(TextConstruct.class); /** * label for the type attribute. */ public static final String ATTRIBUTE_TYPE = "type"; /** * Create a new instance, specifying the prefix and local name. * * @param prefix The prefix. * @param name The local name. */ public TextConstruct(String prefix, String name) { this(prefix, name, Namespaces.NS_ATOM); } /** * Create a new instance. Set the default type to TextConstructType.TEXT. * * @param name The name that will be applied. */ public TextConstruct(String name) { this(Namespaces.PREFIX_ATOM, name); } /** * Create a new instance. Set the XML name for the element. * * @param name The name to set. */ public TextConstruct(XmlName name) { super(name); } /** * * @param prefix * @param name * @param namespaceUri */ public TextConstruct(String prefix, String name, String namespaceUri) { super(prefix, name, namespaceUri); initialise(); } /** * */ protected final void initialise() { this.type = ContentType.TEXT; this.content = null; } /** * Marshal the data in this object to an Element object. * * @return The data expressed in an Element. */ public Element marshall() { Element element = new Element(getQualifiedName(), Namespaces.NS_ATOM); if( type != null ) { Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type.toString()); element.addAttribute(typeAttribute); } if( content != null ) { element.appendChild(content); } return element; } /** * Unmarshal the text element into this object. * * This unmarshaller only handles plain text content, although it can * recognise the three different type elements of text, html and xhtml. This * is an area that can be improved in a future implementation, if necessary. * * @param text The text element. * * @throws UnmarshallException If the specified element is not of * the correct type, where the localname is used * to specify the valid name. Also thrown * if there is an issue accessing the data. */ public void unmarshall(Element text) throws UnmarshallException { unmarshall(text, null); } /** * * @param text * @param validationProperties * @return * @throws org.purl.sword.base.UnmarshallException */ public SwordValidationInfo unmarshall(Element text, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf(text, xmlName)) { return handleIncorrectElement(text, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>(); try { initialise(); // get the attributes int attributeCount = text.getAttributeCount(); Attribute attribute = null; for( int i = 0; i < attributeCount; i++ ) { attribute = text.getAttribute(i); if( ATTRIBUTE_TYPE.equals(attribute.getQualifiedName())) { boolean success = true; String value = attribute.getValue(); if( ContentType.TEXT.toString().equals(value) ) { type = ContentType.TEXT; } else if( ContentType.HTML.toString().equals(value) ) { type = ContentType.HTML; } else if( ContentType.XHTML.toString().equals(value) ) { type = ContentType.XHTML; } else { log.error("Unable to parse extract type in " + getQualifiedName() ); SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(attribute), "Invalid content type has been specified", SwordValidationInfoType.ERROR); info.setContentDescription(value); attributeItems.add(info); success = false; } if( success ) { SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(attribute)); info.setContentDescription(type.toString()); attributeItems.add(info); } } else { SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(attribute), SwordValidationInfo.UNKNOWN_ATTRIBUTE, SwordValidationInfoType.INFO); info.setContentDescription(attribute.getValue()); attributeItems.add(info); } } // retrieve all of the sub-elements int length = text.getChildCount(); if( length > 0 ) { content = unmarshallString(text); } } catch( Exception ex ) { log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); } SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeItems, validationProperties); } return result; } public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } /** * * @param existing * @param attributeItems * @return */ protected SwordValidationInfo validate(List<SwordValidationInfo> existing, List<SwordValidationInfo> attributeItems, Properties validationContext) { boolean validateAll = (existing == null); SwordValidationInfo result = new SwordValidationInfo(xmlName); result.setContentDescription(content); // item specific rules if( content == null ) { result.addValidationInfo( new SwordValidationInfo(xmlName, "Missing content for element", SwordValidationInfoType.WARNING)); } if( validateAll ) { SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(xmlName.getPrefix(), ATTRIBUTE_TYPE, xmlName.getNamespace())); info.setContentDescription(type.toString()); result.addAttributeValidationInfo(info); } result.addUnmarshallValidationInfo(existing, attributeItems); return result; } /** * Get the content in this TextConstruct. * * @return The content, expressed as a string. */ public String getContent() { return content; } /** * Set the content. This only supports text content. * * @param content The content. */ public void setContent(String content) { this.content = content; } /** * Get the type. * * @return The type. */ public ContentType getType() { return type; } /** * Set the type. * * @param type The type. */ public void setType(ContentType type) { this.type = type; } /** * Get a string representation. * * @return The string. */ public String toString() { return "Summary - content: " + getContent() + " type: " + getType(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Id extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "id", Namespaces.NS_ATOM); public Id() { super(XML_NAME); } public Id(String uri) { this(); setContent(uri); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.Namespaces; import org.purl.sword.base.XmlName; /** * Represents an ATOM Rights element. This is a simple subclass of the * TextConstruct class. * * @author Neil Taylor */ public class Rights extends TextConstruct { /** * Local name for the element. */ private static final XmlName XML_NAME = new XmlName( Namespaces.PREFIX_ATOM, "rights", Namespaces.NS_ATOM); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'rights'. */ public Rights() { super(XML_NAME); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.Namespaces; import org.purl.sword.base.XmlName; /** * Represents an ATOM Title element. This is a simple subclass of the * TextConstruct class. * * @author Neil Taylor */ public class Title extends TextConstruct { /** * Local name part of the element. */ @Deprecated public static final String ELEMENT_NAME = "title"; /** * XML Name representation. */ private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "title", Namespaces.NS_ATOM); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'title'. */ public Title() { super(XML_NAME); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Accept extends BasicStringContentElement { /** * The XmlName representation for this element. */ private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_APP, "accept", Namespaces.NS_APP); public Accept() { super(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace()); } public Accept(String version) { this(); setContent(version); } /** * Get the XmlName for this class. * * @return The prefix, localname and namespace for this element. */ public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import nu.xom.Element; import nu.xom.Elements; import org.apache.log4j.Logger; import org.purl.sword.base.HttpHeaders; import org.purl.sword.base.Namespaces; import org.purl.sword.base.SwordElementInterface; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.SwordValidationInfoType; import org.purl.sword.base.UnmarshallException; import org.purl.sword.base.XmlElement; import org.purl.sword.base.XmlName; /** * Represents an ATOM entry. * * @author Neil Taylor * */ public class Entry extends XmlElement implements SwordElementInterface { /** * Local name for the element. */ @Deprecated public static final String ELEMENT_NAME = "entry"; /** * Local name for the atom id element. */ @Deprecated public static final String ELEMENT_ID = "id"; /** * Local name for the atom published element. */ @Deprecated public static final String ELEMENT_PUBLISHED = "published"; /** * Local name for the atom updated element. */ @Deprecated public static final String ELEMENT_UPDATED = "updated"; /** * Local name for the atom category element. */ @Deprecated public static final String ELEMENT_CATEGORY = "category"; /** * Local name for the atom generator element. */ @Deprecated public static final String ELEMENT_GENERATOR = "generator"; /** * A list of authors associated with this entry. There can be 0 * or more of these elements. */ private List<Author> authors; /** * The atom:category data. There can be 0 or more of these elements. */ private List<Category> categories; /** * A single content element for the Entry. */ private Content content; /** * A single content element for the Entry. */ private Generator generator; /** * A list of contributors associated with this entry. There can be 0 or * more of these elements. */ private List<Contributor> contributors; /** * This is a simplified version. The ID can also have atomCommonAttributes, * but these have not been modeled in this version. The content of * ID is an unconstrained string, which is intended to represent a URI. */ private Id id; /** * A list of link elements. This can contain 0 or more entries. */ private List<Link> links; /** * Simplified version of the atom:published element. This implementation * does not record the general atomCommonAttributes. The date is * taken from an xsd:dateTime value. * * This item is optional. */ private Published published; /** * A single, optional, content element for the Entry. */ private Rights rights; /** * A single, optional, content element for the Entry. */ @Deprecated private Source source; /** * A single, optional, summary element for the Entry. */ private Summary summary; /** * A required title element for the entry. */ private Title title; /** * The date on which the entry was last updated. */ private Updated updated; /** * The log. */ private static Logger log = Logger.getLogger(Entry.class); /** * The prefix, local name and namespace used for this element. */ private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "entry", Namespaces.NS_ATOM); /** * Create a new instance of the class and initialise it. * Also, set the prefix to 'atom' and the local name to 'entry'. */ public Entry() { this(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace()); } /** * Create a new instance of the class an initalise it, setting the * element namespace and name. * * @param prefix The namespace prefix of the element * @param element The element name */ public Entry(String prefix, String element) { this(prefix, element, XML_NAME.getNamespace()); } /** * * @param prefix * @param element * @param namespaceUri */ public Entry(String prefix, String element, String namespaceUri) { super(prefix, element, namespaceUri); initialise(); } public Entry(XmlName name) { this(name.getPrefix(), name.getLocalName(), name.getNamespace()); } public static XmlName elementName() { return XML_NAME; } protected boolean isElementChecked(XmlName elementName) { if( elementName == null ) { return false; } return elementName.equals(Author.elementName()) | elementName.equals(Category.elementName()) | elementName.equals(Content.elementName()) | elementName.equals(Generator.elementName()) | elementName.equals(Contributor.elementName()) | elementName.equals(Id.elementName()) | elementName.equals(Link.elementName()) | elementName.equals(Published.elementName()) | elementName.equals(Rights.elementName()) | elementName.equals(Source.elementName()) | elementName.equals(Summary.elementName()) | elementName.equals(Title.elementName()) | elementName.equals(Updated.elementName()); } /** * */ protected void initialise() { authors = new ArrayList<Author>(); categories = new ArrayList<Category>(); contributors = new ArrayList<Contributor>(); links = new ArrayList<Link>(); } /** * Marshal the data stored in this object into Element objects. * * @return An element that holds the data associated with this object. */ public Element marshall() { Element entry = new Element(getQualifiedName(), Namespaces.NS_ATOM); entry.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD); entry.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM); this.marshallElements(entry); return entry; } protected void marshallElements(Element entry) { if (id != null) { entry.appendChild(id.marshall()); } for (Author author : authors) { entry.appendChild(author.marshall()); } if (content != null) { entry.appendChild(content.marshall()); } if (generator != null) { entry.appendChild(generator.marshall()); } for (Author contributor : contributors) { entry.appendChild(contributor.marshall()); } for (Link link : links) { entry.appendChild(link.marshall()); } if (published != null) { entry.appendChild(published.marshall()); } if (rights != null) { entry.appendChild(rights.marshall()); } if (summary != null) { entry.appendChild(summary.marshall()); } if (title != null) { entry.appendChild(title.marshall()); } if (source != null) { entry.appendChild(source.marshall()); } if (updated != null) { entry.appendChild(updated.marshall()); } for (Category category : categories) { entry.appendChild(category.marshall()); } } /** * Unmarshal the contents of the Entry element into the internal data objects * in this object. * * @param entry The Entry element to process. * * @throws UnmarshallException If the element does not contain an ATOM entry * element, or if there is a problem processing the element or any * subelements. */ public void unmarshall(Element entry) throws UnmarshallException { unmarshall(entry, null); } public SwordValidationInfo unmarshallWithoutValidate(Element entry, Properties validationProperties) throws UnmarshallException { if (! isInstanceOf(entry, xmlName) ) { return handleIncorrectElement(entry, validationProperties); } // used to hold the element and attribute unmarshal info results SwordValidationInfo result = new SwordValidationInfo(xmlName); try { initialise(); // FIXME - attributes? // retrieve all of the sub-elements Elements elements = entry.getChildElements(); Element element = null; int length = elements.size(); for (int i = 0; i < length; i++) { element = elements.get(i); if (isInstanceOf(element, Author.elementName())) { Author author = new Author(); result.addUnmarshallElementInfo(author.unmarshall(element, validationProperties)); authors.add(author); } else if (isInstanceOf(element, Category.elementName())) { Category category = new Category(); result.addUnmarshallElementInfo(category.unmarshall(element, validationProperties)); categories.add(category); } else if (isInstanceOf(element, Content.elementName())) { if( content == null ) { content = new Content(); result.addUnmarshallElementInfo(content.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Content.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Generator.elementName())) { if( generator == null ) { generator = new Generator(); result.addUnmarshallElementInfo(generator.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Contributor.elementName())) { Contributor contributor = new Contributor(); result.addUnmarshallElementInfo(contributor.unmarshall(element, validationProperties)); contributors.add(contributor); } else if (isInstanceOf(element, Id.elementName())) { if( id == null ) { id = new Id(); result.addUnmarshallElementInfo(id.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Id.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Link.elementName())) { Link link = new Link(); result.addUnmarshallElementInfo(link.unmarshall(element, validationProperties)); links.add(link); } else if (isInstanceOf(element, Published.elementName())) { if( published == null ) { published = new Published(); result.addUnmarshallElementInfo(published.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Published.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Rights.elementName())) { if( rights == null ) { rights = new Rights(); result.addUnmarshallElementInfo(rights.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Rights.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Summary.elementName())) { if( summary == null ) { summary = new Summary(); result.addUnmarshallElementInfo(summary.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Summary.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Title.elementName())) { if( title == null ) { title = new Title(); result.addUnmarshallElementInfo(title.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Title.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Updated.elementName())) { if( updated == null ) { updated = new Updated(); result.addUnmarshallElementInfo(updated.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Updated.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if (isInstanceOf(element, Source.elementName())) { if( source == null ) { source = new Source(); result.addUnmarshallElementInfo(source.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(Source.elementName(), SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.WARNING); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } else if( validationProperties != null ) { XmlName name = new XmlName(element); if( ! isElementChecked(name) ) { SwordValidationInfo info = new SwordValidationInfo(name, SwordValidationInfo.UNKNOWN_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); result.addUnmarshallElementInfo(info); } } } // for } catch (Exception ex) { log.error("Unable to parse an element in Entry: " + ex.getMessage()); ex.printStackTrace(); throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); } return result; } public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) throws UnmarshallException { SwordValidationInfo result = unmarshallWithoutValidate(entry, validationProperties); if( validationProperties != null ) { result = validate(result, validationProperties); } return result; } /** * * @return */ public SwordValidationInfo validate(Properties validationContext) { return validate(null, validationContext); } /** * * @param info * @param validationContext * @return */ protected SwordValidationInfo validate(SwordValidationInfo info, Properties validationContext) { // determine if a full validation is required boolean validateAll = (info == null); SwordValidationInfo result = info; if( result == null ) { result = new SwordValidationInfo(xmlName); } // id, title an updated are required if( id == null ) { result.addValidationInfo(new SwordValidationInfo(Id.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR, SwordValidationInfoType.ERROR)); } else if( id != null && validateAll ) { result.addValidationInfo(id.validate(validationContext)); } if( title == null ) { result.addValidationInfo(new SwordValidationInfo(Title.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR, SwordValidationInfoType.ERROR)); } else if( title != null && validateAll ) { result.addValidationInfo(title.validate(validationContext)); } if( updated == null ) { result.addValidationInfo(new SwordValidationInfo(Updated.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR, SwordValidationInfoType.ERROR)); } else if( updated != null && validateAll ) { result.addValidationInfo(updated.validate(validationContext)); } // additional sword requirements on the element if( contributors.isEmpty() ) { String contributor = validationContext.getProperty(HttpHeaders.X_ON_BEHALF_OF); if( contributor != null ) { result.addValidationInfo(new SwordValidationInfo(Contributor.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR + " This item SHOULD contain the value of the X-On-Behalf-Of header, if one was present in the POST request.", SwordValidationInfoType.ERROR)); } } else if( (! contributors.isEmpty()) && validateAll ) { Iterator<Contributor> iterator = contributors.iterator(); while( iterator.hasNext() ) { Contributor contributor = iterator.next(); result.addValidationInfo(contributor.validate(validationContext)); } } if( generator == null ) { result.addValidationInfo(new SwordValidationInfo(Generator.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR + " SHOULD contain the URI and version of the server software.", SwordValidationInfoType.ERROR)); } else if( generator != null && validateAll ) { result.addValidationInfo(generator.validate(validationContext)); } if( validateAll ) { // process the remaining items Iterator<Link> linksIterator = links.iterator(); while( linksIterator.hasNext() ) { Link link = linksIterator.next(); result.addValidationInfo(link.validate(validationContext)); } Iterator<Author> authorIterator = authors.iterator(); while( authorIterator.hasNext() ) { Author author = authorIterator.next(); result.addValidationInfo(author.validate(validationContext)); } if( content != null ) { result.addValidationInfo(content.validate(validationContext)); } if( published != null ) { result.addValidationInfo(published.validate(validationContext)); } if( rights != null ) { result.addValidationInfo(rights.validate(validationContext)); } if( summary != null ) { result.addValidationInfo(summary.validate(validationContext)); } Iterator<Category> categoryIterator = categories.iterator(); while( categoryIterator.hasNext() ) { Category category = categoryIterator.next(); result.addValidationInfo(category.validate(validationContext)); } } return result; } /** * Get an iterator for the authors in the Entry. * * @return An iterator. */ public Iterator<Author> getAuthors() { return authors.iterator(); } /** * Add an author to the Entry. * * @param author The author to add. */ public void addAuthors(Author author) { this.authors.add(author); } /** * Clear the list of authors. */ public void clearAuthors() { this.authors.clear(); } /** * Get an iterator for the categories in this Entry. * * @return An iterator. */ public Iterator<String> getCategories() { ArrayList<String> items = new ArrayList<String>(); for( int i = 0; i < categories.size(); i++ ) { items.add(categories.get(i).getContent()); } return items.iterator(); } /** * Add a category. * * @param category the category to add. */ public void addCategory(String category) { this.categories.add(new Category(category)); } /** * Clear the list of categories. */ public void clearCategories() { this.categories.clear(); } /** * Get the content element for this Entry. * * @return The content element. */ public Content getContent() { return content; } /** * Set the content element for this Entry. * @param content */ public void setContent(Content content) { this.content = content; } /** * Get the generator for this Entry. * * @return The generator element. */ public Generator getGenerator() { return generator; } /** * Set the generator for this Entry. * @param generator */ public void setGenerator(Generator generator) { this.generator = generator; } /** * Get a list of contributors. * * @return An iterator. */ public Iterator<Contributor> getContributors() { return contributors.iterator(); } /** * Add a contributor. * * @param contributor The contributor. */ public void addContributor(Contributor contributor) { this.contributors.add(contributor); } /** * Clear the list of contributors. */ public void clearContributors() { this.contributors.clear(); } /** * Get the ID for this Entry. * * @return The ID. */ public String getId() { if( id == null ) { return null; } return id.getContent(); } /** * Set the ID for this Entry. * * @param id The ID. */ public void setId(String id) { this.id = new Id(id); } /** * Get the list of links for this Entry. * * @return An iterator. */ public Iterator<Link> getLinks() { return links.iterator(); } /** * Get the link for this Entry. * * @param link The link. */ public void addLink(Link link) { this.links.add(link); } /** * Clear the list of links. */ public void clearLinks() { this.links.clear(); } /** * Get the published date, expressed as a String. * * @return The date. */ public String getPublished() { if( published == null ) { return null; } return published.getContent(); } /** * Set the published date. The date should be in one of the * supported formats. This method will not check that the string * is in the correct format. * * @param published The string. */ public void setPublished(String published) { this.published = new Published(published); } /** * Get the rights for this Entry. * @return The rights. */ public Rights getRights() { return rights; } /** * Set the rights for this Entry. * * @param rights The rights. */ public void setRights(Rights rights) { this.rights = rights; } /** * Get the source for this Entry. * @return The source. * @deprecated */ @Deprecated public Source getSource() { return source; } /** * Set the source for this entry. * * @param source The source. * @deprecated */ @Deprecated public void setSource(Source source) { this.source = source; } /** * Get the summary. * * @return The summary. */ public Summary getSummary() { return summary; } /** * Set the summary. * * @param summary The summary. */ public void setSummary(Summary summary) { this.summary = summary; } /** * Get the title. * * @return The title. */ public Title getTitle() { return title; } /** * Set the title. * * @param title The title. */ public void setTitle(Title title) { this.title = title; } /** * Get the updated date, expressed as a String. See * org.purl.sword.XmlElement.stringToDate for the * list of supported formats. This particular method * will not check if the date is formatted correctly. * * @return The date. */ public String getUpdated() { if( updated == null ) { return null; } return updated.getContent(); } /** * Set the updated date. The date should match one of the * supported formats. This method will not check the format of the * string. * * @param updated The string. * @see Entry#setPublished(String) setPublished */ public void setUpdated(String updated) { this.updated = new Updated(updated); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; /** * Represents a content type for a text element. * * @author Neil Taylor */ public enum ContentType { TEXT ("text"), HTML ("html"), XHTML ("xhtml"); /** * String representation of the type. */ private final String type; /** * Create a new instance and set the string * representation of the type. * * @param type The type, expressed as a string. */ private ContentType(String type) { this.type = type; } /** * Retrieve a string representation of this object. * * @return A string. */ @Override public String toString() { return this.type; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Published extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "published", Namespaces.NS_ATOM); public Published() { super(XML_NAME); } public Published(String uri) { this(); setContent(uri); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.Namespaces; import org.purl.sword.base.XmlName; /** * Represents an ATOM Summary element. This is a simple subclass of the * TextConstruct class. * * @author Neil Taylor */ public class Summary extends TextConstruct { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "summary", Namespaces.NS_ATOM); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'summary'. */ public Summary() { super(XML_NAME); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import java.util.ArrayList; import java.util.List; import java.util.Properties; import nu.xom.Element; import nu.xom.Elements; import org.purl.sword.base.Namespaces; import org.purl.sword.base.SwordElementInterface; import org.purl.sword.base.UnmarshallException; import org.purl.sword.base.XmlElement; import org.purl.sword.base.SwordValidationInfo; import org.purl.sword.base.SwordValidationInfoType; import org.purl.sword.base.XmlName; /** * Represents an Author type, as used in ATOM. This class is used as the * base class for the different areas of ATOM that represent information * about people. This includes the atom:author and atom:contributor * elements. * * @author Neil Taylor */ public class Author extends XmlElement implements SwordElementInterface { /** * Local name for the element. */ @Deprecated public static final String ELEMENT_NAME = "author"; /** * Label for the 'name' attribute. */ @Deprecated public static final String ELEMENT_AUTHOR_NAME = "name"; /** * Label for the 'uri' attribute. */ @Deprecated public static final String ELEMENT_URI = "uri"; /** * Label for the 'email' attribute. */ @Deprecated public static final String ELEMENT_EMAIL = "email"; /** * The author's name. */ private Name name; /** * The author's URI. */ private Uri uri; /** * The author's email. */ private Email email; /** * */ private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "author", Namespaces.NS_ATOM); /** * Create a new instance and set the prefix to * 'atom' and the local name to 'author'. */ public Author() { this(XML_NAME); } public Author(XmlName name) { super(name); } /** * Create a new instance and set the element name. * * @param prefix The prefix to use when marshalling the data. * @param localName The localName to use when marshalling the data. */ public Author(String prefix, String localName ) { this(prefix, localName, XML_NAME.getNamespace()); } /** * * @param prefix * @param localName * @param namespaceUri */ public Author(String prefix, String localName, String namespaceUri) { super(prefix, localName, XML_NAME.getNamespace()); } /** * Get the XmlName for this class. * * @return The prefix, localname and namespace for this element. */ public static XmlName elementName() { return XML_NAME; } /** * Marshall the data in this object to a XOM Element. The element * will have the full name that is specified in the constructor. * * @return A XOM Element. */ public Element marshall() { Element element = new Element(getQualifiedName(), xmlName.getNamespace()); if( name != null ) { element.appendChild(name.marshall()); } if( uri != null ) { element.appendChild(uri.marshall()); } if( email != null ) { element.appendChild(email.marshall()); } return element; } /** * Unmarshall the author details from the specified element. The element * is a XOM element. * * @param author The element to unmarshall. */ public SwordValidationInfo unmarshall(Element author, Properties validationProperties) throws UnmarshallException { if( ! isInstanceOf( author, xmlName) ) { handleIncorrectElement(author, validationProperties); } ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>(); ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>(); processUnexpectedAttributes(author, attributeItems); // retrieve all of the sub-elements Elements elements = author.getChildElements(); Element element = null; int length = elements.size(); for(int i = 0; i < length; i++ ) { element = elements.get(i); if( isInstanceOf(element, Name.elementName() )) { name = new Name(); validationItems.add(name.unmarshall(element, validationProperties)); } else if( isInstanceOf(element, Uri.elementName())) { uri = new Uri(); validationItems.add(uri.unmarshall(element, validationProperties)); } else if( isInstanceOf(element, Email.elementName() )) { email = new Email(); validationItems.add(email.unmarshall(element, validationProperties)); } else if( validationProperties != null ) { SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), SwordValidationInfo.UNKNOWN_ELEMENT, SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } // for SwordValidationInfo result = null; if( validationProperties != null ) { result = validate(validationItems, attributeItems, validationProperties); } return result; } public SwordValidationInfo validate(Properties validationContext) { return validate(null, null, validationContext); } public SwordValidationInfo validate(List<SwordValidationInfo> elements, List<SwordValidationInfo> attributes, Properties validationContext) { SwordValidationInfo result = new SwordValidationInfo(xmlName); if( name == null ) { SwordValidationInfo info = new SwordValidationInfo(Name.elementName(), SwordValidationInfo.MISSING_ELEMENT_ERROR, SwordValidationInfoType.ERROR); result.addValidationInfo(info); } else if( elements == null && name != null) { result.addValidationInfo(name.validate(validationContext)); } if( elements == null && uri != null ) { result.addValidationInfo(uri.validate(validationContext)); } if( elements == null && email != null ) { result.addValidationInfo(email.validate(validationContext)); } result.addUnmarshallValidationInfo(elements, attributes); return result; } /** * Unmarshall the author details from the specified element. The element * is a XOM element. * * @param author The element to unmarshall. */ public void unmarshall(Element author) throws UnmarshallException { unmarshall(author, null); } /** * Retrieve the author name. * * @return The name. */ public String getName() { if( name == null ) { return null; } return name.getContent(); } /** * Set the author name. * * @param name The name. */ public void setName(String name) { this.name = new Name(name); } /** * Get the author URI. * * @return The URI. */ public String getUri() { if( uri == null ) { return null; } return uri.getContent(); } /** * Set the author URI. * * @param uri the URI. */ public void setUri(String uri) { this.uri = new Uri(uri); } /** * Get the author email. * * @return The email. */ public String getEmail() { if( email == null ) { return null; } return email.getContent(); } /** * Set the author email. * * @param email The email. */ public void setEmail(String email) { this.email = new Email(email); } /** * Return the string. * @return String. */ @Override public String toString() { return "name: " + getName() + " email: " + getEmail() + " uri: " + getUri(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Uri extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "uri", Namespaces.NS_ATOM); public Uri() { super(XML_NAME); } public Uri(String uri) { this(); setContent(uri); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.atom; import org.purl.sword.base.*; /** * * @author Neil Taylor (nst@aber.ac.uk) */ public class Name extends BasicStringContentElement { private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, "name", Namespaces.NS_ATOM); public Name() { super(XML_NAME); } public Name(String name) { this(); setContent(name); } public static XmlName elementName() { return XML_NAME; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.server; import org.purl.sword.base.AtomDocumentRequest; import org.purl.sword.base.AtomDocumentResponse; import org.purl.sword.base.Deposit; import org.purl.sword.base.DepositResponse; import org.purl.sword.base.SWORDAuthenticationException; import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDException; import org.purl.sword.base.ServiceDocument; import org.purl.sword.base.ServiceDocumentRequest; /** * An abstract interface to be implemented by repositories wishing to provide * a SWORD compliant service. * * http://www.ukoln.ac.uk/repositories/digirep/index/SWORD * * @author Stuart Lewis */ public interface SWORDServer { /** * Answer a Service Document request sent on behalf of a user * * @param sdr The Service Document Request object * * @exception SWORDAuthenticationException Thrown if the authentication fails * @exception SWORDErrorException Thrown if there was an error with the input not matching * the capabilities of the server * @exception SWORDException Thrown in an un-handalable Exception occurs. * This will be dealt with by sending a HTTP 500 Server Exception * * @return The ServiceDocument representing the service document */ public ServiceDocument doServiceDocument(ServiceDocumentRequest sdr) throws SWORDAuthenticationException, SWORDErrorException, SWORDException; /** * Answer a SWORD deposit * * @param deposit The Deposit object * * @exception SWORDAuthenticationException Thrown if the authentication fails * @exception SWORDErrorException Thrown if there was an error with the input not matching * the capabilities of the server * @exception SWORDException Thrown if an un-handalable Exception occurs. * This will be dealt with by sending a HTTP 500 Server Exception * * @return The response to the deposit */ public DepositResponse doDeposit(Deposit deposit) throws SWORDAuthenticationException, SWORDErrorException, SWORDException; /** * Answer a request for an entry document * * @param adr The Atom Document Request object * * @exception SWORDAuthenticationException Thrown if the authentication fails * @exception SWORDErrorException Thrown if there was an error with the input not matching * the capabilities of the server * @exception SWORDException Thrown if an un-handalable Exception occurs. * This will be dealt with by sending a HTTP 500 Server Exception * * @return The response to the atom document request */ public AtomDocumentResponse doAtomDocument(AtomDocumentRequest adr) throws SWORDAuthenticationException, SWORDErrorException, SWORDException; }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.server; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.purl.sword.base.HttpHeaders; import org.purl.sword.base.SWORDAuthenticationException; import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDException; import org.purl.sword.base.ServiceDocument; import org.purl.sword.base.ServiceDocumentRequest; /** * ServiceDocumentServlet * * @author Stuart Lewis */ public class ServiceDocumentServlet extends HttpServlet { /** The repository */ private SWORDServer myRepository; /** Authentication type. */ private String authN; /** Maximum file upload size in kB **/ private int maxUploadSize; /** Logger */ private static Logger log = Logger.getLogger(ServiceDocumentServlet.class); /** * Initialise the servlet. * * @throws ServletException */ public void init() throws ServletException { // Instantiate the correct SWORD Server class String className = getServletContext().getInitParameter("sword-server-class"); if (className == null) { log.fatal("Unable to read value of 'sword-server-class' from Servlet context"); } else { try { myRepository = (SWORDServer) Class.forName(className) .newInstance(); log.info("Using " + className + " as the SWORDServer"); } catch (Exception e) { log.fatal("Unable to instantiate class from 'server-class': " + className); throw new ServletException( "Unable to instantiate class from 'server-class': " + className, e); } } // Set the authentication method authN = getServletContext().getInitParameter("authentication-method"); if ((authN == null) || ("".equals(authN))) { authN = "None"; } log.info("Authentication type set to: " + authN); String maxUploadSizeStr = getServletContext().getInitParameter("maxUploadSize"); if ((maxUploadSizeStr == null) || (maxUploadSizeStr.equals("")) || (maxUploadSizeStr.equals("-1"))) { maxUploadSize = -1; log.warn("No maxUploadSize set, so setting max file upload size to unlimited."); } else { try { maxUploadSize = Integer.parseInt(maxUploadSizeStr); log.info("Setting max file upload size to " + maxUploadSize); } catch (NumberFormatException nfe) { maxUploadSize = -1; log.warn("maxUploadSize not a number, so setting max file upload size to unlimited."); } } } /** * Process the get request. */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create the ServiceDocumentRequest ServiceDocumentRequest sdr = new ServiceDocumentRequest(); // Are there any authentication details? String usernamePassword = getUsernamePassword(request); if ((usernamePassword != null) && (!usernamePassword.equals(""))) { int p = usernamePassword.indexOf(':'); if (p != -1) { sdr.setUsername(usernamePassword.substring(0, p)); sdr.setPassword(usernamePassword.substring(p + 1)); } } else if (authenticateWithBasic()) { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); return; } // Set the x-on-behalf-of header sdr.setOnBehalfOf(request.getHeader(HttpHeaders.X_ON_BEHALF_OF .toString())); // Set the IP address sdr.setIPAddress(request.getRemoteAddr()); // Set the deposit location sdr.setLocation(getUrl(request)); // Get the ServiceDocument try { ServiceDocument sd = myRepository.doServiceDocument(sdr); if ((sd.getService().getMaxUploadSize() == -1) && (maxUploadSize != -1)) { sd.getService().setMaxUploadSize(maxUploadSize); } // Print out the Service Document response.setContentType("application/atomsvc+xml; charset=UTF-8"); PrintWriter out = response.getWriter(); out.write(sd.marshall()); out.flush(); } catch (SWORDAuthenticationException sae) { if (authN.equals("Basic")) { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); } } catch (SWORDErrorException see) { // Return the relevant HTTP status code response.sendError(see.getStatus(), see.getDescription()); } catch (SWORDException se) { se.printStackTrace(); // Throw a HTTP 500 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, se.getMessage()); } } /** * Process the post request. This will return an unimplemented response. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Send a '501 Not Implemented' response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } /** * Utiliy method to return the username and password (separated by a colon * ':') * * @param request * @return The username and password combination */ private String getUsernamePassword(HttpServletRequest request) { try { String authHeader = request.getHeader("Authorization"); if (authHeader != null) { StringTokenizer st = new StringTokenizer(authHeader); if (st.hasMoreTokens()) { String basic = st.nextToken(); if (basic.equalsIgnoreCase("Basic")) { String credentials = st.nextToken(); String userPass = new String(Base64 .decodeBase64(credentials.getBytes())); return userPass; } } } } catch (Exception e) { log.debug(e.toString()); } return null; } /** * Utility method to decide if we are using HTTP Basic authentication * * @return if HTTP Basic authentication is in use or not */ private boolean authenticateWithBasic() { return (authN.equalsIgnoreCase("Basic")); } /** * Utility method to construct the URL called for this Servlet * * @param req The request object * @return The URL */ private static String getUrl(HttpServletRequest req) { String reqUrl = req.getRequestURL().toString(); String queryString = req.getQueryString(); log.debug("Requested url is: " + reqUrl); if (queryString != null) { reqUrl += "?" + queryString; } log.debug("Requested url with Query String is: " + reqUrl); return reqUrl; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.server; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.servlet.http.HttpServletResponse; import org.purl.sword.atom.Author; import org.purl.sword.atom.Content; import org.purl.sword.atom.Contributor; import org.purl.sword.atom.Generator; import org.purl.sword.atom.InvalidMediaTypeException; import org.purl.sword.atom.Link; import org.purl.sword.atom.Summary; import org.purl.sword.atom.Title; import org.purl.sword.base.AtomDocumentRequest; import org.purl.sword.base.AtomDocumentResponse; import org.purl.sword.base.Collection; import org.purl.sword.base.Deposit; import org.purl.sword.base.DepositResponse; import org.purl.sword.base.ErrorCodes; import org.purl.sword.base.SWORDAuthenticationException; import org.purl.sword.base.SWORDEntry; import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDException; import org.purl.sword.base.Service; import org.purl.sword.base.ServiceDocument; import org.purl.sword.base.ServiceDocumentRequest; import org.purl.sword.base.Workspace; import org.apache.log4j.Logger; /** * A 'dummy server' which acts as dumb repository which implements the * SWORD ServerInterface. It accepts any type of deposit, and tries to * return appropriate responses. * * It supports authentication: if the username and password match * (case sensitive) it authenticates the user, if not, the authentication * fails. * * @author Stuart Lewis */ public class DummyServer implements SWORDServer { /** A counter to count submissions, so the response to a deposit can increment */ private static int counter = 0; /** Logger */ private static Logger log = Logger.getLogger(ServiceDocumentServlet.class); /** * Provides a dumb but plausible service document - it contains * an anonymous workspace and collection, and one personalised * for the onBehalfOf user. * * @param sdr The request * @throws SWORDAuthenticationException If the credentials are bad * @throws SWORDErrorException If something goes wrong, such as */ public ServiceDocument doServiceDocument(ServiceDocumentRequest sdr) throws SWORDAuthenticationException, SWORDErrorException, SWORDException { // Authenticate the user String username = sdr.getUsername(); String password = sdr.getPassword(); if ((username != null) && (password != null) && (((username.equals("")) && (password.equals(""))) || (!username.equalsIgnoreCase(password))) ) { // User not authenticated throw new SWORDAuthenticationException("Bad credentials"); } // Allow users to force the throwing of a SWORD error exception by setting // the OBO user to 'error' if ((sdr.getOnBehalfOf() != null) && (sdr.getOnBehalfOf().equals("error"))) { // Throw the error exception throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, "Mediated deposits not allowed"); } // Create and return a dummy ServiceDocument ServiceDocument document = new ServiceDocument(); Service service = new Service("1.3", true, true); document.setService(service); log.debug("sdr.getLocation() is: " + sdr.getLocation()); String location = sdr.getLocation().substring(0, sdr.getLocation().length() - 16); log.debug("location is: " + location); if (sdr.getLocation().contains("?nested=")) { Workspace workspace = new Workspace(); workspace.setTitle("Nested service document workspace"); Collection collection = new Collection(); collection.setTitle("Nested collection: " + sdr.getLocation().substring(sdr.getLocation().indexOf('?') + 1)); collection.setLocation(location + "/deposit/nested"); collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); collection.addAccepts("application/zip"); collection.addAccepts("application/xml"); collection.setAbstract("A nested collection that users can deposit into"); collection.setTreatment("This is a dummy server"); collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); workspace.addCollection(collection); service.addWorkspace(workspace); } else { Workspace workspace = new Workspace(); workspace.setTitle("Anonymous submitters workspace"); Collection collection = new Collection(); collection.setTitle("Anonymous submitters collection"); collection.setLocation(location + "/deposit/anon"); collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); collection.addAccepts("application/zip"); collection.addAccepts("application/xml"); collection.setAbstract("A collection that anonymous users can deposit into"); collection.setTreatment("This is a dummy server"); collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); collection.setService(location + "/client/servicedocument?nested=anon"); workspace.addCollection(collection); collection = new Collection(); collection.setTitle("Anonymous submitters other collection"); collection.setLocation(location + "/deposit/anonymous"); collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); collection.addAccepts("application/zip"); collection.addAccepts("application/xml"); collection.setAbstract("Another collection that anonymous users can deposit into"); collection.setTreatment("This is a dummy server"); collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); workspace.addCollection(collection); service.addWorkspace(workspace); if (sdr.getUsername() != null) { workspace = new Workspace(); workspace.setTitle("Authenticated workspace for " + username); collection = new Collection(); collection.setTitle("Authenticated collection for " + username); collection.setLocation(location + "/deposit/" + username); collection.addAccepts("application/zip"); collection.addAccepts("application/xml"); collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.8f); collection.setAbstract("A collection that " + username + " can deposit into"); collection.setTreatment("This is a dummy server"); collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); collection.setService(location + "/client/servicedocument?nested=authenticated"); workspace.addCollection(collection); collection = new Collection(); collection.setTitle("Second authenticated collection for " + username); collection.setLocation(location + "/deposit/" + username + "-2"); collection.addAccepts("application/zip"); collection.addAccepts("application/xml"); collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.123f); collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); collection.setAbstract("A collection that " + username + " can deposit into"); collection.setTreatment("This is a dummy server"); collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); workspace.addCollection(collection); } service.addWorkspace(workspace); } String onBehalfOf = sdr.getOnBehalfOf(); if ((onBehalfOf != null) && (!onBehalfOf.equals(""))) { Workspace workspace = new Workspace(); workspace.setTitle("Personal workspace for " + onBehalfOf); Collection collection = new Collection(); collection.setTitle("Personal collection for " + onBehalfOf); collection.setLocation(location + "/deposit?user=" + onBehalfOf); collection.addAccepts("application/zip"); collection.addAccepts("application/xml"); collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.8f); collection.setAbstract("An abstract goes in here"); collection.setCollectionPolicy("A collection policy"); collection.setMediation(true); collection.setTreatment("treatment in here too"); workspace.addCollection(collection); service.addWorkspace(workspace); } return document; } public DepositResponse doDeposit(Deposit deposit) throws SWORDAuthenticationException, SWORDErrorException, SWORDException { // Authenticate the user String username = deposit.getUsername(); String password = deposit.getPassword(); if ((username != null) && (password != null) && (((username.equals("")) && (password.equals(""))) || (!username.equalsIgnoreCase(password))) ) { // User not authenticated throw new SWORDAuthenticationException("Bad credentials"); } // Check this is a collection that takes obo deposits, else thrown an error if (((deposit.getOnBehalfOf() != null) && (!deposit.getOnBehalfOf().equals(""))) && (!deposit.getLocation().contains("deposit?user="))) { throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, "Mediated deposit not allowed to this collection"); } // Get the filenames StringBuffer filenames = new StringBuffer("Deposit file contained: "); if (deposit.getFilename() != null) { filenames.append("(filename = " + deposit.getFilename() + ") "); } if (deposit.getSlug() != null) { filenames.append("(slug = " + deposit.getSlug() + ") "); } ZipInputStream zip = null; try { File depositFile = deposit.getFile(); zip = new ZipInputStream(new FileInputStream(depositFile)); ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { filenames.append(" ").append(ze.toString()); } } catch (IOException ioe) { throw new SWORDException("Failed to open deposited zip file", ioe, ErrorCodes.ERROR_CONTENT); } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { log.error("Unable to close zip stream", e); } } } // Handle the deposit if (!deposit.isNoOp()) { counter++; } DepositResponse dr = new DepositResponse(Deposit.CREATED); SWORDEntry se = new SWORDEntry(); Title t = new Title(); t.setContent("DummyServer Deposit: #" + counter); se.setTitle(t); se.addCategory("Category"); if (deposit.getSlug() != null) { se.setId(deposit.getSlug() + " - ID: " + counter); } else { se.setId("ID: " + counter); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); TimeZone utc = TimeZone.getTimeZone("UTC"); sdf.setTimeZone (utc); String milliFormat = sdf.format(new Date()); se.setUpdated(milliFormat); Summary s = new Summary(); s.setContent(filenames.toString()); se.setSummary(s); Author a = new Author(); if (username != null) { a.setName(username); } else { a.setName("unknown"); } se.addAuthors(a); Link em = new Link(); em.setRel("edit-media"); em.setHref("http://www.myrepository.ac.uk/sdl/workflow/my deposit"); se.addLink(em); Link e = new Link(); e.setRel("edit"); e.setHref("http://www.myrepository.ac.uk/sdl/workflow/my deposit.atom"); se.addLink(e); if (deposit.getOnBehalfOf() != null) { Contributor c = new Contributor(); c.setName(deposit.getOnBehalfOf()); c.setEmail(deposit.getOnBehalfOf() + "@myrepository.ac.uk"); se.addContributor(c); } Generator generator = new Generator(); generator.setContent("Stuart's Dummy SWORD Server"); generator.setUri("http://dummy-sword-server.example.com/"); generator.setVersion("1.3"); se.setGenerator(generator); Content content = new Content(); try { content.setType("application/zip"); } catch (InvalidMediaTypeException ex) { ex.printStackTrace(); } content.setSource("http://www.myrepository.ac.uk/sdl/uploads/upload-" + counter + ".zip"); se.setContent(content); se.setTreatment("Short back and sides"); if (deposit.isVerbose()) { se.setVerboseDescription("I've done a lot of hard work to get this far!"); } se.setNoOp(deposit.isNoOp()); dr.setEntry(se); dr.setLocation("http://www.myrepository.ac.uk/atom/" + counter); return dr; } public AtomDocumentResponse doAtomDocument(AtomDocumentRequest adr) throws SWORDAuthenticationException, SWORDErrorException, SWORDException { // Authenticate the user String username = adr.getUsername(); String password = adr.getPassword(); if ((username != null) && (password != null) && (((username.equals("")) && (password.equals(""))) || (!username.equalsIgnoreCase(password))) ) { // User not authenticated throw new SWORDAuthenticationException("Bad credentials"); } return new AtomDocumentResponse(HttpServletResponse.SC_OK); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.purl.sword.base.AtomDocumentRequest; import org.purl.sword.base.AtomDocumentResponse; import org.purl.sword.base.SWORDAuthenticationException; import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDException; /** * EntryDocumentServlet * * @author Glen Robson * @author Stuart Lewis */ public class AtomDocumentServlet extends DepositServlet { /** * Process the get request. */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // Create the atom document request object AtomDocumentRequest adr = new AtomDocumentRequest(); // Are there any authentication details? String usernamePassword = getUsernamePassword(request); if ((usernamePassword != null) && (!usernamePassword.equals(""))) { int p = usernamePassword.indexOf(':'); if (p != -1) { adr.setUsername(usernamePassword.substring(0, p)); adr.setPassword(usernamePassword.substring(p + 1)); } } else if (authenticateWithBasic()) { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); return; } // Set the IP address adr.setIPAddress(request.getRemoteAddr()); // Set the deposit location adr.setLocation(getUrl(request)); // Generate the response AtomDocumentResponse dr = myRepository.doAtomDocument(adr); // Print out the Deposit Response response.setStatus(dr.getHttpResponse()); response.setContentType("application/atom+xml; charset=UTF-8"); PrintWriter out = response.getWriter(); out.write(dr.marshall()); out.flush(); } catch (SWORDAuthenticationException sae) { // Ask for credentials again String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); } catch (SWORDException se) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (SWORDErrorException see) { // Get the details and send the right SWORD error document super.makeErrorDocument(see.getErrorURI(), see.getStatus(), see.getDescription(), request, response); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.purl.sword.server; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.purl.sword.atom.Summary; import org.purl.sword.atom.Title; import org.purl.sword.base.ChecksumUtils; import org.purl.sword.base.Deposit; import org.purl.sword.base.DepositResponse; import org.purl.sword.base.ErrorCodes; import org.purl.sword.base.HttpHeaders; import org.purl.sword.base.SWORDAuthenticationException; import org.purl.sword.base.SWORDErrorDocument; import org.purl.sword.base.SWORDException; import org.purl.sword.base.SWORDErrorException; /** * DepositServlet * * @author Stuart Lewis */ public class DepositServlet extends HttpServlet { /** Sword repository */ protected SWORDServer myRepository; /** Authentication type */ private String authN; /** Maximum file upload size in kB **/ private int maxUploadSize; /** Temp directory */ private String tempDirectory; /** Counter */ private static AtomicInteger counter = new AtomicInteger(0); /** Logger */ private static Logger log = Logger.getLogger(DepositServlet.class); /** * Initialise the servlet * * @throws ServletException */ public void init() throws ServletException { // Instantiate the correct SWORD Server class String className = getServletContext().getInitParameter("sword-server-class"); if (className == null) { log.fatal("Unable to read value of 'sword-server-class' from Servlet context"); } else { try { myRepository = (SWORDServer) Class.forName(className) .newInstance(); log.info("Using " + className + " as the SWORDServer"); } catch (Exception e) { log .fatal("Unable to instantiate class from 'sword-server-class': " + className); throw new ServletException( "Unable to instantiate class from 'sword-server-class': " + className, e); } } authN = getServletContext().getInitParameter("authentication-method"); if ((authN == null) || (authN.equals(""))) { authN = "None"; } log.info("Authentication type set to: " + authN); String maxUploadSizeStr = getServletContext().getInitParameter("maxUploadSize"); if ((maxUploadSizeStr == null) || (maxUploadSizeStr.equals("")) || (maxUploadSizeStr.equals("-1"))) { maxUploadSize = -1; log.warn("No maxUploadSize set, so setting max file upload size to unlimited."); } else { try { maxUploadSize = Integer.parseInt(maxUploadSizeStr); log.info("Setting max file upload size to " + maxUploadSize); } catch (NumberFormatException nfe) { maxUploadSize = -1; log.warn("maxUploadSize not a number, so setting max file upload size to unlimited."); } } tempDirectory = getServletContext().getInitParameter( "upload-temp-directory"); if ((tempDirectory == null) || (tempDirectory.equals(""))) { tempDirectory = System.getProperty("java.io.tmpdir"); } if (!tempDirectory.endsWith(System.getProperty("file.separator"))) { tempDirectory += System.getProperty("file.separator"); } File tempDir = new File(tempDirectory); log.info("Upload temporary directory set to: " + tempDir); if (!tempDir.exists() && !tempDir.mkdirs()) { throw new ServletException( "Upload directory did not exist and I can't create it. " + tempDir); } if (!tempDir.isDirectory()) { log.fatal("Upload temporary directory is not a directory: " + tempDir); throw new ServletException( "Upload temporary directory is not a directory: " + tempDir); } if (!tempDir.canWrite()) { log.fatal("Upload temporary directory cannot be written to: " + tempDir); throw new ServletException( "Upload temporary directory cannot be written to: " + tempDir); } } /** * Process the Get request. This will return an unimplemented response. */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Send a '501 Not Implemented' response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } /** * Process a post request. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create the Deposit request Deposit d = new Deposit(); Date date = new Date(); log.debug("Starting deposit processing at " + date.toString() + " by " + request.getRemoteAddr()); // Are there any authentication details? String usernamePassword = getUsernamePassword(request); if ((usernamePassword != null) && (!usernamePassword.equals(""))) { int p = usernamePassword.indexOf(':'); if (p != -1) { d.setUsername(usernamePassword.substring(0, p)); d.setPassword(usernamePassword.substring(p + 1)); } } else if (authenticateWithBasic()) { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); return; } // Set up some variables String filename = null; // Do the processing try { // Write the file to the temp directory filename = tempDirectory + "SWORD-" + request.getRemoteAddr() + "-" + counter.addAndGet(1); log.debug("Package temporarily stored as: " + filename); InputStream inputstream = request.getInputStream(); OutputStream outputstream = new FileOutputStream(new File(filename)); try { byte[] buf = new byte[1024]; int len; while ((len = inputstream.read(buf)) > 0) { outputstream.write(buf, 0, len); } } finally { inputstream.close(); outputstream.close(); } // Check the size is OK File file = new File(filename); long fLength = file.length() / 1024; if ((maxUploadSize != -1) && (fLength > maxUploadSize)) { this.makeErrorDocument(ErrorCodes.MAX_UPLOAD_SIZE_EXCEEDED, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "The uploaded file exceeded the maximum file size this server will accept (the file is " + fLength + "kB but the server will only accept files as large as " + maxUploadSize + "kB)", request, response); return; } // Check the MD5 hash String receivedMD5 = ChecksumUtils.generateMD5(filename); log.debug("Received filechecksum: " + receivedMD5); d.setMd5(receivedMD5); String md5 = request.getHeader("Content-MD5"); log.debug("Received file checksum header: " + md5); if ((md5 != null) && (!md5.equals(receivedMD5))) { // Return an error document this.makeErrorDocument(ErrorCodes.ERROR_CHECKSUM_MISMATCH, HttpServletResponse.SC_PRECONDITION_FAILED, "The received MD5 checksum for the deposited file did not match the checksum sent by the deposit client", request, response); log.debug("Bad MD5 for file. Aborting with appropriate error message"); return; } else { // Set the file to be deposited d.setFile(file); // Set the X-On-Behalf-Of header String onBehalfOf = request.getHeader(HttpHeaders.X_ON_BEHALF_OF.toString()); if ((onBehalfOf != null) && (onBehalfOf.equals("reject"))) { // user name is "reject", so throw a not know error to allow the client to be tested throw new SWORDErrorException(ErrorCodes.TARGET_OWNER_UKNOWN,"unknown user \"reject\""); } else { d.setOnBehalfOf(onBehalfOf); } // Set the X-Packaging header d.setPackaging(request.getHeader(HttpHeaders.X_PACKAGING)); // Set the X-No-Op header String noop = request.getHeader(HttpHeaders.X_NO_OP); log.error("X_NO_OP value is " + noop); if ((noop != null) && (noop.equals("true"))) { d.setNoOp(true); } else if ((noop != null) && (noop.equals("false"))) { d.setNoOp(false); }else if (noop == null) { d.setNoOp(false); } else { throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST,"Bad no-op"); } // Set the X-Verbose header String verbose = request.getHeader(HttpHeaders.X_VERBOSE); if ((verbose != null) && (verbose.equals("true"))) { d.setVerbose(true); } else if ((verbose != null) && (verbose.equals("false"))) { d.setVerbose(false); }else if (verbose == null) { d.setVerbose(false); } else { throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST,"Bad verbose"); } // Set the slug String slug = request.getHeader(HttpHeaders.SLUG); if (slug != null) { d.setSlug(slug); } // Set the content disposition d.setContentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION)); // Set the IP address d.setIPAddress(request.getRemoteAddr()); // Set the deposit location d.setLocation(getUrl(request)); // Set the content type d.setContentType(request.getContentType()); // Set the content length String cl = request.getHeader(HttpHeaders.CONTENT_LENGTH); if ((cl != null) && (!cl.equals(""))) { d.setContentLength(Integer.parseInt(cl)); } // Get the DepositResponse DepositResponse dr = myRepository.doDeposit(d); // Echo back the user agent if (request.getHeader(HttpHeaders.USER_AGENT.toString()) != null) { dr.getEntry().setUserAgent(request.getHeader(HttpHeaders.USER_AGENT.toString())); } // Echo back the packaging format if (request.getHeader(HttpHeaders.X_PACKAGING.toString()) != null) { dr.getEntry().setPackaging(request.getHeader(HttpHeaders.X_PACKAGING.toString())); } // Print out the Deposit Response response.setStatus(dr.getHttpResponse()); if ((dr.getLocation() != null) && (!dr.getLocation().equals(""))) { response.setHeader("Location", dr.getLocation()); } response.setContentType("application/atom+xml; charset=UTF-8"); PrintWriter out = response.getWriter(); out.write(dr.marshall()); out.flush(); } } catch (SWORDAuthenticationException sae) { // Ask for credentials again if (authN.equals("Basic")) { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); } } catch (SWORDErrorException see) { // Get the details and send the right SWORD error document log.error(see.toString()); this.makeErrorDocument(see.getErrorURI(), see.getStatus(), see.getDescription(), request, response); return; } catch (SWORDException se) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error(se.toString()); } catch (NoSuchAlgorithmException nsae) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error(nsae.toString()); } finally { // Try deleting the temp file if (filename != null) { File f = new File(filename); if (f != null && !f.delete()) { log.error("Unable to delete file: " + filename); } } } } /** * Utility method to construct a SWORDErrorDocumentTest * * @param errorURI The error URI to pass * @param status The HTTP status to return * @param summary The textual description to give the user * @param request The HttpServletRequest object * @param response The HttpServletResponse to send the error document to * @throws IOException */ protected void makeErrorDocument(String errorURI, int status, String summary, HttpServletRequest request, HttpServletResponse response) throws IOException { SWORDErrorDocument sed = new SWORDErrorDocument(errorURI); Title title = new Title(); title.setContent("ERROR"); sed.setTitle(title); Calendar calendar = Calendar.getInstance(); String utcformat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; SimpleDateFormat zulu = new SimpleDateFormat(utcformat); String serializeddate = zulu.format(calendar.getTime()); sed.setUpdated(serializeddate); Summary sum = new Summary(); sum.setContent(summary); sed.setSummary(sum); if (request.getHeader(HttpHeaders.USER_AGENT.toString()) != null) { sed.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT.toString())); } response.setStatus(status); response.setContentType("application/atom+xml; charset=UTF-8"); PrintWriter out = response.getWriter(); out.write(sed.marshall().toXML()); out.flush(); } /** * Utility method to return the username and password (separated by a colon * ':') * * @param request * @return The username and password combination */ protected String getUsernamePassword(HttpServletRequest request) { try { String authHeader = request.getHeader("Authorization"); if (authHeader != null) { StringTokenizer st = new StringTokenizer(authHeader); if (st.hasMoreTokens()) { String basic = st.nextToken(); if (basic.equalsIgnoreCase("Basic")) { String credentials = st.nextToken(); String userPass = new String(Base64 .decodeBase64(credentials.getBytes())); return userPass; } } } } catch (Exception e) { log.debug(e.toString()); } return null; } /** * Utility method to decide if we are using HTTP Basic authentication * * @return if HTTP Basic authentication is in use or not */ protected boolean authenticateWithBasic() { return (authN.equalsIgnoreCase("Basic")); } /** * Utility method to construct the URL called for this Servlet * * @param req The request object * @return The URL */ protected static String getUrl(HttpServletRequest req) { String reqUrl = req.getRequestURL().toString(); String queryString = req.getQueryString(); if (queryString != null) { reqUrl += "?" + queryString; } return reqUrl; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.searchArtifacts; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Options; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.authorize.AuthorizeException; import org.dspace.content.DSpaceObject; import org.xml.sax.SAXException; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; /** * Navigation that adds code needed for the old dspace search * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent { @Override public Serializable getKey() { try { Request request = ObjectModelHelper.getRequest(objectModel); String key = request.getScheme() + request.getServerName() + request.getServerPort() + request.getSitemapURI() + request.getQueryString(); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso != null) { key += "-" + dso.getHandle(); } return HashUtil.hash(key); } catch (SQLException sqle) { // Ignore all errors and just return that the component is not cachable. return "0"; } } @Override public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } public void addOptions(Options options) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { /* Create skeleton menu structure to ensure consistent order between aspects, * even if they are never used */ options.addList("browse"); options.addList("account"); options.addList("context"); options.addList("administrative"); } /** * Insure that the context path is added to the page meta. */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // Add metadata for quick searches: pageMeta.addMetadata("search", "simpleURL").addContent( contextPath + "/search"); pageMeta.addMetadata("search", "advancedURL").addContent( contextPath + "/advanced-search"); pageMeta.addMetadata("search", "queryField").addContent("query"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.util.HashMap; import java.util.Map; import org.dspace.app.xmlui.wing.Message; import org.dspace.core.ConfigurationManager; import org.dspace.curate.Curator; /** * * @author wbossons */ public class FlowCurationUtils { private static final Map<String, String> map = new HashMap<String, String>(); protected static Curator getCurator(String taskName) { if (taskName != null && taskName.length() == 0) { taskName = null; } Curator curator = new Curator(); curator.addTask(taskName); curator.setInvoked(Curator.Invoked.INTERACTIVE); return curator; } protected static FlowResult getRunFlowResult(String taskName, Curator curator) { if (map.isEmpty()) { String statusCodes = ConfigurationManager.getProperty("curate", "ui.statusmessages"); for (String pair : statusCodes.split(",")) { String[] parts = pair.split("="); map.put(parts[0].trim(), parts[1].trim()); } } String status = map.get(String.valueOf(curator.getStatus(taskName))); if (status == null) { // invalid = use string for 'other status = map.get("other"); } String result = curator.getResult(taskName); FlowResult flowResult = new FlowResult(); flowResult.setOutcome(true); flowResult.setMessage(new Message("default","The task, " + taskName + " was completed with the status: " + status + ".\n" + "Results: " + "\n" + ((result != null) ? result : "Nothing to do for this DSpace object."))); flowResult.setContinue(true); return flowResult; } protected static FlowResult getQueueFlowResult(String taskName, boolean status, String objId, String queueName) { FlowResult flowResult = new FlowResult(); flowResult.setOutcome(true); flowResult.setMessage(new Message("default", " The task, " + taskName + ", has " + ((status) ? "been queued for id, " + objId + " in the " + queueName + " queue.": "has not been queued for id, " + objId + ". An error occurred."))); flowResult.setContinue(true); return flowResult; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.utils.RequestUtils; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.authorize.AuthorizeException; import org.dspace.content.BitstreamFormat; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; import org.dspace.content.NonUniqueMetadataException; import org.dspace.core.Constants; import org.dspace.core.Context; /** * */ public class FlowRegistryUtils { /** Language Strings */ private static final Message T_add_metadata_schema_success_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.add_metadata_schema_success_notice"); private static final Message T_delete_metadata_schema_success_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.delete_metadata_schema_success_notice"); private static final Message T_add_metadata_field_success_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.add_metadata_field_success_notice"); private static final Message T_edit_metadata_field_success_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.edit_metadata_field_success_notice"); private static final Message T_move_metadata_field_sucess_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.move_metadata_field_success_notice"); private static final Message T_delete_metadata_field_success_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.delete_metadata_field_success_notice"); private static final Message T_edit_bitstream_format_success_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.edit_bitstream_format_success_notice"); private static final Message T_delete_bitstream_format_success_notice = new Message("default","xmlui.administrative.FlowRegistryUtils.delete_bitstream_format_success_notice"); /** * Add a new metadata schema. The ID of the new schema will be added * as the "schemaID" parameter on the results object. * * @param context The DSpace context * @param namespace The new schema's namespace * @param name The new schema's name. * @return A flow result */ public static FlowResult processAddMetadataSchema(Context context, String namespace, String name) throws SQLException, AuthorizeException, NonUniqueMetadataException, UIException { FlowResult result = new FlowResult(); result.setContinue(false); // Decode the namespace and name try { namespace = URLDecoder.decode(namespace, Constants.DEFAULT_ENCODING); name = URLDecoder.decode(name,Constants.DEFAULT_ENCODING); } catch (UnsupportedEncodingException uee) { throw new UIException(uee); } if (namespace == null || namespace.length() <= 0) { result.addError("namespace"); } if (name == null || name.length() <= 0 || name.indexOf('.') != -1 || name.indexOf('_') != -1 || name.indexOf(' ') != -1) { // The name must not be empty nor contain dot, underscore or spaces. result.addError("name"); } if (result.getErrors() == null) { MetadataSchema schema = new MetadataSchema(); schema.setNamespace(namespace); schema.setName(name); schema.create(context); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_add_metadata_schema_success_notice); result.setParameter("schemaID", schema.getSchemaID()); } return result; } /** * Delete the given schemas. * * @param context The DSpace context * @param schemaIDs A list of schema IDs to be deleted. * @return A flow result */ public static FlowResult processDeleteMetadataSchemas(Context context, String[] schemaIDs) throws SQLException, AuthorizeException, NonUniqueMetadataException { FlowResult result = new FlowResult(); int count = 0; for (String id : schemaIDs) { MetadataSchema schema = MetadataSchema.find(context, Integer.valueOf(id)); // First remove and fields in the schema MetadataField[] fields = MetadataField.findAllInSchema(context, schema.getSchemaID()); for (MetadataField field : fields) { field.delete(context); } // Once all the fields are gone, then delete the schema. schema.delete(context); count++; } if (count > 0) { context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_delete_metadata_schema_success_notice); } return result; } /** * Add a new metadata field. The newly created field's ID will be added as * the "fieldID" parameter on the results object. * * @param context The DSpace context * @param schemaID The id of the schema where this new field should be added. * @param element The field's element. * @param qualifier The field's qualifier. * @param note A scope not about the field. * @return A results object */ public static FlowResult processAddMetadataField(Context context, int schemaID, String element, String qualifier, String note) throws IOException, AuthorizeException, SQLException, UIException { FlowResult result = new FlowResult(); result.setContinue(false); // Decode the element, qualifier, and note. try { element = URLDecoder.decode(element, Constants.DEFAULT_ENCODING); qualifier = URLDecoder.decode(qualifier,Constants.DEFAULT_ENCODING); note = URLDecoder.decode(note,Constants.DEFAULT_ENCODING); } catch (UnsupportedEncodingException uee) { throw new UIException(uee); } // Check if the field name is good. result.setErrors(checkMetadataFieldName(element, qualifier)); // Make sure qualifier is null if blank. if ("".equals(qualifier)) { qualifier = null; } if (result.getErrors() == null) { try { MetadataField field = new MetadataField(); field.setSchemaID(schemaID); field.setElement(element); field.setQualifier(qualifier); field.setScopeNote(note); field.create(context); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_add_metadata_field_success_notice); result.setParameter("fieldID", field.getFieldID()); } catch (NonUniqueMetadataException nume) { result.addError("duplicate_field"); } } return result; } /** * Edit a metadata field. * * @param context The DSpace context. * @param schemaID The ID of the schema for this field. * @param fieldID The id of this field. * @param element A new element value * @param qualifier A new qualifier value * @param note A new note value. * @return A results object. */ public static FlowResult processEditMetadataField(Context context, int schemaID, int fieldID, String element, String qualifier, String note) throws IOException, AuthorizeException, SQLException, UIException { FlowResult result = new FlowResult(); result.setContinue(false); // Decode the element, qualifier, and note. try { element = URLDecoder.decode(element, Constants.DEFAULT_ENCODING); qualifier = URLDecoder.decode(qualifier,Constants.DEFAULT_ENCODING); note = URLDecoder.decode(note,Constants.DEFAULT_ENCODING); } catch (UnsupportedEncodingException uee) { throw new UIException(uee); } // Check if the field name is good. result.setErrors(checkMetadataFieldName(element, qualifier)); // Make sure qualifier is null if blank. if ("".equals(qualifier)) { qualifier = null; } // Check to make sure the field is unique, sometimes the NonUniqueMetadataException is not thrown. MetadataField possibleDuplicate = MetadataField.findByElement(context, schemaID, element, qualifier); if (possibleDuplicate != null && possibleDuplicate.getFieldID() != fieldID) { result.addError("duplicate_field"); } if (result.getErrors() == null) { try { // Update the metadata for a DC type MetadataField field = MetadataField.find(context, fieldID); field.setElement(element); field.setQualifier(qualifier); field.setScopeNote(note); field.update(context); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_edit_metadata_field_success_notice); } catch (NonUniqueMetadataException nume) { // This shouldn't ever occure. result.addError("duplicate_field"); } } return result; } /** * Simple method to check the a metadata field's name: element and qualifier. * * @param element The field's element. * @param qualifier The field's qualifier * @return A list of errors found, null if none are found. */ private static List<String> checkMetadataFieldName(String element, String qualifier) { List<String> errors = new ArrayList<String>(); // Is the element empty? if (element == null || element.length() <= 0) { element = ""; // so that the rest of the checks don't fail. errors.add("element_empty"); } // Is there a bad character in the element? if (element.indexOf('.') != -1 || element.indexOf('_') != -1 || element.indexOf(' ') != -1) { errors.add("element_badchar"); } // Is the element too long? if (element.length() > 64) { errors.add("element_tolong"); } // The qualifier can be empty. if (qualifier != null && qualifier.length() > 0) { if (qualifier.length() > 64) { errors.add("qualifier_tolong"); } if (qualifier.indexOf('.') != -1 || qualifier.indexOf('_') != -1 || qualifier.indexOf(' ') != -1) { errors.add("qualifier_badchar"); } } // If there were no errors then just return null. if (errors.size() == 0) { return null; } return errors; } /** * Move the specified metadata fields to the target schema. * * @param context The DSpace context * @param schemaID The target schema ID * @param fieldIDs The fields to be moved. * @return A results object. */ public static FlowResult processMoveMetadataField(Context context, int schemaID, String[] fieldIDs) throws NumberFormatException, SQLException, AuthorizeException, NonUniqueMetadataException, IOException { FlowResult result = new FlowResult(); int count = 0; for (String id : fieldIDs) { MetadataField field = MetadataField.find(context, Integer.valueOf(id)); field.setSchemaID(schemaID); field.update(context); count++; } if (count > 0) { context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_move_metadata_field_sucess_notice); } return result; } /** * Delete the specified metadata fields. * * @param context The DSpace context * @param fieldIDs The fields to be deleted. * @return A results object */ public static FlowResult processDeleteMetadataField(Context context, String[] fieldIDs) throws NumberFormatException, SQLException, AuthorizeException { FlowResult result = new FlowResult(); int count = 0; for (String id : fieldIDs) { MetadataField field = MetadataField.find(context, Integer.valueOf(id)); field.delete(context); count++; } if (count > 0) { context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_delete_metadata_field_success_notice); } return result; } /** * Edit a bitstream format. If the formatID is -1 then a new format is created. * The formatID of the new format is added as a parameter to the results object. * * FIXME: the reason we accept a request object is so that we can use the * RequestUtils.getFieldvalues() to get the multivalue field values. * * @param context The dspace context * @param formatID The id of the format being updated. * @param request The request object, for all the field entries. * @return A results object */ public static FlowResult processEditBitstreamFormat(Context context, int formatID, Request request) throws SQLException, AuthorizeException { FlowResult result = new FlowResult(); result.setContinue(false); // Get the values String mimeType = request.getParameter("mimetype"); String shortDescription = request.getParameter("short_description"); String description = request.getParameter("description"); String supportLevel = request.getParameter("support_level"); String internal = request.getParameter("internal"); List<String> extensionsList = RequestUtils.getFieldValues(request, "extensions"); String[] extensions = extensionsList.toArray(new String[extensionsList.size()]); // The format must at least have a name. if (formatID != 1 && (shortDescription == null || shortDescription.length() == 0)) { result.addError("short_description"); return result; } // Remove leading periods from file extensions. for (int i = 0; i < extensions.length; i++) { if (extensions[i].startsWith(".")) { extensions[i] = extensions[i].substring(1); } } // Get or create the format BitstreamFormat format; if (formatID >= 0) { format = BitstreamFormat.find(context, formatID); } else { format = BitstreamFormat.create(context); } // Update values format.setMIMEType(mimeType); if (formatID != 1) // don't change the unknow format. { format.setShortDescription(shortDescription); } format.setDescription(description); format.setSupportLevel(Integer.valueOf(supportLevel)); if (internal == null) { format.setInternal(false); } else { format.setInternal(true); } format.setExtensions(extensions); // Commit the change format.update(); context.commit(); // Return status result.setContinue(true); result.setOutcome(true); result.setMessage(T_edit_bitstream_format_success_notice); result.setParameter("formatID",format.getID()); return result; } /** * Delete the specified bitstream formats. * * @param context The DSpace context * @param formatIDs The formats-to-be-deleted. * @return A results object. */ public static FlowResult processDeleteBitstreamFormats(Context context, String[] formatIDs) throws NumberFormatException, SQLException, AuthorizeException { FlowResult result = new FlowResult(); int count = 0; for (String id : formatIDs) { BitstreamFormat format = BitstreamFormat.find(context,Integer.valueOf(id)); format.delete(); count++; } if (count > 0) { context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_delete_bitstream_format_success_notice); } return result; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.cocoon.environment.Request; import org.apache.cocoon.servlet.multipart.Part; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.ResourcePolicy; import org.dspace.browse.BrowseException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.harvest.HarvestedCollection; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.harvest.OAIHarvester; import org.dspace.harvest.OAIHarvester.HarvestScheduler; import org.dspace.content.crosswalk.CrosswalkException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.curate.Curator; import org.dspace.eperson.Group; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.xml.sax.SAXException; /** * Utility methods to processes actions on Communities and Collections. * * @author scott phillips */ public class FlowContainerUtils { /** Possible Collection roles */ public static final String ROLE_ADMIN = "ADMIN"; public static final String ROLE_WF_STEP1 = "WF_STEP1"; public static final String ROLE_WF_STEP2 = "WF_STEP2"; public static final String ROLE_WF_STEP3 = "WF_STEP3"; public static final String ROLE_SUBMIT = "SUBMIT"; public static final String ROLE_DEFAULT_READ = "DEFAULT_READ"; // Collection related functions /** * Process the collection metadata edit form. * * @param context The current DSpace context. * @param collectionID The collection id. * @param deleteLogo Determines if the logo should be deleted along with the metadata editing action. * @param request the Cocoon request object * @return A process result's object. */ public static FlowResult processEditCollection(Context context, int collectionID, boolean deleteLogo, Request request) throws SQLException, IOException, AuthorizeException { FlowResult result = new FlowResult(); Collection collection = Collection.find(context, collectionID); // Get the metadata String name = request.getParameter("name"); String shortDescription = request.getParameter("short_description"); String introductoryText = request.getParameter("introductory_text"); String copyrightText = request.getParameter("copyright_text"); String sideBarText = request.getParameter("side_bar_text"); String license = request.getParameter("license"); String provenanceDescription = request.getParameter("provenance_description"); // If they don't have a name then make it untitled. if (name == null || name.length() == 0) { name = "Untitled"; } // If empty, make it null. if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } if (license != null && license.length() == 0) { license = null; } if (provenanceDescription != null && provenanceDescription.length() == 0) { provenanceDescription = null; } // Save the metadata collection.setMetadata("name", name); collection.setMetadata("short_description", shortDescription); collection.setMetadata("introductory_text", introductoryText); collection.setMetadata("copyright_text", copyrightText); collection.setMetadata("side_bar_text", sideBarText); collection.setMetadata("license", license); collection.setMetadata("provenance_description", provenanceDescription); // Change or delete the logo if (deleteLogo) { // Remove the logo collection.setLogo(null); } else { // Update the logo Object object = request.get("logo"); Part filePart = null; if (object instanceof Part) { filePart = (Part) object; } if (filePart != null && filePart.getSize() > 0) { InputStream is = filePart.getInputStream(); collection.setLogo(is); } } // Save everything collection.update(); context.commit(); // No notice... result.setContinue(true); return result; } /** * Process the collection harvesting options form. * * @param context The current DSpace context. * @param collectionID The collection id. * @param request the Cocoon request object * @return A process result's object. */ public static FlowResult processSetupCollectionHarvesting(Context context, int collectionID, Request request) throws SQLException, IOException, AuthorizeException { FlowResult result = new FlowResult(); HarvestedCollection hc = HarvestedCollection.find(context, collectionID); String contentSource = request.getParameter("source"); // First, if this is not a harvested collection (anymore), set the harvest type to 0; possibly also wipe harvest settings if (contentSource.equals("source_normal")) { if (hc != null) { hc.delete(); } result.setContinue(true); } else { FlowResult subResult = testOAISettings(context, request); // create a new harvest instance if all the settings check out if (hc == null) { hc = HarvestedCollection.create(context, collectionID); } // if the supplied options all check out, set the harvesting parameters on the collection if (subResult.getErrors().isEmpty()) { String oaiProvider = request.getParameter("oai_provider"); boolean oaiAllSets = "all".equals(request.getParameter("oai-set-setting")); String oaiSetId; if(oaiAllSets) { oaiSetId = "all"; } else { oaiSetId = request.getParameter("oai_setid"); } String metadataKey = request.getParameter("metadata_format"); String harvestType = request.getParameter("harvest_level"); hc.setHarvestParams(Integer.parseInt(harvestType), oaiProvider, oaiSetId, metadataKey); hc.setHarvestStatus(HarvestedCollection.STATUS_READY); } else { result.setErrors(subResult.getErrors()); result.setContinue(false); return result; } hc.update(); } // Save everything context.commit(); // No notice... //result.setMessage(new Message("default","Harvesting options successfully modified.")); result.setOutcome(true); result.setContinue(true); return result; } /** * Use the collection's harvest settings to immediately perform a harvest cycle. * * @param context The current DSpace context. * @param collectionID The collection id. * @param request the Cocoon request object * @return A process result's object. * @throws TransformerException * @throws SAXException * @throws ParserConfigurationException * @throws CrosswalkException */ public static FlowResult processRunCollectionHarvest(Context context, int collectionID, Request request) throws SQLException, IOException, AuthorizeException, CrosswalkException, ParserConfigurationException, SAXException, TransformerException { FlowResult result = new FlowResult(); OAIHarvester harvester; List<String> testErrors = new ArrayList<String>(); Collection collection = Collection.find(context, collectionID); HarvestedCollection hc = HarvestedCollection.find(context, collectionID); //TODO: is there a cleaner way to do this? try { if (!HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_STOPPED)) { synchronized(HarvestScheduler.lock) { HarvestScheduler.setInterrupt(HarvestScheduler.HARVESTER_INTERRUPT_INSERT_THREAD, collectionID); HarvestScheduler.lock.notify(); } } else { harvester = new OAIHarvester(context, collection, hc); harvester.runHarvest(); } } catch (Exception e) { testErrors.add(e.getMessage()); result.setErrors(testErrors); result.setContinue(false); return result; } result.setContinue(true); return result; } /** * Purge the collection of all items, then run a fresh harvest cycle. * * @param context The current DSpace context. * @param collectionID The collection id. * @param request the Cocoon request object * @return A process result's object. * @throws TransformerException * @throws SAXException * @throws ParserConfigurationException * @throws CrosswalkException * @throws BrowseException */ public static FlowResult processReimportCollection(Context context, int collectionID, Request request) throws SQLException, IOException, AuthorizeException, CrosswalkException, ParserConfigurationException, SAXException, TransformerException, BrowseException { Collection collection = Collection.find(context, collectionID); HarvestedCollection hc = HarvestedCollection.find(context, collectionID); ItemIterator it = collection.getAllItems(); //IndexBrowse ib = new IndexBrowse(context); while (it.hasNext()) { Item item = it.next(); //System.out.println("Deleting: " + item.getHandle()); //ib.itemRemoved(item); collection.removeItem(item); } hc.setHarvestResult(null,""); hc.update(); collection.update(); context.commit(); return processRunCollectionHarvest(context, collectionID, request); } /** * Test the supplied OAI settings. * * @param context * @param request * @return */ public static FlowResult testOAISettings(Context context, Request request) { FlowResult result = new FlowResult(); String oaiProvider = request.getParameter("oai_provider"); String oaiSetId = request.getParameter("oai_setid"); oaiSetId = request.getParameter("oai-set-setting"); if(!"all".equals(oaiSetId)) { oaiSetId = request.getParameter("oai_setid"); } String metadataKey = request.getParameter("metadata_format"); String harvestType = request.getParameter("harvest_level"); int harvestTypeInt = 0; if (oaiProvider == null || oaiProvider.length() == 0) { result.addError("oai_provider"); } if (oaiSetId == null || oaiSetId.length() == 0) { result.addError("oai_setid"); } if (metadataKey == null || metadataKey.length() == 0) { result.addError("metadata_format"); } if (harvestType == null || harvestType.length() == 0) { result.addError("harvest_level"); } else { harvestTypeInt = Integer.parseInt(harvestType); } if (result.getErrors() == null) { List<String> testErrors = OAIHarvester.verifyOAIharvester(oaiProvider, oaiSetId, metadataKey, (harvestTypeInt>1)); result.setErrors(testErrors); } if (result.getErrors() == null || result.getErrors().isEmpty()) { result.setOutcome(true); // On a successful test we still want to stay in the loop, not continue out of it //result.setContinue(true); result.setMessage(new Message("default","Harvesting settings are valid.")); } else { result.setOutcome(false); result.setContinue(false); // don't really need a message when the errors are highlighted already //result.setMessage(new Message("default","Harvesting is not properly configured.")); } return result; } /** * Look up the id of the template item for a given collection. * * @param context The current DSpace context. * @param collectionID The collection id. * @return The id of the template item. * @throws IOException */ public static int getTemplateItemID(Context context, int collectionID) throws SQLException, AuthorizeException, IOException { Collection collection = Collection.find(context, collectionID); Item template = collection.getTemplateItem(); if (template == null) { collection.createTemplateItem(); template = collection.getTemplateItem(); collection.update(); template.update(); context.commit(); } return template.getID(); } /** * Look up the id of a group authorized for one of the given roles. If no group is currently * authorized to perform this role then a new group will be created and assigned the role. * * @param context The current DSpace context. * @param collectionID The collection id. * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ. * @return The id of the group associated with that particular role, or -1 if the role was not found. */ public static int getCollectionRole(Context context, int collectionID, String roleName) throws SQLException, AuthorizeException, IOException { Collection collection = Collection.find(context, collectionID); // Determine the group based upon wich role we are looking for. Group role = null; if (ROLE_ADMIN.equals(roleName)) { role = collection.getAdministrators(); if (role == null) { role = collection.createAdministrators(); } } else if (ROLE_SUBMIT.equals(roleName)) { role = collection.getSubmitters(); if (role == null) { role = collection.createSubmitters(); } } else if (ROLE_WF_STEP1.equals(roleName)) { role = collection.getWorkflowGroup(1); if (role == null) { role = collection.createWorkflowGroup(1); } } else if (ROLE_WF_STEP2.equals(roleName)) { role = collection.getWorkflowGroup(2); if (role == null) { role = collection.createWorkflowGroup(2); } } else if (ROLE_WF_STEP3.equals(roleName)) { role = collection.getWorkflowGroup(3); if (role == null) { role = collection.createWorkflowGroup(3); } } // In case we needed to create a group, save our changes collection.update(); context.commit(); // If the role name was valid then role should be non null, if (role != null) { return role.getID(); } return -1; } /** * Delete one of collection's roles * * @param context The current DSpace context. * @param collectionID The collection id. * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ. * @param groupID The id of the group associated with this role. * @return A process result's object. */ public static FlowResult processDeleteCollectionRole(Context context, int collectionID, String roleName, int groupID) throws SQLException, UIException, IOException, AuthorizeException { FlowResult result = new FlowResult(); Collection collection = Collection.find(context,collectionID); Group role = Group.find(context, groupID); // First, Unregister the role if (ROLE_ADMIN.equals(roleName)) { collection.removeAdministrators(); } else if (ROLE_SUBMIT.equals(roleName)) { collection.removeSubmitters(); } else if (ROLE_WF_STEP1.equals(roleName)) { collection.setWorkflowGroup(1, null); } else if (ROLE_WF_STEP2.equals(roleName)) { collection.setWorkflowGroup(2, null); } else if (ROLE_WF_STEP3.equals(roleName)) { collection.setWorkflowGroup(3, null); } // Second, remove all authorizations for this role by searching for all policies that this // group has on the collection and remove them otherwise the delete will fail because // there are dependencies. @SuppressWarnings("unchecked") // the cast is correct List<ResourcePolicy> policies = AuthorizeManager.getPolicies(context,collection); for (ResourcePolicy policy : policies) { if (policy.getGroupID() == groupID) { policy.delete(); } } // Finally, Delete the role's actual group. collection.update(); role.delete(); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The role was successfully deleted.")); return result; } /** * Look up the id of a group authorized for one of the given roles. If no group is currently * authorized to perform this role then a new group will be created and assigned the role. * * @param context The current DSpace context. * @param collectionID The collection id. * @return The id of the group associated with that particular role or -1 */ public static int getCollectionDefaultRead(Context context, int collectionID) throws SQLException, AuthorizeException { Collection collection = Collection.find(context,collectionID); Group[] itemGroups = AuthorizeManager.getAuthorizedGroups(context, collection, Constants.DEFAULT_ITEM_READ); Group[] bitstreamGroups = AuthorizeManager.getAuthorizedGroups(context, collection, Constants.DEFAULT_BITSTREAM_READ); int itemGroupID = -1; // If there are more than one groups assigned either of these privileges then this role based method will not work. // The user will need to go to the authorization section to manually straighten this out. if (itemGroups.length != 1 || bitstreamGroups.length != 1) { // do nothing the itemGroupID is already set to -1 } else { Group itemGroup = itemGroups[0]; Group bitstreamGroup = bitstreamGroups[0]; // If the same group is not assigned both of these privileges then this role based method will not work. The user // will need to go to the authorization section to manually straighten this out. if (itemGroup.getID() != bitstreamGroup.getID()) { // do nothing the itemGroupID is already set to -1 } else { itemGroupID = itemGroup.getID(); } } return itemGroupID; } /** * Change default privileges from the anonymous group to a new group that will be created and * appropriate privileges assigned. The id of this new group will be returned. * * @param context The current DSpace context. * @param collectionID The collection id. * @return The group ID of the new group. */ public static int createCollectionDefaultReadGroup(Context context, int collectionID) throws SQLException, AuthorizeException, UIException { int roleID = getCollectionDefaultRead(context, collectionID); if (roleID != 0) { throw new UIException("Unable to create a new default read group because either the group allready exists or multiple groups are assigned the default privleges."); } Collection collection = Collection.find(context,collectionID); Group role = Group.create(context); role.setName("COLLECTION_"+collection.getID() +"_DEFAULT_READ"); // Remove existing privileges from the anonymous group. AuthorizeManager.removePoliciesActionFilter(context, collection, Constants.DEFAULT_ITEM_READ); AuthorizeManager.removePoliciesActionFilter(context, collection, Constants.DEFAULT_BITSTREAM_READ); // Grant our new role the default privileges. AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, role); AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, role); // Commit the changes role.update(); context.commit(); return role.getID(); } /** * Change the default read privileges to the anonymous group. * * If getCollectionDefaultRead() returns -1 or the anonymous group then nothing * is done. * * @param context The current DSpace context. * @param collectionID The collection id. * @return A process result's object. */ public static FlowResult changeCollectionDefaultReadToAnonymous(Context context, int collectionID) throws SQLException, AuthorizeException, UIException { FlowResult result = new FlowResult(); int roleID = getCollectionDefaultRead(context, collectionID); if (roleID < 1) { throw new UIException("Unable to delete the default read role because the role is either allready assigned to the anonymous group or multiple groups are assigned the default priveleges."); } Collection collection = Collection.find(context,collectionID); Group role = Group.find(context, roleID); Group anonymous = Group.find(context,0); // Delete the old role, this will remove the default privileges. role.delete(); // Set anonymous as the default read group. AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, anonymous); AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, anonymous); // Commit the changes context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","All new items submitted to this collection will default to anonymous read.")); return result; } /** * Delete collection itself * * @param context The current DSpace context. * @param collectionID The collection id. * @return A process result's object. */ public static FlowResult processDeleteCollection(Context context, int collectionID) throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); Collection collection = Collection.find(context, collectionID); Community[] parents = collection.getCommunities(); for (Community parent: parents) { parent.removeCollection(collection); parent.update(); } context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The collection was successfully deleted.")); return result; } /** * Create a new collection * * @param context The current DSpace context. * @param communityID The id of the parent community. * @return A process result's object. */ public static FlowResult processCreateCollection(Context context, int communityID, Request request) throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); Community parent = Community.find(context, communityID); Collection newCollection = parent.createCollection(); // Get the metadata String name = request.getParameter("name"); String shortDescription = request.getParameter("short_description"); String introductoryText = request.getParameter("introductory_text"); String copyrightText = request.getParameter("copyright_text"); String sideBarText = request.getParameter("side_bar_text"); String license = request.getParameter("license"); String provenanceDescription = request.getParameter("provenance_description"); // If they don't have a name then make it untitled. if (name == null || name.length() == 0) { name = "Untitled"; } // If empty, make it null. if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } if (license != null && license.length() == 0) { license = null; } if (provenanceDescription != null && provenanceDescription.length() == 0) { provenanceDescription = null; } // Save the metadata newCollection.setMetadata("name", name); newCollection.setMetadata("short_description", shortDescription); newCollection.setMetadata("introductory_text", introductoryText); newCollection.setMetadata("copyright_text", copyrightText); newCollection.setMetadata("side_bar_text", sideBarText); newCollection.setMetadata("license", license); newCollection.setMetadata("provenance_description", provenanceDescription); // Set the logo Object object = request.get("logo"); Part filePart = null; if (object instanceof Part) { filePart = (Part) object; } if (filePart != null && filePart.getSize() > 0) { InputStream is = filePart.getInputStream(); newCollection.setLogo(is); } // Save everything newCollection.update(); context.commit(); // success result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The collection was successfully created.")); result.setParameter("collectionID", newCollection.getID()); return result; } // Community related functions /** * Create a new community * * @param context The current DSpace context. * @param communityID The id of the parent community (-1 for a top-level community). * @return A process result's object. */ public static FlowResult processCreateCommunity(Context context, int communityID, Request request) throws AuthorizeException, IOException, SQLException { FlowResult result = new FlowResult(); Community parent = Community.find(context, communityID); Community newCommunity; if (parent != null) { newCommunity = parent.createSubcommunity(); } else { newCommunity = Community.create(null, context); } String name = request.getParameter("name"); String shortDescription = request.getParameter("short_description"); String introductoryText = request.getParameter("introductory_text"); String copyrightText = request.getParameter("copyright_text"); String sideBarText = request.getParameter("side_bar_text"); // If they don't have a name then make it untitled. if (name == null || name.length() == 0) { name = "Untitled"; } // If empty, make it null. if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } newCommunity.setMetadata("name", name); newCommunity.setMetadata("short_description", shortDescription); newCommunity.setMetadata("introductory_text", introductoryText); newCommunity.setMetadata("copyright_text", copyrightText); newCommunity.setMetadata("side_bar_text", sideBarText); // Upload the logo Object object = request.get("logo"); Part filePart = null; if (object instanceof Part) { filePart = (Part) object; } if (filePart != null && filePart.getSize() > 0) { InputStream is = filePart.getInputStream(); newCommunity.setLogo(is); } // Save everything newCommunity.update(); context.commit(); // success result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The community was successfully created.")); result.setParameter("communityID", newCommunity.getID()); return result; } /** * Process the community metadata edit form. * * @param context The current DSpace context. * @param communityID The community id. * @param deleteLogo Determines if the logo should be deleted along with the metadata editing action. * @param request the Cocoon request object * @return A process result's object. */ public static FlowResult processEditCommunity(Context context, int communityID, boolean deleteLogo, Request request) throws AuthorizeException, IOException, SQLException { FlowResult result = new FlowResult(); Community community = Community.find(context, communityID); String name = request.getParameter("name"); String shortDescription = request.getParameter("short_description"); String introductoryText = request.getParameter("introductory_text"); String copyrightText = request.getParameter("copyright_text"); String sideBarText = request.getParameter("side_bar_text"); // If they don't have a name then make it untitled. if (name == null || name.length() == 0) { name = "Untitled"; } // If empty, make it null. if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } // Save the data community.setMetadata("name", name); community.setMetadata("short_description", shortDescription); community.setMetadata("introductory_text", introductoryText); community.setMetadata("copyright_text", copyrightText); community.setMetadata("side_bar_text", sideBarText); if (deleteLogo) { // Remove the logo community.setLogo(null); } else { // Update the logo Object object = request.get("logo"); Part filePart = null; if (object instanceof Part) { filePart = (Part) object; } if (filePart != null && filePart.getSize() > 0) { InputStream is = filePart.getInputStream(); community.setLogo(is); } } // Save everything community.update(); context.commit(); // No notice... result.setContinue(true); return result; } /** * Delete community itself * * @param context The current DSpace context. * @param communityID The community id. * @return A process result's object. */ public static FlowResult processDeleteCommunity(Context context, int communityID) throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); Community community = Community.find(context, communityID); community.delete(); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The community was successfully deleted.")); return result; } /** * Look up the id of a group authorized for one of the given roles. If no group is currently * authorized to perform this role then a new group will be created and assigned the role. * * @param context The current DSpace context. * @param communityID The collection id. * @param roleName ADMIN. * @return The id of the group associated with that particular role, or -1 if the role was not found. */ public static int getCommunityRole(Context context, int communityID, String roleName) throws SQLException, AuthorizeException, IOException { Community community = Community.find(context, communityID); // Determine the group based upon which role we are looking for. Group role = null; if (ROLE_ADMIN.equals(roleName)) { role = community.getAdministrators(); if (role == null) { role = community.createAdministrators(); } } // In case we needed to create a group, save our changes community.update(); context.commit(); // If the role name was valid then role should be non null, if (role != null) { return role.getID(); } return -1; } /** * Delete one of a community's roles * * @param context The current DSpace context. * @param communityID The community id. * @param roleName ADMIN. * @param groupID The id of the group associated with this role. * @return A process result's object. */ public static FlowResult processDeleteCommunityRole(Context context, int communityID, String roleName, int groupID) throws SQLException, UIException, IOException, AuthorizeException { FlowResult result = new FlowResult(); Community community = Community.find(context, communityID); Group role = Group.find(context, groupID); // First, unregister the role if (ROLE_ADMIN.equals(roleName)) { community.removeAdministrators(); } // Second, remove all authorizations for this role by searching for all policies that this // group has on the collection and remove them otherwise the delete will fail because // there are dependencies. @SuppressWarnings("unchecked") // the cast is correct List<ResourcePolicy> policies = AuthorizeManager.getPolicies(context, community); for (ResourcePolicy policy : policies) { if (policy.getGroupID() == groupID) { policy.delete(); } } // Finally, delete the role's actual group. community.update(); role.delete(); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The role was successfully deleted.")); return result; } /** * Delete a collection's template item (which is not a member of the collection). * * @param context * @param collectionID * @return * @throws SQLException * @throws AuthorizeException * @throws IOException */ public static FlowResult processDeleteTemplateItem(Context context, int collectionID) throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); Collection collection = Collection.find(context, collectionID); collection.removeTemplateItem(); context.commit(); result.setContinue(true); result.setOutcome(true); return result; } /** * processCurateCollection * * Utility method to process curation tasks * submitted via the DSpace GUI * * @param context * @param dsoID * @param request * */ public static FlowResult processCurateCollection(Context context, int dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception { String task = request.getParameter("curate_task"); Curator curator = FlowCurationUtils.getCurator(task); Collection collection = Collection.find(context, dsoID); if (collection != null) { curator.curate(collection); } return FlowCurationUtils.getRunFlowResult(task, curator); } /** * queues curation tasks */ public static FlowResult processQueueCollection(Context context, int dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception { String task = request.getParameter("curate_task"); Curator curator = FlowCurationUtils.getCurator(task); String objId = String.valueOf(dsoID); String taskQueueName = ConfigurationManager.getProperty("curate", "ui.queuename"); boolean status = false; Collection collection = Collection.find(context, dsoID); if (collection != null) { objId = collection.getHandle(); try { curator.queue(context, objId, taskQueueName); status = true; } catch (IOException ioe) { // no-op } } return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); } /** * processCurateCommunity * * Utility method to process curation tasks * submitted via the DSpace GUI * * @param context * @param dsoID * @param request * */ public static FlowResult processCurateCommunity(Context context, int dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception { String task = request.getParameter("curate_task"); Curator curator = FlowCurationUtils.getCurator(task); Community community = Community.find(context, dsoID); if (community != null) { curator.curate(community); } return FlowCurationUtils.getRunFlowResult(task, curator); } /** * queues curation tasks */ public static FlowResult processQueueCommunity(Context context, int dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception { String task = request.getParameter("curate_task"); Curator curator = FlowCurationUtils.getCurator(task); String objId = String.valueOf(dsoID); String taskQueueName = ConfigurationManager.getProperty("curate", "ui.queuename"); boolean status = false; Community community = Community.find(context, dsoID); if (community != null) { objId = community.getHandle(); try { curator.queue(context, objId, taskQueueName); status = true; } catch (IOException ioe) { // no-op } } return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); } /** * Check whether this metadata value is a proper XML fragment. If the value is not * then an error message will be returned that might (sometimes not) tell the user how * to correct the problem. * * @param value The metadat's value * @return An error string of the problem or null if there is no problem with the metadata's value. */ public static String checkXMLFragment(String value) { // escape the ampersand correctly; value = escapeXMLEntities(value); // Try and parse the XML into a mini-DOM String xml = "<?xml version='1.0' encoding='UTF-8'?><fragment>"+value+"</fragment>"; ByteArrayInputStream inputStream = null; try { inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { inputStream = new ByteArrayInputStream(xml.getBytes()); //not supposed to happen, but never hurts } SAXBuilder builder = new SAXBuilder(); try { // This will generate an error if not valid XML. builder.build(inputStream); } catch (JDOMException jdome) { // It's not XML return jdome.getMessage(); } catch (IOException ioe) { // This shouldn't ever occur because we are parsing // an in-memory string, but in case it does we'll just return // it as a normal error. return ioe.getMessage(); } return null; } /** * Sanitize any XML that was inputed by the user, this will clean up * any unescaped characters so that they can be stored as proper XML. * These are errors that in general we want to take care of on behalf * of the user. * * @param value The unsanitized value * @return A sanitized value */ public static String escapeXMLEntities(String value) { if (value == null) { return null; } // Escape any XML entities int amp = -1; while ((amp = value.indexOf('&', amp+1)) > -1) { // Is it an xml entity named by number? if (substringCompare(value,amp+1,'#')) { continue; } // &amp; if (substringCompare(value,amp+1,'a','m','p',';')) { continue; } // &apos; if (substringCompare(value,amp+1,'a','p','o','s',';')) { continue; } // &quot; if (substringCompare(value,amp+1,'q','u','o','t',';')) { continue; } // &lt; if (substringCompare(value,amp+1,'l','t',';')) { continue; } // &gt; if (substringCompare(value,amp+1,'g','t',';')) { continue; } // Replace the ampersand with an XML entity. value = value.substring(0,amp) + "&amp;" + value.substring(amp+1); } return value; } /** * Check if the given character sequence is located in the given * string at the specified index. If it is then return true, otherwise false. * * @param string The string to test against * @param index The location within the string * @param characters The character sequence to look for. * @return true if the character sequence was found, otherwise false. */ private static boolean substringCompare(String string, int index, char ... characters) { // Is the string long enough? if (string.length() <= index + characters.length) { return false; } // Do all the characters match? for (char character : characters) { if (string.charAt(index) != character) { return false; } index++; } return false; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; /** * Display a generic error message saying the user can * not preform the requested action. * * @author Scott phillips */ public class NotAuthorized extends AbstractDSpaceTransformer { private static final Message T_title = message("xmlui.administrative.NotAuthorized.title"); private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_trail = message("xmlui.administrative.NotAuthorized.trail"); private static final Message T_head = message("xmlui.administrative.NotAuthorized.head"); private static final Message T_para1a = message("xmlui.administrative.NotAuthorized.para1a"); private static final Message T_para1b = message("xmlui.administrative.NotAuthorized.para1b"); private static final Message T_para1c = message("xmlui.administrative.NotAuthorized.para1c"); private static final Message T_para2 = message("xmlui.administrative.NotAuthorized.para2"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException { String loginURL = contextPath+"/login"; String feedbackURL = contextPath+"/feedback"; Division main = body.addDivision("not-authorized","primary administrative"); main.setHead(T_head); Para para1 = main.addPara(); para1.addContent(T_para1a); para1.addXref(feedbackURL,T_para1b); para1.addContent(T_para1c); main.addPara().addXref(loginURL,T_para2); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.metadataimport; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Button; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Cell; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.content.DCValue; import org.xml.sax.SAXException; import org.dspace.app.bulkedit.BulkEditChange; /** * Web interface to Bulk Metadata Import app. * ported from org.dspace.app.webui.servlet.MetadataImportServlet * * Display form for user to review changes and confirm * * @author Kim Shepherd */ public class MetadataImportUpload extends AbstractDSpaceTransformer { /** Language strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); private static final Message T_no_changes = message("xmlui.administrative.metadataimport.general.no_changes"); private static final Message T_new_item = message("xmlui.administrative.metadataimport.general.new_item"); private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); private static final Message T_para = message("xmlui.administrative.metadataimport.MetadataImportUpload.hint"); private static final Message T_submit_confirm = message("xmlui.administrative.metadataimport.MetadataImportUpload.submit_confirm"); private static final Message T_changes_pending = message("xmlui.administrative.metadataimport.MetadataImportUpload.changes_pending"); private static final Message T_item_addition = message("xmlui.administrative.metadataimport.MetadataImportUpload.item_add"); private static final Message T_item_deletion = message("xmlui.administrative.metadataimport.MetadataImportUpload.item_remove"); private static final Message T_collection_newowner = message("xmlui.administrative.metadataimport.MetadataImportUpload.collection_newowner"); private static final Message T_collection_oldowner = message("xmlui.administrative.metadataimport.MetadataImportUpload.collection_oldowner"); private static final Message T_collection_mapped = message("xmlui.administrative.metadataimport.MetadataImportUpload.collection_mapped"); private static final Message T_collection_unmapped = message("xmlui.administrative.metadataimport.MetadataImportUpload.collection_unmapped"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws SAXException, WingException, SQLException { // Get list of changes Request request = ObjectModelHelper.getRequest(objectModel); ArrayList<BulkEditChange> changes = null; int num_changes = 0; if(request.getAttribute("changes") != null) { changes = ((ArrayList<BulkEditChange>)request.getAttribute("changes")); num_changes = changes.size(); } // DIVISION: metadata-import Division div = body.addInteractiveDivision("metadata-import",contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART,"primary administrative"); div.setHead(T_head1); if(num_changes > 0) { div.addPara(T_para); Table mdchanges = div.addTable("metadata-changes", num_changes, 2); // Display the changes for (BulkEditChange change : changes) { // Get the changes List<DCValue> adds = change.getAdds(); List<DCValue> removes = change.getRemoves(); List<Collection> newCollections = change.getNewMappedCollections(); List<Collection> oldCollections = change.getOldMappedCollections(); if ((adds.size() > 0) || (removes.size() > 0) || (newCollections.size() > 0) || (oldCollections.size() > 0) || (change.getNewOwningCollection() != null) || (change.getOldOwningCollection() != null)) { Row headerrow = mdchanges.addRow(Row.ROLE_HEADER); // Show the item if (!change.isNewItem()) { Item i = change.getItem(); Cell cell = headerrow.addCell(); cell.addContent(T_changes_pending); cell.addContent(" " + i.getID() + " (" + i.getHandle() + ")"); } else { headerrow.addCellContent(T_new_item); } headerrow.addCell(); } // Show new owning collection if (change.getNewOwningCollection() != null) { Collection c = change.getNewOwningCollection(); if (c != null) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); colrow.addCellContent(T_collection_newowner); colrow.addCellContent(cHandle + " (" + cName + ")"); } } // Show old owning collection if (change.getOldOwningCollection() != null) { Collection c = change.getOldOwningCollection(); if (c != null) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); colrow.addCellContent(T_collection_oldowner); colrow.addCellContent(cHandle + " (" + cName + ")"); } } // Show new mapped collections for (Collection c : newCollections) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); colrow.addCellContent(T_collection_mapped); colrow.addCellContent(cHandle + " (" + cName + ")"); } // Show old mapped collections for (Collection c : oldCollections) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); colrow.addCellContent(T_collection_unmapped); colrow.addCellContent(cHandle + " (" + cName + ")"); } // Show additions for (DCValue dcv : adds) { Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); String md = dcv.schema + "." + dcv.element; if (dcv.qualifier != null) { md += "." + dcv.qualifier; } if (dcv.language != null) { md += "[" + dcv.language + "]"; } Cell cell = mdrow.addCell(); cell.addContent(T_item_addition); cell.addContent(" (" + md + ")"); mdrow.addCellContent(dcv.value); } // Show removals for (DCValue dcv : removes) { Row mdrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); String md = dcv.schema + "." + dcv.element; if (dcv.qualifier != null) { md += "." + dcv.qualifier; } if (dcv.language != null) { md += "[" + dcv.language + "]"; } Cell cell = mdrow.addCell(); cell.addContent(T_item_deletion); cell.addContent(" (" + md + ")"); mdrow.addCellContent(dcv.value); } } Para actions = div.addPara(); Button applychanges = actions.addButton("submit_confirm"); applychanges.setValue(T_submit_confirm); Button cancel = actions.addButton("submit_return"); cancel.setValue(T_submit_return); } else { Para nochanges = div.addPara(); nochanges.addContent(T_no_changes); Para actions = div.addPara(); Button cancel = actions.addButton("submit_return"); cancel.setValue(T_submit_return); } div.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.metadataimport; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Button; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Cell; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.content.DCValue; import org.xml.sax.SAXException; import org.dspace.app.bulkedit.BulkEditChange; /** * Web interface to Bulk Metadata Import app. * ported from org.dspace.app.webui.servlet.MetadataImportServlet * * Display summary of committed changes * * @author Kim Shepherd */ public class MetadataImportConfirm extends AbstractDSpaceTransformer { /** Language strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); private static final Message T_changes = message("xmlui.administrative.metadataimport.general.changes"); private static final Message T_new_item = message("xmlui.administrative.metadataimport.general.new_item"); private static final Message T_no_changes = message("xmlui.administrative.metadataimport.general.no_changes"); private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); private static final Message T_success = message("xmlui.administrative.metadataimport.MetadataImportConfirm.success"); private static final Message T_changes_committed = message("xmlui.administrative.metadataimport.MetadataImportConfirm.changes_committed"); private static final Message T_item_addition = message("xmlui.administrative.metadataimport.MetadataImportConfirm.item_added"); private static final Message T_item_deletion = message("xmlui.administrative.metadataimport.MetadataImportConfirm.item_removed"); private static final Message T_collection_newowner = message("xmlui.administrative.metadataimport.MetadataImportConfirm.collection_newowner"); private static final Message T_collection_oldowner = message("xmlui.administrative.metadataimport.MetadataImportConfirm.collection_oldowner"); private static final Message T_collection_mapped = message("xmlui.administrative.metadataimport.MetadataImportConfirm.collection_mapped"); private static final Message T_collection_unmapped = message("xmlui.administrative.metadataimport.MetadataImportConfirm.collection_unmapped"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws SAXException, WingException, SQLException { // Get list of changes Request request = ObjectModelHelper.getRequest(objectModel); ArrayList<BulkEditChange> changes = null; if(request.getAttribute("changes") != null) { changes = ((ArrayList<BulkEditChange>)request.getAttribute("changes")); } if (changes == null) { changes = new ArrayList<BulkEditChange>(); } // DIVISION: metadata-import Division div = body.addInteractiveDivision("metadata-import",contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART,"primary administrative"); div.setHead(T_head1); Para para = div.addPara(); para.addContent(T_success); para.addContent(" " + changes.size() + " "); para.addContent(T_changes); if(changes.size() > 0) { Table mdchanges = div.addTable("metadata-changes", changes.size(), 2); // Display the changes for (BulkEditChange change : changes) { // Get the changes List<DCValue> adds = change.getAdds(); List<DCValue> removes = change.getRemoves(); List<Collection> newCollections = change.getNewMappedCollections(); List<Collection> oldCollections = change.getOldMappedCollections(); if ((adds.size() > 0) || (removes.size() > 0) || (newCollections.size() > 0) || (oldCollections.size() > 0) || (change.getNewOwningCollection() != null) || (change.getOldOwningCollection() != null)) { Row headerrow = mdchanges.addRow(Row.ROLE_HEADER); // Show the item if (!change.isNewItem()) { Item i = change.getItem(); Cell cell = headerrow.addCell(); cell.addContent(T_changes_committed); cell.addContent(" " + i.getID() + " (" + i.getHandle() + ")"); } else { headerrow.addCellContent(T_new_item); } headerrow.addCell(); } // Show new owning collection if (change.getNewOwningCollection() != null) { Collection c = change.getNewOwningCollection(); if (c != null) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); colrow.addCellContent(T_collection_newowner); colrow.addCellContent(cHandle + " (" + cName + ")"); } } // Show old owning collection if (change.getOldOwningCollection() != null) { Collection c = change.getOldOwningCollection(); if (c != null) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); colrow.addCellContent(T_collection_oldowner); colrow.addCellContent(cHandle + " (" + cName + ")"); } } // Show new mapped collections for (Collection c : newCollections) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); colrow.addCellContent(T_collection_mapped); colrow.addCellContent(cHandle + " (" + cName + ")"); } // Show old mapped collections for (Collection c : oldCollections) { String cHandle = c.getHandle(); String cName = c.getName(); Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); colrow.addCellContent(T_collection_unmapped); colrow.addCellContent(cHandle + " (" + cName + ")"); } // Show additions for (DCValue dcv : adds) { Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); String md = dcv.schema + "." + dcv.element; if (dcv.qualifier != null) { md += "." + dcv.qualifier; } if (dcv.language != null) { md += "[" + dcv.language + "]"; } Cell cell = mdrow.addCell(); cell.addContent(T_item_addition); cell.addContent(" (" + md + ")"); mdrow.addCellContent(dcv.value); } // Show removals for (DCValue dcv : removes) { Row mdrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); String md = dcv.schema + "." + dcv.element; if (dcv.qualifier != null) { md += "." + dcv.qualifier; } if (dcv.language != null) { md += "[" + dcv.language + "]"; } Cell cell = mdrow.addCell(); cell.addContent(T_item_deletion); cell.addContent(" (" + md + ")"); mdrow.addCellContent(dcv.value); } } } else { Para nochanges = div.addPara(); nochanges.addContent(T_no_changes); } Para actions = div.addPara(); Button cancel = actions.addButton("submit_return"); cancel.setValue(T_submit_return); div.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.metadataimport; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Button; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.xml.sax.SAXException; /** * Web interface to Bulk Metadata Import app. * ported from org.dspace.app.webui.servlet.MetadataImportServlet * * Initial select file / upload CSV form * * @author Kim Shepherd */ public class MetadataImportMain extends AbstractDSpaceTransformer { /** Language strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); private static final Message T_submit_upload = message("xmlui.administrative.metadataimport.MetadataImportMain.submit_upload"); private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws SAXException, WingException, SQLException { // DIVISION: metadata-import Division div = body.addInteractiveDivision("metadata-import",contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART,"primary administrative"); div.setHead(T_head1); Para file = div.addPara(); file.addFile("file"); Para actions = div.addPara(); Button button = actions.addButton("submit_upload"); button.setValue(T_submit_upload); div.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import java.util.ArrayList; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.CheckBox; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.content.MetadataSchema; /** * This is the main entry point for managing the metadata registry. This transformer * shows the list of all current schemas and a form for adding new schema's to the * registry. * * @author Scott Phillips */ public class MetadataRegistryMain extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.registries.MetadataRegistryMain.title"); private static final Message T_metadata_registry_trail = message("xmlui.administrative.registries.general.metadata_registry_trail"); private static final Message T_head1 = message("xmlui.administrative.registries.MetadataRegistryMain.head1"); private static final Message T_para1 = message("xmlui.administrative.registries.MetadataRegistryMain.para1"); private static final Message T_column1 = message("xmlui.administrative.registries.MetadataRegistryMain.column1"); private static final Message T_column2 = message("xmlui.administrative.registries.MetadataRegistryMain.column2"); private static final Message T_column3 = message("xmlui.administrative.registries.MetadataRegistryMain.column3"); private static final Message T_column4 = message("xmlui.administrative.registries.MetadataRegistryMain.column4"); private static final Message T_submit_delete = message("xmlui.administrative.registries.MetadataRegistryMain.submit_delete"); private static final Message T_head2 = message("xmlui.administrative.registries.MetadataRegistryMain.head2"); private static final Message T_namespace = message("xmlui.administrative.registries.MetadataRegistryMain.namespace"); private static final Message T_namespace_help = message("xmlui.administrative.registries.MetadataRegistryMain.namespace_help"); private static final Message T_namespace_error = message("xmlui.administrative.registries.MetadataRegistryMain.namespace_error"); private static final Message T_name = message("xmlui.administrative.registries.MetadataRegistryMain.name"); private static final Message T_name_help = message("xmlui.administrative.registries.MetadataRegistryMain.name_help"); private static final Message T_name_error = message("xmlui.administrative.registries.MetadataRegistryMain.name_error"); private static final Message T_submit_add = message("xmlui.administrative.registries.MetadataRegistryMain.submit_add"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); } public void addBody(Body body) throws WingException, SQLException { // Get all our parameters first Request request = ObjectModelHelper.getRequest(objectModel); String namespaceValue = request.getParameter("namespace"); String nameValue = request.getParameter("name"); String errorString = parameters.getParameter("errors",null); ArrayList<String> errors = new ArrayList<String>(); if (errorString != null) { for (String error : errorString.split(",")) { errors.add(error); } } MetadataSchema[] schemas = MetadataSchema.findAll(context); // DIVISION: metadata-registry-main Division main = body.addInteractiveDivision("metadata-registry-main",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry "); main.setHead(T_head1); main.addPara(T_para1); Table table = main.addTable("metadata-registry-main-table", schemas.length+1, 5); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_column1); header.addCellContent(T_column2); header.addCellContent(T_column3); header.addCellContent(T_column4); for (MetadataSchema schema : schemas) { int schemaID = schema.getSchemaID(); String namespace = schema.getNamespace(); String name = schema.getName(); String url = contextPath + "/admin/metadata-registry?administrative-continue="+knot.getId()+"&submit_edit&schemaID="+schemaID; Row row = table.addRow(); if (schemaID > 1) { // If the schema is not in the required DC schema allow the user to delete it. CheckBox select = row.addCell().addCheckBox("select_schema"); select.setLabel(String.valueOf(schemaID)); select.addOption(String.valueOf(schemaID)); } else { // The DC schema can not be removed. row.addCell(); } row.addCell().addContent(schemaID); row.addCell().addXref(url,namespace); row.addCell().addXref(url,name); } if (schemas.length > 1) { // Only give the delete option if there are more schema's than the required dublin core. main.addPara().addButton("submit_delete").setValue(T_submit_delete); } // DIVISION: add new schema Division newSchema = main.addDivision("add-schema"); newSchema.setHead(T_head2); List form = newSchema.addList("new-schema",List.TYPE_FORM); Text namespace = form.addItem().addText("namespace"); namespace.setLabel(T_namespace); namespace.setRequired(); namespace.setHelp(T_namespace_help); if (namespaceValue != null) { namespace.setValue(namespaceValue); } if (errors.contains("namespace")) { namespace.addError(T_namespace_error); } Text name = form.addItem().addText("name"); name.setLabel(T_name); name.setRequired(); name.setHelp(T_name_help); if (nameValue != null) { name.setValue(nameValue); } if (errors.contains("name")) { name.addError(T_name_error); } form.addItem().addButton("submit_add").setValue(T_submit_add); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import java.util.ArrayList; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.AuthorizeException; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; /** * Prompt the user with a list of to-be-deleted metadata fields and * ask the user if they are sure they want them deleted. * * @author Scott phillips */ public class DeleteMetadataFieldsConfirm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_submit_delete = message("xmlui.general.delete"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); private static final Message T_title = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.title"); private static final Message T_metadata_registry_trail = message("xmlui.administrative.registries.general.metadata_registry_trail"); private static final Message T_trail = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.trail"); private static final Message T_head = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.head"); private static final Message T_para1 = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.para1"); private static final Message T_warning = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.warning"); private static final Message T_para2 = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.para2"); private static final Message T_column1 = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column1"); private static final Message T_column2 = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column2"); private static final Message T_column3 = message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column3"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { // Get all our parameters String idsString = parameters.getParameter("fieldIDs", null); ArrayList<MetadataField> fields = new ArrayList<MetadataField>(); for (String id : idsString.split(",")) { MetadataField field = MetadataField.find(context,Integer.valueOf(id)); fields.add(field); } // DIVISION: metadata-field-confirm-delete Division deleted = body.addInteractiveDivision("metadata-field-confirm-delete",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); deleted.setHead(T_head); deleted.addPara(T_para1); Para warning = deleted.addPara(); warning.addHighlight("bold").addContent(T_warning); warning.addContent(T_para2); Table table = deleted.addTable("field-confirm-delete",fields.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); for (MetadataField field : fields) { if (field == null) { continue; } String fieldID = String.valueOf(field.getFieldID()); String fieldEelement = field.getElement(); String fieldQualifier = field.getQualifier(); MetadataSchema schema = MetadataSchema.find(context, field.getSchemaID()); String schemaName = schema.getName(); StringBuilder fieldName = new StringBuilder() .append(schemaName) .append(".") .append(fieldEelement); if (fieldQualifier != null && fieldQualifier.length() > 0) { fieldName.append(".").append(fieldQualifier); } String fieldScopeNote = field.getScopeNote(); Row row = table.addRow(); row.addCell().addContent(fieldID); row.addCell().addContent(fieldName.toString()); row.addCell().addContent(fieldScopeNote); } Para buttons = deleted.addPara(); buttons.addButton("submit_confirm").setValue(T_submit_delete); buttons.addButton("submit_cancel").setValue(T_submit_cancel); deleted.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import java.util.ArrayList; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.RequestUtils; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.CheckBox; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Select; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.app.xmlui.wing.element.TextArea; import org.dspace.content.BitstreamFormat; /** * Enable the user to edit a bitstream format's metadata. * * @author Scott Phillips */ public class EditBitstreamFormat extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.registries.EditBitstreamFormat.title"); private static final Message T_format_registry_trail = message("xmlui.administrative.registries.general.format_registry_trail"); private static final Message T_trail = message("xmlui.administrative.registries.EditBitstreamFormat.trail"); private static final Message T_head1 = message("xmlui.administrative.registries.EditBitstreamFormat.head1"); private static final Message T_head2 = message("xmlui.administrative.registries.EditBitstreamFormat.head2"); private static final Message T_para1 = message("xmlui.administrative.registries.EditBitstreamFormat.para1"); private static final Message T_name = message("xmlui.administrative.registries.EditBitstreamFormat.name"); private static final Message T_name_help = message("xmlui.administrative.registries.EditBitstreamFormat.name_help"); private static final Message T_name_error = message("xmlui.administrative.registries.EditBitstreamFormat.name_error"); private static final Message T_mimetype = message("xmlui.administrative.registries.EditBitstreamFormat.mimetype"); private static final Message T_mimetype_help = message("xmlui.administrative.registries.EditBitstreamFormat.mimetype_help"); private static final Message T_description = message("xmlui.administrative.registries.EditBitstreamFormat.description"); private static final Message T_support = message("xmlui.administrative.registries.EditBitstreamFormat.support"); private static final Message T_support_help = message("xmlui.administrative.registries.EditBitstreamFormat.support_help"); private static final Message T_support_0 = message("xmlui.administrative.registries.EditBitstreamFormat.support_0"); private static final Message T_support_1 = message("xmlui.administrative.registries.EditBitstreamFormat.support_1"); private static final Message T_support_2 = message("xmlui.administrative.registries.EditBitstreamFormat.support_2"); private static final Message T_internal = message("xmlui.administrative.registries.EditBitstreamFormat.internal"); private static final Message T_internal_help = message("xmlui.administrative.registries.EditBitstreamFormat.internal_help"); private static final Message T_extensions = message("xmlui.administrative.registries.EditBitstreamFormat.extensions"); private static final Message T_extensions_help = message("xmlui.administrative.registries.EditBitstreamFormat.extensions_help"); private static final Message T_submit_save = message("xmlui.general.save"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/format-registry",T_format_registry_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException { // Get our parameters & state int formatID = parameters.getParameterAsInteger("formatID",-1); BitstreamFormat format = null; if (formatID >= 0) { format = BitstreamFormat.find(context, formatID); } String errorString = parameters.getParameter("errors",null); ArrayList<String> errors = new ArrayList<String>(); if (errorString != null) { for (String error : errorString.split(",")) { errors.add(error); } } Request request = ObjectModelHelper.getRequest(objectModel); String mimetypeValue = request.getParameter("mimetype"); String nameValue = request.getParameter("short_description"); String descriptionValue = request.getParameter("description"); String supportLevelValue = request.getParameter("support_level"); String internalValue = request.getParameter("internal"); java.util.List<String> extensionsList = RequestUtils.getFieldValues(request, "extensions"); String[] extensionValues = extensionsList.toArray(new String[extensionsList.size()]); // Remove leading periods from file extensions. for (int i = 0; i < extensionValues.length; i++) { if (extensionValues[i].startsWith(".")) { extensionValues[i] = extensionValues[i].substring(1); } } if (format != null) { if (mimetypeValue == null) { mimetypeValue = format.getMIMEType(); } if (nameValue == null) { nameValue = format.getShortDescription(); } if (descriptionValue == null) { descriptionValue = format.getDescription(); } if (supportLevelValue == null) { supportLevelValue = String.valueOf(format.getSupportLevel()); } if (request.getParameter("mimetype") == null) { internalValue = format.isInternal() ? "true" : null; } if (request.getParameter("extensions") == null) { extensionValues = format.getExtensions(); } } // DIVISION: edit-bitstream-format Division main = body.addInteractiveDivision("edit-bitstream-format",contextPath+"/admin/format-registry",Division.METHOD_POST,"primary administrative format-registry"); if (formatID == -1) { main.setHead(T_head1); } else { main.setHead(T_head2.parameterize(nameValue)); } main.addPara(T_para1); List form = main.addList("edit-bitstream-format",List.TYPE_FORM); Text name = form.addItem().addText("short_description"); name.setRequired(); name.setLabel(T_name); name.setHelp(T_name_help); name.setValue(nameValue); name.setSize(35); if (errors.contains("short_description")) { name.addError(T_name_error); } Text mimeType = form.addItem().addText("mimetype"); mimeType.setLabel(T_mimetype); mimeType.setHelp(T_mimetype_help); mimeType.setValue(mimetypeValue); mimeType.setSize(35); // Do not allow anyone to change the name of the unknown format. if (format != null && format.getID() == 1) { name.setDisabled(); } TextArea description = form.addItem().addTextArea("description"); description.setLabel(T_description); description.setValue(descriptionValue); description.setSize(3, 35); Select supportLevel = form.addItem().addSelect("support_level"); supportLevel.setLabel(T_support); supportLevel.setHelp(T_support_help); supportLevel.addOption(0,T_support_0); supportLevel.addOption(1,T_support_1); supportLevel.addOption(2,T_support_2); supportLevel.setOptionSelected(supportLevelValue); CheckBox internal = form.addItem().addCheckBox("internal"); internal.setLabel(T_internal); internal.setHelp(T_internal_help); internal.addOption((internalValue != null),"true"); Text extensions = form.addItem().addText("extensions"); extensions.setLabel(T_extensions); extensions.setHelp(T_extensions_help); extensions.enableAddOperation(); extensions.enableDeleteOperation(); for (String extensionValue : extensionValues) { extensions.addInstance().setValue(extensionValue); } Item actions = form.addItem(); actions.addButton("submit_save").setValue(T_submit_save); actions.addButton("submit_cancel").setValue(T_submit_cancel); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import java.util.ArrayList; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.AuthorizeException; import org.dspace.content.BitstreamFormat; /** * Confirm the deletition of bitstream formats by listing to-be-deleted * formats and asking the user for confirmation. * * @author Scott phillips */ public class DeleteBitstreamFormatsConfirm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_submit_delete = message("xmlui.general.delete"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); private static final Message T_title = message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.title"); private static final Message T_format_registry_trail = message("xmlui.administrative.registries.general.format_registry_trail"); private static final Message T_trail = message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.trail"); private static final Message T_head = message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.head"); private static final Message T_para1 = message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.para1"); private static final Message T_column1 = message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column1"); private static final Message T_column2 = message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column2"); private static final Message T_column3 = message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column3"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/format-registry",T_format_registry_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { // Get all our parameters String idsString = parameters.getParameter("formatIDs", null); ArrayList<BitstreamFormat> formats = new ArrayList<BitstreamFormat>(); for (String id : idsString.split(",")) { BitstreamFormat format = BitstreamFormat.find(context,Integer.valueOf(id)); formats.add(format); } // DIVISION: bitstream-format-confirm-delete Division deleted = body.addInteractiveDivision("bitstream-format-confirm-delete",contextPath+"/admin/format-registry",Division.METHOD_POST,"primary administrative format-registry"); deleted.setHead(T_head); deleted.addPara(T_para1); Table table = deleted.addTable("format-confirm-delete",formats.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); for (BitstreamFormat format : formats) { if (format == null) { continue; } String formatID = String.valueOf(format.getID()); String mimetype = format.getMIMEType(); String name = format.getShortDescription(); Row row = table.addRow(); row.addCell().addContent(formatID); row.addCell().addContent(mimetype); row.addCell().addContent(name); } Para buttons = deleted.addPara(); buttons.addButton("submit_confirm").setValue(T_submit_delete); buttons.addButton("submit_cancel").setValue(T_submit_cancel); deleted.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import java.util.ArrayList; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.AuthorizeException; import org.dspace.content.MetadataSchema; /** * Prompt the user to determin if they really want to delete the displayed schemas. * * @author Scott phillips */ public class DeleteMetadataSchemaConfirm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.title"); private static final Message T_metadata_registry_trail = message("xmlui.administrative.registries.general.metadata_registry_trail"); private static final Message T_trail = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.trail"); private static final Message T_head = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.head"); private static final Message T_para1 = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.para1"); private static final Message T_warning = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.warning"); private static final Message T_para2 = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.para2"); private static final Message T_column1 = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column1"); private static final Message T_column2 = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column2"); private static final Message T_column3 = message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column3"); private static final Message T_submit_delete = message("xmlui.general.delete"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { // Get all our parameters String idsString = parameters.getParameter("schemaIDs", null); ArrayList<MetadataSchema> schemas = new ArrayList<MetadataSchema>(); for (String id : idsString.split(",")) { MetadataSchema schema = MetadataSchema.find(context,Integer.valueOf(id)); schemas.add(schema); } // DIVISION: metadata-schema-confirm-delete Division deleted = body.addInteractiveDivision("metadata-schema-confirm-delete",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); deleted.setHead(T_head); deleted.addPara(T_para1); Para warning = deleted.addPara(); warning.addHighlight("bold").addContent(T_warning); warning.addContent(T_para2); Table table = deleted.addTable("schema-confirm-delete",schemas.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); for (MetadataSchema schema : schemas) { Row row = table.addRow(); row.addCell().addContent(schema.getSchemaID()); row.addCell().addContent(schema.getNamespace()); row.addCell().addContent(schema.getName()); } Para buttons = deleted.addPara(); buttons.addButton("submit_confirm").setValue(T_submit_delete); buttons.addButton("submit_cancel").setValue(T_submit_cancel); deleted.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import java.util.ArrayList; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.CheckBox; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.Highlight; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.app.xmlui.wing.element.TextArea; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; /** * Edit a metadata schema by: listing all the existing fields in * the schema, prompt the user to add a new field. If a current * field is selected then the field may be updated in the same * place where new field addition would be. * * @author Scott Phillips */ public class EditMetadataSchema extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.registries.EditMetadataSchema.title"); private static final Message T_metadata_registry_trail = message("xmlui.administrative.registries.general.metadata_registry_trail"); private static final Message T_trail = message("xmlui.administrative.registries.EditMetadataSchema.trail"); private static final Message T_head1 = message("xmlui.administrative.registries.EditMetadataSchema.head1"); private static final Message T_para1 = message("xmlui.administrative.registries.EditMetadataSchema.para1"); private static final Message T_head2 = message("xmlui.administrative.registries.EditMetadataSchema.head2"); private static final Message T_column1 = message("xmlui.administrative.registries.EditMetadataSchema.column1"); private static final Message T_column2 = message("xmlui.administrative.registries.EditMetadataSchema.column2"); private static final Message T_column3 = message("xmlui.administrative.registries.EditMetadataSchema.column3"); private static final Message T_column4 = message("xmlui.administrative.registries.EditMetadataSchema.column4"); private static final Message T_empty = message("xmlui.administrative.registries.EditMetadataSchema.empty"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_submit_delete = message("xmlui.administrative.registries.EditMetadataSchema.submit_delete"); private static final Message T_submit_move = message("xmlui.administrative.registries.EditMetadataSchema.submit_move"); private static final Message T_head3 = message("xmlui.administrative.registries.EditMetadataSchema.head3"); private static final Message T_name = message("xmlui.administrative.registries.EditMetadataSchema.name"); private static final Message T_note = message("xmlui.administrative.registries.EditMetadataSchema.note"); private static final Message T_note_help = message("xmlui.administrative.registries.EditMetadataSchema.note_help"); private static final Message T_submit_add = message("xmlui.administrative.registries.EditMetadataSchema.submit_add"); private static final Message T_head4 = message("xmlui.administrative.registries.EditMetadataSchema.head4"); private static final Message T_submit_update = message("xmlui.administrative.registries.EditMetadataSchema.submit_update"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); private static final Message T_error = message("xmlui.administrative.registries.EditMetadataSchema.error"); private static final Message T_error_duplicate_field = message("xmlui.administrative.registries.EditMetadataSchema.error_duplicate_field"); private static final Message T_error_element_empty = message("xmlui.administrative.registries.EditMetadataSchema.error_element_empty"); private static final Message T_error_element_badchar = message("xmlui.administrative.registries.EditMetadataSchema.error_element_badchar"); private static final Message T_error_element_tolong = message("xmlui.administrative.registries.EditMetadataSchema.error_element_tolong"); private static final Message T_error_qualifier_tolong = message("xmlui.administrative.registries.EditMetadataSchema.error_qualifier_tolong"); private static final Message T_error_qualifier_badchar = message("xmlui.administrative.registries.EditMetadataSchema.error_qualifier_badchar"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/",T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException { // Get our parameters & state int schemaID = parameters.getParameterAsInteger("schemaID",-1); int updateID = parameters.getParameterAsInteger("updateID",-1); int highlightID = parameters.getParameterAsInteger("highlightID",-1); MetadataSchema schema = MetadataSchema.find(context,schemaID); MetadataField[] fields = MetadataField.findAllInSchema(context, schemaID); String schemaName = schema.getName(); String schemaNamespace = schema.getNamespace(); String errorString = parameters.getParameter("errors",null); ArrayList<String> errors = new ArrayList<String>(); if (errorString != null) { for (String error : errorString.split(",")) { errors.add(error); } } // DIVISION: edit-schema Division main = body.addInteractiveDivision("metadata-schema-edit",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); main.setHead(T_head1.parameterize(schemaName)); main.addPara(T_para1.parameterize(schemaNamespace)); // DIVISION: add or updating a metadata field if (updateID >= 0) { // Updating an existing field addUpdateFieldForm(main, schemaName, updateID, errors); } else { // Add a new field addNewFieldForm(main, schemaName, errors); } // DIVISION: existing fields Division existingFields = main.addDivision("metadata-schema-edit-existing-fields"); existingFields.setHead(T_head2); Table table = existingFields.addTable("metadata-schema-edit-existing-fields", fields.length+1, 5); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_column1); header.addCellContent(T_column2); header.addCellContent(T_column3); header.addCellContent(T_column4); for (MetadataField field : fields) { String id = String.valueOf(field.getFieldID()); String fieldElement = field.getElement(); String fieldQualifier = field.getQualifier(); String fieldName = schemaName +"."+ fieldElement; if (fieldQualifier != null && fieldQualifier.length() > 0) { fieldName += "." + fieldQualifier; } boolean highlight = false; if (field.getFieldID() == highlightID) { highlight = true; } String fieldScopeNote = field.getScopeNote(); String url = contextPath + "/admin/metadata-registry?administrative-continue="+knot.getId()+"&submit_edit&fieldID="+id; Row row; if (highlight) { row = table.addRow(null, null, "highlight"); } else { row = table.addRow(); } CheckBox select = row.addCell().addCheckBox("select_field"); select.setLabel(id); select.addOption(id); row.addCell().addContent(id); row.addCell().addXref(url,fieldName); row.addCell().addContent(fieldScopeNote); } if (fields.length == 0) { // No fields, let the user know. table.addRow().addCell(1,4).addHighlight("italic").addContent(T_empty); main.addPara().addButton("submit_return").setValue(T_submit_return); } else { // Only show the actions if there are fields available to preform them on. Para actions = main.addPara(); actions.addButton("submit_delete").setValue(T_submit_delete); if (MetadataSchema.findAll(context).length > 1) { actions.addButton("submit_move").setValue(T_submit_move); } actions.addButton("submit_return").setValue(T_submit_return); } main.addHidden("administrative-continue").setValue(knot.getId()); } /** * Add a form prompting the user to add a new field to the this schema. * * @param div The division to add the form too. * @param schemaName The schemaName currently being operated on. * @param errors A list of errors from previous attempts at adding new fields. */ public void addNewFieldForm(Division div, String schemaName, java.util.List<String> errors) throws WingException { Request request = ObjectModelHelper.getRequest(objectModel); String elementValue = request.getParameter("newElement"); String qualifierValue = request.getParameter("newQualifier"); String noteValue = request.getParameter("newNote"); Division newField = div.addDivision("edit-schema-new-field"); newField.setHead(T_head3); List form = newField.addList("edit-schema-new-field-form",List.TYPE_FORM); addFieldErrors(form, errors); form.addLabel(T_name); Highlight item =form.addItem().addHighlight("big"); item.addContent(schemaName+" . "); Text element = item.addText("newElement"); item.addContent(" . "); Text qualifier = item.addText("newQualifier"); element.setSize(15); element.setValue(elementValue); qualifier.setSize(15); qualifier.setValue(qualifierValue); TextArea scopeNote =form.addItem().addTextArea("newNote"); scopeNote.setLabel(T_note); scopeNote.setHelp(T_note_help); scopeNote.setSize(2, 35); scopeNote.setValue(noteValue); form.addItem().addButton("submit_add").setValue(T_submit_add); } /** * Update an existing field by promting the user for it's values. * * @param div The division to add the form too. * @param schemaName The schemaName currently being operated on. * @param fieldID The id of the field being updated. * @param errors A list of errors from previous attempts at updaating the field. */ public void addUpdateFieldForm(Division div, String schemaName, int fieldID, java.util.List<String> errors) throws WingException, SQLException { MetadataField field = MetadataField.find(context, fieldID); Request request = ObjectModelHelper.getRequest(objectModel); String elementValue = request.getParameter("updateElement"); String qualifierValue = request.getParameter("updateQualifier"); String noteValue = request.getParameter("updateNote"); if (elementValue == null) { elementValue = field.getElement(); } if (qualifierValue == null) { qualifierValue = field.getQualifier(); } if (noteValue == null) { noteValue = field.getScopeNote(); } Division newField = div.addDivision("edit-schema-update-field"); newField.setHead(T_head4.parameterize(field.getFieldID())); List form = newField.addList("edit-schema-update-field-form",List.TYPE_FORM); addFieldErrors(form, errors); form.addLabel(T_name); Highlight item =form.addItem().addHighlight("big"); item.addContent(schemaName+" . "); Text element = item.addText("updateElement"); item.addContent(" . "); Text qualifier = item.addText("updateQualifier"); element.setSize(13); element.setValue(elementValue); qualifier.setSize(13); qualifier.setValue(qualifierValue); TextArea scopeNote =form.addItem().addTextArea("updateNote"); scopeNote.setLabel(T_note); scopeNote.setHelp(T_note_help); scopeNote.setSize(2, 35); scopeNote.setValue(noteValue); Item actions = form.addItem(); actions.addButton("submit_update").setValue(T_submit_update); actions.addButton("submit_cancel").setValue(T_submit_cancel); } /** * Determine if there were any special errors and display approparte * text. Because of the inline nature of the element and qualifier * fields these errors can not be placed on the field. Instead they * have to be added as seperate items above the field. * * @param form The form to add errors to. * @param errors A list of errors. */ public void addFieldErrors(List form, java.util.List<String> errors) throws WingException { if (errors.contains("duplicate_field")) { form.addLabel(T_error); form.addItem(T_error_duplicate_field); } if (errors.contains("element_empty")) { form.addLabel(T_error); form.addItem(T_error_element_empty); } if (errors.contains("element_badchar")) { form.addLabel(T_error); form.addItem(T_error_element_badchar); } if (errors.contains("element_tolong")) { form.addLabel(T_error); form.addItem(T_error_element_tolong); } if (errors.contains("qualifier_tolong")) { form.addLabel(T_error); form.addItem(T_error_qualifier_tolong); } if (errors.contains("qualifier_badchar")) { form.addLabel(T_error); form.addItem(T_error_qualifier_badchar); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import java.util.ArrayList; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Cell; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Select; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.AuthorizeException; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; /** * Show a list of selected fields, and prompt the user to enter a destination schema for these fields. * * @author Scott Phillips */ public class MoveMetadataFields extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.registries.MoveMetadataField.title"); private static final Message T_metadata_registry_trail = message("xmlui.administrative.registries.general.metadata_registry_trail"); private static final Message T_trail = message("xmlui.administrative.registries.MoveMetadataField.trail"); private static final Message T_head1 = message("xmlui.administrative.registries.MoveMetadataField.head1"); private static final Message T_para1 = message("xmlui.administrative.registries.MoveMetadataField.para1"); private static final Message T_column1 = message("xmlui.administrative.registries.MoveMetadataField.column1"); private static final Message T_column2 = message("xmlui.administrative.registries.MoveMetadataField.column2"); private static final Message T_column3 = message("xmlui.administrative.registries.MoveMetadataField.column3"); private static final Message T_para2 = message("xmlui.administrative.registries.MoveMetadataField.para2"); private static final Message T_submit_move = message("xmlui.administrative.registries.MoveMetadataField.submit_move"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { // Get all our parameters MetadataSchema[] schemas = MetadataSchema.findAll(context); String idsString = parameters.getParameter("fieldIDs", null); ArrayList<MetadataField> fields = new ArrayList<MetadataField>(); for (String id : idsString.split(",")) { MetadataField field = MetadataField.find(context,Integer.valueOf(id)); fields.add(field); } // DIVISION: metadata-field-move Division moved = body.addInteractiveDivision("metadata-field-move",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); moved.setHead(T_head1); moved.addPara(T_para1); Table table = moved.addTable("metadata-field-move",fields.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); for (MetadataField field : fields) { String fieldID = String.valueOf(field.getFieldID()); String fieldEelement = field.getElement(); String fieldQualifier = field.getQualifier(); MetadataSchema schema = MetadataSchema.find(context, field.getSchemaID()); String schemaName = schema.getName(); StringBuilder fieldName = new StringBuilder() .append(schemaName) .append(".") .append(fieldEelement); if (fieldQualifier != null && fieldQualifier.length() > 0) { fieldName.append(".").append(fieldQualifier); } String fieldScopeNote = field.getScopeNote(); Row row = table.addRow(); row.addCell().addContent(fieldID); row.addCell().addContent(fieldName.toString()); row.addCell().addContent(fieldScopeNote); } Row row = table.addRow(); Cell cell = row.addCell(1,3); cell.addContent(T_para2); Select toSchema = cell.addSelect("to_schema"); for (MetadataSchema schema : schemas) { toSchema.addOption(schema.getSchemaID(), schema.getNamespace()); } Para buttons = moved.addPara(); buttons.addButton("submit_move").setValue(T_submit_move); buttons.addButton("submit_cancel").setValue(T_submit_cancel); moved.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.registries; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Cell; import org.dspace.app.xmlui.wing.element.CheckBox; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.content.BitstreamFormat; /** * Main management page for bitstream formats, this page lists all known formats * enabling the user to add more, updating existing, or delete formats. * * @author Scott Phillips */ public class FormatRegistryMain extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.registries.FormatRegistryMain.title"); private static final Message T_format_registry_trail = message("xmlui.administrative.registries.general.format_registry_trail"); private static final Message T_head = message("xmlui.administrative.registries.FormatRegistryMain.head"); private static final Message T_para1 = message("xmlui.administrative.registries.FormatRegistryMain.para1"); private static final Message T_new_link = message("xmlui.administrative.registries.FormatRegistryMain.new_link"); private static final Message T_column1 = message("xmlui.administrative.registries.FormatRegistryMain.column1"); private static final Message T_column2 = message("xmlui.administrative.registries.FormatRegistryMain.column2"); private static final Message T_column3 = message("xmlui.administrative.registries.FormatRegistryMain.column3"); private static final Message T_column4 = message("xmlui.administrative.registries.FormatRegistryMain.column4"); private static final Message T_column5 = message("xmlui.administrative.registries.FormatRegistryMain.column5"); private static final Message T_internal = message("xmlui.administrative.registries.FormatRegistryMain.internal"); private static final Message T_support_0 = message("xmlui.administrative.registries.FormatRegistryMain.support_0"); private static final Message T_support_1 = message("xmlui.administrative.registries.FormatRegistryMain.support_1"); private static final Message T_support_2 = message("xmlui.administrative.registries.FormatRegistryMain.support_2"); private static final Message T_submit_delete = message("xmlui.administrative.registries.FormatRegistryMain.submit_delete"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/",T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/format-registry",T_format_registry_trail); } public void addBody(Body body) throws WingException, SQLException { // Get our parameters & state int highlightID = parameters.getParameterAsInteger("highlightID",-1); BitstreamFormat[] formats = BitstreamFormat.findAll(context); String addURL = contextPath+"/admin/format-registry?administrative-continue="+knot.getId()+"&submit_add"; // DIVISION: bitstream-format-registry Division main = body.addInteractiveDivision("bitstream-format-registry",contextPath+"/admin/format-registry",Division.METHOD_POST,"primary administrative format-registry"); main.setHead(T_head); main.addPara(T_para1); main.addPara().addXref(addURL,T_new_link); Table table = main.addTable("bitstream-format-registry", formats.length+1, 5); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_column1); header.addCellContent(T_column2); header.addCellContent(T_column3); header.addCellContent(T_column4); header.addCellContent(T_column5); for (BitstreamFormat format : formats) { String id = String.valueOf(format.getID()); String mimeType = format.getMIMEType(); String name = format.getShortDescription(); int supportLevel = format.getSupportLevel(); boolean internal = format.isInternal(); boolean highlight = false; if (format.getID() == highlightID) { highlight = true; } String url = contextPath + "/admin/format-registry?administrative-continue="+knot.getId()+"&submit_edit&formatID="+id; Row row; if (highlight) { row = table.addRow(null, null, "highlight"); } else { row = table.addRow(); } // Select checkbox Cell cell = row.addCell(); if (format.getID() > 1) { // Do not allow unknown to be removed. CheckBox select = cell.addCheckBox("select_format"); select.setLabel(id); select.addOption(id); } // ID row.addCell().addContent(id); // Name row.addCell().addXref(url,name); // Mime type cell = row.addCell(); cell.addXref(url,mimeType); if (internal) { cell.addContent(" "); cell.addContent(T_internal); } // support level switch (supportLevel) { case 0: row.addCell().addXref(url,T_support_0); break; case 1: row.addCell().addXref(url,T_support_1); break; case 2: row.addCell().addXref(url,T_support_2); break; } } main.addPara().addButton("submit_delete").setValue(T_submit_delete); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.http.HttpEnvironment; import org.apache.commons.lang.StringUtils; import org.dspace.app.xmlui.utils.AuthenticationUtil; import org.dspace.app.xmlui.wing.Message; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.eperson.AccountManager; import org.dspace.eperson.EPerson; import org.dspace.eperson.EPersonDeletionException; /** * Utility methods to processes actions on EPeople. These methods are used * exclusively from the administrative flow scripts. * * @author scott phillips */ public class FlowEPersonUtils { /** Language Strings */ private static final Message T_add_eperson_success_notice = new Message("default","xmlui.administrative.FlowEPersonUtils.add_eperson_success_notice"); private static final Message T_edit_eperson_success_notice = new Message("default","xmlui.administrative.FlowEPersonUtils.edit_eperson_success_notice"); private static final Message T_reset_password_success_notice = new Message("default","xmlui.administrative.FlowEPersonUtils.reset_password_success_notice"); private static final Message t_delete_eperson_success_notice = new Message("default","xmlui.administrative.FlowEPersonUtils.delete_eperson_success_notice"); private static final Message t_delete_eperson_failed_notice = new Message("default","xmlui.administrative.FlowEPersonUtils.delete_eperson_failed_notice"); /** * Add a new eperson. This method will check that the email address, * first name, and last name are non empty. Also a check is performed * to see if the requested email address is already in use by another * user. * * @param context The current DSpace context * @param request The HTTP request parameters * @param objectModel Cocoon's object model * @return A process result's object. */ public static FlowResult processAddEPerson(Context context, Request request, Map objectModel) throws SQLException, AuthorizeException { FlowResult result = new FlowResult(); result.setContinue(false); // default to no continue // Get all our request parameters String email = request.getParameter("email_address").trim(); String first = request.getParameter("first_name").trim(); String last = request.getParameter("last_name").trim(); String phone = request.getParameter("phone").trim(); boolean login = (request.getParameter("can_log_in") != null) ? true : false; boolean certificate = (request.getParameter("certificate") != null) ? true : false; // If we have errors, the form needs to be resubmitted to fix those problems if (StringUtils.isEmpty(email)) { result.addError("email_address"); } if (StringUtils.isEmpty(first)) { result.addError("first_name"); } if (StringUtils.isEmpty(last)) { result.addError("last_name"); } // Check if the email address is all ready being used. EPerson potentialDupicate = EPerson.findByEmail(context,email); if (potentialDupicate != null) { // special error that the front end knows about. result.addError("eperson_email_key"); } // No errors, so we try to create the EPerson from the data provided if (result.getErrors() == null) { EPerson newPerson = AuthenticationUtil.createNewEperson(objectModel,email); newPerson.setFirstName(first); newPerson.setLastName(last); newPerson.setMetadata("phone", phone); newPerson.setCanLogIn(login); newPerson.setRequireCertificate(certificate); newPerson.setSelfRegistered(false); newPerson.update(); context.commit(); // success result.setContinue(true); result.setOutcome(true); result.setMessage(T_add_eperson_success_notice); result.setParameter("epersonID", newPerson.getID()); } return result; } /** * Edit an eperson's metadata, the email address, first name, and last name are all * required. The user's email address can be updated but it must remain unique, if * the email address already exists then the an error is produced. * * @param context The current DSpace context * @param request The HTTP request parameters * @param ObjectModel Cocoon's object model * @param epersonID The unique id of the eperson being edited. * @return A process result's object. */ public static FlowResult processEditEPerson(Context context, Request request, Map ObjectModel, int epersonID) throws SQLException, AuthorizeException { FlowResult result = new FlowResult(); result.setContinue(false); // default to failure // Get all our request parameters String email = request.getParameter("email_address"); String first = request.getParameter("first_name"); String last = request.getParameter("last_name"); String phone = request.getParameter("phone"); boolean login = (request.getParameter("can_log_in") != null) ? true : false; boolean certificate = (request.getParameter("certificate") != null) ? true : false; // If we have errors, the form needs to be resubmitted to fix those problems if (StringUtils.isEmpty(email)) { result.addError("email_address"); } if (StringUtils.isEmpty(first)) { result.addError("first_name"); } if (StringUtils.isEmpty(last)) { result.addError("last_name"); } // No errors, so we edit the EPerson with the data provided if (result.getErrors() == null) { // Grab the person in question EPerson personModified = EPerson.find(context, epersonID); // Make sure the email address we are changing to is unique String originalEmail = personModified.getEmail(); if (originalEmail == null || !originalEmail.equals(email)) { EPerson potentialDupicate = EPerson.findByEmail(context,email); if (potentialDupicate == null) { personModified.setEmail(email); } else if (potentialDupicate.equals(personModified)) { // set a special field in error so that the transformer can display a pretty error. result.addError("eperson_email_key"); return result; } } String originalFirstName = personModified.getFirstName(); if (originalFirstName == null || !originalFirstName.equals(first)) { personModified.setFirstName(first); } String originalLastName = personModified.getLastName(); if (originalLastName == null || !originalLastName.equals(last)) { personModified.setLastName(last); } String originalPhone = personModified.getMetadata("phone"); if (originalPhone == null || !originalPhone.equals(phone)) { personModified.setMetadata("phone", phone); } personModified.setCanLogIn(login); personModified.setRequireCertificate(certificate); personModified.update(); context.commit(); result.setContinue(true); result.setOutcome(true); // FIXME: rename this message result.setMessage(T_edit_eperson_success_notice); } // Everything was fine return result; } /** * Send the user a forgot password email message. The message will * contain a token that the user can use to login and pick a new password. * * @param context The current DSpace context * @param epersonID The unique id of the eperson being edited. * @return A process result's object. */ public static FlowResult processResetPassword(Context context, int epersonID) throws IOException, MessagingException, SQLException, AuthorizeException { EPerson eperson = EPerson.find(context, epersonID); // Note, this may throw an error is the email is bad. AccountManager.sendForgotPasswordInfo(context,eperson.getEmail()); FlowResult result = new FlowResult(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_reset_password_success_notice); return result; } /** * Log this user in as another user. If the operation failed then the flow result * will be set to failure with it's message set correctly. Note that after logging out * the user may not have sufficient privileges to continue. * * @param context The current DSpace context. * @param objectModel Object model to obtain the HTTP request from. * @param epersonID The epersonID of the person to login as. * @return The flow result. */ public static FlowResult processLoginAs(Context context, Map objectModel, int epersonID) throws SQLException { FlowResult result = new FlowResult(); result.setContinue(true); result.setOutcome(true); final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); EPerson eperson = EPerson.find(context,epersonID); try { AuthenticationUtil.loginAs(context, request, eperson); } catch (AuthorizeException ae) { // give the exception error as a notice. result.setOutcome(false); result.setMessage(new Message(null,ae.getMessage())); } return result; } /** * Delete the epeople specified by the epeopleIDs parameter. This assumes that the * deletion has been confirmed. * * @param context The current DSpace context * @param epeopleIDs The unique id of the eperson being edited. * @return A process result's object. */ public static FlowResult processDeleteEPeople(Context context, String[] epeopleIDs) throws NumberFormatException, SQLException, AuthorizeException, EPersonDeletionException { FlowResult result = new FlowResult(); List<String> unableList = new ArrayList<String>(); for (String id : epeopleIDs) { EPerson personDeleted = EPerson.find(context, Integer.valueOf(id)); try { personDeleted.delete(); } catch (EPersonDeletionException epde) { String firstName = personDeleted.getFirstName(); String lastName = personDeleted.getLastName(); String email = personDeleted.getEmail(); unableList.add(firstName + " " + lastName + " ("+email+")"); } } if (unableList.size() > 0) { result.setOutcome(false); result.setMessage(t_delete_eperson_failed_notice); String characters = null; for(String unable : unableList ) { if (characters == null) { characters = unable; } else { characters += ", " + unable; } } result.setCharacters(characters); } else { result.setOutcome(true); result.setMessage(t_delete_eperson_success_notice); } return result; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.mapper; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Button; import org.dspace.app.xmlui.wing.element.CheckBox; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.core.Constants; import org.xml.sax.SAXException; /** * List all items in this collection that are mapped from other collections. * * @author Scott phillips */ public class BrowseItemForm extends AbstractDSpaceTransformer { /** Language strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); private static final Message T_title = message("xmlui.administrative.mapper.BrowseItemForm.title"); private static final Message T_trail = message("xmlui.administrative.mapper.BrowseItemForm.trail"); private static final Message T_head1 = message("xmlui.administrative.mapper.BrowseItemForm.head1"); private static final Message T_submit_unmap = message("xmlui.administrative.mapper.BrowseItemForm.submit_unmap"); private static final Message T_column1 = message("xmlui.administrative.mapper.BrowseItemForm.column1"); private static final Message T_column2 = message("xmlui.administrative.mapper.BrowseItemForm.column2"); private static final Message T_column3 = message("xmlui.administrative.mapper.BrowseItemForm.column3"); private static final Message T_column4 = message("xmlui.administrative.mapper.BrowseItemForm.column4"); private static final Message T_no_remove = message("xmlui.administrative.mapper.BrowseItemForm.no_remove"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_mapper_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws SAXException, WingException, SQLException { // Get our parameters and state; int collectionID = parameters.getParameterAsInteger("collectionID",-1); Collection collection = Collection.find(context,collectionID); List<Item> items = getMappedItems(collection); // DIVISION: browse-items Division div = body.addInteractiveDivision("browse-items",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper"); div.setHead(T_head1); if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.REMOVE)) { Para actions = div.addPara(); actions.addButton("submit_unmap").setValue(T_submit_unmap); actions.addButton("submit_return").setValue(T_submit_return); } else { Para actions = div.addPara(); Button button = actions.addButton("submit_unmap"); button.setValue(T_submit_unmap); button.setDisabled(); actions.addButton("submit_return").setValue(T_submit_return); div.addPara().addHighlight("fade").addContent(T_no_remove); } Table table = div.addTable("browse-items-table",1,1); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_column1); header.addCellContent(T_column2); header.addCellContent(T_column3); header.addCellContent(T_column4); for (Item item : items) { String itemID = String.valueOf(item.getID()); Collection owningCollection = item.getOwningCollection(); String owning = owningCollection.getMetadata("name"); String author = "unkown"; DCValue[] dcAuthors = item.getDC("contributor",Item.ANY,Item.ANY); if (dcAuthors != null && dcAuthors.length >= 1) { author = dcAuthors[0].value; } String title = "untitled"; DCValue[] dcTitles = item.getDC("title",null,Item.ANY); if (dcTitles != null && dcTitles.length >= 1) { title = dcTitles[0].value; } String url = contextPath+"/handle/"+item.getHandle(); Row row = table.addRow(); CheckBox select = row.addCell().addCheckBox("itemID"); select.setLabel("Select"); select.addOption(itemID); row.addCellContent(owning); row.addCell().addXref(url,author); row.addCell().addXref(url,title); } if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.REMOVE)) { Para actions = div.addPara(); actions.addButton("submit_unmap").setValue(T_submit_unmap); actions.addButton("submit_return").setValue(T_submit_return); } else { Para actions = div.addPara(); Button button = actions.addButton("submit_unmap"); button.setValue(T_submit_unmap); button.setDisabled(); actions.addButton("submit_return").setValue(T_submit_return); div.addPara().addHighlight("fade").addContent(T_no_remove); } div.addHidden("administrative-continue").setValue(knot.getId()); } /** * Get a list of all items that are mapped from other collections. * * @param collection The collection to look in. */ private List<Item> getMappedItems(Collection collection) throws SQLException { ArrayList<Item> items = new ArrayList<Item>(); // get all items from that collection ItemIterator iterator = collection.getItems(); try { while (iterator.hasNext()) { Item item = iterator.next(); if (! item.isOwningCollection(collection)) { items.add(item); } } } finally { if (iterator != null) { iterator.close(); } } return items; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.mapper; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.CheckBox; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.content.Collection; import org.dspace.content.DCValue; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.handle.HandleManager; import org.dspace.search.DSQuery; import org.dspace.search.QueryArgs; import org.dspace.search.QueryResults; import org.xml.sax.SAXException; /** * Search for items from other collections to map into this collection. * * @author Scott phillips */ public class SearchItemForm extends AbstractDSpaceTransformer { /** Language strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); private static final Message T_title = message("xmlui.administrative.mapper.SearchItemForm.title"); private static final Message T_trail = message("xmlui.administrative.mapper.SearchItemForm.trail"); private static final Message T_head1 = message("xmlui.administrative.mapper.SearchItemForm.head1"); private static final Message T_submit_map = message("xmlui.administrative.mapper.SearchItemForm.submit_map"); private static final Message T_column1 = message("xmlui.administrative.mapper.SearchItemForm.column1"); private static final Message T_column2 = message("xmlui.administrative.mapper.SearchItemForm.column2"); private static final Message T_column3 = message("xmlui.administrative.mapper.SearchItemForm.column3"); private static final Message T_column4 = message("xmlui.administrative.mapper.SearchItemForm.column4"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_mapper_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws SAXException, WingException, SQLException, IOException { // Get our parameters and state; int collectionID = parameters.getParameterAsInteger("collectionID",-1); Collection collection = Collection.find(context,collectionID); String query = decodeFromURL(parameters.getParameter("query",null)); java.util.List<Item> items = preformSearch(collection,query); // DIVISION: manage-mapper Division div = body.addInteractiveDivision("search-items",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper"); div.setHead(T_head1.parameterize(query)); Para actions = div.addPara(); actions.addButton("submit_map").setValue(T_submit_map); actions.addButton("submit_cancel").setValue(T_submit_cancel); Table table = div.addTable("search-items-table",1,1); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_column1); header.addCellContent(T_column2); header.addCellContent(T_column3); header.addCellContent(T_column4); for (Item item : items) { String itemID = String.valueOf(item.getID()); Collection owningCollection = item.getOwningCollection(); String owning = owningCollection.getMetadata("name"); String author = "unkown"; DCValue[] dcAuthors = item.getDC("contributor",Item.ANY,Item.ANY); if (dcAuthors != null && dcAuthors.length >= 1) { author = dcAuthors[0].value; } String title = "untitled"; DCValue[] dcTitles = item.getDC("title",null,Item.ANY); if (dcTitles != null && dcTitles.length >= 1) { title = dcTitles[0].value; } String url = contextPath+"/handle/"+item.getHandle(); Row row = table.addRow(); boolean canBeMapped = true; Collection[] collections = item.getCollections(); for (Collection c : collections) { if (c.getID() == collectionID) { canBeMapped = false; } } if (canBeMapped) { CheckBox select = row.addCell().addCheckBox("itemID"); select.setLabel("Select"); select.addOption(itemID); } else { row.addCell().addContent(""); } row.addCellContent(owning); row.addCell().addXref(url,author); row.addCell().addXref(url,title); } actions = div.addPara(); actions.addButton("submit_map").setValue(T_submit_map); actions.addButton("submit_cancel").setValue(T_submit_cancel); div.addHidden("administrative-continue").setValue(knot.getId()); } /** * Search the repository for items in other collections that can be mapped into this one. * * @param collection The collection to mapp into * @param query The search query. */ private java.util.List<Item> preformSearch(Collection collection, String query) throws SQLException, IOException { // Search the repository QueryArgs queryArgs = new QueryArgs(); queryArgs.setQuery(query); queryArgs.setPageSize(Integer.MAX_VALUE); QueryResults results = DSQuery.doQuery(context, queryArgs); // Get a list of found items ArrayList<Item> items = new ArrayList<Item>(); @SuppressWarnings("unchecked") java.util.List<String> handles = results.getHitHandles(); for (String handle : handles) { DSpaceObject resultDSO = HandleManager.resolveToObject(context, handle); if (resultDSO instanceof Item) { Item item = (Item) resultDSO; if (!item.isOwningCollection(collection)) { items.add(item); } } } return items; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.mapper; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Button; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.core.Constants; import org.xml.sax.SAXException; /** * Manage the mapping of items into this collection, allow the user to * search for new items to import or browse a list of currently mapped * items. * * @author Scott phillips */ public class MapperMain extends AbstractDSpaceTransformer { /** Language strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); private static final Message T_title = message("xmlui.administrative.mapper.MapperMain.title"); private static final Message T_head1 = message("xmlui.administrative.mapper.MapperMain.head1"); private static final Message T_para1 = message("xmlui.administrative.mapper.MapperMain.para1"); private static final Message T_para2 = message("xmlui.administrative.mapper.MapperMain.para2"); private static final Message T_stat_label = message("xmlui.administrative.mapper.MapperMain.stat_label"); private static final Message T_stat_info = message("xmlui.administrative.mapper.MapperMain.stat_info"); private static final Message T_search_label = message("xmlui.administrative.mapper.MapperMain.search_label"); private static final Message T_submit_search = message("xmlui.administrative.mapper.MapperMain.submit_search"); private static final Message T_submit_browse = message("xmlui.administrative.mapper.MapperMain.submit_browse"); private static final Message T_no_add = message("xmlui.administrative.mapper.MapperMain.no_add"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_mapper_trail); } public void addBody(Body body) throws SAXException, WingException, SQLException { // Get our parameters and state; int collectionID = parameters.getParameterAsInteger("collectionID",-1); Collection collection = Collection.find(context,collectionID); int[] counts = getNumberOfMappedAndUnmappedItems(collection); int count_native = counts[0]; int count_import = counts[1]; // DIVISION: manage-mapper Division div = body.addInteractiveDivision("manage-mapper",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper"); div.setHead(T_head1); div.addPara(T_para1.parameterize(collection.getMetadata("name"))); div.addPara(T_para2); // LIST: Author search form List form = div.addList("mapper-form"); form.addLabel(T_stat_label); form.addItem(T_stat_info.parameterize(count_import,count_native+count_import)); form.addLabel(T_search_label); org.dspace.app.xmlui.wing.element.Item queryItem = form.addItem(); Text query = queryItem.addText("query"); Button button = queryItem.addButton("submit_author"); button.setValue(T_submit_search); if (!AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD)) { query.setDisabled(); button.setDisabled(); queryItem.addHighlight("fade").addContent(T_no_add); } // PARA: actions Para actions = div.addPara(); actions.addButton("submit_browse").setValue(T_submit_browse); actions.addButton("submit_return").setValue(T_submit_return); div.addHidden("administrative-continue").setValue(knot.getId()); } /** * Count the number of unmapped and mapped items in this collection * * @param collection The collection to count from. * @return a two integer array of native items and imported items. */ private int[] getNumberOfMappedAndUnmappedItems(Collection collection) throws SQLException { int count_native = 0; int count_import = 0; // get all items from that collection ItemIterator iterator = collection.getItems(); try { // iterate through the items in this collection, and count how many // are native, and how many are imports, and which collections they // came from while (iterator.hasNext()) { Item item = iterator.next(); if (item.isOwningCollection(collection)) { count_native++; } else { count_import++; } } } finally { if (iterator != null) { iterator.close(); } } int[] counts = new int[2]; counts[0] = count_native; counts[1] = count_import; return counts; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import javax.servlet.http.HttpSession; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.acting.AbstractAction; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Redirector; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.SourceResolver; import org.dspace.app.xmlui.utils.ContextUtil; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.eperson.EPerson; /** * * This action simply records pipeline events that it sees, keeping track of the users and * pages they are viewing. Later the control panel's activity viewer can access this data to * get a realtime snap shot of current activity of the repository. * * @author Scott Phillips */ public class CurrentActivityAction extends AbstractAction { /** The maximum number of events that are recorded */ public static final int MAX_EVENTS; /** The HTTP header that contains the real IP for this request, this is used when DSpace is placed behind a load balancer */ public static final String IP_HEADER; /** The ordered list of events, by access time */ private static Queue<Event> events = new LinkedList<Event>(); /** record events that are from anynmous users */ private static boolean recordAnonymousEvents = true; /** record events from automatic bots */ private static boolean recordBotEvents = false; /** * Allow the DSpace.cfg to override our activity max and ip header. */ static { // If the dspace.cfg has a max event count then use it. if (ConfigurationManager.getProperty("xmlui.controlpanel.activity.max") != null) { MAX_EVENTS = ConfigurationManager.getIntProperty("xmlui.controlpanel.activity.max"); } else { MAX_EVENTS = 250; } if (ConfigurationManager.getProperty("xmlui.controlpanel.activity.ipheader") != null) { IP_HEADER = ConfigurationManager.getProperty("xmlui.controlpanel.activity.ipheader"); } else { IP_HEADER = "X-Forwarded-For"; } } /** * Record this current event. */ public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception { Request request = ObjectModelHelper.getRequest(objectModel); Context context = ContextUtil.obtainContext(objectModel); // Ensure only one thread is manipulating the events queue at a time. synchronized (events) { // Create and store our events Event event = new Event(context,request); // Check if we should record the event boolean record = true; if (!recordAnonymousEvents && event.isAnonymous()) { record = false; } if (!recordBotEvents && event.isBot()) { record = false; } if (record) { events.add(event); } // Remove the oldest element from the list if we are over our max // number of elements. while (events.size() > MAX_EVENTS) { events.poll(); } } return null; } /** * @return a list of all current events. */ public static List<Event> getEvents() { List<Event> list = new ArrayList<Event>(); // Make sure only one thread is manipulating the events queue at a time. synchronized (events) { list.addAll(events); } return list; } public static boolean getRecordAnonymousEvents() { return recordAnonymousEvents; } public static void setRecordAnonymousEvents(boolean record) { recordAnonymousEvents = record; } public static boolean getRecordBotEvents() { return recordBotEvents; } public static void setRecordBotEvents(boolean record) { recordBotEvents = record; } /** * An object that represents an activity event. */ public static class Event { /** The Servlet session */ private String sessionID; /** The eperson ID */ private int epersonID = -1; /** The url being viewed */ private String url; /** A timestap of this event */ private long timestamp; /** The user-agent for the request */ private String userAgent; /** The ip address of the requester */ private String ip; /** * Construct a new activity event, grabing various bits of data about the request from the context and request. */ public Event(Context context, Request request) { if (context != null) { EPerson eperson = context.getCurrentUser(); if (eperson != null) { epersonID = eperson.getID(); } } if (request != null) { url = request.getSitemapURI(); HttpSession session = request.getSession(true); if (session != null) { sessionID = session.getId(); } userAgent = request.getHeader("User-Agent"); ip = request.getHeader(IP_HEADER); if (ip == null) { ip = request.getRemoteAddr(); } } // The current time timestamp = System.currentTimeMillis(); } public String getSessionID() { return sessionID; } public int getEPersonID() { return epersonID; } public String getURL() { return url; } public long getTimeStamp() { return timestamp; } public String getUserAgent() { return userAgent; } public String getIP() { return ip; } /** * Is this event anonymous? * @return */ public boolean isAnonymous() { return (epersonID == -1); } /** * Is this event from a bot? * @return */ public boolean isBot() { if (userAgent == null) { return false; } String ua = userAgent.toLowerCase(); return (ua.contains("google/") || ua.contains("msnbot/") || ua.contains("googlebot/") || ua.contains("webcrawler/") || ua.contains("inktomi") || ua.contains("teoma") || ua.contains("bot")); } /** * Return the activity viewer's best guess as to what browser or bot was initiating the request. * * @return A short name for the browser or bot. */ public String getDectectedBrowser() { if (userAgent == null) { return "No browser provided"; } String userAgentLower = userAgent.toLowerCase(); // BOTS if (userAgentLower.contains("google/")) { return "Google (bot)"; } if (userAgentLower.contains("msnbot/")) { return "MSN (bot)"; } if (userAgentLower.contains("googlebot/")) { return "Google (bot)"; } if (userAgentLower.contains("webcrawler/")) { return "WebCrawler (bot)"; } if (userAgentLower.contains("inktomi")) { return "Inktomi (bot)"; } if (userAgentLower.contains("teoma")) { return "Teoma (bot)"; } if (userAgentLower.contains("bot")) { return "Unknown (bot)"; } // Normal Browsers if (userAgent.contains("Lotus-Notes/")) { return "Lotus-Notes"; } if (userAgent.contains("Opera")) { return "Opera"; } if (userAgent.contains("Safari/")) { if (userAgent.contains("Chrome")) { return "Chrome"; } return "Safari"; } if (userAgent.contains("Konqueror/")) { return "Konqueror"; } // Internet explorer browsers if (userAgent.contains("MSIE")) { if (userAgent.contains("MSIE 9")) { return "MSIE 9"; } if (userAgent.contains("MSIE 8")) { return "MSIE 8"; } if (userAgent.contains("MSIE 7")) { return "MSIE 7"; } if (userAgent.contains("MSIE 6")) { return "MSIE 6"; } if (userAgent.contains("MSIE 5")) { return "MSIE 5"; } // Can't fine the version number return "MSIE"; } // Gecko based browsers if (userAgent.contains("Gecko/")) { if (userAgent.contains("Camio/")) { return "Gecko/Camino"; } if (userAgent.contains("Chimera/")) { return "Gecko/Chimera"; } if (userAgent.contains("Firebird/")) { return "Gecko/Firebird"; } if (userAgent.contains("Phoenix/")) { return "Gecko/Phoenix"; } if (userAgent.contains("Galeon")) { return "Gecko/Galeon"; } if (userAgent.contains("Firefox/1")) { return "Firefox 1.x"; } if (userAgent.contains("Firefox/2")) { return "Firefox 2.x"; } if (userAgent.contains("Firefox/3")) { return "Firefox 3.x"; } if (userAgent.contains("Firefox/4")) { return "Firefox 4.x"; } if (userAgent.contains("Firefox/")) { return "Firefox"; // can't find the exact version } if (userAgent.contains("Netscape/")) { return "Netscape"; } // Can't find the exact distribution return "Gecko"; } // Generic browser types (lots of things report these names) if (userAgent.contains("KHTML/")) { return "KHTML"; } if (userAgent.contains("Netscape/")) { return "Netscape"; } if (userAgent.contains("Mozilla/")) { return "Mozilla"; // Almost everything says they are mozilla. } // if you get all the way to the end and still nothing, return unknown. return "Unknown"; } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.io.IOException; import java.sql.SQLException; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.browse.BrowseException; import org.dspace.browse.IndexBrowse; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.core.Constants; import org.dspace.core.Context; /** * * @author Scott Phillips */ public class FlowMapperUtils { /** Language Strings */ private static final Message T_map_items = new Message("default","xmlui.administrative.FlowMapperUtils.map_items"); private static final Message T_unmaped_items = new Message("default","xmlui.administrative.FlowMapperUtils.unmaped_items"); /** * Map the given items into this collection * * @param context The current DSpace content * @param collectionID The collection to map items into. * @param itemIDs The items to map. * @return Flow result */ public static FlowResult processMapItems(Context context, int collectionID, String[] itemIDs) throws SQLException, AuthorizeException, UIException, IOException { FlowResult result = new FlowResult(); result.setContinue(false); Collection toCollection = Collection.find(context,collectionID); for (String itemID : itemIDs) { Item item = Item.find(context, Integer.valueOf(itemID)); if (AuthorizeManager.authorizeActionBoolean(context, item, Constants.READ)) { // make sure item doesn't belong to this collection if (!item.isOwningCollection(toCollection)) { toCollection.addItem(item); // FIXME Exception handling try { IndexBrowse ib = new IndexBrowse(context); ib.indexItem(item); } catch (BrowseException bex) { throw new UIException("Unable to process browse", bex); } } } } context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_map_items); return result; } /** * Unmap the given items from this collection * * @param context The DSpace context * @param collectionID The collection to unmap these items from. * @param itemIDs The items to be unmapped. * @return A flow result */ public static FlowResult processUnmapItems(Context context, int collectionID, String[] itemIDs) throws SQLException, AuthorizeException, UIException, IOException { FlowResult result = new FlowResult(); result.setContinue(false); Collection toCollection = Collection.find(context,collectionID); for (String itemID : itemIDs) { Item item = Item.find(context, Integer.valueOf(itemID)); if (AuthorizeManager.authorizeActionBoolean(context, item, Constants.READ)) { // make sure item doesn't belong to this collection if (!item.isOwningCollection(toCollection)) { toCollection.removeItem(item); // FIXME Exception handling try { IndexBrowse ib = new IndexBrowse(context); ib.indexItem(item); } catch (BrowseException bex) { throw new UIException("Unable to process browse", bex); } } } } context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_unmaped_items); return result; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; /** * Confirmation step for the deletion of an entire collection * @author Alexey Maslov */ public class DeleteCollectionConfirm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.collection.DeleteCollectionConfirm.title"); private static final Message T_trail = message("xmlui.administrative.collection.DeleteCollectionConfirm.trail"); private static final Message T_main_head = message("xmlui.administrative.collection.DeleteCollectionConfirm.main_head"); private static final Message T_main_para = message("xmlui.administrative.collection.DeleteCollectionConfirm.main_para"); private static final Message T_confirm_item1 = message("xmlui.administrative.collection.DeleteCollectionConfirm.confirm_item1"); private static final Message T_confirm_item2 = message("xmlui.administrative.collection.DeleteCollectionConfirm.confirm_item2"); private static final Message T_confirm_item3 = message("xmlui.administrative.collection.DeleteCollectionConfirm.confirm_item3"); private static final Message T_submit_confirm = message("xmlui.general.delete"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { int collectionID = parameters.getParameterAsInteger("collectionID", -1); Collection thisCollection = Collection.find(context, collectionID); // DIVISION: main Division main = body.addInteractiveDivision("collection-confirm-delete",contextPath+"/admin/collection",Division.METHOD_POST,"primary administrative collection"); main.setHead(T_main_head.parameterize(collectionID)); main.addPara(T_main_para.parameterize(thisCollection.getMetadata("name"))); List deleteConfirmHelp = main.addList("consequences",List.TYPE_BULLETED); deleteConfirmHelp.addItem(T_confirm_item1); deleteConfirmHelp.addItem(T_confirm_item2); deleteConfirmHelp.addItem(T_confirm_item3); Para buttonList = main.addPara(); buttonList.addButton("submit_confirm").setValue(T_submit_confirm); buttonList.addButton("submit_cancel").setValue(T_submit_cancel); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.app.xmlui.wing.element.TextArea; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Community; /** * Presents the user with a form to enter the initial metadata for creation of a new collection * @author Alexey Maslov */ public class CreateCollectionForm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.collection.CreateCollectionForm.title"); private static final Message T_trail = message("xmlui.administrative.collection.CreateCollectionForm.trail"); private static final Message T_main_head = message("xmlui.administrative.collection.CreateCollectionForm.main_head"); private static final Message T_label_name = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_name"); private static final Message T_label_short_description = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_short_description"); private static final Message T_label_introductory_text = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_introductory_text"); private static final Message T_label_copyright_text = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_copyright_text"); private static final Message T_label_side_bar_text = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_side_bar_text"); private static final Message T_label_license = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_license"); private static final Message T_label_provenance_description = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_provenance_description"); private static final Message T_label_logo = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_logo"); private static final Message T_submit_save = message("xmlui.administrative.collection.CreateCollectionForm.submit_save"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { int communityID = parameters.getParameterAsInteger("communityID", -1); Community parentCommunity = Community.find(context, communityID); // DIVISION: main Division main = body.addInteractiveDivision("create-collection",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); main.setHead(T_main_head.parameterize(parentCommunity.getMetadata("name"))); // The grand list of metadata options List metadataList = main.addList("metadataList", "form"); // collection name metadataList.addLabel(T_label_name); Text name = metadataList.addItem().addText("name"); name.setSize(40); // short description metadataList.addLabel(T_label_short_description); Text short_description = metadataList.addItem().addText("short_description"); short_description.setSize(40); // introductory text metadataList.addLabel(T_label_introductory_text); TextArea introductory_text = metadataList.addItem().addTextArea("introductory_text"); introductory_text.setSize(6, 40); // copyright text metadataList.addLabel(T_label_copyright_text); TextArea copyright_text = metadataList.addItem().addTextArea("copyright_text"); copyright_text.setSize(6, 40); // legacy sidebar text; may or may not be used for news metadataList.addLabel(T_label_side_bar_text); TextArea side_bar_text = metadataList.addItem().addTextArea("side_bar_text"); side_bar_text.setSize(6, 40); // license text metadataList.addLabel(T_label_license); TextArea license = metadataList.addItem().addTextArea("license"); license.setSize(6, 40); // provenance description metadataList.addLabel(T_label_provenance_description); TextArea provenance_description = metadataList.addItem().addTextArea("provenance_description"); provenance_description.setSize(6, 40); // the row to upload a new logo metadataList.addLabel(T_label_logo); metadataList.addItem().addFile("logo"); Para buttonList = main.addPara(); buttonList.addButton("submit_save").setValue(T_submit_save); buttonList.addButton("submit_cancel").setValue(T_submit_cancel); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Radio; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.harvest.HarvestedCollection; import org.dspace.core.ConfigurationManager; /** * This is the other form that deals with harvesting. This one comes up when the collection is * edited with the harvesting options set and verified. Allows two actions: "import" and "reingest", * as well as "change", which takes the user to the other harvesting form. * @author Alexey Maslov */ public class EditCollectionHarvestingForm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); private static final Message T_title = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.title"); private static final Message T_trail = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.trail"); private static final Message T_label_source = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.label_source"); private static final Message T_source_normal = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_normal"); private static final Message T_source_harvested = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_harvested"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_submit_save = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.submit_save"); private static final Message T_main_settings_head = message("xmlui.administrative.collection.EditCollectionHarvestingForm.main_settings_head"); private static final Message T_label_oai_provider = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_oai_provider"); private static final Message T_label_setid = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_setid"); private static final Message T_label_metadata_format = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_metadata_format"); private static final Message T_label_harvest_level = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_level"); private static final Message T_label_harvest_result = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_result"); private static final Message T_harvest_result_new = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_result_new"); private static final Message T_label_harvest_status = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_status"); private static final Message T_harvest_status_ready = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_ready"); private static final Message T_harvest_status_busy = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_busy"); private static final Message T_harvest_status_queued = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_queued"); private static final Message T_harvest_status_oai_error = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_oai_error"); private static final Message T_harvest_status_unknown_error = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_unknown_error"); private static final Message T_option_md_only = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_only"); private static final Message T_option_md_and_ref = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_and_ref"); private static final Message T_option_md_and_bs = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_and_bs"); private static final Message T_submit_change_settings = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_change_settings"); private static final Message T_submit_import_now = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_import_now"); private static final Message T_submit_reimport_collection = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_reimport_collection"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { int collectionID = parameters.getParameterAsInteger("collectionID", -1); Collection thisCollection = Collection.find(context, collectionID); HarvestedCollection hc = HarvestedCollection.find(context, collectionID); String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); String oaiProviderValue = hc.getOaiSource(); String oaiSetIdValue = hc.getOaiSetId(); String metadataFormatValue = hc.getHarvestMetadataConfig(); int harvestLevelValue = hc.getHarvestType(); int harvestStatusValue = hc.getHarvestStatus(); // DIVISION: main Division main = body.addInteractiveDivision("collection-harvesting-edit",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); main.setHead(T_main_head.parameterize(thisCollection.getMetadata("name"))); List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); options.addItem().addHighlight("bold").addXref(baseURL+"&submit_harvesting",T_options_harvest); options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); // The top-level, all-setting, countent source radio button List harvestSource = main.addList("harvestSource", "form"); harvestSource.addLabel(T_label_source); Radio source = harvestSource.addItem().addRadio("source"); source.addOption(false, "source_normal", T_source_normal); // was hc == null - always false source.addOption(true, "source_harvested", T_source_harvested); // was hc != null - always true List settings = main.addList("harvestSettings", "form"); settings.setHead(T_main_settings_head); settings.addLabel(T_label_oai_provider); settings.addItem(oaiProviderValue); settings.addLabel(T_label_setid); settings.addItem(oaiSetIdValue); // The big complex way of getting to our metadata settings.addLabel(T_label_metadata_format); String key = "harvester.oai.metadataformats." + metadataFormatValue; String metadataString = ConfigurationManager.getProperty(key); String displayName; if (metadataString.indexOf(',') != -1) { displayName = metadataString.substring(metadataString.indexOf(',') + 1); } else { displayName = metadataFormatValue + "(" + metadataString + ")"; } settings.addItem(displayName); settings.addLabel(T_label_harvest_level); Item harvestLevel = settings.addItem(); switch (harvestLevelValue) { case 1: harvestLevel.addContent(T_option_md_only); break; case 2: harvestLevel.addContent(T_option_md_and_ref); break; default: harvestLevel.addContent(T_option_md_and_bs); break; } /* Results of the last harvesting cycle */ if (harvestLevelValue > 0) { settings.addLabel(T_label_harvest_result); Item harvestResult = settings.addItem(); if (hc.getHarvestMessage() != null) { harvestResult.addContent(hc.getHarvestMessage() + " on " + hc.getHarvestStartTime()); } else { harvestResult.addContent(T_harvest_result_new); } } /* Current status */ settings.addLabel(T_label_harvest_status); Item harvestStatus = settings.addItem(); switch(harvestStatusValue) { case HarvestedCollection.STATUS_READY: harvestStatus.addContent(T_harvest_status_ready); break; case HarvestedCollection.STATUS_BUSY: harvestStatus.addContent(T_harvest_status_busy); break; case HarvestedCollection.STATUS_QUEUED: harvestStatus.addContent(T_harvest_status_queued); break; case HarvestedCollection.STATUS_OAI_ERROR: harvestStatus.addContent(T_harvest_status_oai_error); break; case HarvestedCollection.STATUS_UNKNOWN_ERROR: harvestStatus.addContent(T_harvest_status_unknown_error); break; } settings.addLabel(); Item harvestButtons = settings.addItem(); harvestButtons.addButton("submit_change").setValue(T_submit_change_settings); harvestButtons.addButton("submit_import_now").setValue(T_submit_import_now); harvestButtons.addButton("submit_reimport").setValue(T_submit_reimport_collection); Para buttonList = main.addPara(); buttonList.addButton("submit_save").setValue(T_submit_save); buttonList.addButton("submit_return").setValue(T_submit_return); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import org.dspace.app.xmlui.aspect.administrative.FlowContainerUtils; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.app.xmlui.wing.element.TextArea; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; /** * Presents the user (in this case an administrator over the collection) with the * form to edit that collection's metadata, logo, and item template. * @author Alexey Maslov */ public class EditCollectionMetadataForm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_title = message("xmlui.administrative.collection.EditCollectionMetadataForm.title"); private static final Message T_trail = message("xmlui.administrative.collection.EditCollectionMetadataForm.trail"); private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); private static final Message T_label_name = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_name"); private static final Message T_label_short_description = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_short_description"); private static final Message T_label_introductory_text = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_introductory_text"); private static final Message T_label_copyright_text = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_copyright_text"); private static final Message T_label_side_bar_text = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_side_bar_text"); private static final Message T_label_license = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_license"); private static final Message T_label_provenance_description = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_provenance_description"); private static final Message T_label_logo = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_logo"); private static final Message T_label_existing_logo = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_existing_logo"); private static final Message T_label_item_template = message("xmlui.administrative.collection.EditCollectionMetadataForm.label_item_template"); private static final Message T_submit_create_template = message("xmlui.administrative.collection.EditCollectionMetadataForm.submit_create_template"); private static final Message T_submit_edit_template = message("xmlui.administrative.collection.EditCollectionMetadataForm.submit_edit_template"); private static final Message T_submit_delete_template = message("xmlui.general.delete"); private static final Message T_submit_delete_logo = message("xmlui.administrative.collection.EditCollectionMetadataForm.submit_delete_logo"); private static final Message T_submit_delete = message("xmlui.administrative.collection.EditCollectionMetadataForm.submit_delete"); private static final Message T_submit_save = message("xmlui.administrative.collection.EditCollectionMetadataForm.submit_save"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { int collectionID = parameters.getParameterAsInteger("collectionID", -1); Collection thisCollection = Collection.find(context, collectionID); String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); //Check that all HTML input fields contain valid XHTML String short_description_error = FlowContainerUtils.checkXMLFragment(thisCollection.getMetadata("short_description")); String introductory_text_error = FlowContainerUtils.checkXMLFragment(thisCollection.getMetadata("introductory_text")); String copyright_text_error = FlowContainerUtils.checkXMLFragment(thisCollection.getMetadata("copyright_text")); String side_bar_text_error = FlowContainerUtils.checkXMLFragment(thisCollection.getMetadata("side_bar_text")); // DIVISION: main Division main = body.addInteractiveDivision("collection-metadata-edit",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); main.setHead(T_main_head.parameterize(thisCollection.getMetadata("name"))); List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); options.addItem().addHighlight("bold").addXref(baseURL+"&submit_metadata",T_options_metadata); options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); options.addItem().addXref(baseURL+"&submit_harvesting",T_options_harvest); options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); // The grand list of metadata options List metadataList = main.addList("metadataList", "form"); // collection name metadataList.addLabel(T_label_name); Text name = metadataList.addItem().addText("name"); name.setSize(40); name.setValue(thisCollection.getMetadata("name")); // short description metadataList.addLabel(T_label_short_description); Text short_description = metadataList.addItem().addText("short_description"); short_description.setValue(thisCollection.getMetadata("short_description")); short_description.setSize(40); if (short_description_error != null) { short_description.addError(short_description_error); } // introductory text metadataList.addLabel(T_label_introductory_text); TextArea introductory_text = metadataList.addItem().addTextArea("introductory_text"); introductory_text.setValue(thisCollection.getMetadata("introductory_text")); introductory_text.setSize(6, 40); if (introductory_text_error != null) { introductory_text.addError(introductory_text_error); } // copyright text metadataList.addLabel(T_label_copyright_text); TextArea copyright_text = metadataList.addItem().addTextArea("copyright_text"); copyright_text.setValue(thisCollection.getMetadata("copyright_text")); copyright_text.setSize(6, 40); if (copyright_text_error != null) { copyright_text.addError(copyright_text_error); } // legacy sidebar text; may or may not be used for news metadataList.addLabel(T_label_side_bar_text); TextArea side_bar_text = metadataList.addItem().addTextArea("side_bar_text"); side_bar_text.setValue(thisCollection.getMetadata("side_bar_text")); side_bar_text.setSize(6, 40); if (side_bar_text_error != null) { side_bar_text.addError(side_bar_text_error); } // license text metadataList.addLabel(T_label_license); TextArea license = metadataList.addItem().addTextArea("license"); license.setValue(thisCollection.getMetadata("license")); license.setSize(6, 40); // provenance description metadataList.addLabel(T_label_provenance_description); TextArea provenance_description = metadataList.addItem().addTextArea("provenance_description"); provenance_description.setValue(thisCollection.getMetadata("provenance_description")); provenance_description.setSize(6, 40); // the row to upload a new logo metadataList.addLabel(T_label_logo); metadataList.addItem().addFile("logo"); // the row displaying an existing logo Item item; if (thisCollection.getLogo() != null) { metadataList.addLabel(T_label_existing_logo); item = metadataList.addItem(); item.addFigure(contextPath + "/bitstream/id/" + thisCollection.getLogo().getID() + "/bob.jpg", null, null); item.addButton("submit_delete_logo").setValue(T_submit_delete_logo); } // item template creation and removal metadataList.addLabel(T_label_item_template); item = metadataList.addItem(); if (thisCollection.getTemplateItem() == null) { item.addButton("submit_create_template").setValue(T_submit_create_template); } else { item.addButton("submit_edit_template").setValue(T_submit_edit_template); item.addButton("submit_delete_template").setValue(T_submit_delete_template); } Para buttonList = main.addPara(); buttonList.addButton("submit_save").setValue(T_submit_save); //Only System Admins can Delete Collections if (AuthorizeManager.isAdmin(context)) { buttonList.addButton("submit_delete").setValue(T_submit_delete); } buttonList.addButton("submit_return").setValue(T_submit_return); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.authorize.AuthorizeException; import org.dspace.eperson.Group; /** * Confirmation step for the deletion a collection's role * @author Alexey Maslov */ public class DeleteCollectionRoleConfirm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.collection.DeleteCollectionRoleConfirm.title"); private static final Message T_trail = message("xmlui.administrative.collection.DeleteCollectionRoleConfirm.trail"); private static final Message T_main_head = message("xmlui.administrative.collection.DeleteCollectionRoleConfirm.main_head"); private static final Message T_main_para_read = message("xmlui.administrative.collection.DeleteCollectionRoleConfirm.main_para_read"); private static final Message T_main_para = message("xmlui.administrative.collection.DeleteCollectionRoleConfirm.main_para"); private static final Message T_submit_confirm = message("xmlui.general.delete"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { String role = parameters.getParameter("role", null); int groupID = parameters.getParameterAsInteger("groupID", -1); Group toBeDeleted = Group.find(context, groupID); // DIVISION: main Division main = body.addInteractiveDivision("collection-role-delete",contextPath+"/admin/collection",Division.METHOD_POST,"primary administrative collection"); main.setHead(T_main_head.parameterize(role)); // Different help message for the default read group to enforce its non-retroactive nature if ("DEFAULT_READ".equals(role)) { main.addPara(T_main_para_read.parameterize(toBeDeleted.getName())); } else { main.addPara(T_main_para.parameterize(toBeDeleted.getName())); } Para buttonList = main.addPara(); buttonList.addButton("submit_confirm").setValue(T_submit_confirm); buttonList.addButton("submit_cancel").setValue(T_submit_cancel); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import java.util.Enumeration; import java.util.HashMap; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.*; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.harvest.HarvestedCollection; import org.dspace.harvest.OAIHarvester; import org.dspace.core.ConfigurationManager; /** * Presents the user (in this case an administrator over the collection) with the * form to edit that collection's metadata, logo, and item template. * @author Alexey Maslov */ public class SetupCollectionHarvestingForm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); private static final Message T_title = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.title"); private static final Message T_trail = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.trail"); private static final Message T_label_source = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.label_source"); private static final Message T_source_normal = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_normal"); private static final Message T_source_harvested = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_harvested"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_submit_save = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.submit_save"); private static final Message T_main_settings_head = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.main_settings_head"); private static final Message T_options_head = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.options_head"); private static final Message T_label_oai_provider = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_oai_provider"); private static final Message T_label_setid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_setid"); private static final Message T_label_metadata_format = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_metadata_format"); private static final Message T_help_oaiurl = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.help_oaiurl"); private static final Message T_error_oaiurl = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.error_oaiurl"); private static final Message T_help_oaisetid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.help_oaisetid"); private static final Message T_error_oaisetid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.error_oaisetid"); private static final Message T_label_harvest_level = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_harvest_level"); private static final Message T_option_md_only = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_only"); private static final Message T_option_md_and_ref = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_and_ref"); private static final Message T_option_md_and_bs = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_and_bs"); private static final Message T_submit_test = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.submit_test"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { int collectionID = parameters.getParameterAsInteger("collectionID", -1); Collection thisCollection = Collection.find(context, collectionID); Request request = ObjectModelHelper.getRequest(objectModel); HarvestedCollection hc = HarvestedCollection.find(context, collectionID); String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); String errorString = parameters.getParameter("errors",null); String[] errors = errorString.split(","); HashMap<String,String> errorMap = new HashMap<String,String>(); for (String error : errors) { //System.out.println(errorString); String[] errorPieces = error.split(":",2); if (errorPieces.length > 1) { errorMap.put(errorPieces[0], errorPieces[1]); } else { errorMap.put(errorPieces[0], errorPieces[0]); } } String oaiProviderValue; String oaiSetIdValue; String metadataFormatValue; int harvestLevelValue; if (hc != null && request.getParameter("submit_test") == null) { oaiProviderValue = hc.getOaiSource(); oaiSetIdValue = hc.getOaiSetId(); metadataFormatValue = hc.getHarvestMetadataConfig(); harvestLevelValue = hc.getHarvestType(); } else { oaiProviderValue = parameters.getParameter("oaiProviderValue", ""); oaiSetIdValue = parameters.getParameter("oaiSetAll", ""); if(!"all".equals(oaiSetIdValue)) { oaiSetIdValue = parameters.getParameter("oaiSetIdValue", null); } metadataFormatValue = parameters.getParameter("metadataFormatValue", ""); String harvestLevelString = parameters.getParameter("harvestLevelValue","0"); if (harvestLevelString.length() == 0) { harvestLevelValue = 0; } else { harvestLevelValue = Integer.parseInt(harvestLevelString); } } // DIVISION: main Division main = body.addInteractiveDivision("collection-harvesting-setup",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); main.setHead(T_main_head.parameterize(thisCollection.getMetadata("name"))); List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); options.addItem().addHighlight("bold").addXref(baseURL+"&submit_harvesting",T_options_harvest); options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); // The top-level, all-setting, countent source radio button List harvestSource = main.addList("harvestSource", "form"); harvestSource.addLabel(T_label_source); Radio source = harvestSource.addItem().addRadio("source"); source.addOption(hc == null || harvestLevelValue == -1, "source_normal", T_source_normal); source.addOption(hc != null, "source_harvested", T_source_harvested); List settings = main.addList("harvestSettings", "form"); settings.setHead(T_main_settings_head); settings.addLabel(T_label_oai_provider); Text oaiProvider = settings.addItem().addText("oai_provider"); oaiProvider.setSize(40); oaiProvider.setValue(oaiProviderValue); oaiProvider.setHelp(T_help_oaiurl); if (errorMap.containsKey(OAIHarvester.OAI_ADDRESS_ERROR)) { oaiProvider.addError(errorMap.get(OAIHarvester.OAI_ADDRESS_ERROR)); } if (errorMap.containsKey("oai_provider")) { oaiProvider.addError(T_error_oaiurl); //oaiProvider.addError("You must provide a set id of the target collection."); } settings.addLabel(T_label_setid); Composite oaiSetComp = settings.addItem().addComposite("oai-set-comp"); Radio oaiSetSettingRadio = oaiSetComp.addRadio("oai-set-setting"); oaiSetSettingRadio.addOption("all".equals(oaiSetIdValue) || oaiSetIdValue == null, "all", "All sets"); oaiSetSettingRadio.addOption(!"all".equals(oaiSetIdValue) && oaiSetIdValue != null, "specific", "Specific sets"); Text oaiSetId = oaiSetComp.addText("oai_setid"); oaiSetId.setSize(40); if(!"all".equals(oaiSetIdValue) && oaiSetIdValue != null) { oaiSetId.setValue(oaiSetIdValue); } oaiSetId.setHelp(T_help_oaisetid); if (errorMap.containsKey(OAIHarvester.OAI_SET_ERROR)) { oaiSetId.addError(errorMap.get(OAIHarvester.OAI_SET_ERROR)); } if (errorMap.containsKey("oai_setid")) { oaiSetId.addError(T_error_oaisetid); } settings.addLabel(T_label_metadata_format); Select metadataFormat = settings.addItem().addSelect("metadata_format"); if (errorMap.containsKey(OAIHarvester.OAI_ORE_ERROR)) { metadataFormat.addError(errorMap.get(OAIHarvester.OAI_ORE_ERROR)); } if (errorMap.containsKey(OAIHarvester.OAI_DMD_ERROR)) { metadataFormat.addError(errorMap.get(OAIHarvester.OAI_DMD_ERROR)); } // Add an entry for each instance of ingestion crosswalks configured for harvesting String metaString = "harvester.oai.metadataformats."; Enumeration pe = ConfigurationManager.propertyNames(); while (pe.hasMoreElements()) { String key = (String)pe.nextElement(); if (key.startsWith(metaString)) { String metadataString = ConfigurationManager.getProperty(key); String metadataKey = key.substring(metaString.length()); String displayName; if (metadataString.indexOf(',') != -1) { displayName = metadataString.substring(metadataString.indexOf(',') + 1); } else { displayName = metadataKey + "(" + metadataString + ")"; } metadataFormat.addOption(metadataKey.equalsIgnoreCase(metadataFormatValue), metadataKey, displayName); } } settings.addLabel(); Item harvestButtons = settings.addItem(); harvestButtons.addButton("submit_test").setValue(T_submit_test); // Various non-critical harvesting options //Division optionsDiv = main.addDivision("collection-harvesting-options","secondary"); //optionsDiv.setHead(T_options_head); List harvestOptions = main.addList("harvestOptions", "form"); harvestOptions.setHead(T_options_head); harvestOptions.addLabel(T_label_harvest_level); Radio harvestLevel = harvestOptions.addItem().addRadio("harvest_level"); harvestLevel.addOption(harvestLevelValue == 1, 1, T_option_md_only); harvestLevel.addOption(harvestLevelValue == 2, 2, T_option_md_and_ref); harvestLevel.addOption(harvestLevelValue != 1 && harvestLevelValue != 2, 3, T_option_md_and_bs); Para buttonList = main.addPara(); buttonList.addButton("submit_save").setValue(T_submit_save); buttonList.addButton("submit_return").setValue(T_submit_return); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import org.dspace.app.util.AuthorizeUtil; import org.dspace.app.xmlui.aspect.administrative.FlowContainerUtils; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Button; import org.dspace.app.xmlui.wing.element.Cell; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; import org.dspace.eperson.Group; /** * Presents the user (most likely a global administrator) with the form to edit * the collection's special authorization groups (or roles). Those include submission * group, workflows, collection admin, and default read. * @author Alexey Maslov */ public class AssignCollectionRoles extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_title = message("xmlui.administrative.collection.AssignCollectionRoles.title"); private static final Message T_trail = message("xmlui.administrative.collection.AssignCollectionRoles.trail"); private static final Message T_main_head = message("xmlui.administrative.collection.AssignCollectionRoles.main_head"); private static final Message T_no_role = message("xmlui.administrative.collection.AssignCollectionRoles.no_role"); private static final Message T_create = message("xmlui.administrative.collection.AssignCollectionRoles.create"); private static final Message T_delete = message("xmlui.general.delete"); private static final Message T_restrict = message("xmlui.administrative.collection.AssignCollectionRoles.restrict"); private static final Message T_help_admins = message("xmlui.administrative.collection.AssignCollectionRoles.help_admins"); private static final Message T_help_wf_step1 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step1"); private static final Message T_help_wf_step2 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step2"); private static final Message T_help_wf_step3 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step3"); private static final Message T_help_submitters = message("xmlui.administrative.collection.AssignCollectionRoles.help_submitters"); private static final Message T_help_default_read = message("xmlui.administrative.collection.AssignCollectionRoles.help_default_read"); private static final Message T_default_read_custom = message("xmlui.administrative.collection.AssignCollectionRoles.default_read_custom"); private static final Message T_default_read_anonymous = message("xmlui.administrative.collection.AssignCollectionRoles.default_read_anonymous"); private static final Message T_edit_authorization = message("xmlui.administrative.collection.AssignCollectionRoles.edit_authorization"); private static final Message T_role_name = message("xmlui.administrative.collection.AssignCollectionRoles.role_name"); private static final Message T_role_group = message("xmlui.administrative.collection.AssignCollectionRoles.role_group"); private static final Message T_role_buttons = message("xmlui.administrative.collection.AssignCollectionRoles.role_buttons"); private static final Message T_label_admins = message("xmlui.administrative.collection.AssignCollectionRoles.label_admins"); private static final Message T_label_wf = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf"); private static final Message T_label_wf_step1 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step1"); private static final Message T_label_wf_step2 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step2"); private static final Message T_label_wf_step3 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step3"); private static final Message T_label_submitters = message("xmlui.administrative.collection.AssignCollectionRoles.label_submitters"); private static final Message T_label_default_read = message("xmlui.administrative.collection.AssignCollectionRoles.label_default_read"); private static final Message T_sysadmins_only = message("xmlui.administrative.collection.AssignCollectionRoles.sysadmins_only"); private static final Message T_not_allowed = message("xmlui.administrative.collection.AssignCollectionRoles.not_allowed"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { int collectionID = parameters.getParameterAsInteger("collectionID", -1); Collection thisCollection = Collection.find(context, collectionID); String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); Group admins = thisCollection.getAdministrators(); Group wfStep1 = thisCollection.getWorkflowGroup(1); Group wfStep2 = thisCollection.getWorkflowGroup(2); Group wfStep3 = thisCollection.getWorkflowGroup(3); Group submitters = thisCollection.getSubmitters(); Group defaultRead = null; int defaultReadID = FlowContainerUtils.getCollectionDefaultRead(context, collectionID); if (defaultReadID >= 0) { defaultRead = Group.find(context, defaultReadID); } // DIVISION: main Division main = body.addInteractiveDivision("collection-assign-roles",contextPath+"/admin/collection",Division.METHOD_POST,"primary administrative collection"); main.setHead(T_main_head.parameterize(thisCollection.getMetadata("name"))); List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); options.addItem().addHighlight("bold").addXref(baseURL+"&submit_roles",T_options_roles); options.addItem().addXref(baseURL+"&submit_harvesting",T_options_harvest); options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); // The table of admin roles Table rolesTable = main.addTable("roles-table", 6, 5); Row tableRow; // The header row Row tableHeader = rolesTable.addRow(Row.ROLE_HEADER); tableHeader.addCell().addContent(T_role_name); tableHeader.addCell().addContent(T_role_group); tableHeader.addCell().addContent(T_role_buttons); rolesTable.addRow(); /* * The collection admins */ // data row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_admins); if (admins != null) { try { AuthorizeUtil.authorizeManageAdminGroup(context, thisCollection); tableRow.addCell().addXref(baseURL + "&submit_edit_admin", admins.getName()); } catch (AuthorizeException authex) { // add a notice, the user is not authorized to create/edit collection's admin group tableRow.addCell().addContent(T_not_allowed); } try { AuthorizeUtil.authorizeRemoveAdminGroup(context, thisCollection); tableRow.addCell().addButton("submit_delete_admin").setValue(T_delete); } catch (AuthorizeException authex) { // nothing to add, the user is not allowed to delete the group } } else { tableRow.addCell().addContent(T_no_role); try { AuthorizeUtil.authorizeManageAdminGroup(context, thisCollection); tableRow.addCell().addButton("submit_create_admin").setValue(T_create); } catch (AuthorizeException authex) { // add a notice, the user is not authorized to create/edit collection's admin group tableRow.addCell().addContent(T_not_allowed); } } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_admins); /* * Workflow steps 1-3 */ // data row try { AuthorizeUtil.authorizeManageWorkflowsGroup(context, thisCollection); tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step1); if (wfStep1 != null) { tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step1", wfStep1.getName()); tableRow.addCell().addButton("submit_delete_wf_step1").setValue(T_delete); } else { tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_wf_step1").setValue(T_create); } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step1); // data row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step2); if (wfStep2 != null) { tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step2", wfStep2.getName()); tableRow.addCell().addButton("submit_delete_wf_step2").setValue(T_delete); } else { tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_wf_step2").setValue(T_create); } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step2); // data row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step3); if (wfStep3 != null) { tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step3", wfStep3.getName()); tableRow.addCell().addButton("submit_delete_wf_step3").setValue(T_delete); } else { tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_wf_step3").setValue(T_create); } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step3); } catch (AuthorizeException authex) { // add a notice, the user is not allowed to manage workflow group tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf); tableRow.addCell().addContent(T_not_allowed); } /* * The collection submitters */ tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_submitters); try { AuthorizeUtil.authorizeManageSubmittersGroup(context, thisCollection); if (submitters != null) { tableRow.addCell().addXref(baseURL + "&submit_edit_submit", submitters.getName()); tableRow.addCell().addButton("submit_delete_submit").setValue(T_delete); } else { tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_submit").setValue(T_create); } } catch (AuthorizeException authex) { tableRow.addCell().addContent(T_not_allowed); } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_submitters); /* * The collection's default read authorizations */ tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_default_read); if (defaultRead == null) { // Custome reading permissions, we can't handle it, just provide a link to the // authorizations manager. tableRow.addCell(1,2).addContent(T_default_read_custom); } else if (defaultRead.getID() == 0) { // Anonymous reading tableRow.addCell().addContent(T_default_read_anonymous); addAdministratorOnlyButton(tableRow.addCell(),"submit_create_default_read",T_restrict); } else { // A specific group is dedicated to reading. tableRow.addCell().addXref(baseURL + "&submit_edit_default_read", defaultRead.getName()); addAdministratorOnlyButton(tableRow.addCell(),"submit_delete_default_read",T_delete); } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_default_read); try { AuthorizeUtil.authorizeManageCollectionPolicy(context, thisCollection); // add one last link to edit the raw authorizations Cell authCell =rolesTable.addRow().addCell(1,3); authCell.addXref(baseURL + "&submit_authorizations", T_edit_authorization); } catch (AuthorizeException authex) { // nothing to add, the user is not authorized to edit collection's policies } Para buttonList = main.addPara(); buttonList.addButton("submit_return").setValue(T_submit_return); main.addHidden("administrative-continue").setValue(knot.getId()); } private void addAdministratorOnlyButton(Cell cell, String buttonName, Message buttonLabel) throws WingException, SQLException { Button button = cell.addButton(buttonName); button.setValue(buttonLabel); if (!AuthorizeManager.isAdmin(context)) { // Only admins can create or delete button.setDisabled(); cell.addHighlight("fade").addContent(T_sysadmins_only); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Radio; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.harvest.HarvestedCollection; /** * The form displayed for collections that do not have any harvesting settings active * (i.e. do not have a row in the harvest_instance table) * * @author Alexey Maslov */ public class ToggleCollectionHarvestingForm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); private static final Message T_title = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.title"); private static final Message T_trail = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.trail"); private static final Message T_label_source = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.label_source"); private static final Message T_source_normal = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_normal"); private static final Message T_source_harvested = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_harvested"); private static final Message T_submit_return = message("xmlui.general.return"); private static final Message T_submit_save = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.submit_save"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException, AuthorizeException { int collectionID = parameters.getParameterAsInteger("collectionID", -1); Collection thisCollection = Collection.find(context, collectionID); // This should always be null; it's an error condition for this tranformer to be called when // a harvest instance exists for this collection HarvestedCollection hc = HarvestedCollection.find(context, collectionID); String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); // DIVISION: main Division main = body.addInteractiveDivision("collection-harvesting-setup",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); main.setHead(T_main_head.parameterize(thisCollection.getMetadata("name"))); List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); options.addItem().addHighlight("bold").addXref(baseURL+"&submit_harvesting",T_options_harvest); options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); // The top-level, all-setting, countent source radio button List harvestSource = main.addList("harvestSource", "form"); harvestSource.addLabel(T_label_source); Radio source = harvestSource.addItem().addRadio("source"); source.addOption(hc == null, "source_normal", T_source_normal); source.addOption(hc != null, "source_harvested", T_source_harvested); Para buttonList = main.addPara(); buttonList.addButton("submit_save").setValue(T_submit_save); buttonList.addButton("submit_return").setValue(T_submit_return); main.addHidden("administrative-continue").setValue(knot.getId()); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.collection; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.SQLException; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Select; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.core.ConfigurationManager; /** * * @author wbossons */ public class CurateCollectionForm extends AbstractDSpaceTransformer { /** Common Package Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); private static final Message T_submit_perform = message("xmlui.general.perform"); private static final Message T_submit_queue = message("xmlui.general.queue"); private static final Message T_submit_return = message("xmlui.general.return"); // End common package language strings // Page/Form specific language strings private static final Message T_main_head = message("xmlui.administrative.collection.CurateCollectionForm.main_head"); private static final Message T_title = message("xmlui.administrative.collection.CurateCollectionForm.title"); private static final Message T_trail = message("xmlui.administrative.collection.CurateCollectionForm.trail"); private static final Message T_label_name = message("xmlui.administrative.collection.CurateCollectionForm.label_name"); /** * common package method for initializing form gui elements * Could be refactored. * * @param pageMeta * @throws WingException */ public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } /** addBody * * @param body * @throws WingException * @throws SQLException * @throws AuthorizeException */ public void addBody(Body body) throws WingException, SQLException, AuthorizeException, UnsupportedEncodingException { int collectionID = parameters.getParameterAsInteger("collectionID", -1); Collection thisCollection = Collection.find(context, collectionID); String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); // DIVISION: main Division main = body.addInteractiveDivision("collection-curate",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); main.setHead(T_main_head.parameterize(thisCollection.getName())); List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); options.addItem().addXref(baseURL+"&submit_harvesting",T_options_harvest); options.addItem().addHighlight("bold").addXref(baseURL+"&submit_curate",T_options_curate); List curationTaskList = main.addList("curationTaskList", "form"); curationTaskList.addLabel(T_label_name); Select select = curationTaskList.addItem().addSelect("curate_task"); select = getCurationOptions(select); select.setSize(1); select.setRequired(); // need submit_curate_task and submit_return Para buttonList = main.addPara(); buttonList.addButton("submit_curate_task").setValue(T_submit_perform); buttonList.addButton("submit_queue_task").setValue(T_submit_queue); buttonList.addButton("submit_return").setValue(T_submit_return); main.addHidden("administrative-continue").setValue(knot.getId()); } private Select getCurationOptions(Select select) throws WingException, UnsupportedEncodingException { String tasksString = ConfigurationManager.getProperty("curate", "ui.tasknames"); String[] tasks = tasksString.split(","); for (String task : tasks) { String[] keyValuePair = task.split("="); select.addOption(URLDecoder.decode(keyValuePair[0].trim(), "UTF-8"), URLDecoder.decode(keyValuePair[1].trim(), "UTF-8")); } return select; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.Map; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.Response; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.DSpaceValidity; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.Item; import org.dspace.eperson.Group; import org.xml.sax.SAXException; /** * * Create the ability to view currently available export archives for download. * * @author Jay Paz */ public class ItemExport extends AbstractDSpaceTransformer implements CacheableProcessingComponent { private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_main_head = message("xmlui.administrative.ItemExport.head"); private static final Message T_export_bad_item_id = message("xmlui.administrative.ItemExport.item.id.error"); private static final Message T_export_bad_col_id = message("xmlui.administrative.ItemExport.collection.id.error"); private static final Message T_export_bad_community_id = message("xmlui.administrative.ItemExport.community.id.error"); private static final Message T_export_item_not_found = message("xmlui.administrative.ItemExport.item.not.found"); private static final Message T_export_col_not_found = message("xmlui.administrative.ItemExport.collection.not.found"); private static final Message T_export_community_not_found = message("xmlui.administrative.ItemExport.community.not.found"); private static final Message T_item_export_success = message("xmlui.administrative.ItemExport.item.success"); private static final Message T_col_export_success = message("xmlui.administrative.ItemExport.collection.success"); private static final Message T_community_export_success = message("xmlui.administrative.ItemExport.community.success"); private static final Message T_avail_head = message("xmlui.administrative.ItemExport.available.head"); /** The Cocoon request */ Request request; /** The Cocoon response */ Response response; java.util.List<Message> errors; java.util.List<String> availableExports; Message message; /** Cached validity object */ private SourceValidity validity; @Override public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, parameters); this.objectModel = objectModel; this.request = ObjectModelHelper.getRequest(objectModel); this.response = ObjectModelHelper.getResponse(objectModel); errors = new ArrayList<Message>(); if (request.getParameter("itemID") != null) { Item item = null; try { item = Item.find(context, Integer.parseInt(request .getParameter("itemID"))); } catch (Exception e) { errors.add(T_export_bad_item_id); } if (item == null) { errors.add(T_export_item_not_found); } else { try { org.dspace.app.itemexport.ItemExport .createDownloadableExport(item, context, false); } catch (Exception e) { errors.add(message(e.getMessage())); } } if (errors.size() <= 0) { message = T_item_export_success; } } else if (request.getParameter("collectionID") != null) { Collection col = null; try { col = Collection.find(context, Integer.parseInt(request .getParameter("collectionID"))); } catch (Exception e) { errors.add(T_export_bad_col_id); } if (col == null) { errors.add(T_export_col_not_found); } else { try { org.dspace.app.itemexport.ItemExport .createDownloadableExport(col, context, false); } catch (Exception e) { errors.add(message(e.getMessage())); } } if (errors.size() <= 0) { message = T_col_export_success; } } else if (request.getParameter("communityID") != null) { Community com = null; try { com = Community.find(context, Integer.parseInt(request .getParameter("communityID"))); } catch (Exception e) { errors.add(T_export_bad_community_id); } if (com == null) { errors.add(T_export_community_not_found); } else { try { org.dspace.app.itemexport.ItemExport .createDownloadableExport(com, context, false); } catch (Exception e) { errors.add(message(e.getMessage())); } } if (errors.size() <= 0) { message = T_community_export_success; } } try { availableExports = org.dspace.app.itemexport.ItemExport .getExportsAvailable(context.getCurrentUser()); } catch (Exception e) { // nothing to do } } /** * Generate the unique cache key. * * @return The generated key hashes the src */ public Serializable getKey() { Request request = ObjectModelHelper.getRequest(objectModel); // Special case, don't cache anything if the user is logging // in. The problem occures because of timming, this cache key // is generated before we know whether the operation has // succeded or failed. So we don't know whether to cache this // under the user's specific cache or under the anonymous user. if (request.getParameter("login_email") != null || request.getParameter("login_password") != null || request.getParameter("login_realm") != null) { return "0"; } StringBuilder key = new StringBuilder(); if (context.getCurrentUser() != null) { key.append(context.getCurrentUser().getEmail()); if (availableExports != null && availableExports.size() > 0) { for (String fileName : availableExports) { key.append(":").append(fileName); } } if (request.getQueryString() != null) { key.append(request.getQueryString()); } } else { key.append("anonymous"); } return HashUtil.hash(key.toString()); } /** * Generate the validity object. * * @return The generated validity object or <code>null</code> if the * component is currently not cacheable. */ public SourceValidity getValidity() { if (this.validity == null) { // Only use the DSpaceValidity object is someone is logged in. if (context.getCurrentUser() != null) { try { DSpaceValidity validity = new DSpaceValidity(); validity.add(eperson); Group[] groups = Group.allMemberGroups(context, eperson); for (Group group : groups) { validity.add(group); } this.validity = validity.complete(); } catch (SQLException sqle) { // Just ignore it and return invalid. } } else { this.validity = NOPValidity.SHARED_INSTANCE; } } return this.validity; } /** * Add Page metadata. */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { pageMeta.addMetadata("title").addContent(T_main_head); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_main_head); } public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { Division main = body.addDivision("export_main"); main.setHead(T_main_head); if (message != null) { main.addDivision("success", "success").addPara(message); } if (errors.size() > 0) { Division errors = main.addDivision("export-errors", "error"); for (Message error : this.errors) { errors.addPara(error); } } if (availableExports != null && availableExports.size() > 0) { Division avail = main.addDivision("available-exports", "available-exports"); avail.setHead(T_avail_head); List fileList = avail.addList("available-files", List.TYPE_ORDERED); for (String fileName : availableExports) { fileList.addItem().addXref( this.contextPath + "/exportdownload/" + fileName, fileName); } } } /** * recycle */ public void recycle() { this.validity = null; this.errors = null; this.message = null; this.availableExports = null; super.recycle(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.authorization; import java.sql.SQLException; import java.util.ArrayList; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Radio; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Select; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.ResourcePolicy; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Constants; import org.dspace.eperson.Group; /** * @author Alexey Maslov */ public class EditPolicyForm extends AbstractDSpaceTransformer { private static final Message T_title = message("xmlui.administrative.authorization.EditPolicyForm.title"); private static final Message T_trail = message("xmlui.administrative.authorization.EditPolicyForm.trail"); private static final Message T_authorize_trail = message("xmlui.administrative.authorization.general.authorize_trail"); private static final Message T_policyList_trail = message("xmlui.administrative.authorization.general.policyList_trail"); private static final Message T_main_head_new = message("xmlui.administrative.authorization.EditPolicyForm.main_head_new"); private static final Message T_main_head_edit = message("xmlui.administrative.authorization.EditPolicyForm.main_head_edit"); private static final Message T_error_no_group = message("xmlui.administrative.authorization.EditPolicyForm.error_no_group"); private static final Message T_error_no_action = message("xmlui.administrative.authorization.EditPolicyForm.error_no_action"); private static final Message T_no_results = message("xmlui.administrative.group.EditGroupForm.no_results"); private static final Message T_groups_column1 = message("xmlui.administrative.authorization.EditPolicyForm.groups_column1"); private static final Message T_groups_column2 = message("xmlui.administrative.authorization.EditPolicyForm.groups_column2"); private static final Message T_groups_column3 = message("xmlui.administrative.authorization.EditPolicyForm.groups_column3"); private static final Message T_groups_column4 = message("xmlui.administrative.authorization.EditPolicyForm.groups_column4"); private static final Message T_submit_save = message("xmlui.general.save"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); private static final Message T_set_group = message("xmlui.administrative.authorization.EditPolicyForm.set_group"); private static final Message T_current_group = message("xmlui.administrative.authorization.EditPolicyForm.current_group"); private static final Message T_groups_head = message("xmlui.administrative.authorization.EditPolicyForm.groups_head"); private static final Message T_policy_currentGroup = message("xmlui.administrative.authorization.EditPolicyForm.policy_currentGroup"); private static final Message T_label_search = message("xmlui.administrative.authorization.EditPolicyForm.label_search"); private static final Message T_submit_search_groups = message("xmlui.administrative.authorization.EditPolicyForm.submit_search_groups"); private static final Message T_label_action = message("xmlui.administrative.authorization.EditPolicyForm.label_action"); private static final Message T_dspace_home = message("xmlui.general.dspace_home"); // How many search results are displayed at once private static final int RESULTS_PER_PAGE = 10; public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail); pageMeta.addTrail().addContent(T_policyList_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException { /* Get and setup our parameters. We should always have an objectType and objectID, since every policy * has to have a parent resource. policyID may, however, be -1 for new, not-yet-created policies and * the groupID is only set if the group is being changed. */ int objectType = parameters.getParameterAsInteger("objectType",-1); int objectID = parameters.getParameterAsInteger("objectID",-1); int policyID = parameters.getParameterAsInteger("policyID",-1); int groupID = parameters.getParameterAsInteger("groupID",-1); int actionID = parameters.getParameterAsInteger("actionID",-1); int page = parameters.getParameterAsInteger("page",0); String query = decodeFromURL(parameters.getParameter("query","-1")); // The current policy, if it exists (i.e. we are not creating a new one) ResourcePolicy policy = ResourcePolicy.find(context, policyID); // The currently set group; it's value depends on wether previously clicked the "Set" button to change // the associated group, came here to edit an existing group, or create a new one. Group currentGroup; if (groupID != -1) { currentGroup = Group.find(context, groupID); } else if (policy != null) { currentGroup = policy.getGroup(); } else { currentGroup = null; } // Same for the current action; it can either blank (-1), manually set, or inherited from the current policy if (policy != null && actionID == -1) { actionID = policy.getAction(); } String errorString = parameters.getParameter("errors",null); ArrayList<String> errors = new ArrayList<String>(); if (errorString != null) { for (String error : errorString.split(",")) { errors.add(error); } } /* Set up our current Dspace object */ DSpaceObject dso; switch (objectType) { case Constants.COMMUNITY: dso = Community.find(context, objectID); break; case Constants.COLLECTION: dso = Collection.find(context, objectID); break; case Constants.ITEM: dso = org.dspace.content.Item.find(context, objectID); break; case Constants.BUNDLE: dso = Bundle.find(context, objectID); break; case Constants.BITSTREAM: dso = Bitstream.find(context, objectID); break; default: dso = null; } // DIVISION: edit-container-policies Division main = body.addInteractiveDivision("edit-policy",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization"); if (policyID >= 0) { objectID = policy.getResourceID(); objectType = policy.getResourceType(); main.setHead(T_main_head_edit.parameterize(policyID,Constants.typeText[objectType],objectID)); } else { main.setHead(T_main_head_new.parameterize(Constants.typeText[objectType], objectID)); } int resourceRelevance = 1 << objectType; // DIVISION: authorization-actions Division actions = main.addDivision("edit-policy-actions"); List actionsList = actions.addList("actions","form"); // actions radio buttons actionsList.addLabel(T_label_action); Item actionSelectItem = actionsList.addItem(); Radio actionSelect = actionSelectItem.addRadio("action_id"); actionSelect.setLabel(T_label_action); //Select actionSelect = actionSelectItem.addSelect("action_id"); //actionsBox.addContent(T_label_action); //Select actionSelect = actionsBox.addSelect("action_id"); for( int i = 0; i < Constants.actionText.length; i++ ) { // only display if action i is relevant // to resource type resourceRelevance if( (Constants.actionTypeRelevance[i] & resourceRelevance) > 0) { if (actionID == i) { actionSelect.addOption(true, i, Constants.actionText[i]); } else { actionSelect.addOption(i, Constants.actionText[i]); } } } if (errors.contains("action_id")) { actionSelect.addError(T_error_no_action); } // currently set group actionsList.addLabel(T_policy_currentGroup); Select groupSelect = actionsList.addItem().addSelect("group_id"); groupSelect.setSize(5); for (Group group : Group.findAll(context, Group.NAME)) { if (group == currentGroup) { groupSelect.addOption(true, group.getID(), group.getName()); } else { groupSelect.addOption(group.getID(), group.getName()); } } if (errors.contains("group_id")) { groupSelect.addError(T_error_no_group); } // the search function actionsList.addLabel(T_label_search); Item searchItem = actionsList.addItem(); Text searchText = searchItem.addText("query"); if (!query.equals("-1")) { searchText.setValue(query); } searchItem.addButton("submit_search_groups").setValue(T_submit_search_groups); actionsList.addLabel(); Item buttons = actionsList.addItem(); buttons.addButton("submit_save").setValue(T_submit_save); buttons.addButton("submit_cancel").setValue(T_submit_cancel); // Display the search results table if (!query.equals("-1")) { Division groupsList = main.addDivision("edit-policy-groupsList"); groupsList.setHead(T_groups_head); this.addGroupSearch(groupsList, currentGroup, dso, query, page); } main.addHidden("administrative-continue").setValue(knot.getId()); } /** * Search for groups to add to this group. */ private void addGroupSearch(Division div, Group sourceGroup, DSpaceObject dso, String query, int page) throws WingException, SQLException { Group[] groups = Group.search(context, query, page*RESULTS_PER_PAGE, (page+1)*RESULTS_PER_PAGE); int totalResults = Group.searchResultCount(context, query); ArrayList<ResourcePolicy> otherPolicies = (ArrayList<ResourcePolicy>)AuthorizeManager.getPolicies(context, dso); if (totalResults > RESULTS_PER_PAGE) { int firstIndex = page*RESULTS_PER_PAGE+1; int lastIndex = page*RESULTS_PER_PAGE + groups.length; String baseURL = contextPath+"/admin/authorize?administrative-continue="+knot.getId(); String nextURL = null, prevURL = null; if (page < ((totalResults - 1) / RESULTS_PER_PAGE)) { nextURL = baseURL + "&page=" + (page + 1); } if (page > 0) { prevURL = baseURL + "&page=" + (page - 1); } div.setSimplePagination(totalResults,firstIndex,lastIndex,prevURL, nextURL); } Table table = div.addTable("policy-edit-search-group",groups.length + 1, 1); Row header = table.addRow(Row.ROLE_HEADER); // Add the header row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_groups_column1); header.addCell().addContent(T_groups_column2); header.addCell().addContent(T_groups_column3); header.addCell().addContent(T_groups_column4); // The rows of search results for (Group group : groups) { String groupID = String.valueOf(group.getID()); String name = group.getName(); url = contextPath+"/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&group_id="+groupID; Row row = table.addRow(); row.addCell().addContent(groupID); row.addCell().addXref(url,name); // Iterate other other polices of our parent resource to see if any match the currently selected group StringBuilder otherAuthorizations = new StringBuilder(); int groupsMatched = 0; for (ResourcePolicy otherPolicy : otherPolicies) { if (otherPolicy.getGroup() == group) { otherAuthorizations.append(otherPolicy.getActionText()).append(", "); groupsMatched++; } } if (groupsMatched > 0) { row.addCell().addContent(otherAuthorizations.substring(0,otherAuthorizations.lastIndexOf(", "))); } else { row.addCell().addContent("-"); } if (group != sourceGroup) { row.addCell().addButton("submit_group_id_" + groupID).setValue(T_set_group); } else { row.addCell().addContent(T_current_group); } } if (groups.length <= 0) { table.addRow().addCell(1, 4).addContent(T_no_results); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.administrative.authorization; import java.sql.SQLException; import java.util.ArrayList; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.ResourcePolicy; /** * @author Alexey Maslov */ public class DeletePoliciesConfirm extends AbstractDSpaceTransformer { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_title = message("xmlui.administrative.authorization.DeletePoliciesConfirm.title"); private static final Message T_trail = message("xmlui.administrative.authorization.DeletePoliciesConfirm.trail"); private static final Message T_authorize_trail = message("xmlui.administrative.authorization.general.authorize_trail"); private static final Message T_policyList_trail = message("xmlui.administrative.authorization.general.policyList_trail"); private static final Message T_confirm_head = message("xmlui.administrative.authorization.DeletePoliciesConfirm.confirm_head"); private static final Message T_confirm_para = message("xmlui.administrative.authorization.DeletePoliciesConfirm.confirm_para"); private static final Message T_head_id = message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_id"); private static final Message T_head_action = message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_action"); private static final Message T_head_group = message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_group"); private static final Message T_submit_confirm = message("xmlui.general.delete"); private static final Message T_submit_cancel = message("xmlui.general.cancel"); public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail); pageMeta.addTrail().addContent(T_policyList_trail); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws WingException, SQLException { // Get all our parameters String idsString = parameters.getParameter("policyIDs", null); ArrayList<ResourcePolicy> policies = new ArrayList<ResourcePolicy>(); for (String id : idsString.split(",")) { ResourcePolicy policy = ResourcePolicy.find(context,Integer.valueOf(id)); policies.add(policy); } // DIVISION: policies-confirm-delete Division deleted = body.addInteractiveDivision("policies-confirm-delete",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization"); deleted.setHead(T_confirm_head); deleted.addPara(T_confirm_para); Table table = deleted.addTable("policies-confirm-delete",policies.size() + 1, 4); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_head_id); header.addCell().addContent(T_head_action); header.addCell().addContent(T_head_group); for (ResourcePolicy policy : policies) { Row row = table.addRow(); row.addCell().addContent(policy.getID()); row.addCell().addContent(policy.getActionText()); if (policy.getGroup() != null) { row.addCell().addContent(policy.getGroup().getName()); } else { row.addCell().addContent("..."); } } Para buttons = deleted.addPara(); buttons.addButton("submit_confirm").setValue(T_submit_confirm); buttons.addButton("submit_cancel").setValue(T_submit_cancel); deleted.addHidden("administrative-continue").setValue(knot.getId()); } }
Java