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.dspace.app.xmlui.wing.element; /** * A class representing a list item. * * The item element in a list serves a dual purpose. It can contain other lists, * allowing for hierarchies and recursive lists. Alternatively it can serve as a * character container to display textual data, possibly enhanced with * hyperlinks, emphasized blocks of text, images and form fields. An item cannot * be both a character container and contain a list. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; public class Item extends RichTextContainer implements StructuralElement { /** The name of the item element */ public static final String E_ITEM = "item"; /** the item's name */ private String name; /** Special rendering hints for this item */ private String rend; /** * Construct a new item. * * @param context * (Required) The context this element is contained in * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Item(WingContext context, String name, String rend) throws WingException { super(context); this.name = name; this.rend = rend; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); if (name != null) { attributes.put(A_NAME, name); } if (name != null) { attributes.put(A_ID, context.generateID(E_ITEM, name)); } if (rend != null) { attributes.put(A_RENDER, rend); } startElement(contentHandler, namespaces, E_ITEM, attributes); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_ITEM); } }
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.wing.element; /** * A class representing a File input controls. The file input control allows the * user to select files from there local system to be uploaded to the server. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; public class File extends Field { /** * Construct a new field. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * * @param name * (Required) a non-unique local identifier used to differentiate * the element from its siblings within an interactive division. * This is the name of the field use when data is submitted back * to the server. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected File(WingContext context, String name, String rend) throws WingException { super(context, name, Field.TYPE_FILE, rend); this.params = new Params(context); } }
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.wing.element; /** * A class representing a table. * * The table element is a container for information presented in tabular format. * It consists of a set of row elements and an optional header. * * @author Scott Phillips */ import java.util.ArrayList; import java.util.List; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; public class Table extends AbstractWingElement implements StructuralElement { /** The name of the table element */ public static final String E_TABLE = "table"; /** The name of the rows attribute */ public static final String A_ROWS = "rows"; /** The name of the cols attribute */ public static final String A_COLS = "cols"; /** The name assigned to this table */ private String name; /** Special rendering instructions for this table */ private String rend; /** The number of rows in the table */ private int rows; /** The number of cols in the table */ private int cols; /** The table's head */ private Head head; /** the rows contained in the table */ private List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>(); /** * Construct a new row. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * * @param rows * (Required) the number of rows in the table. * @param cols * (Required) the number of columns in the table. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Table(WingContext context, String name, int rows, int cols, String rend) throws WingException { super(context); require(name, "The 'name' parameter is required for all tables."); greater(rows, 0, "The 'rows' parameter must be grater than zero."); greater(cols, 0, "The 'cols' parameter must be grater than zero."); this.name = name; this.rows = rows; this.cols = cols; this.rend = rend; } /** * Set the head element which is the label associated with this table. */ public Head setHead() throws WingException { this.head = new Head(context, null); return head; } /** * Set the head element which is the label associated with this table. * * @param characters * (May be null) Unprocessed characters to be included */ public void setHead(String characters) throws WingException { Head head = this.setHead(); head.addContent(characters); } /** * Set the head element which is the label associated with this table. * * @param message * (Required) A key into the i18n catalogue for translation into * the user's preferred language. */ public void setHead(Message message) throws WingException { Head head = this.setHead(); head.addContent(message); } /** * Add a new row to the table. The row element is contained inside a table * and serves as a container of cell elements. A required 'role' attribute * determines how the row and its cells are used. * * * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param role * (May be null) determine what kind of information the row * carries, either header or data. See row.ROLES * @param rend * (May be null) a rendering hint used to override the default * display of the element. * * @return a new table row */ public Row addRow(String name, String role, String rend) throws WingException { Row row = new Row(context, name, role, rend); contents.add(row); return row; } /** * Add a new row to the table. The row element is contained inside a table * and serves as a container of cell elements. A required 'role' attribute * determines how the row and its cells are used. * * @param role * (May be null) determines what kind of information the row * carries, either header or data. See row.ROLES * * @return a new table row */ public Row addRow(String role) throws WingException { return this.addRow(null, role, null); } /** * Add a new row to the table. The row element is contained inside a table * and serves as a container of cell elements. * * @return a new table row */ public Row addRow() throws WingException { return this.addRow(null, null, null); } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); attributes.put(A_NAME, name); attributes.put(A_ID, context.generateID(E_TABLE, name)); attributes.put(A_ROWS, rows); attributes.put(A_COLS, cols); if (rend != null) { attributes.put(A_RENDER, rend); } startElement(contentHandler, namespaces, E_TABLE, attributes); if (head != null) { head.toSAX(contentHandler, lexicalHandler, namespaces); } for (AbstractWingElement content : contents) { content.toSAX(contentHandler, lexicalHandler, namespaces); } endElement(contentHandler, namespaces, E_TABLE); } /** * dispose */ public void dispose() { if (head != null) { head.dispose(); } for (AbstractWingElement content : contents) { content.dispose(); } head = null; contents.clear(); contents = null; super.dispose(); } }
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.wing.element; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This basic interface is implemented by all WingElements, once an element has * been created it can be translated into SAX events and disposed of. * * @author Scott Phillips */ public interface WingElement { /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public abstract void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException; /** * Dispose */ public void dispose(); }
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.wing.element; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This class represents a head for either a table, division, or list. * * @author Scott Phillips */ public class Head extends TextContainer implements StructuralElement { /** The name of the head element */ public static final String E_HEAD = "head"; /** The head's name */ private String name; /** * Construct a new head. * * @param context * (Required) The context this element is contained in * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. */ protected Head(WingContext context, String name) throws WingException { super(context); this.name = name; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); if (this.name != null) { attributes.put(A_NAME, name); attributes.put(A_ID, context.generateID(E_HEAD, name)); } startElement(contentHandler, namespaces, E_HEAD, attributes); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_HEAD); } }
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.wing.element; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This class represents a list's label element, they are associated with an * item and annotates that item with a number, a textual description of some * sort, or a simple bullet. * * @author Scott Phillips */ public class Label extends TextContainer implements StructuralElement { /** The name of the label element */ public static final String E_LABEL = "label"; /** The label's name */ private String name; /** Special rendering hints */ private String rend; /** * Construct a new label. * * @param context * (Required) The context this element is contained in * @param name * (May be null) The label's name * @param rend * (May be null) a rendering hint used to override the default * display of the element. * @throws WingException */ protected Label(WingContext context, String name, String rend) throws WingException { super(context); this.name = name; this.rend = rend; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); if (this.name != null) { attributes.put(A_NAME, name); attributes.put(A_ID, context.generateID(E_LABEL, name)); } if (this.rend != null) { attributes.put(A_RENDER, this.rend); } startElement(contentHandler, namespaces, E_LABEL, attributes); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_LABEL); } }
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.wing.element; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This is a class representing an individual metadata field in sudo-dublin core * format. The metadata elements carries generic metadata information in the * form of an attribute-value pair. * * @author Scott Phillips */ public class Metadata extends TextContainer implements MetadataElement { /** The name of the metadata element */ public static final String E_METADATA = "metadata"; /** The name of the element attribute */ public static final String A_ELEMENT = "element"; /** The name of the qualifier attribute */ public static final String A_QUALIFIER = "qualifier"; /** The name of the language attribute */ public static final String A_LANGUAGE = "lang"; /** The metadata's element */ private String element; /** The metadata's qualifier */ private String qualifier; /** The metadata's language */ private String language; /** * Determine the addititive model for the metadata, should * the metadata allways be added to the document or only if * it does not allready exist? */ private boolean allowMultiple; /** * Construct a new metadata. * * @param element * (Required) The element of this metadata * @param qualifier * (May be null) The qualifier of this metadata * @param language * (May be null) the language of this metadata * @param allowMultiple * (Required) Are multipe metadata elements with the same element, * qualifier, and language allowed? */ protected Metadata(WingContext context, String element, String qualifier, String language, boolean allowMultiple) throws WingException { super(context); this.element = element; this.qualifier = qualifier; this.language = language; this.allowMultiple = allowMultiple; } /** * If an metadata with the same element, qualifier, and language exist * within the document should this metadata element be added into the * document or should only one metadata be allowed. */ protected boolean allowMultiple() { return this.allowMultiple; } /** * Determine if the given element, qualifier, and lang are equal to this * metadata. * * @param element * (Required) The element of this metadata * @param qualifier * (May be null) The qualifier of this metadata * @param language * (May be null) the language of this metadata * @return True if the given parameters are equal to this metadata. */ protected boolean equals(String element, String qualifier, String language) { // Element should never be null. if (this.element == null || element == null) { return false; } if (!stringEqualsWithNulls(this.element, element)) { return false; } if (!stringEqualsWithNulls(this.qualifier, qualifier)) { return false; } if (!stringEqualsWithNulls(this.language, language)) { return false; } // Element, qualifier, and language are equal. return true; } /** * This is just a silly private method to make the method above easier to * read. Compare the two parameters to see if they are equal while taking * into account nulls. So if both values are null that is considered an * equals. * * The method is meant to replace the syntax current.equals(test) so that it * works when current is null. * * @param current * (May be null) The current value. * @param test * (May be null) The value to be compared to current * @return If the strings are equal. */ private boolean stringEqualsWithNulls(String current, String test) { if (current == null) { return (test == null); } else { return current.equals(test); } } /** * Translate into SAX events. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); attributes.put(A_ELEMENT, element); if (this.qualifier != null) { attributes.put(A_QUALIFIER, qualifier); } if (this.language != null) { attributes.put(A_LANGUAGE, language); } startElement(contentHandler, namespaces, E_METADATA, attributes); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_METADATA); } }
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.wing.element; /** * This interface represents all structural wing elements. * * There are two broad types of wing elements: structural and metadata. The * metadata elements describe information about the page, while structural * elements describe how to layout the page. * * @author Scott Phillips */ public interface StructuralElement { /** The name of the 'name' attribute */ public static final String A_NAME = "n"; /** The name of the id attribute */ public static final String A_ID = "id"; /** The name of the render attribute */ public static final String A_RENDER = "rend"; }
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.wing.element; /** * A class representing a radio input control. Radio input controls allow the * user to select one value among many. If the user selects one value then all * other values are set to off. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; public class Radio extends Field { /** * Construct a new field. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * * @param name * (Required) a non-unique local identifier used to differentiate * the element from its siblings within an interactive division. * This is the name of the field use when data is submitted back * to the server. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Radio(WingContext context, String name, String rend) throws WingException { super(context, name, Field.TYPE_RADIO, rend); this.params = new Params(context); } /** * Enable the add operation for this field. When this is enabled the * front end will add a button to add more items to the field. * */ public void enableAddOperation() throws WingException { this.params.enableAddOperation(); } /** * Enable the delete operation for this field. When this is enabled then * the front end will provide a way for the user to select fields (probably * checkboxes) along with a submit button to delete the selected fields. * */ public void enableDeleteOperation()throws WingException { this.params.enableDeleteOperation(); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. */ public Option addOption(String returnValue) throws WingException { Option option = new Option(context, returnValue); options.add(option); return option; } /** * Add an option. * * @param selected * (Required) Set the field as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. */ public Option addOption(boolean selected, String returnValue) throws WingException { if (selected) { setOptionSelected(returnValue); } return addOption(returnValue); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param characters * (Required) The text to set as the visible option. */ public void addOption(String returnValue, String characters) throws WingException { Option option = this.addOption(returnValue); option.addContent(characters); } /** * Add an option. * * @param selected * (Required) Set the field as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param characters * (Required) The text to set as the visible option. */ public void addOption(boolean selected,String returnValue, String characters) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,characters); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param characters * (Required) The text to set as the visible option. */ public void addOption(int returnValue, String characters) throws WingException { Option option = this.addOption(String.valueOf(returnValue)); option.addContent(characters); } /** * Add an option. * * @param selected * (Required) Set the field as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param characters * (Required) The text to set as the visible option. */ public void addOption(boolean selected, int returnValue, String characters) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,characters); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(String returnValue, Message message) throws WingException { Option option = this.addOption(returnValue); option.addContent(message); } /** * Add an option. * * @param selected * (Required) Set the field as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(boolean selected, String returnValue, Message message) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,message); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(int returnValue, Message message) throws WingException { Option option = this.addOption(String.valueOf(returnValue)); option.addContent(message); } /** * Add an option. * * @param selected * (Required) Set the field as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(boolean selected, int returnValue, Message message) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,message); } /** * Set the given option as selected. * * @param returnValue * (Required) The return value of the option to be selected. */ public void setOptionSelected(String returnValue) throws WingException { Value value = new Value(context,Value.TYPE_OPTION,returnValue); values.add(value); } /** * Set the given option as selected. * * @param returnValue * (Required) The return value of the option to be selected. */ public void setOptionSelected(int returnValue) throws WingException { Value value = new Value(context,Value.TYPE_OPTION,String.valueOf(returnValue)); values.add(value); } /** * Add a field instance * @return instance */ public Instance addInstance() throws WingException { Instance instance = new Instance(context); instances.add(instance); return instance; } }
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.wing.element; /** * A class representing a highlighted inline element of text. * * The hi element is used for emphasis of text and occurs inside character * containers like "p" and "list item". It can be mixed freely with content, and * any content contained within the element itself will be emphasized in a * manner specified by the required "rend" attribute. Additionally, the "hi" * element is the only character container component that is recursive, allowing * it to contain other character components. (including other hi elements!) * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; public class Highlight extends RichTextContainer implements StructuralElement { /** The name of the highlight element */ public static final String E_HIGHLIGHT = "hi"; /** Special rendering instructions for this highlight */ private String rend; /** * Construct a new highlight element. * * @param context * (Required) The context this element is contained in. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Highlight(WingContext context, String rend) throws WingException { super(context); this.rend = rend; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); if (this.rend != null) { attributes.put(A_RENDER, this.rend); } startElement(contentHandler, namespaces, E_HIGHLIGHT, attributes); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_HIGHLIGHT); } }
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.wing.element; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.Namespace; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingConstants; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingInvalidArgument; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.NamespaceSupport; import java.util.Map; /** * This class represents a generic element inside the Wing framework. * * The primary purpose of this abstract class is to create a generic datatype * for storage of any WingElement. Second, this class also provides a set of * utilities for easy maintenance of each wing element. There are a set of * methods for sending SAX events that handle namespaces and attributes so that * each individual wing element does not. * * There are also a set of utility methods for checking method parameters. * * @author Scott Phillips */ public abstract class AbstractWingElement implements WingElement { /** * The current context this element is operating under. From the context * contentHandler, namespace support, and unique id generation can be found. * This context is shared between many elements. */ protected WingContext context; /** * Construct a new WingElement. All wing elements must have access to a * current WingContext. * * @param context * (Required) The context this element is contained in. */ protected AbstractWingElement(WingContext context) { if (context == null) { throw new IllegalArgumentException("Context may not be null."); } this.context = context; } /** * Construct a new WingElement without access to the current wing Context. * This means that the wing element will not be able to know the component * name because the context is not available. * * This invocation method is intended for wing element implementations that * are outside the wing pacakage. */ protected AbstractWingElement() { } /** * Return the currently registered wing context. * */ protected WingContext getWingContext() { return this.context; } /** * Set the WingContext, note there are potential side effects of changing * the WingContext once it has been used. This context should not be changed * after elements have been added to a wingElement. * * @param context * The new WingContext. */ protected void setWingContext(WingContext context) { this.context = context; } /** * These methods: require, restrict, greater, lesser, greater, requireFalse, * requireTrue are simple methods to describe the restrictions and * requirements of attribute values. */ /** * Check to make sure the parameter is not null or an empty string. * * @param parameter * A non null and none empty string * @param message * The exception message thrown if parameter is invalid. */ protected void require(String parameter, String message) throws WingInvalidArgument { if (parameter == null || parameter.equals("")) { throw new WingInvalidArgument(message); } } /** * Check to make sure the parameter is not null or an empty string. * * @param parameter * A non null and none empty string * @param message * The exception message thrown if parameter is invalid. */ protected void require(Message parameter, String message) throws WingInvalidArgument { if (parameter == null) { throw new WingInvalidArgument(message); } } /** * Check to make sure that the parameter is a member of one of the options. * This method will accept null values, if you need to restrict and not * allow null values then use the require() method in conjunction with this * method. * * @param parameter * A null string, or a member of the options array. * @param options * A list of possible values for the parameter. * @param message * The exception message thrown if the parameter is invalid. */ protected void restrict(String parameter, String[] options, String message) throws WingInvalidArgument { if (parameter == null) { return; } for (String test : options) { if (parameter.equals(test)) { return; } } // short circuit the method call. throw new WingInvalidArgument(message); } /** * Check to make sure that the parameter is GREATER THAN (note: not equal * to) the given greater variable. * * @param parameter * An int who's value is greater than greater. * @param greater * An int who's value is lesser that greater. * @param message * The exception message thrown if the parameter is invalid. */ protected void greater(int parameter, int greater, String message) throws WingInvalidArgument { if (parameter <= greater) { throw new WingInvalidArgument(message); } } /** * Check to make sure that the parameter is LESS THAN (note: not equal to) * the given lesser variable. * * @param parameter * An int who's value is less than lesser. * @param lesser * An int who's value is greater that lesser. * @param message * The exception message thrown if the parameter is invalid. */ protected void lesser(int parameter, int lesser, String message) throws WingInvalidArgument { if (parameter >= lesser) { throw new WingInvalidArgument(message); } } /** * Check to make sure that the boolean test value is false. * * @param test * A false value. * @param message * The exception message thrown if "test" is invalid. */ protected void requireFalse(boolean test, String message) throws WingInvalidArgument { if (test) { throw new WingInvalidArgument(message); } } /** * Check to make sure that the boolean test value is true. * * @param test * A true value. * @param message * The exception message thrown if "test" is invalid. */ protected void requireTrue(boolean test, String message) throws WingInvalidArgument { if (!test) { throw new WingInvalidArgument(message); } } /** * Send the SAX event to start this element. * * Assume the DRI namespace. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. * @param name * (Required) The element's localName * @param attributes * (May be null) Attributes for this element. */ protected void startElement(ContentHandler contentHandler, NamespaceSupport namespaces, String name, AttributeMap attributes) throws SAXException { startElement(contentHandler, namespaces, WingConstants.DRI, name, attributes); } /** * Send the SAX events to start this element. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. * @param namespace * (Required) The namespace of this element. * @param name * (Required) The local name of this element. * @param attributes * (May be null) Attributes for this element */ protected void startElement(ContentHandler contentHandler, NamespaceSupport namespaces, Namespace namespace, String name, AttributeMap attributes) throws SAXException { String prefix = namespaces.getPrefix(namespace.URI); contentHandler.startElement(namespace.URI, name, qName(prefix, name), map2sax(namespace, namespaces, attributes)); } /** * Send the SAX event for these plain characters, not wrapped in any * elements. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param characters * (May be null) Characters to send. */ protected void sendCharacters(ContentHandler contentHandler, String characters) throws SAXException { if (characters != null) { char[] contentArray = characters.toCharArray(); contentHandler.characters(contentArray, 0, contentArray.length); } } /** * Send the SAX events to end this element. * * Assume the DRI namespace. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. * @param name * (Required) The localName of this element. */ protected void endElement(ContentHandler contentHandler, NamespaceSupport namespaces, String name) throws SAXException { endElement(contentHandler, namespaces, WingConstants.DRI, name); } /** * Send the SAX events to end this element. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. * @param namespace * (Required) The namespace of this element. * @param name * (Required) The local name of this element. */ protected void endElement(ContentHandler contentHandler, NamespaceSupport namespaces, Namespace namespace, String name) throws SAXException { String prefix = namespaces.getPrefix(namespace.URI); contentHandler.endElement(namespace.URI, name, qName(prefix, name)); } /** * Build the SAX attributes object based upon Java's String Map. * * @param namespaces * SAX Helper class to keep track of namespaces able to determine * the correct prefix for a given namespace URI. * @param attributeMap * Map of attributes and values. * @return SAX Attributes object of the given map. */ private Attributes map2sax(Namespace elementNamespace,NamespaceSupport namespaces, AttributeMap attributeMap) { return map2sax(elementNamespace,namespaces, null, attributeMap); } /** * Build the SAX attributes object based upon Java's String map. This * convenience method will build, or add to an existing attributes object, * the attributes detailed in the AttributeMap. * * @param namespaces * SAX Helper class to keep track of namespaces able to determine * the correct prefix for a given namespace URI. * @param attributes * An existing SAX AttributesImpl object to add attributes too. * If the value is null then a new attributes object will be * created to house the attributes. * @param attributeMap * A map of attributes and values. * @return */ private AttributesImpl map2sax(Namespace elementNamespace, NamespaceSupport namespaces, AttributesImpl attributes, AttributeMap attributeMap) { if (attributes == null) { attributes = new AttributesImpl(); } if (attributeMap != null) { // Figure out the namespace issue Namespace namespace = attributeMap.getNamespace(); String uri; if (namespace != null) { uri = namespace.URI; } else { uri = WingConstants.DRI.URI; } String prefix = namespaces.getPrefix(uri); // copy each one over. for (Map.Entry<String, String> attr : attributeMap.entrySet()) { if (attr.getValue() == null) { continue; } // If the indended namespace is the element's namespace then we // leave // off the namespace declaration because w3c say's its redundent // and breaks lots of xsl stuff. if (elementNamespace.URI.equals(uri)) { attributes.addAttribute("", attr.getKey(), attr.getKey(), "CDATA", attr.getValue()); } else { attributes.addAttribute(uri, attr.getKey(), qName(prefix, attr.getKey()), "CDATA", attr.getValue()); } } } return attributes; } /** * Create the qName for the element with the given localName and namespace * prefix. * * @param prefix * (May be null) The namespace prefix. * @param localName * (Required) The element's local name. * @return */ private String qName(String prefix, String localName) { if (prefix == null || prefix.equals("")) { return localName; } else { return prefix + ":" + localName; } } /** * Dispose */ public void dispose() { this.context = 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.dspace.app.xmlui.wing.element; /** * A class representing a table cell. * * The cell element contained in a row of a table carries content for that * table. It is a character container, just like p, item, and hi, and its * primary purpose is to display textual data, possibly enhanced with * hyperlinks, emphasized blocks of text, images and form fields. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; public class Cell extends RichTextContainer implements StructuralElement { /** The name of the cell element */ public static final String E_CELL = "cell"; /** The name of the role attribute */ public static final String A_ROLE = "role"; /** The name of the rows attribute */ public static final String A_ROWS = "rows"; /** The name of the cols attribute */ public static final String A_COLS = "cols"; /** The name of this cell */ private String name; /** The role of this cell, see ROLES below */ private String role; /** How many rows does this table span */ private int rows; /** How many cols does this table span */ private int cols; /** Special rendering instructions */ private String rend; /** The possible cell role types */ public static final String ROLE_DATA = "data"; public static final String ROLE_HEADER = "header"; /** All the possible cell role types collected into one array */ public static final String[] ROLES = { ROLE_DATA, ROLE_HEADER }; /** * Construct a new cell. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param role * (May be null) determines what kind of information the cell * carries, either header or data. See cell.ROLES * @param rows * (May be zero for no defined value) determines how many rows * does this cell span. * @param cols * (May be zero for no defined value) determines how many columns * does this cell span. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Cell(WingContext context, String name, String role, int rows, int cols, String rend) throws WingException { super(context); restrict(role, ROLES, "The 'role' parameter must be one of these values: 'data' or 'header'."); greater(rows, -1, "The 'rows' parameter must be greater than or equal to zero."); greater(cols, -1, "The 'cols' parameter must be greater than or equal to zero."); this.name = name; this.role = role; this.rows = rows; this.cols = cols; this.rend = rend; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); if (name != null) { attributes.put(A_NAME, name); attributes.put(A_ID, context.generateID(E_CELL, name)); } if (role != null) { attributes.put(A_ROLE, role); } // else // attributes.put(A_ROLE, ROLE_DATA); if (rows > 0) { attributes.put(A_ROWS, rows); } if (cols > 0) { attributes.put(A_COLS, cols); } if (rend != null) { attributes.put(A_RENDER, rend); } startElement(contentHandler, namespaces, E_CELL, attributes); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_CELL); } /** * dispose */ public void dispose() { if (contents != null) { for (AbstractWingElement content : contents) { content.dispose(); } contents.clear(); } contents = null; super.dispose(); } }
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.wing.element; /** * A class representing a password input control. The password control acts just * like a text control but the value being typed by the user is hidden from * view. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; public class Password extends Field { /** * Construct a new field. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * @param name * (Required) a non-unique local identifier used to differentiate * the element from its siblings within an interactive division. * This is the name of the field use when data is submitted back * to the server. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Password(WingContext context, String name, String rend) throws WingException { super(context, name, Field.TYPE_PASSWORD, rend); this.params = new Params(context); } /** * Set the size of the password field. * * @param size * (Required) The size of the password field. */ public void setSize(int size) { this.params.setSize(size); } /** * Set the size and maximum length of the field. * * @param size * (May be zero for no defined value) The size of the password field. * @param maxLength * (May be zero for no defined value) the maximum length of the field. */ public void setSize(int size, int maxLength) { this.params.setSize(size); this.params.setMaxLength(maxLength); } }
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.wing.element; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dspace.app.xmlui.wing.WingConstants; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.jdom.Attribute; import org.jdom.Content; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Text; import org.jdom.input.SAXBuilder; import org.jdom.output.SAXOutputter; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This class represents data that is translated from simple HTML or plain text. * * This class represents a simple HTML fragment. It allows for user supplied * HTML to be translated on the fly into DRI. * * At the present time it only supports the following tags: h1, h2, h3, h4, h5, * p, a, b, i, u, ol, li and img. Each are translated into their DRI equivelents, note * the "h" tags are translated into a paragraph of rend=heading. * * If the linkbreaks flag is set then line breaks are treated as paragraphs. This * allows plain text files to also be included and they will be mapped into DRI as * well. * * @author Scott Phillips * @author Jay Paz */ public class SimpleHTMLFragment extends AbstractWingElement { /** The HTML Fragment */ private String fragment; /** Determine if blank lines mark a new paragraph */ private boolean blankLines; /** * Construct a fragment object for translating into DRI. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * @param blankLines * (Required) Determine if blank lines should be treated as * paragraphs delimeters. * @param fragment * (Required) The HTML Fragment to be translated into DRI. * @throws WingException */ protected SimpleHTMLFragment(WingContext context, boolean blankLines, String fragment) throws WingException { super(context); this.blankLines = blankLines; this.fragment = fragment; } /** * Translate this element into SAX * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical events * (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { try { String xml = "<fragment>" + fragment + "</fragment>"; ByteArrayInputStream inputStream = new ByteArrayInputStream(xml .getBytes()); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(inputStream); try { translate(document.getRootElement()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new JDOMException( "Error translating HTML fragment into DRI", e); } SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); SAXOutputter outputter = new SAXOutputter(); outputter.setContentHandler(filter); outputter.setLexicalHandler(filter); Element root = document.getRootElement(); @SuppressWarnings("unchecked") // This cast is correct List<Element> children = root.getChildren(); for (Element child : children) { outputter.output(child); } } catch (JDOMException e) { //If we are here, then a parsing error occurred within the XHTML fragment. We'll just assume // that this is not supposed to be XHTML and display the fragment as plain text within <dri:p> tags. startElement(contentHandler, namespaces, Para.E_PARA, null); sendCharacters(contentHandler, fragment); endElement(contentHandler, namespaces, Para.E_PARA); } catch (IOException ioe) { throw new SAXException(ioe); } } /** * Remove the given content from the Element. * * If the content is an element then render it as text and include it's * children in the parent. * * @param content * The DOM Content to be removed. */ private void removeContent(Content content) { if (content instanceof Element) { // If it's an element replace the content with a text node. Element element = (Element) content; if (element.getContent().size() == 0) { // The element contains nothing, we can use shorthand notation // for it. StringBuilder replacement = new StringBuilder().append("<").append(element.getName()); @SuppressWarnings("unchecked") // This cast is correct List<Attribute> attributes = element.getAttributes(); for (Attribute attribute : attributes) { replacement .append(" ").append(attribute.getName()).append("=\"").append(attribute.getValue()).append("\"").toString(); } replacement.append("/>"); Element parent = element.getParentElement(); int index = parent.indexOf(element); parent.setContent(index, new Text(replacement.toString())); } else { // The element contains data StringBuilder prepend = new StringBuilder(); prepend.append("<").append(element.getName()); @SuppressWarnings("unchecked") // This cast is correct List<Attribute> attributes = element.getAttributes(); for (Attribute attribute : attributes) { prepend.append(" ").append(attribute.getName()).append("=\"").append(attribute.getValue()).append("\""); } prepend.append(">"); String postpend = "</" + element.getName() + ">"; Element parent = element.getParentElement(); int index = parent.indexOf(element); parent.addContent(index, new Text(postpend)); parent.addContent(index, element.removeContent()); parent.addContent(index, new Text(prepend.toString())); parent.removeContent(element); } } else { // If it's not an element just remove the content from the document. Element parent = content.getParentElement(); parent.removeContent(content); } } /** * Wrap the given set of contents into a paragraph and place it at the * supplied index. * * This method will also check for trivial paragraphs, i.e. those that * contain nothing but white space. If they are found then they are removed. * * @param parent * The parent element to attach the wrapped paragraph too. * @param index * The index within the parent for where the content should be * attached. * @param contents * The contents that should be wrapped in a paragraph. * @return wheather a paragraph was actualy added. */ private boolean paragraphWrap(Element parent, int index, List<Content> contents) { if (contents == null || contents.size() <= 0) { return false; } boolean empty = true; for (Content content : contents) { if (!empty) { continue; } if (content instanceof Text) { Text text = (Text) content; if (!"".equals(text.getTextNormalize())) { empty = false; } } else { empty = false; } } if (empty) { return false; } // May be usefull for debugging: // contents.add(0, new Text("("+index+") ")); Element para = new Element(Para.E_PARA); para.addContent(contents); if (index >= 0) { parent.addContent(index, para); } else { parent.addContent(para); } return true; } /** * Ensure that the given element only has the supplied attributes. Also * remove any possible namespaces on the attributes. * * @param element * The element to be checked. * @param names * A list of all allowed attribute names, all others will be * removed. */ private void limitAttributes(Element element, String... names) { Map<String, String> attributes = new HashMap<String, String>(); for (String name : names) { String value = element.getAttributeValue(name); if (value != null) { attributes.put(name, value); } } element.setAttributes(new ArrayList<Attributes>()); for (Map.Entry<String, String> attr : attributes.entrySet()) { element.setAttribute(attr.getKey(), attr.getValue()); } } /** * Move the old attribute to a new attribute. * * @param element * The element * @param oldName * The old attribute's name. * @param newName * The new attribute's name. */ private void moveAttribute(Element element, String oldName, String newName) { Attribute attribute = element.getAttribute(oldName); if (attribute != null) { attribute.setName(newName); } } /** * Translate the given HTML fragment into a DRI document. * * The translation is broken up into two steps, 1) recurse through all * elements and either translate them into their DRI equivelents or remove * them from the document. * * The second step, 2) is to iterate over all top level elements and ensure * that they only consist of paragraphs. Also at this stage if linkBreaks is * true then \n are treated as paragraph breaks. * * @param parent * The Element to translate into DRI. */ private void translate(Element parent) { // Step 1: // Recurse through all elements and either // translate them or remove them. for (int i = 0; i < parent.getContentSize(); i++) { Content decedent = parent.getContent(i); if (decedent instanceof org.jdom.Text) { } else if (decedent instanceof Element) { Element element = (Element) decedent; String name = element.getName(); // First all the DRI elements, allow them to pass. if ("p".equals(name)) { // Paragraphs are tricky, it may be either an HTML // or DRI <p> element. However, while HTML will allow // <p> to nest DRI does not, thus first we need to // check if this is at the block level, if it is then // we need remove it. if (parent.isRootElement()) { // The paragraph is not nested, so translate it to // a DRI <p> moveAttribute(element, "class", "rend"); limitAttributes(element, "id", "n", "rend"); translate(element); } else { // The paragraph is nested which is not allowed in // DRI, so remove it. removeContent(element); } } else if ("h1".equals(name) || "h2".equals(name) || "h3".equals(name) || "h4".equals(name) || "h5".equals(name)) { // The HTML <H1> tag is translated into the DRI // <p rend="heading"> tag. if (parent.isRootElement()) { limitAttributes(element); element.setName("p"); element.setAttribute("rend", "heading"); translate(element); } else { // DRI paragraphs can not be nested. removeContent(element); } } else if ("a".equals(name)) { // The HTML <a> tag is translated into the DRI // <xref> tag. moveAttribute(element, "href", "target"); limitAttributes(element, "target"); element.setName("xref"); translate(element); } else if ("ol".equals(name)) { // the HTML tag <ol> its translated into the DRI // <list> tag // <list type="ordered" n="list_part_one" // id="css.submit.LicenseAgreement.list.list_part_one"> moveAttribute(element, "class", "rend"); limitAttributes(element, "id", "n", "rend"); element.setName("list"); element.setAttribute("type", "ordered"); translate(element); } else if ("li".equals(name)) { // the HTML tag <li> its translated into the DRI // <item> tag moveAttribute(element, "class", "rend"); limitAttributes(element, "id", "n", "rend"); element.setName("item"); translate(element); } else if ("b".equals(name)) { // The HTML <b> tag is translated to a highlight // element with a rend of bold. limitAttributes(element); element.setName("hi"); element.setAttribute("rend", "bold"); translate(element); } else if ("i".equals(name)) { // The HTML <i> tag is translated to a highlight // element with a rend of italic. limitAttributes(element); element.setName("hi"); element.setAttribute("rend", "italic"); translate(element); } else if ("u".equals(name)) { // The HTML <u> tag is translated to a highlight // element with a rend of underline. limitAttributes(element); element.setName("hi"); element.setAttribute("rend", "underline"); translate(element); } else if ("img".equals(name)) { // The HTML <img> element is translated into a DRI figure moveAttribute(element, "src", "source"); limitAttributes(element, "source"); element.setName("figure"); translate(element); } // Next all the DRI elements that we allow to pass through. else if ("hi".equals(name)) { limitAttributes(element, "rend"); translate(element); } else if ("xref".equals(name)) { limitAttributes(element, "target"); translate(element); } else if ("figure".equals(name)) { limitAttributes(element, "rend", "source", "target"); translate(element); } else { removeContent(decedent); } } else { removeContent(decedent); } } // Step 2: // Ensure that all top level elements are encapusalted inside // a block level element (i.e. a paragraph) if (parent.isRootElement()) { List<Content> removed = new ArrayList<Content>(); for (int i = 0; i < parent.getContentSize(); i++) { Content current = parent.getContent(i); if ((current instanceof Element) && ("p".equals(((Element) current).getName()))) { // A paragraph is being open, combine anything up to this // point into a paragraph. if (paragraphWrap(parent, i, removed)) { removed.clear(); i++; // account for the field added } } else if ((current instanceof Element) && ("list".equals(((Element) current).getName()))) { if (paragraphWrap(parent, i, removed)) { removed.clear(); i++; // account for the field added } } else { // If we break paragraphs based upon blank lines then we // need to check if // there are any in this text element. if (this.blankLines && current instanceof Text) { String rawText = ((Text) current).getText(); parent.removeContent(current); i--;// account text field removed. // Regular expressiot to split based upon blank lines. // FIXME: This may not work for windows people who // insist on using \r\n for line breaks. @SuppressWarnings("unchecked") String[] parts = rawText.split("\n\\s*\n"); if (parts.length > 0) { for (int partIdx = 0; partIdx < parts.length - 1; partIdx++) { removed.add(new Text(parts[partIdx])); if (paragraphWrap(parent, i+1, removed)) { removed.clear(); i++;// account for the field added } } removed.add(new Text(parts[parts.length - 1])); } } else { removed.add(current); parent.removeContent(current); i--; // move back to account for the removed content. } } } // if anything is left, wrap it up in a para also. if (removed.size() > 0) { paragraphWrap(parent, -1, removed); removed.clear(); } } } /** * This is a simple SAX Handler that filters out start and end documents. * This class is needed for two reasons, 1) namespaces need to be corrected * from the originating HTML fragment, 2) to get around a JDOM bug where it * can not output SAX events for just a document fragment. Since it only * works with documents this class was created to filter out the events. * * As far as I can tell the first time the bug was identified is in the * following email, point #1: * * http://www.servlets.com/archive/servlet/ReadMsg?msgId=491592&listName=jdom-interest * * I, Scott Phillips, checked the JDOM CVS source tree on 3-8-2006 and the * bug had not been patch at that time. * */ public static class SAXFilter implements ContentHandler, LexicalHandler { private final String URI = WingConstants.DRI.URI; private ContentHandler contentHandler; // private LexicalHandler lexicalHandler; may be used in the future private NamespaceSupport namespaces; public SAXFilter(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) { this.contentHandler = contentHandler; // this.lexicalHandler = lexicalHandler; this.namespaces = namespaces; } /** * Create the qName for the element with the given localName and * namespace prefix. * * @param localName * (Required) The element's local name. * @return */ private String qName(String localName) { String prefix = namespaces.getPrefix(URI); if (prefix == null || prefix.equals("")) { return localName; } else { return prefix + ":" + localName; } } /** ContentHandler methods: */ public void endDocument() { // Filter out endDocument events } public void startDocument() { // filter out startDocument events } public void characters(char[] ch, int start, int length) throws SAXException { contentHandler.characters(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { contentHandler.endElement(URI, localName, qName(localName)); } public void endPrefixMapping(String prefix) throws SAXException { // No namespaces may be declared. } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { contentHandler.ignorableWhitespace(ch, start, length); } public void processingInstruction(String target, String data) throws SAXException { // filter out processing instructions } public void setDocumentLocator(Locator locator) { // filter out document locators } public void skippedEntity(String name) throws SAXException { contentHandler.skippedEntity(name); } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { contentHandler.startElement(URI, localName, qName(localName), atts); } public void startPrefixMapping(String prefix, String uri) throws SAXException { // No namespaces can be declared. } /** Lexical Handler methods: */ public void startDTD(String name, String publicId, String systemId) throws SAXException { // filter out DTDs } public void endDTD() throws SAXException { // filter out DTDs } public void startEntity(String name) throws SAXException { // filter out Entities } public void endEntity(String name) throws SAXException { // filter out Entities } public void startCDATA() throws SAXException { // filter out CDATA } public void endCDATA() throws SAXException { // filter out CDATA } public void comment(char[] ch, int start, int length) throws SAXException { // filter out comments; } } }
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.wing.element; /** * A class represented parameters to fields. The parameter element is basically a * grab bag of attributes associated with various fields. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; import java.util.Arrays; public class Params extends AbstractWingElement implements StructuralElement { /** The name of the params element */ public static final String E_PARAMS = "params"; /** The name of the operations attribute */ public static final String A_OPERATIONS = "operations"; /** The name of the return value attribute */ public static final String A_RETURN_VALUE = "returnValue"; /** The name of the size attribute */ public static final String A_SIZE = "size"; /** The name of the max length attribute */ public static final String A_MAX_LENGTH = "maxlength"; /** The name of the multiple attribute */ public static final String A_MULTIPLE = "multiple"; /** The name of the rows attribute */ public static final String A_ROWS = "rows"; /** The name of the cols attribute */ public static final String A_COLS = "cols"; /** True if this field is authority-controlled */ public static final String A_AUTHORITY_CONTROLLED = "authorityControlled"; /** True if an authority value is required */ public static final String A_AUTHORITY_REQUIRED = "authorityRequired"; /** The name of the field to use for a list of choices */ public static final String A_CHOICES = "choices"; /** Type of presentation recommended for showing choices to user */ /** See PRESENTATION_* */ public static final String A_CHOICES_PRESENTATION = "choicesPresentation"; /** The name of the field to use for a list of choices */ public static final String A_CHOICES_CLOSED = "choicesClosed"; /** Possible operations */ public static final String OPERATION_ADD = "add"; public static final String OPERATION_DELETE = "delete"; public static final String[] OPERATIONS = { OPERATION_ADD, OPERATION_DELETE }; /** Possible UI presentation values */ public static final String PRESENTATION_SELECT = "select"; public static final String PRESENTATION_SUGGEST = "suggest"; public static final String PRESENTATION_LOOKUP = "lookup"; public static final String PRESENTATION_NONE = "none"; public static final String[] PRESENTATIONS = { PRESENTATION_SELECT, PRESENTATION_SUGGEST, PRESENTATION_LOOKUP, PRESENTATION_NONE }; /** *********** Parameter Attributes *************** */ /** The supported operations for this field */ protected boolean addOperation; protected boolean deleteOperation; /** The return value for the field, checkboxes and radio buttons. */ protected String returnValue; /** The field size */ protected int size = -1; /** The maximum length of the field */ protected int maxlength = -1; /** Weather multiple values for this field are allowed */ protected boolean multiple = false; /** The number of rows the field should span */ protected int rows = -1; /** The number of cols the field should span */ protected int cols = -1; /** Value of the AuthorityControlled attribute */ protected boolean authority = false; /** Value of the Authority_Required attribute */ protected boolean authority_required = false; /** Value of the Choices attribute */ protected String choices = null; /** Value of the Choices Presentation attribute */ protected String presentation = null; /** Value of choicesClosed option */ protected boolean choicesClosed = false; /** * Construct a new parameter's element * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * */ protected Params(WingContext context) throws WingException { super(context); } /** * Enable the add operation for this field set. When this is enabled the * front end will add a button to add more items to the field. * */ public void enableAddOperation() throws WingException { this.addOperation = true; } /** * Enable the delete operation for this field set. When this is enabled then * the front end will provide a way for the user to select fields (probably * checkboxes) along with a submit button to delete the selected fields. * */ public void enableDeleteOperation()throws WingException { this.deleteOperation = true; } /** * Set the size of the field. * * This applies to text, password, and select fields. * * @param size * (Required) The size of the field. */ public void setSize(int size) { this.size = size; } /** * Set the maximum length of the field. * * This applies to text, password, and textarea fields. * * @param maxlength * (Required) The maximum length of the field. */ public void setMaxLength(int maxlength) { this.maxlength = maxlength; } /** * Set the number of rows of this field. * * The applies only to textarea fields. * * @param rows * (Required) The number of rows. */ public void setRows(int rows) { this.rows = rows; } /** * Set the number of columns of this field. * * The applies only to textarea fields. * * @param cols * (Required) The number of columns. */ public void setCols(int cols) { this.cols = cols; } /** * The returned value for this field if it is checked (or selected). * * The applies to radio and checkbox fields. * * @param returnValue * (Required) The value to be returned if this field is checked. */ public void setReturnValue(String returnValue) { this.returnValue = returnValue; } /** * Determine if this field can accept multiple values. * * The applies only to select fields. * * @param multiple * (Required) whether the field can accept multiple values. */ public void setMultiple(boolean multiple) { this.multiple = multiple; } /** * Set this field to be authority-controlled. * */ public void setAuthorityControlled() { this.authority = true; } /** * Set this field to be authority-controlled. * * @param value true if authority-controlled. */ public void setAuthorityControlled(boolean value) { this.authority = value; } /** * Set this field as authority_required. */ public void setAuthorityRequired() { this.authority_required = true; } /** * Set this field to either be required or not required as determined by the * required parameter. * * @param value * Determine if the authority control is required or not on this field. */ public void setAuthorityRequired(boolean value) { this.authority_required = value; } /** * * @param fieldKey pre-determined metadata field key */ public void setChoices(String fieldKey) { this.choices = fieldKey; } /** * Set the kind of UI presentation requested for this choice, e.g. * select vs. suggest. Value must match one of the PRESENTATIONS. * * @param value pre-determined metadata field key */ public void setChoicesPresentation(String value) throws WingException { restrict(value, PRESENTATIONS, "The 'presentation' parameter must be one of these values: "+Arrays.deepToString(PRESENTATIONS)); this.presentation = value; } /** * Sets whether choices are "closed" to the set returned by plugin. * * @param value pre-determined metadata field key */ public void setChoicesClosed(boolean value) { this.choicesClosed = value; } /** * Sets whether choices are "closed" to the set returned by plugin. */ public void setChoicesClosed() { this.choicesClosed = true; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical events * (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); // Determine if there are any operations String operations = null; if (addOperation ) { if (operations == null) { operations = OPERATION_ADD; } else { operations += " " + OPERATION_ADD; } } if (addOperation) { if (operations == null) { operations = OPERATION_DELETE; } else { operations += " " + OPERATION_DELETE; } } if (operations != null) { attributes.put(A_OPERATIONS, operations); } if (this.returnValue != null) { attributes.put(A_RETURN_VALUE, this.returnValue); } if (this.size > -1) { attributes.put(A_SIZE, this.size); } if (this.maxlength > -1) { attributes.put(A_MAX_LENGTH, this.maxlength); } if (this.multiple) { attributes.put(A_MULTIPLE, this.multiple); } if (this.rows > -1) { attributes.put(A_ROWS, this.rows); } if (this.cols > -1) { attributes.put(A_COLS, this.cols); } if (this.authority) { attributes.put(A_AUTHORITY_CONTROLLED, this.authority); } if (this.authority_required) { attributes.put(A_AUTHORITY_REQUIRED, this.authority_required); } if (this.choices != null) { attributes.put(A_CHOICES, this.choices); } if (this.presentation != null) { attributes.put(A_CHOICES_PRESENTATION, this.presentation); } if (this.choicesClosed) { attributes.put(A_CHOICES_CLOSED, true); } startElement(contentHandler, namespaces, E_PARAMS, attributes); endElement(contentHandler, namespaces, E_PARAMS); } }
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.wing.element; /** * A class that represents a List element. * * The list element is used to display sets of sequential data. It contains an * optional head element, as well as any number of item elements. Items contain * textual information or other list elements. An item can also be associated * with a label element that annotates an item with a number, a textual * description of some sort, or a simple bullet. The list type (ordered, * bulletted, gloss, etc.) is then determined either by the content of labels on * items or by an explicit value of the "type" attribute. Note that if labels * are used in conjunction with any items in a list, all of the items in that * list must have a label. It is also recommended to avoid mixing label styles * unless an explicit type is specified. * * typically rendering types are not predefined, but for lists there is a set of * standard rendering options available for the rend attribute to be set too. * This is not an exhaustive list. * * horizontal: The list should be rendered horizontally. * * vertical: The list should be rendered vertically. * * columns: The list should be rendered in equal length columns as determined by * the theme. * * columns2: The list should be rendered in two equal columns. * * columns3: The list should be rendered in three equal columns. * * alphabet: The list should be rendered as an alphabetical index. * * numeric: The list should be rendered as a numeric index. * * @author Scott Phillips */ import java.util.ArrayList; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingConstants; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; public class List extends AbstractWingElement implements WingMergeableElement, StructuralElement { /** The name of the list element */ public static final String E_LIST = "list"; /** The name of the type attribute */ public static final String A_TYPE = "type"; /** Has this element been merged? */ private boolean merged = false; /** Has a child element been merged: head, list, or item */ private boolean childMerged = false; /** The possible list types * */ public static final String TYPE_SIMPLE = "simple"; public static final String TYPE_ORDERED = "ordered"; public static final String TYPE_BULLETED = "bulleted"; public static final String TYPE_GLOSS = "gloss"; public static final String TYPE_PROGRESS = "progress"; public static final String TYPE_FORM = "form"; /** All the possible list types collected into one array */ public static final String[] TYPES = { TYPE_SIMPLE, TYPE_ORDERED, TYPE_BULLETED, TYPE_GLOSS, TYPE_PROGRESS, TYPE_FORM }; /** The list's name */ private String name; /** The list's type, see types above. * */ private String type; /** Any special rendering instructions * */ private String rend; /** The lists head * */ private Head head; /** All content of this container, items & lists */ private java.util.List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>(); /** * Construct a new list. * * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * @param type * (May be null) determines the list type. If this is blank the * list type is inferred from the context and use. * @param rend * (May be null) a rendering hint used to override the default * display of the element. There are a set of predefined * rendering values, see the class documentation above. */ protected List(WingContext context, String name, String type, String rend) throws WingException { super(context); require(name, "The 'name' parameter is required for all lists."); restrict( type, TYPES, "The 'type' parameter must be one of these values: 'simple', 'ordered', 'bulleted', 'gloss', or 'form'."); this.name = name; this.type = type; this.rend = rend; } /** * Set the head element which is the label associated with this list. This * method should be called before any other elements have been added to the * list. */ public Head setHead() throws WingException { Head head = new Head(context, null); this.head = head; return head; } /** * Set the head element which is the label associated with this list. This * method should be called before any other elements have been added to the * list. * * @param characters * (Required) Untranslated character data to be included as the * list's head. */ public void setHead(String characters) throws WingException { Head head = setHead(); head.addContent(characters); } /** * Set the head element which is the label associated with this list. This * method should be called before any other elements have been added to the * list. * * @param key * (Required) Key to the i18n catalogue to translate the content * into the language preferred by the user. */ public void setHead(Message key) throws WingException { Head head = setHead(); head.addContent(key); } /** * Add a label element, they are associated with an item and annotates that * item with a number, a textual description of some sort, or a simple * bullet. * * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ public Label addLabel(String name, String rend) throws WingException { Label label = new Label(context, name, rend); contents.add(label); return label; } /** * Add a label element, they are associated with an item and annotates that * item with a number, a textual description of some sort, or a simple * bullet. * * @param characters * (Required) Untranslated character data to be included. */ public void addLabel(String characters) throws WingException { require(characters, "The 'characters' parameter is required for list labels."); Label label = new Label(context, null, null); label.addContent(characters); contents.add(label); } /** * Add a label element, they are associated with an item and annotates that * item with a number, a textual description of some sort, or a simple * bullet. This version of label provides no textual label but may be used * to indicate some implicit labeling such as ordered lists. * */ public void addLabel() throws WingException { Label label = new Label(context, null, null); contents.add(label); } /** * Add a label element, they are associated with an item and annotates that * item with a number, a textual description of some sort, or a simple * bullet. * * @param key * (Required) Key to the i18n catalogue to translate the content * into the language preferred by the user. */ public void addLabel(Message key) throws WingException { require(key, "The 'key' parameter is required for list labels."); Label label = new Label(context, null, null); label.addContent(key); contents.add(label); } /** * Add an empty unnamed item. * * @return a new Item */ public Item addItem() throws WingException { return addItem(null,null); } /** * Add an item element, which serves a dual purpose. It can contain other * lists, allowing for hierarchies and recursive lists. Alternatively it can * serve as a character container to display textual data, possibly enhanced * with hyperlinks, emphasized blocks of text, images and form fields. An * item cannot be both a character container and contain a list. * * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param rend * (May be null) a rendering hint used to override the default * display of the element. * * @return a new Item */ public Item addItem(String name, String rend) throws WingException { Item item = new Item(context, name, rend); contents.add(item); return item; } /** * Add an item element that contains only character content. * * @param characters * (Required) Untranslated character data to be included. */ public void addItem(String characters) throws WingException { require(characters, "The 'characters' parameter is required for list items."); Item item = this.addItem(null, null); item.addContent(characters); } /** * Add an item element that contains only translated content. * * @param key * (Required) Key to the i18n catalogue to translate the content * into the language preferred by the user. */ public void addItem(Message key) throws WingException { require(key, "The 'key' parameter is required for list items."); Item item = this.addItem(null, null); item.addContent(key); } /** * Add an item to the list that contains a link. The link will consist of * the given content and linked to the given target. * * @param target * (Required) The link target. * @param characters * (Required) Untranslated character data to be included as the * link's body. */ public void addItemXref(String target, String characters) throws WingException { Item item = this.addItem(null, null); item.addXref(target, characters); } /** * Add an item to the list that contains a link. The link will consist of * the given content and linked to the given target. * * @param target * (Required) The link target. * @param key * (Required) i18n key for translating content into the user's * preferred language. */ public void addItemXref(String target, Message key) throws WingException { Item item = this.addItem(null, null); item.addXref(target, key); } /** * Add a new sublist to this list. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * @param type * (May be null) determines the list type. If this is blank the * list type is inferred from the context and use. * @param rend * (May be null) a rendering hint used to override the default * display of the element. * @return A new sub list. */ public List addList(String name, String type, String rend) throws WingException { List list = new List(context, name, type, rend); contents.add(list); return list; } /** * Add a new sublist to this list. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * @param type * (May be null) determines the list type. If this is blank the * list type is inferred from the context and use. * @return A new sub list. */ public List addList(String name, String type) throws WingException { List list = new List(context, name, type, null); contents.add(list); return list; } /** * Add a new sublist to this list. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * @return A new sub list. */ public List addList(String name) throws WingException { return addList(name, null, null); } /** * Determine if the given SAX startElement event is equivalent to this list. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return True if this list is equivalent to the given SAX Event. */ public boolean mergeEqual(String namespace, String localName, String qName, Attributes attributes) { // Check if it's in our name space and an options element. if (!WingConstants.DRI.URI.equals(namespace)) { return false; } if (!E_LIST.equals(localName)) { return false; } String name = attributes.getValue(A_NAME); if (name == null) { return false; } if (!name.equals(this.name)) { return false; } return true; } /** * Merge the given SAX startElement event into this list's child. If this * SAX event matches a child element of this list then it should be removed * from the internal book keep of this element and returned. Typically this * is accomplished by looping through all children elements and returned the * first one that returns true for the mergeEqual method. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return The child element */ public WingMergeableElement mergeChild(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException { this.childMerged = true; WingMergeableElement found = null; for (AbstractWingElement content : contents) { if (content instanceof WingMergeableElement) { WingMergeableElement candidate = (WingMergeableElement) content; if (candidate.mergeEqual(namespace, localName, qName, attributes)) { found = candidate; } } } contents.remove(found); return found; } /** * Inform this list that it is being merged with an existing element. * Practically this means that when this method is being transformed to SAX * it should assume that the element's SAX events have all ready been sent. * In this case the element would only need to transform to SAX the children * of this element. * * Further more if the element needs to add any attributes to the SAX * startElement event it may modify the attributes object passed to make * changes. * * @return The attributes for this merged element */ public Attributes merge(Attributes attributes) throws SAXException, WingException { this.merged = true; return attributes; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { if (!this.merged) { AttributeMap attributes = new AttributeMap(); attributes.put(A_NAME, this.name); attributes.put(A_ID, this.context.generateID(E_LIST, this.name)); if (this.type != null) { attributes.put(A_TYPE, this.type); } if (this.rend != null) { attributes.put(A_RENDER, this.rend); } startElement(contentHandler, namespaces, E_LIST, attributes); } if (!childMerged && head != null) { head.toSAX(contentHandler, lexicalHandler, namespaces); } for (AbstractWingElement content : contents) { content.toSAX(contentHandler, lexicalHandler, namespaces); } if (!this.merged) { endElement(contentHandler, namespaces, E_LIST); } } /** * dispose */ public void dispose() { if (head != null) { head.dispose(); } head = null; for (AbstractWingElement content : contents) { content.dispose(); } contents.clear(); contents = null; super.dispose(); } }
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.wing.element; /** * A class representing a CheckBox input control. The checkbox input control is * a boolean control which may be toggled by the user. A checkbox may have * several fields which share the same name and each of those fields may be * toggled independently. This is distinct from a radio button where only one * field may be toggled. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; public class CheckBox extends Field { /** * Construct a new field. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * * @param name * (Required) a non-unique local identifier used to differentiate * the element from its siblings within an interactive division. * This is the name of the field use when data is submitted back * to the server. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected CheckBox(WingContext context, String name, String rend) throws WingException { super(context, name, Field.TYPE_CHECKBOX, rend); this.params = new Params(context); } /** * Enable the add operation for this field. When this is enabled the * front end will add a button to add more items to the field. * */ public void enableAddOperation() throws WingException { this.params.enableAddOperation(); } /** * Enable the delete operation for this field. When this is enabled then * the front end will provide a way for the user to select fields (probably * checkboxes) along with a submit button to delete the selected fields. * */ public void enableDeleteOperation()throws WingException { this.params.enableDeleteOperation(); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. */ public Option addOption(String returnValue) throws WingException { Option option = new Option(context, returnValue); options.add(option); return option; } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. */ public Option addOption(int returnValue) throws WingException { return addOption(String.valueOf(returnValue)); } /** * Add an option. * * @param selected * (Required) Set the option is checked * @param returnValue * (Required) The value to be passed back if this option is * checked. */ public Option addOption(boolean selected, String returnValue) throws WingException { if (selected) { setOptionSelected(returnValue); } return addOption(returnValue); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * checked. * @param characters * (Required) The text to set as the visible option. */ public void addOption(String returnValue, String characters) throws WingException { Option option = this.addOption(returnValue); option.addContent(characters); } /** * Add an option. * * @param selected * (Required) Set the option is checked * @param returnValue * (Required) The value to be passed back if this option is * checked. * @param characters * (Required) The text to set as the visible option. */ public void addOption(boolean selected,String returnValue, String characters) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,characters); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * checked. * @param characters * (Required) The text to set as the visible option. */ public void addOption(int returnValue, String characters) throws WingException { Option option = this.addOption(String.valueOf(returnValue)); option.addContent(characters); } /** * Add an option. * * @param selected * (Required) Set the option as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param characters * (Required) The text to set as the visible option. */ public void addOption(boolean selected, int returnValue, String characters) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,characters); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(String returnValue, Message message) throws WingException { Option option = this.addOption(returnValue); option.addContent(message); } /** * Add an option. * * @param selected * (Required) Set the option as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(boolean selected, String returnValue, Message message) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,message); } /** * Add an option. * * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(int returnValue, Message message) throws WingException { Option option = this.addOption(String.valueOf(returnValue)); option.addContent(message); } /** * Add an option. * * @param selected * (Required) Set the field as selected. * @param returnValue * (Required) The value to be passed back if this option is * selected. * @param message * (Required) The transalted text to set as the visible option. */ public void addOption(boolean selected, int returnValue, Message message) throws WingException { if (selected) { setOptionSelected(returnValue); } addOption(returnValue,message); } /** * Set the given option as checked. * * @param returnValue * (Required) The return value of the option to be selected. */ public void setOptionSelected(String returnValue) throws WingException { Value value = new Value(context,Value.TYPE_OPTION,returnValue); values.add(value); } /** * Set the given option as selected. * * @param returnValue * (Required) The return value of the option to be selected. */ public void setOptionSelected(int returnValue) throws WingException { Value value = new Value(context,Value.TYPE_OPTION,String.valueOf(returnValue)); values.add(value); } /** * Add a field instance * @return instance */ public Instance addInstance() throws WingException { Instance instance = new Instance(context); instances.add(instance); return instance; } }
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.wing.element; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * This is an interface to represent all WingElements that can be merged. * * @author Scott Phillips */ public interface WingMergeableElement extends WingElement { /** * Determine if the given SAX startElement event is equivalent to this * WingElement. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return True if this WingElement is equivalent to the given SAX Event. */ public boolean mergeEqual(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException; /** * Merge the given SAX startElement event into this element's child. If this * SAX event matches a child element of this element then it should be * removed from the internal book keep of this element and returned. * typically this is accomplished by looping through all children elements * and returned the first one that returns true for the mergeEqual method. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return The child element */ public WingMergeableElement mergeChild(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException; /** * Inform this element that it is being merged with an existing element. * Practically this means that when this method is being transformed to SAX it * should assume that the element's SAX events have all ready been sent. In * this case the element would only need to transform to SAX the children of * this element. * * Further more if the element needs to add any attributes to the SAX * startElement event it may modify the attributes object passed to make * changes. * * @return The attributes for this merged element */ public Attributes merge(Attributes attributes) throws SAXException, WingException; }
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.wing.element; import java.util.ArrayList; import java.util.List; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingConstants; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * A class representing a set of metadata about the page being generated. * * @author Scott Phillips */ public class PageMeta extends AbstractWingElement implements WingMergeableElement, MetadataElement { /** Name of the pageMeta element */ public static final String E_PAGE_META = "pageMeta"; /** Has this PageMeta element been merged? */ private boolean merged = false; /** * A page meta may hold two types of elements, trails or * metadata. Each of these types are seperated so that * we can search through each time as we merge documents. */ private List<Metadata> metadatum = new ArrayList<Metadata>(); private List<Trail> trails = new ArrayList<Trail>(); /** * Construct a new pageMeta * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. */ protected PageMeta(WingContext context) throws WingException { super(context); } /** * Add metadata about this page. * * @param element * (Required) The metadata element. * @param qualifier * (May be null) The metadata qualifier. * @param language * (May be null) The metadata's language * @param allowMultiple * (Required) determine if multipe metadata element with the same * element, qualifier and language are allowed. * @return A new metadata */ public Metadata addMetadata(String element, String qualifier, String language, boolean allowMultiple) throws WingException { Metadata metadata = new Metadata(context, element, qualifier, language, allowMultiple); metadatum.add(metadata); return metadata; } /** * Add metadata about this page. * * @param element * (Required) The metadata element. * @param qualifier * (May be null) The metadata qualifier. * @param language * (May be null) The metadata's language * @return A new metadata */ public Metadata addMetadata(String element, String qualifier, String language) throws WingException { return addMetadata(element, qualifier, language, false); } /** * Add metadata about this page. * * @param element * (Required) The metadata element. * @param qualifier * (May be null) The metadata qualifier. * @return A new metadata */ public Metadata addMetadata(String element, String qualifier) throws WingException { return addMetadata(element, qualifier, null, false); } /** * Add metadata about this page. * * @param element * (Required) The metadata element. * @return A new metadata */ public Metadata addMetadata(String element) throws WingException { return addMetadata(element, null, null, false); } /** * Add a new trail to the page. * * @param target * (May be null) Target URL for this trail item. * @param rend * (May be null) special rendering instructions * @return a new trail */ public Trail addTrail(String target, String rend) throws WingException { Trail trail = new Trail(context, target, rend); trails.add(trail); return trail; } /** * Add a new trail to the page without a link or render attribute. * * @return a new trail */ public Trail addTrail() throws WingException { return addTrail(null,null); } /** * Add a new trail link to the page. * * @param target * (May be null) The Target URL for this trail item. * @param characters * (May be null) The textual contents of this trail item. */ public void addTrailLink(String target, String characters) throws WingException { Trail trail = addTrail(target, null); trail.addContent(characters); } /** * Add a new trail link to the page. * * @param target * (May be null) The Target URL for this trail item. * @param message * (Required) The textual contents of this trail item to be * translated */ public void addTrailLink(String target, Message message) throws WingException { Trail trail = addTrail(target, null); trail.addContent(message); } /** * Determine if the given SAX event is a PageMeta element. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return True if this WingElement is equivalent to the given SAX Event. */ public boolean mergeEqual(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException { if (!WingConstants.DRI.URI.equals(namespace)) { return false; } if (!E_PAGE_META.equals(localName)) { return false; } return true; } /** * Since metadata can not be merged there are no mergeable children. This * just return's null. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return The child element */ public WingMergeableElement mergeChild(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException { // We don't merge our children but we do have one special optimization, // if a metadata or trail is allready in the document then we do not add // our own trail or metadata for that particular item. if (WingConstants.DRI.URI.equals(namespace) && Trail.E_TRAIL.equals(localName)) { for (Trail trail : trails) { trail.dispose(); } trails.clear(); } if (WingConstants.DRI.URI.equals(namespace) && Metadata.E_METADATA.equals(localName)) { String element = attributes.getValue(Metadata.A_ELEMENT); String qualifier = attributes.getValue(Metadata.A_QUALIFIER); String language = attributes.getValue(Metadata.A_LANGUAGE); List<Metadata> remove = new ArrayList<Metadata>(); for (Metadata metadata : metadatum) { if (metadata.equals(element,qualifier,language) && !metadata.allowMultiple()) { remove.add(metadata); } } // Remove all the metadata elements we found. for (Metadata metadata : remove) { metadata.dispose(); metadatum.remove(metadata); } } return null; } /** * Inform this element that it is being merged with an existing element. */ public Attributes merge(Attributes attributes) throws SAXException, WingException { this.merged = true; return attributes; } /** * Translate this element into SAX events. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { if (!merged) { startElement(contentHandler, namespaces, E_PAGE_META, null); } for (Metadata metadata : metadatum) { metadata.toSAX(contentHandler, lexicalHandler, namespaces); } for (Trail trail : trails) { trail.toSAX(contentHandler, lexicalHandler, namespaces); } if (!merged) { endElement(contentHandler, namespaces, E_PAGE_META); } } /** * dispose */ public void dispose() { for (Metadata metadata : metadatum) { metadata.dispose(); } for (Trail trail : trails) { trail.dispose(); } trails.clear(); trails = null; metadatum.clear(); metadatum = null; super.dispose(); } }
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.wing.element; import java.util.ArrayList; import java.util.List; import org.dspace.app.xmlui.wing.WingConstants; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * A class representing the page division. * * The body contains any number of divisions (div elements) which group content * into interactive and non interactive display blocks. * * @author Scott Phillips */ public class Body extends AbstractWingElement implements WingMergeableElement { /** The name of the body element */ public static final String E_BODY = "body"; /** Has this element been merged */ private boolean merged = false; /** The divisions contained within this body */ private List<Division> divisions = new ArrayList<Division>(); /** * Generate a new Body framework element. This method will NOT open or close * a body element instead it expects that those events are being handled by * the caller. It is important to note that other divisions (div elements) * may precede or follow the divisions created through this object. * * @param context * (Required) The context this element is contained in. */ protected Body(WingContext context) throws WingException { super(context); } /** * Append a new division (div element) to the document's body. The division * created is not interactive meaning that it may not contain any form * elements, to create an interactive division use addInteractiveDivision(). * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * @param rend * (May be null) a rendering hint used to override the default * display of the element. * @return a new division. */ public Division addDivision(String name, String rend) throws WingException { Division div = new Division(context, name, rend); divisions.add(div); return div; } /** * Append a new division (div element) to the document's body. This is a * short cut method for divisions with out special rendering instructions. * The division created is not interactive meaning that it may not contain * any form elements, to create an interactive division use * addInteractiveDivision(). * * @param name * a local identifier used to differentiate the element from its * siblings * @return A new division. */ public Division addDivision(String name) throws WingException { return this.addDivision(name, null); } /** * Append a new interactive division (div element) to the document's body. * An interactive division is able to contain form elements as. The extra * parameters required such as action and method dictate where and how the * form data should be processed. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * @param action * (Required) determines where the form information should be * sent for processing. * @param method * (Required) determines the method used to pass gathered field * values to the handler specified by the action attribute. The * multipart method should be used if there are any file fields * used within the division. * @param rend * (May be null) a rendering hint used to override the default * display of the element. * @return A new division. */ public Division addInteractiveDivision(String name, String action, String method, String rend) throws WingException { Division div = new Division(context, name, action, method, rend); divisions.add(div); return div; } /** * Is this SAX event equivalent to this body? * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return True if it is equivalent. */ public boolean mergeEqual(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException { if (!WingConstants.DRI.URI.equals(namespace)) { return false; } if (!E_BODY.equals(localName)) { return false; } return true; } /** * Merge this SAX event into the body. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return */ public WingMergeableElement mergeChild(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException { Division found = null; for (Division candidate : divisions) { if (candidate.mergeEqual(namespace, localName, qName, attributes)) { found = candidate; } } divisions.remove(found); return found; } /** * Inform this element that it is being merged with an existing body. * * @param attributes * The to-be-merged attributes */ public Attributes merge(Attributes attributes) throws SAXException, WingException { this.merged = true; return attributes; } /** * Translate into SAX * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical events * (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { if (!merged) { startElement(contentHandler, namespaces, E_BODY, null); } for (Division division : divisions) { division.toSAX(contentHandler, lexicalHandler, namespaces); } if (!merged) { endElement(contentHandler, namespaces, E_BODY); } } /** * dispose */ public void dispose() { for (Division division : divisions) { division.dispose(); } super.dispose(); } }
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.wing.element; /** * A class that represents a table row. * * The row element is contained inside a table and serves as a container of cell * elements. A required 'role' attribute determines how the row and its cells * are used. * * @author Scott Phillips */ import java.util.ArrayList; import java.util.List; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; public class Row extends AbstractWingElement implements StructuralElement { /** The name of the row element */ public static final String E_ROW = "row"; /** The name of the role attribute */ public static final String A_ROLE = "role"; /** The row's name */ private String name; /** The row's role, see ROLES below */ private String role; /** Special rendering instructions */ private String rend; /** The row (and cell) role types: */ public static final String ROLE_DATA = "data"; public static final String ROLE_HEADER = "header"; /** All the roles collected into one array */ public static final String[] ROLES = { ROLE_DATA, ROLE_HEADER }; /** The contents of this row */ List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>(); /** * Construct a new table row. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param role * (May be null) determines what kind of information the row * carries, either header or data. See row.ROLES * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Row(WingContext context, String name, String role, String rend) throws WingException { super(context); restrict(role, ROLES, "The 'role' parameter must be one of these values: 'data' or 'header'."); this.name = name; this.role = role; this.rend = rend; } /** * Add a new cell to the table. The cell element contained in a row of a * table carries content for that table. It is a character container, just * like p, item, and hi, and its primary purpose is to display textual data, * possibly enhanced with hyperlinks, emphasized blocks of text, images and * form fields. * * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param role * (May be null) determines what kind of information the cell * carries, either header or data. See cell.ROLES * @param rows * (May be zero for no defined value) determines how many rows * does this cell span. * @param cols * (May be zero for no defined value) determines how many columns * does this cell span. * @param rend * (May be null) a rendering hint used to override the default * display of the element. * @return a new table cell. */ public Cell addCell(String name, String role, int rows, int cols, String rend) throws WingException { Cell cell = new Cell(context, name, role, rows, cols, rend); contents.add(cell); return cell; } /** * Add a new cell to the table. The cell element contained in a row of a * table carries content for that table. It is a character container, just * like p, item, and hi, and its primary purpose is to display textual data, * possibly enhanced with hyperlinks, emphasized blocks of text, images and * form fields. * * @param rows * (May be zero for no defined value) determines how many rows * does this cell span. * @param cols * (May be zero for no defined value) determines how many columns * does this cell span. * @return a new table cell. */ public Cell addCell(int rows, int cols) throws WingException { return addCell(null, null, rows, cols, null); } /** * Add a new cell to the table. The cell element contained in a row of a * table carries content for that table. It is a character container, just * like p, item, and hi, and its primary purpose is to display textual data, * possibly enhanced with hyperlinks, emphasized blocks of text, images and * form fields. * * @param name * (May be null) a local identifier used to differentiate the * element from its siblings. * @param role * (May be null) determines what kind of information the cell * carries, either header or data. See cell.ROLES * @param rend * (May be null) a rendering hint used to override the default * display of the element. * @return a new table cell. */ public Cell addCell(String name, String role, String rend) throws WingException { return addCell(name, role, 0, 0, rend); } /** * Add a new cell to the table. The cell element contained in a row of a * table carries content for that table. It is a character container, just * like p, item, and hi, and its primary purpose is to display textual data, * possibly enhanced with hyperlinks, emphasized blocks of text, images and * form fields. * * @param role * (May be null) determines what kind of information the cell * carries, either header or data. See cell.ROLES * @return a new table cell. */ public Cell addCell(String role) throws WingException { return addCell(null, role, 0, 0, null); } /** * Add a new cell to the table. The cell element contained in a row of a * table carries content for that table. It is a character container, just * like p, item, and hi, and its primary purpose is to display textual data, * possibly enhanced with hyperlinks, emphasized blocks of text, images and * form fields. * * @return a new table cell. */ public Cell addCell() throws WingException { return addCell(null, null, 0, 0, null); } /** * Add a new cell to the table. The cell element contained in a row of a * table carries content for that table. It is a character container, just * like p, item, and hi, and its primary purpose is to display textual data, * possibly enhanced with hyperlinks, emphasized blocks of text, images and * form fields. * * Once the cell has been created set the cell's contents to the provided * content. * * @param characters * (Required) Untranslated character data to be included. */ public void addCellContent(String characters) throws WingException { Cell cell = this.addCell(); cell.addContent(characters); } /** * Add a new cell to the table. The cell element contained in a row of a * table carries content for that table. It is a character container, just * like p, item, and hi, and its primary purpose is to display textual data, * possibly enhanced with hyperlinks, emphasized blocks of text, images and * form fields. * * Once the cell has been created set the cell's contents to the provided * content. * * @param message * (Required) Key to the i18n catalogue to translate the content * into the language preferred by the user. */ public void addCellContent(Message message) throws WingException { Cell cell = this.addCell(); cell.addContent(message); } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); if (name != null) { attributes.put(A_NAME, name); attributes.put(A_ID, context.generateID(E_ROW, name)); } if (role != null) { attributes.put(A_ROLE, role); } if (rend != null) { attributes.put(A_RENDER, rend); } startElement(contentHandler, namespaces, E_ROW, attributes); for (AbstractWingElement content : contents) { content.toSAX(contentHandler, lexicalHandler, namespaces); } endElement(contentHandler, namespaces, E_ROW); } /** * dispose */ public void dispose() { for (AbstractWingElement content : contents) { content.dispose(); } contents.clear(); contents = null; super.dispose(); } }
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.wing.element; /** * A class representing a text input control. The text input control allows the * user to enter one-line of text. * * @author Scott Phillips */ import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; public class Text extends Field { /** * Construct a new field. * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * * @param name * (Required) a non-unique local identifier used to differentiate * the element from its siblings within an interactive division. * This is the name of the field use when data is submitted back * to the server. * @param rend * (May be null) a rendering hint used to override the default * display of the element. */ protected Text(WingContext context, String name, String rend) throws WingException { super(context, name, Field.TYPE_TEXT, rend); this.params = new Params(context); } /** * Set the size of the text field. * * @param size * (May be zero for no defined value) he default size for a * field. */ public void setSize(int size) { this.params.setSize(size); } /** * Set the size and maximum size of the text field. * * @param size * (May be zero for no defined value) he default size for a * field. * @param maxLength * (May be zero for no defined value) The maximum length that the * theme should accept for form input. */ public void setSize(int size, int maxLength) { this.params.setSize(size); this.params.setMaxLength(maxLength); } /** * Enable the add operation for this field. When this is enabled the * front end will add a button to add more items to the field. * */ public void enableAddOperation() throws WingException { this.params.enableAddOperation(); } /** * Enable the delete operation for this field. When this is enabled then * the front end will provide a way for the user to select fields (probably * checkboxes) along with a submit button to delete the selected fields. * */ public void enableDeleteOperation()throws WingException { this.params.enableDeleteOperation(); } /** ******************************************************************** */ /** Raw Values * */ /** ******************************************************************** */ /** * Set the raw value of the field removing any previous raw values. */ public Value setValue() throws WingException { removeValueOfType(Value.TYPE_RAW); Value value = new Value(context, Value.TYPE_RAW); values.add(value); return value; } /** * Set the raw value of the field removing any previous raw values. * * @param characters * (May be null) Field value as a string */ public void setValue(String characters) throws WingException { Value value = this.setValue(); value.addContent(characters); } /** * Set the raw value of the field removing any previous raw values. * * @param message * (Required) A key into the i18n catalogue for translation into * the user's preferred language. */ public void setValue(Message message) throws WingException { Value value = this.setValue(); value.addContent(message); } /** * Set the authority value of the field removing any previous authority values. * Initialized to an empty value. */ public Value setAuthorityValue() throws WingException { return setAuthorityValue("", "UNSET"); } /** * Set the authority value of the field removing any previous authority values. * Initialized to an empty value. */ public Value setAuthorityValue(String characters, String confidence) throws WingException { this.removeValueOfType(Value.TYPE_AUTHORITY); Value value = new Value(context, Value.TYPE_AUTHORITY, confidence); value.addContent(characters); values.add(value); return value; } /** * Add a field instance * @return instance */ public Instance addInstance() throws WingException { Instance instance = new Instance(context); instances.add(instance); return instance; } }
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.wing.element; import java.util.ArrayList; import org.dspace.app.xmlui.wing.WingConstants; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * A class representing a set of navigational options. * * @author Scott Phillips */ public class Options extends AbstractWingElement implements WingMergeableElement { /** The name of the options element */ public static final String E_OPTIONS = "options"; /** Has this element been merged? */ private boolean merged = false; /** The lists contained in this Options element */ private java.util.List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>(); /** * Generate a new Options framework element. * * @param context * (Required) The context this element is contained in. */ protected Options(WingContext context) throws WingException { super(context); } /** * Add a new sublist to this item. Note that an item may contain either * characters (with formating & fields) or lists but not both. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * * @param type * (May be null) determines the list type. If this is blank the * list type is infered from the context and use. * @param rend * (May be null) a rendering hint used to override the default * display of the element. * @return A new sub list. */ public List addList(String name, String type, String rend) throws WingException { List list = new List(context, name, type, rend); contents.add(list); return list; } /** * Add a new sublist to this item. Note that an item may contain either * characters (with formating & fields) or lists but not both. * * @param name * (Required) a local identifier used to differentiate the * element from its siblings. * @return A new sub list. */ public List addList(String name) throws WingException { return addList(name, null, null); } /** * * Return true if this SAX Event an options element? * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return Return true if this SAX Event an options element? */ public boolean mergeEqual(String namespace, String localName, String qName, Attributes attributes) { // Check if it's in our name space and an options element. if (!WingConstants.DRI.URI.equals(namespace)) { return false; } if (!E_OPTIONS.equals(localName)) { return false; } return true; } /** * Find the sublist that this SAX event represents. * * @param namespace * The element's name space * @param localName * The local, unqualified, name for this element * * @param qName * The qualified name for this element * @param attributes * The element's attributes * @return Return the sublist */ public WingMergeableElement mergeChild(String namespace, String localName, String qName, Attributes attributes) throws SAXException, WingException { WingMergeableElement found = null; for (AbstractWingElement content : contents) { if (content instanceof WingMergeableElement) { WingMergeableElement candidate = (WingMergeableElement) content; if (candidate.mergeEqual(namespace, localName, qName, attributes)) { found = candidate; } } } contents.remove(found); return found; } /** * Inform the options element that it is being merged with an existing * options element. * * @return The attributes for this merged element */ public Attributes merge(Attributes attributes) throws SAXException, WingException { this.merged = true; return attributes; } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { if (!merged) { startElement(contentHandler, namespaces, E_OPTIONS, null); } for (AbstractWingElement content : contents) { content.toSAX(contentHandler, lexicalHandler, namespaces); } if (!merged) { endElement(contentHandler, namespaces, E_OPTIONS); } } /** * dispose */ public void dispose() { for (AbstractWingElement content : contents) { content.dispose(); } contents.clear(); contents = null; super.dispose(); } }
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.wing.element; import java.util.ArrayList; import java.util.List; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * Instance represents multiple value instances of a field. * * * @author Scott Phillips */ public class Instance extends Container { /** The name of the field instance element */ public static final String E_INSTANCE = "instance"; /** * Construct a new field value, when used in a multiple value context * * @param context * (Required) The context this element is contained in */ protected Instance(WingContext context) throws WingException { super(context); } /** ******************************************************************** */ /** Values * */ /** ******************************************************************** */ /** * Set the raw value of the field removing any previous raw values. */ public Value setValue() throws WingException { this.removeValueOfType(Value.TYPE_RAW); Value value = new Value(context, Value.TYPE_RAW); contents.add(value); return value; } /** * Set the raw value of the field removing any previous raw values. * * @param characters * (May be null) Field value as a string */ public void setValue(String characters) throws WingException { Value value = this.setValue(); value.addContent(characters); } /** * Set the raw value of the field removing any previous raw values. * * @param message * (Required) A key into the i18n catalogue for translation into * the user's preferred language. */ public void setValue(Message message) throws WingException { Value value = this.setValue(); value.addContent(message); } /** * Set the raw value of the field removing any previous raw values. This * will set the field as either checked or unchecked. This should only be * used on checkbox or radio button fields. * * @param checked * (Required) Whether the checkbox is checked or not. */ public void setValue(boolean checked) throws WingException { this.removeValueOfType(Value.TYPE_RAW); Value value = new Value(context, Value.TYPE_RAW,checked); contents.add(value); } /** * Set the authority value of the field removing any previous authority values. * Initialized to an empty value. */ public Value setAuthorityValue() throws WingException { return setAuthorityValue("", "UNSET"); } /** * Set the authority value of the field removing any previous authority values. * * @param characters * (May be null) Field value as a string */ public Value setAuthorityValue(String characters, String confidence) throws WingException { this.removeValueOfType(Value.TYPE_AUTHORITY); Value value = new Value(context, Value.TYPE_AUTHORITY, confidence); value.addContent(characters); contents.add(value); return value; } /** * Set the given option as selected. * * @param returnValue * (Required) The return value of the option to be selected. */ public void setOptionSelected(String returnValue) throws WingException { Value value = new Value(context,Value.TYPE_OPTION,returnValue); contents.add(value); } /** * Set the given option as selected. * * @param returnValue * (Required) The return value of the option to be selected. */ public void setOptionSelected(int returnValue) throws WingException { setOptionSelected(String.valueOf(returnValue)); } /** ******************************************************************** */ /** Interpreted Values * */ /** ******************************************************************** */ /** * Set the interpreted value of the field removing any previous interpreted * values. */ public Value setInterpretedValue() throws WingException { removeValueOfType(Value.TYPE_INTERPRETED); Value value = new Value(context, Value.TYPE_INTERPRETED); contents.add(value); return value; } /** * Set the interpreted value of the field removing any previous interpreted * values. * * @param characters * (May be null) Field value as a string */ public void setInterpretedValue(String characters) throws WingException { Value value = this.setInterpretedValue(); value.addContent(characters); } /** * Set the interpreted value of the field removing any previous interpreted * values. * * @param message * (Required) A key into the i18n catalogue for translation into * the user's preferred language. */ public void setInterpretedValue(Message message) throws WingException { Value value = this.setInterpretedValue(); value.addContent(message); } /** ******************************************************************** */ /** Special Values * */ /** ******************************************************************** */ /** * Add an option value, there may be many of these. These values reference * an option all ready added to the field. * * @param option * (Required) The return value of the selected option. */ public Value addOptionValue(String option) throws WingException { Value value = new Value(context, Value.TYPE_OPTION, option); contents.add(value); return value; } /** * Set the checkbox (or radio) value of this field. This is a parameter * whether the field is selected or not along with the return string that * should be used with this parameter. * * @param checked * (Required) determine if the value is selected or not. * @param characters * (may be null) The returned value for this field, if selected. */ public void setCheckedValue(boolean checked, String characters) throws WingException { this.removeValueOfType(Value.TYPE_RAW); Value value = new Value(context,Value.TYPE_RAW,checked); contents.add(value); value.addContent(characters); } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical events * (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { startElement(contentHandler, namespaces, E_INSTANCE, null); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_INSTANCE); } /** * Private function to remove all values of a particular type. * * @param removeType * The type to be removed. */ private void removeValueOfType(String removeType) { List<Value> found = new ArrayList<Value>(); for (AbstractWingElement awe : contents) { if (awe instanceof Value) { Value value = (Value) awe; if (value.getType().equals(removeType)) { found.add(value); } } } for (Value remove : found) { contents.remove(remove); remove.dispose(); } } }
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.wing.element; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This is a class representing a trail element. Trail elements carry * information about the user's current location in the system relative to the * repository's root page. * * @author Scott Phillips */ public class Trail extends TextContainer { /** The name of the trail element */ public static final String E_TRAIL = "trail"; /** The name of the target attribute */ public static final String A_TARGET = "target"; /** The name of the render attribute */ public static final String A_RENDER = "rend"; /** The trail's target */ private String target; /** Any special rendering instructions for the trail. */ private String rend; /** * Construct a new trail * * @param target * (May be null) The trail's target * @param rend * (May be null) Special rendering instructions. */ protected Trail(WingContext context, String target, String rend) throws WingException { super(context); this.target = target; this.rend = rend; } /** * Translate into SAX events. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { AttributeMap attributes = new AttributeMap(); if (this.target != null) { attributes.put(A_TARGET, target); } if (this.rend != null) { attributes.put(A_RENDER, rend); } startElement(contentHandler, namespaces, E_TRAIL, attributes); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_TRAIL); } }
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.wing.element; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This class represents help instructions for a single field. * * @author Scott Phillips */ public class Help extends TextContainer implements StructuralElement { /** The name of the help element */ public static final String E_HELP = "help"; /** * Construct a new field help. * * @param context * (Required) The context this element is contained in */ protected Help(WingContext context) throws WingException { super(context); } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { startElement(contentHandler, namespaces, E_HELP, null); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_HELP); } }
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.wing.element; import org.dspace.app.xmlui.wing.WingContext; import org.dspace.app.xmlui.wing.WingException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; /** * This class represents error instructions for a single field. * * @author Scott Phillips */ public class Error extends TextContainer implements StructuralElement { /** The name of the erorr element */ public static final String E_ERROR = "error"; /** * Construct a new field error. * * @param context * (Required) The context this element is contained in */ protected Error(WingContext context) throws WingException { super(context); } /** * Translate this element and all contained elements into SAX events. The * events should be routed to the contentHandler found in the WingContext. * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) throws SAXException { startElement(contentHandler, namespaces, E_ERROR, null); super.toSAX(contentHandler, lexicalHandler, namespaces); endElement(contentHandler, namespaces, E_ERROR); } }
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.wing; 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.Field; import org.dspace.app.xmlui.wing.element.Figure; import org.dspace.app.xmlui.wing.element.Head; import org.dspace.app.xmlui.wing.element.Help; import org.dspace.app.xmlui.wing.element.Highlight; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.Label; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.Meta; import org.dspace.app.xmlui.wing.element.Metadata; import org.dspace.app.xmlui.wing.element.Options; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Params; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.app.xmlui.wing.element.Trail; import org.dspace.app.xmlui.wing.element.UserMeta; import org.dspace.app.xmlui.wing.element.Value; import org.dspace.app.xmlui.wing.element.Instance; import org.dspace.app.xmlui.wing.element.WingDocument; import org.dspace.app.xmlui.wing.element.Xref; /** * * Static constants relating to Wing and the DRI schema. * * @author Scott Phillips */ public class WingConstants { /** The DRI schema's namespace */ public static final Namespace DRI = new Namespace( "http://di.tamu.edu/DRI/1.0/"); /** Cocoon's i18n namespace */ public static final Namespace I18N = new Namespace( "http://apache.org/cocoon/i18n/2.1"); /** All the DRI mergeable elements */ public static final String[] MERGEABLE_ELEMENTS = { WingDocument.E_DOCUMENT, Meta.E_META, UserMeta.E_USER_META, PageMeta.E_PAGE_META, Metadata.E_METADATA, Body.E_BODY, Options.E_OPTIONS, List.E_LIST }; /** All the DRI metadata elements */ public static final String[] METADATA_ELEMENTS = { Meta.E_META, UserMeta.E_USER_META, PageMeta.E_PAGE_META, Trail.E_TRAIL, Metadata.E_METADATA }; /** All the DRI structural elements */ public static final String[] STRUCTURAL_ELEMENTS = { Division.E_DIVISION, Head.E_HEAD, Table.E_TABLE, Row.E_ROW, Cell.E_CELL, Para.E_PARA, List.E_LIST, Label.E_LABEL, Item.E_ITEM, Highlight.E_HIGHLIGHT, Xref.E_XREF, Figure.E_FIGURE, Field.E_FIELD, Params.E_PARAMS, Help.E_HELP, Value.E_VALUE, Instance.E_INSTANCE }; /** All the DRI text container elements */ public static final String[] TEXT_CONTAINERS = { Metadata.E_METADATA, Trail.E_TRAIL, Head.E_HEAD, Xref.E_XREF, Figure.E_FIGURE, Help.E_HELP, Value.E_VALUE, Label.E_LABEL, Cell.E_CELL, Para.E_PARA, Highlight.E_HIGHLIGHT, Item.E_ITEM }; /** All the DRI rich text container elements */ public static final String[] RICH_TEXT_CONTAINERS = { Cell.E_CELL, Para.E_PARA, Highlight.E_HIGHLIGHT, Item.E_ITEM, Value.E_VALUE}; }
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.wing; import org.apache.avalon.framework.parameters.ParameterException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.caching.CacheableProcessingComponent; 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.wing.element.PageMeta; import org.dspace.core.ConfigurationManager; import org.xml.sax.SAXException; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Include metadata in the resulting DRI document as derived from the sitemap * parameters. * * Parameters should consist of a dublin core name and value. The format for * a parameter name must follow the form: "<element>.<qualifier>.<language>#order" * The qualifier, language, and order are all optional components. The order * component is an integer and is needed to insure that parameter names are * unique. Since Cocoon's parameters are Hashes duplicate names are not allowed * the order syntax allows the sitemap programer to specify an order in which * these metadata values should be placed inside the document. * * The following are a valid examples: * * <map:parameter name="theme.name.en" value="My Theme"/> * * <map:parameter name="theme.path" value="/MyTheme/"/> * * <map:parameter name="theme.css#1" value="style.css"/> * * <map:parameter name="theme.css#2" value="style.css-ie"/> * * <map:parameter name="theme.css#2" value="style.css-ff"/> * * @author Scott Phillips * @author Roel Van Reeth (roel at atmire dot com) * @author Art Lowel (art dot lowel at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class IncludePageMeta extends AbstractWingTransformer implements CacheableProcessingComponent { /** The metadata loaded from the sitemap parameters. */ private List<Metadata> metadataList; /** * Generate the unique key. * This key must be unique inside the space of this component. * * @return The generated key hashes the src */ public Serializable getKey() { String key = ""; for (Metadata metadata : metadataList) { key = "-" + metadata.getName() + "=" + metadata.getValue(); } return HashUtil.hash(key); } /** * Generate the validity object. * * @return The generated validity object or <code>null</code> if the * component is currently not cacheable. */ public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } /** * Extract the metadata name value pairs from the sitemap parameters. */ public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) throws ProcessingException, SAXException, IOException { try { String[] names = parameters.getNames(); metadataList = new ArrayList<Metadata>(); for (String name : names) { String[] nameParts = name.split("#"); String dcName = null; int order = -1; if (nameParts.length == 1) { dcName = nameParts[0]; order = 1; } else if (nameParts.length == 2) { dcName = nameParts[0]; order = Integer.valueOf(nameParts[1]); } else { throw new ProcessingException("Unable to parse page metadata name, '" + name + "', into parts."); } String[] dcParts = dcName.split("\\."); String element = null; String qualifier = null; String language = null; if (dcParts.length == 1) { element = dcParts[0]; } else if (dcParts.length == 2) { element = dcParts[0]; qualifier = dcParts[1]; } else if (dcParts.length == 3) { element = dcParts[0]; qualifier = dcParts[1]; language = dcParts[2]; } else { throw new ProcessingException("Unable to parse page metadata name, '" + name + "', into parts."); } String value = parameters.getParameter(name); Metadata metadata = new Metadata(element,qualifier,language,order,value); metadataList.add(metadata); } Collections.sort(metadataList); } catch (ParameterException pe) { throw new ProcessingException(pe); } // Initialize the Wing framework. try { this.setupWing(); } catch (WingException we) { throw new ProcessingException(we); } // concatenation if (ConfigurationManager.getBooleanProperty("xmlui.theme.enableConcatenation",false)) { metadataList = enableConcatenation(); } } /** * Alters the URL to CSS, JS or JSON files to concatenate them. * Enable the ConcatenationReader in the theme sitemap for * concatenation to work correctly */ private List<Metadata> enableConcatenation() { Metadata last = null; List<Metadata> newMetadataList = new ArrayList<Metadata>(); for (Metadata metadata : metadataList) { // only try to concatenate css and js String curfile = metadata.getValue(); if (curfile.lastIndexOf('?') != -1) { curfile = curfile.substring(0, curfile.lastIndexOf('?')); } if (curfile.endsWith(".css") || curfile.endsWith(".js") || curfile.endsWith(".json")) { String curval = metadata.getValue(); // check if this metadata and the last one are compatible if(last != null && checkConcatenateMerge(last, metadata)) { // merge String lastval = last.getValue(); curval = metadata.getValue(); String newval = lastval.substring(0,lastval.lastIndexOf('.')) + ","; newval += curval.substring(curval.lastIndexOf('/')+1,curval.lastIndexOf('.')); newval += lastval.substring(lastval.lastIndexOf('.')); last.value = newval; } else { // no merge, so add to list newMetadataList.add(metadata); // handle query string cases if(curval.lastIndexOf('?') != -1) { if(curval.substring(curval.lastIndexOf('?')).equals("?nominify")) { // concat should still be possible, so set last last = metadata; } else if(curval.substring(curval.lastIndexOf('?')).equals("?noconcat")) { // no concat should be possible so set last to null last = null; // query string can be removed curval = curval.substring(0, curval.lastIndexOf('?')); metadata.value = curval; } else { // no concat should be possible so set last to null last = null; // query string should be set to "nominify" curval = curval.substring(0, curval.lastIndexOf('?')) + "?nominify"; metadata.value = curval; } } else { // multiple possibilities: // * last == null, so set it // * no merge is possible, so change last to this metadata // no query string, so concat and merge should be possible later on last = metadata; } } } else { // wrong extension newMetadataList.add(metadata); } } return newMetadataList; } private boolean checkConcatenateMerge(Metadata last, Metadata current) { // check if elements are equal if(last.getElement() == null) { if(current.getElement() != null) { return false; } } else if(!last.getElement().equals(current.getElement())) { return false; } // check if qualifiers are equal if(last.getQualifier() == null) { if(current.getQualifier() != null) { return false; } } else if(!last.getQualifier().equals(current.getQualifier())) { return false; } // check if languages are equal if(last.getLanguage() == null) { if(current.getLanguage() != null) { return false; } } else if(!last.getLanguage().equals(current.getLanguage())) { return false; } String curval = current.getValue(); String lastval = last.getValue(); // check if extensions and query strings are equal if(!lastval.substring(lastval.lastIndexOf('.')).equals(curval.substring(curval.lastIndexOf('.')))) { return false; } // check if paths are equal if(!lastval.substring(0,lastval.lastIndexOf('/')+1).equals(curval.substring(0,curval.lastIndexOf('/')+1))) { return false; } // only valid nonempty query string is "nominify" if(curval.lastIndexOf('?') != -1 && !"?nominify".equals(curval.substring(curval.lastIndexOf('?')))) { return false; } return true; } /** * Include the metadata in the page metadata. */ public void addPageMeta(PageMeta pageMeta) throws WingException { for (Metadata metadata : metadataList) { String element = metadata.getElement(); String qualifier = metadata.getQualifier(); String language = metadata.getLanguage(); String value = metadata.getValue(); // Add our new metadata. pageMeta.addMetadata(element, qualifier, language) .addContent(value); } } /** * Private class to keep track of metadata name/value pairs. */ static class Metadata implements Comparable<Metadata> { private String element; private String qualifier; private String language; private int order; private String value; public Metadata(String element,String qualifier, String language, int order, String value) { this.element = element; this.qualifier = qualifier; this.language = language; this.order = order; this.value = value; } public String getElement() { return this.element; } public String getQualifier() { return this.qualifier; } public String getLanguage() { return this.language; } public int getOrder() { return this.order; } public String getName() { String name = this.element; if (this.qualifier != null) { name += "." + this.qualifier; if (this.language != null) { name += "." + this.language; } } name += "#" + order; return name; } public String getValue() { return this.value; } public int compareTo(Metadata other) { String myName = this.element + "." +this.qualifier + "." + this.language; String otherName = other.element + "." + other.qualifier + "." + other.language; int result = myName.compareTo(otherName); if (result == 0) { if (this.order == other.order ) { result = 0; // These two metadata element's names are completely identical. } else if (this.order > other.order) { result = 1; // The other metadata element belongs AFTER this element. } else { result = -1; // The other metadata element belongs BEFORE this element. } } 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.wing; import java.io.Serializable; /** * * This class represents an i18n message, which is composed of three parts: a * catalogue, a key, and a set of dictionary parameters. The catalogue tells * the translater where to find the key, the key tells the transformer which * specific text should be used, and the parameters provide for non translated * data to be inserted into the resulting string. * * This class design such that the Message object can be made static my any * class that needs to use it. If dicionary parameters are used then a new * instance is created specificaly for those parameters, this prevents * concurent threads from over writting parameters of each other. * * @author Scott Phillips */ public class Message implements Serializable { /** What catalogue this key is to be found in. */ protected final String catalogue; /** The key to look up in the catalogue. */ protected final String key; /** * Create a new translatable element. * * @param catalogue * The catalogue were this key is to be found. * @param key * The key to look up in the catalogue. */ public Message(String catalogue, String key) { this.catalogue = catalogue; this.key = key; } /** * * @return The catalogue this key is to be found in. */ public String getCatalogue() { return this.catalogue; } /** * * @return The key to look-up in the catalogue. */ public String getKey() { return this.key; } /** * * Parameterize this translate key by specifying * dictionary parameters. This will not modify the * current translate object but instead create a * cloned copy that has been parameterized. * * @param dictionaryParameters The dictionary parameters */ public Message parameterize(Object ... dictionaryParameters) { return new ParameterizedMessage(catalogue,key,dictionaryParameters); } /** * Return any dictionary parameters that are used by this * translation message. * * Since this is the basic implementation it does not support * parameters we just return an empty array. * * @return Any parameters to the catalogue key */ public Object[] getDictionaryParameters() { return new Object[0]; } /** * * Specialized translate class that handles parameterized messages. * Parameterized messages contain a catalogue and key like normal but * also add the ability for extra parameters to be added to the * message. These parameters are inserted into the final translated * string based upon the key's definition. * * No one out side of this class should even know this class exists, * hence the privacy, but haveing two implementations allows us to * sepearete all the functionality for paramaterization into this * one place. Since most of the messages used are unparameterized * this is not wasted on them and is only invoked when needed. There * may be some performance increase by doing this but i doubt it is * of much consequence, instead the main reason is to be able to create * a new instance when messages are parameterized so that concurrent * threads do not step on each other. * */ private static class ParameterizedMessage extends Message { /** * Parameters to the dictionary key, they may be filled into places in the * final translated version */ private final Object[] dictionaryParameters; /** * Create a new translatable element. * * @param catalogue * The catalogue were this key is to be found. * @param key * The key to look up in the catalogue. */ public ParameterizedMessage(String catalogue, String key, Object ... dictionaryParameters) { super(catalogue,key); this.dictionaryParameters = dictionaryParameters; } /** * Return the dicionary parameters for this message. * * @return Any parameters to the catalogue key */ public Object[] getDictionaryParameters() { return dictionaryParameters; } } }
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.wing; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Options; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.UserMeta; /** * * The WingTransformer is a simple framework for dealing with DSpace based SAX * events. The implementing class is responsible for catching the appropriate * events and filtering them into these method calls. This allows implementors * to have easy access to the document without dealing with the messiness of the * SAX event system. * * If the implementing class needs to insert anything into the document they * these methods should be implemented such that they insert the correct data * into the appropriate places * * @author Scott Phillips */ public interface WingTransformer { /** What to add at the end of the body */ public void addBody(Body body) throws Exception; /** What to add to the options list */ public void addOptions(Options options) throws Exception; /** What user metadata to add to the document */ public void addUserMeta(UserMeta userMeta) throws Exception; /** What page metadata to add to the document */ public void addPageMeta(PageMeta pageMeta) throws Exception; /** What is a unique name for this component? */ public String getComponentName(); }
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.workflow; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.InProgressSubmission; import org.dspace.content.Item; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * Class representing an item going through the workflow process in DSpace * * @author Robert Tansley * @version $Revision: 5844 $ */ public class WorkflowItem implements InProgressSubmission { /** log4j category */ private static Logger log = Logger.getLogger(WorkflowItem.class); /** The item this workflow object pertains to */ private Item item; /** Our context */ private Context ourContext; /** The table row corresponding to this workflow item */ private TableRow wfRow; /** The collection the item is being submitted to */ private Collection collection; /** EPerson owning the current state */ private EPerson owner; /** * Construct a workspace item corresponding to the given database row * * @param context * the context this object exists in * @param row * the database row */ WorkflowItem(Context context, TableRow row) throws SQLException { ourContext = context; wfRow = row; item = Item.find(context, wfRow.getIntColumn("item_id")); collection = Collection.find(context, wfRow .getIntColumn("collection_id")); if (wfRow.isColumnNull("owner")) { owner = null; } else { owner = EPerson.find(context, wfRow.getIntColumn("owner")); } // Cache ourselves context.cache(this, row.getIntColumn("workflow_id")); } /** * Get a workflow item from the database. The item, collection and submitter * are loaded into memory. * * @param context * DSpace context object * @param id * ID of the workspace item * * @return the workflow item, or null if the ID is invalid. */ public static WorkflowItem find(Context context, int id) throws SQLException { // First check the cache WorkflowItem fromCache = (WorkflowItem) context.fromCache( WorkflowItem.class, id); if (fromCache != null) { return fromCache; } TableRow row = DatabaseManager.find(context, "workflowitem", id); if (row == null) { if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "find_workflow_item", "not_found,workflow_id=" + id)); } return null; } else { if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "find_workflow_item", "workflow_id=" + id)); } return new WorkflowItem(context, row); } } /** * return all workflowitems * * @param c active context * @return WorkflowItem [] of all workflows in system */ public static WorkflowItem[] findAll(Context c) throws SQLException { List<WorkflowItem> wfItems = new ArrayList<WorkflowItem>(); TableRowIterator tri = DatabaseManager.queryTable(c, "workflowitem", "SELECT * FROM workflowitem"); try { // make a list of workflow items while (tri.hasNext()) { TableRow row = tri.next(); WorkflowItem wi = new WorkflowItem(c, row); wfItems.add(wi); } } finally { if (tri != null) { tri.close(); } } return wfItems.toArray(new WorkflowItem[wfItems.size()]); } /** * Get all workflow items that were original submissions by a particular * e-person. These are ordered by workflow ID, since this should likely keep * them in the order in which they were created. * * @param context * the context object * @param ep * the eperson * * @return the corresponding workflow items */ public static WorkflowItem[] findByEPerson(Context context, EPerson ep) throws SQLException { List<WorkflowItem> wfItems = new ArrayList<WorkflowItem>(); TableRowIterator tri = DatabaseManager.queryTable(context, "workflowitem", "SELECT workflowitem.* FROM workflowitem, item WHERE " + "workflowitem.item_id=item.item_id AND " + "item.submitter_id= ? " + "ORDER BY workflowitem.workflow_id", ep.getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); // Check the cache WorkflowItem wi = (WorkflowItem) context.fromCache( WorkflowItem.class, row.getIntColumn("workflow_id")); if (wi == null) { wi = new WorkflowItem(context, row); } wfItems.add(wi); } } finally { if (tri != null) { tri.close(); } } return wfItems.toArray(new WorkflowItem[wfItems.size()]); } /** * Get all workflow items for a particular collection. * * @param context * the context object * @param c * the collection * * @return array of the corresponding workflow items */ public static WorkflowItem[] findByCollection(Context context, Collection c) throws SQLException { List<WorkflowItem> wsItems = new ArrayList<WorkflowItem>(); TableRowIterator tri = DatabaseManager.queryTable(context, "workflowitem", "SELECT workflowitem.* FROM workflowitem WHERE " + "workflowitem.collection_id= ? ", c.getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); // Check the cache WorkflowItem wi = (WorkflowItem) context.fromCache( WorkflowItem.class, row.getIntColumn("workflow_id")); // not in cache? turn row into workflowitem if (wi == null) { wi = new WorkflowItem(context, row); } wsItems.add(wi); } } finally { if (tri != null) { tri.close(); } } return wsItems.toArray(new WorkflowItem[wsItems.size()]); } /** * Check to see if a particular item is currently under Workflow. * If so, its WorkflowItem is returned. If not, null is returned * * @param context * the context object * @param i * the item * * @return workflow item corresponding to the item, or null */ public static WorkflowItem findByItem(Context context, Item i) throws SQLException { // Look for the unique workflowitem entry where 'item_id' references this item TableRow row = DatabaseManager.findByUnique(context, "workflowitem", "item_id", i.getID()); if (row == null) { return null; } else { return new WorkflowItem(context, row); } } /** * Get the internal ID of this workflow item * * @return the internal identifier */ public int getID() { return wfRow.getIntColumn("workflow_id"); } /** * get owner of WorkflowItem * * @return EPerson owner */ public EPerson getOwner() { return owner; } /** * set owner of WorkflowItem * * @param ep * owner */ public void setOwner(EPerson ep) { owner = ep; if (ep == null) { wfRow.setColumnNull("owner"); } else { wfRow.setColumn("owner", ep.getID()); } } /** * Get state of WorkflowItem * * @return state */ public int getState() { return wfRow.getIntColumn("state"); } /** * Set state of WorkflowItem * * @param newstate * new state (from <code>WorkflowManager</code>) */ public void setState(int newstate) { wfRow.setColumn("state", newstate); } /** * Update the workflow item, including the unarchived item. */ public void update() throws SQLException, IOException, AuthorizeException { // FIXME check auth log.info(LogManager.getHeader(ourContext, "update_workflow_item", "workflow_item_id=" + getID())); // Update the item item.update(); // Update ourselves DatabaseManager.update(ourContext, wfRow); } /** * delete the WorkflowItem, retaining the Item */ public void deleteWrapper() throws SQLException, IOException, AuthorizeException { // Remove from cache ourContext.removeCached(this, getID()); // delete any pending tasks WorkflowManager.deleteTasks(ourContext, this); // FIXME - auth? DatabaseManager.delete(ourContext, wfRow); } // InProgressSubmission methods public Item getItem() { return item; } public Collection getCollection() { return collection; } public EPerson getSubmitter() throws SQLException { return item.getSubmitter(); } public boolean hasMultipleFiles() { return wfRow.getBooleanColumn("multiple_files"); } public void setMultipleFiles(boolean b) { wfRow.setColumn("multiple_files", b); } public boolean hasMultipleTitles() { return wfRow.getBooleanColumn("multiple_titles"); } public void setMultipleTitles(boolean b) { wfRow.setColumn("multiple_titles", b); } public boolean isPublishedBefore() { return wfRow.getBooleanColumn("published_before"); } public void setPublishedBefore(boolean b) { wfRow.setColumn("published_before", b); } }
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.workflow; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.mail.MessagingException; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; import org.dspace.content.DCDate; import org.dspace.content.DCValue; import org.dspace.content.InstallItem; import org.dspace.content.Item; import org.dspace.content.WorkspaceItem; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.Email; import org.dspace.core.I18nUtil; import org.dspace.core.LogManager; import org.dspace.curate.WorkflowCurator; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.handle.HandleManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * Workflow state machine * * Notes: * * Determining item status from the database: * * When an item has not been submitted yet, it is in the user's personal * workspace (there is a row in PersonalWorkspace pointing to it.) * * When an item is submitted and is somewhere in a workflow, it has a row in the * WorkflowItem table pointing to it. The state of the workflow can be * determined by looking at WorkflowItem.getState() * * When a submission is complete, the WorkflowItem pointing to the item is * destroyed and the archive() method is called, which hooks the item up to the * archive. * * Notification: When an item enters a state that requires notification, * (WFSTATE_STEP1POOL, WFSTATE_STEP2POOL, WFSTATE_STEP3POOL,) the workflow needs * to notify the appropriate groups that they have a pending task to claim. * * Revealing lists of approvers, editors, and reviewers. A method could be added * to do this, but it isn't strictly necessary. (say public List * getStateEPeople( WorkflowItem wi, int state ) could return people affected by * the item's current state. */ public class WorkflowManager { // states to store in WorkflowItem for the GUI to report on // fits our current set of workflow states (stored in WorkflowItem.state) public static final int WFSTATE_SUBMIT = 0; // hmm, probably don't need public static final int WFSTATE_STEP1POOL = 1; // waiting for a reviewer to // claim it public static final int WFSTATE_STEP1 = 2; // task - reviewer has claimed it public static final int WFSTATE_STEP2POOL = 3; // waiting for an admin to // claim it public static final int WFSTATE_STEP2 = 4; // task - admin has claimed item public static final int WFSTATE_STEP3POOL = 5; // waiting for an editor to // claim it public static final int WFSTATE_STEP3 = 6; // task - editor has claimed the // item public static final int WFSTATE_ARCHIVE = 7; // probably don't need this one // either /** Symbolic names of workflow steps. */ private static final String workflowText[] = { "SUBMIT", // 0 "STEP1POOL", // 1 "STEP1", // 2 "STEP2POOL", // 3 "STEP2", // 4 "STEP3POOL", // 5 "STEP3", // 6 "ARCHIVE" // 7 }; /* support for 'no notification' */ private static Map<Integer, Boolean> noEMail = new HashMap<Integer, Boolean>(); /** log4j logger */ private static Logger log = Logger.getLogger(WorkflowManager.class); /** * Translate symbolic name of workflow state into number. * The name is case-insensitive. Returns -1 when name cannot * be matched. * @param state symbolic name of workflow state, must be one of * the elements of workflowText array. * @return numeric workflow state or -1 for error. */ public static int getWorkflowID(String state) { for (int i = 0; i < workflowText.length; ++i) { if (state.equalsIgnoreCase(workflowText[i])) { return i; } } return -1; } /** * startWorkflow() begins a workflow - in a single transaction do away with * the PersonalWorkspace entry and turn it into a WorkflowItem. * * @param c * Context * @param wsi * The WorkspaceItem to convert to a workflow item * @return The resulting workflow item */ public static WorkflowItem start(Context c, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException { // FIXME Check auth Item myitem = wsi.getItem(); Collection collection = wsi.getCollection(); log.info(LogManager.getHeader(c, "start_workflow", "workspace_item_id=" + wsi.getID() + "item_id=" + myitem.getID() + "collection_id=" + collection.getID())); // record the start of the workflow w/provenance message recordStart(c, myitem); // create the WorkflowItem TableRow row = DatabaseManager.row("workflowitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", wsi.getCollection().getID()); DatabaseManager.insert(c, row); WorkflowItem wfi = new WorkflowItem(c, row); wfi.setMultipleFiles(wsi.hasMultipleFiles()); wfi.setMultipleTitles(wsi.hasMultipleTitles()); wfi.setPublishedBefore(wsi.isPublishedBefore()); // remove the WorkspaceItem wsi.deleteWrapper(); // now get the workflow started wfi.setState(WFSTATE_SUBMIT); advance(c, wfi, null); // Return the workflow item return wfi; } /** * startWithoutNotify() starts the workflow normally, but disables * notifications (useful for large imports,) for the first workflow step - * subsequent notifications happen normally */ public static WorkflowItem startWithoutNotify(Context c, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException { // make a hash table entry with item ID for no notify // notify code checks no notify hash for item id noEMail.put(Integer.valueOf(wsi.getItem().getID()), Boolean.TRUE); return start(c, wsi); } /** * getOwnedTasks() returns a List of WorkflowItems containing the tasks * claimed and owned by an EPerson. The GUI displays this info on the * MyDSpace page. * * @param e * The EPerson we want to fetch owned tasks for. */ public static List<WorkflowItem> getOwnedTasks(Context c, EPerson e) throws java.sql.SQLException { ArrayList<WorkflowItem> mylist = new ArrayList<WorkflowItem>(); String myquery = "SELECT * FROM WorkflowItem WHERE owner= ? "; TableRowIterator tri = DatabaseManager.queryTable(c, "workflowitem", myquery,e.getID()); try { while (tri.hasNext()) { mylist.add(new WorkflowItem(c, tri.next())); } } finally { if (tri != null) { tri.close(); } } return mylist; } /** * getPooledTasks() returns a List of WorkflowItems an EPerson could claim * (as a reviewer, etc.) for display on a user's MyDSpace page. * * @param e * The Eperson we want to fetch the pooled tasks for. */ public static List<WorkflowItem> getPooledTasks(Context c, EPerson e) throws SQLException { ArrayList<WorkflowItem> mylist = new ArrayList<WorkflowItem>(); String myquery = "SELECT workflowitem.* FROM workflowitem, TaskListItem" + " WHERE tasklistitem.eperson_id= ? " + " AND tasklistitem.workflow_id=workflowitem.workflow_id"; TableRowIterator tri = DatabaseManager .queryTable(c, "workflowitem", myquery, e.getID()); try { while (tri.hasNext()) { mylist.add(new WorkflowItem(c, tri.next())); } } finally { if (tri != null) { tri.close(); } } return mylist; } /** * claim() claims a workflow task for an EPerson * * @param wi * WorkflowItem to do the claim on * @param e * The EPerson doing the claim */ public static void claim(Context c, WorkflowItem wi, EPerson e) throws SQLException, IOException, AuthorizeException { int taskstate = wi.getState(); switch (taskstate) { case WFSTATE_STEP1POOL: // authorize DSpaceActions.SUBMIT_REVIEW doState(c, wi, WFSTATE_STEP1, e); break; case WFSTATE_STEP2POOL: // authorize DSpaceActions.SUBMIT_STEP2 doState(c, wi, WFSTATE_STEP2, e); break; case WFSTATE_STEP3POOL: // authorize DSpaceActions.SUBMIT_STEP3 doState(c, wi, WFSTATE_STEP3, e); break; // if we got here, we weren't pooled... error? // FIXME - log the error? } log.info(LogManager.getHeader(c, "claim_task", "workflow_item_id=" + wi.getID() + "item_id=" + wi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "newowner_id=" + wi.getOwner().getID() + "old_state=" + taskstate + "new_state=" + wi.getState())); } /** * advance() sends an item forward in the workflow (reviewers, * approvers, and editors all do an 'approve' to move the item forward) if * the item arrives at the submit state, then remove the WorkflowItem and * call the archive() method to put it in the archive, and email notify the * submitter of a successful submission * * @param c * Context * @param wi * WorkflowItem do do the approval on * @param e * EPerson doing the approval */ public static void advance(Context c, WorkflowItem wi, EPerson e) throws SQLException, IOException, AuthorizeException { advance(c, wi, e, true, true); } /** * advance() sends an item forward in the workflow (reviewers, * approvers, and editors all do an 'approve' to move the item forward) if * the item arrives at the submit state, then remove the WorkflowItem and * call the archive() method to put it in the archive, and email notify the * submitter of a successful submission * * @param c * Context * @param wi * WorkflowItem do do the approval on * @param e * EPerson doing the approval * * @param curate * boolean indicating whether curation tasks should be done * * @param record * boolean indicating whether to record action */ public static boolean advance(Context c, WorkflowItem wi, EPerson e, boolean curate, boolean record) throws SQLException, IOException, AuthorizeException { int taskstate = wi.getState(); boolean archived = false; // perform curation tasks if needed if (curate && WorkflowCurator.needsCuration(wi)) { if (! WorkflowCurator.doCuration(c, wi)) { // don't proceed - either curation tasks queued, or item rejected log.info(LogManager.getHeader(c, "advance_workflow", "workflow_item_id=" + wi.getID() + ",item_id=" + wi.getItem().getID() + ",collection_id=" + wi.getCollection().getID() + ",old_state=" + taskstate + ",doCuration=false")); return archived; } } switch (taskstate) { case WFSTATE_SUBMIT: archived = doState(c, wi, WFSTATE_STEP1POOL, e); break; case WFSTATE_STEP1: // authorize DSpaceActions.SUBMIT_REVIEW // Record provenance if (record) { recordApproval(c, wi, e); } archived = doState(c, wi, WFSTATE_STEP2POOL, e); break; case WFSTATE_STEP2: // authorize DSpaceActions.SUBMIT_STEP2 // Record provenance if (record) { recordApproval(c, wi, e); } archived = doState(c, wi, WFSTATE_STEP3POOL, e); break; case WFSTATE_STEP3: // authorize DSpaceActions.SUBMIT_STEP3 // We don't record approval for editors, since they can't reject, // and thus didn't actually make a decision archived = doState(c, wi, WFSTATE_ARCHIVE, e); break; // error handling? shouldn't get here } log.info(LogManager.getHeader(c, "advance_workflow", "workflow_item_id=" + wi.getID() + ",item_id=" + wi.getItem().getID() + ",collection_id=" + wi.getCollection().getID() + ",old_state=" + taskstate + ",new_state=" + wi.getState())); return archived; } /** * unclaim() returns an owned task/item to the pool * * @param c * Context * @param wi * WorkflowItem to operate on * @param e * EPerson doing the operation */ public static void unclaim(Context c, WorkflowItem wi, EPerson e) throws SQLException, IOException, AuthorizeException { int taskstate = wi.getState(); switch (taskstate) { case WFSTATE_STEP1: // authorize DSpaceActions.STEP1 doState(c, wi, WFSTATE_STEP1POOL, e); break; case WFSTATE_STEP2: // authorize DSpaceActions.APPROVE doState(c, wi, WFSTATE_STEP2POOL, e); break; case WFSTATE_STEP3: // authorize DSpaceActions.STEP3 doState(c, wi, WFSTATE_STEP3POOL, e); break; // error handling? shouldn't get here // FIXME - what to do with error - log it? } log.info(LogManager.getHeader(c, "unclaim_workflow", "workflow_item_id=" + wi.getID() + ",item_id=" + wi.getItem().getID() + ",collection_id=" + wi.getCollection().getID() + ",old_state=" + taskstate + ",new_state=" + wi.getState())); } /** * abort() aborts a workflow, completely deleting it (administrator do this) * (it will basically do a reject from any state - the item ends up back in * the user's PersonalWorkspace * * @param c * Context * @param wi * WorkflowItem to operate on * @param e * EPerson doing the operation */ public static void abort(Context c, WorkflowItem wi, EPerson e) throws SQLException, AuthorizeException, IOException { // authorize a DSpaceActions.ABORT if (!AuthorizeManager.isAdmin(c)) { throw new AuthorizeException( "You must be an admin to abort a workflow"); } // stop workflow regardless of its state deleteTasks(c, wi); log.info(LogManager.getHeader(c, "abort_workflow", "workflow_item_id=" + wi.getID() + "item_id=" + wi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "eperson_id=" + e.getID())); // convert into personal workspace returnToWorkspace(c, wi); } // returns true if archived private static boolean doState(Context c, WorkflowItem wi, int newstate, EPerson newowner) throws SQLException, IOException, AuthorizeException { Collection mycollection = wi.getCollection(); Group mygroup = null; boolean archived = false; wi.setState(newstate); switch (newstate) { case WFSTATE_STEP1POOL: // any reviewers? // if so, add them to the tasklist wi.setOwner(null); // get reviewers (group 1 ) mygroup = mycollection.getWorkflowGroup(1); if ((mygroup != null) && !(mygroup.isEmpty())) { // get a list of all epeople in group (or any subgroups) EPerson[] epa = Group.allMembers(c, mygroup); // there were reviewers, change the state // and add them to the list createTasks(c, wi, epa); wi.update(); // email notification notifyGroupOfTask(c, wi, mygroup, epa); } else { // no reviewers, skip ahead wi.setState(WFSTATE_STEP1); archived = advance(c, wi, null, true, false); } break; case WFSTATE_STEP1: // remove reviewers from tasklist // assign owner deleteTasks(c, wi); wi.setOwner(newowner); break; case WFSTATE_STEP2POOL: // clear owner // any approvers? // if so, add them to tasklist // if not, skip to next state wi.setOwner(null); // get approvers (group 2) mygroup = mycollection.getWorkflowGroup(2); if ((mygroup != null) && !(mygroup.isEmpty())) { //get a list of all epeople in group (or any subgroups) EPerson[] epa = Group.allMembers(c, mygroup); // there were approvers, change the state // timestamp, and add them to the list createTasks(c, wi, epa); // email notification notifyGroupOfTask(c, wi, mygroup, epa); } else { // no reviewers, skip ahead wi.setState(WFSTATE_STEP2); archived = advance(c, wi, null, true, false); } break; case WFSTATE_STEP2: // remove admins from tasklist // assign owner deleteTasks(c, wi); wi.setOwner(newowner); break; case WFSTATE_STEP3POOL: // any editors? // if so, add them to tasklist wi.setOwner(null); mygroup = mycollection.getWorkflowGroup(3); if ((mygroup != null) && !(mygroup.isEmpty())) { // get a list of all epeople in group (or any subgroups) EPerson[] epa = Group.allMembers(c, mygroup); // there were editors, change the state // timestamp, and add them to the list createTasks(c, wi, epa); // email notification notifyGroupOfTask(c, wi, mygroup, epa); } else { // no editors, skip ahead wi.setState(WFSTATE_STEP3); archived = advance(c, wi, null, true, false); } break; case WFSTATE_STEP3: // remove editors from tasklist // assign owner deleteTasks(c, wi); wi.setOwner(newowner); break; case WFSTATE_ARCHIVE: // put in archive in one transaction // remove workflow tasks deleteTasks(c, wi); mycollection = wi.getCollection(); Item myitem = archive(c, wi); // now email notification notifyOfArchive(c, myitem, mycollection); archived = true; break; } if (!archived) { wi.update(); } return archived; } /** * Get the text representing the given workflow state * * @param state the workflow state * @return the text representation */ public static String getWorkflowText(int state) { if (state > -1 && state < workflowText.length) { return workflowText[state]; } throw new IllegalArgumentException("Invalid workflow state passed"); } /** * Commit the contained item to the main archive. The item is associated * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. * * @return the fully archived item. */ private static Item archive(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { // FIXME: Check auth Item item = wfi.getItem(); Collection collection = wfi.getCollection(); log.info(LogManager.getHeader(c, "archive_item", "workflow_item_id=" + wfi.getID() + "item_id=" + item.getID() + "collection_id=" + collection.getID())); InstallItem.installItem(c, wfi); // Log the event log.info(LogManager.getHeader(c, "install_item", "workflow_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME")); return item; } /** * notify the submitter that the item is archived */ private static void notifyOfArchive(Context c, Item i, Collection coll) throws SQLException, IOException { try { // Get submitter EPerson ep = i.getSubmitter(); // Get the Locale Locale supportedLocale = I18nUtil.getEPersonLocale(ep); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive")); // Get the item handle to email to user String handle = HandleManager.findHandle(c, i); // Get title DCValue[] titles = i.getDC("title", null, Item.ANY); String title = ""; try { title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled"); } catch (MissingResourceException e) { title = "Untitled"; } if (titles.length > 0) { title = titles[0].value; } email.addRecipient(ep.getEmail()); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(HandleManager.getCanonicalForm(handle)); email.send(); } catch (MessagingException e) { log.warn(LogManager.getHeader(c, "notifyOfArchive", "cannot email user" + " item_id=" + i.getID())); } } /** * Return the workflow item to the workspace of the submitter. The workflow * item is removed, and a workspace item created. * * @param c * Context * @param wfi * WorkflowItem to be 'dismantled' * @return the workspace item */ private static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { Item myitem = wfi.getItem(); Collection mycollection = wfi.getCollection(); // FIXME: How should this interact with the workflow system? // FIXME: Remove license // FIXME: Provenance statement? // Create the new workspace item row TableRow row = DatabaseManager.row("workspaceitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", mycollection.getID()); DatabaseManager.insert(c, row); int wsi_id = row.getIntColumn("workspace_item_id"); WorkspaceItem wi = WorkspaceItem.find(c, wsi_id); wi.setMultipleFiles(wfi.hasMultipleFiles()); wi.setMultipleTitles(wfi.hasMultipleTitles()); wi.setPublishedBefore(wfi.isPublishedBefore()); wi.update(); //myitem.update(); log.info(LogManager.getHeader(c, "return_to_workspace", "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + wi.getID())); // Now remove the workflow object manually from the database DatabaseManager.updateQuery(c, "DELETE FROM WorkflowItem WHERE workflow_id=" + wfi.getID()); return wi; } /** * rejects an item - rejection means undoing a submit - WorkspaceItem is * created, and the WorkflowItem is removed, user is emailed * rejection_message. * * @param c * Context * @param wi * WorkflowItem to operate on * @param e * EPerson doing the operation * @param rejection_message * message to email to user */ public static WorkspaceItem reject(Context c, WorkflowItem wi, EPerson e, String rejection_message) throws SQLException, AuthorizeException, IOException { // authorize a DSpaceActions.REJECT // stop workflow deleteTasks(c, wi); // rejection provenance Item myitem = wi.getItem(); // Get current date String now = DCDate.getCurrent().toString(); // Get user's name + email address String usersName = getEPersonName(e); // Here's what happened String provDescription = "Rejected by " + usersName + ", reason: " + rejection_message + " on " + now + " (GMT) "; // Add to item as a DC field myitem.addDC("description", "provenance", "en", provDescription); myitem.update(); // convert into personal workspace WorkspaceItem wsi = returnToWorkspace(c, wi); // notify that it's been rejected notifyOfReject(c, wi, e, rejection_message); log.info(LogManager.getHeader(c, "reject_workflow", "workflow_item_id=" + wi.getID() + "item_id=" + wi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "eperson_id=" + e.getID())); return wsi; } // creates workflow tasklist entries for a workflow // for all the given EPeople private static void createTasks(Context c, WorkflowItem wi, EPerson[] epa) throws SQLException { // create a tasklist entry for each eperson for (int i = 0; i < epa.length; i++) { // can we get away without creating a tasklistitem class? // do we want to? TableRow tr = DatabaseManager.row("tasklistitem"); tr.setColumn("eperson_id", epa[i].getID()); tr.setColumn("workflow_id", wi.getID()); DatabaseManager.insert(c, tr); } } // deletes all tasks associated with a workflowitem static void deleteTasks(Context c, WorkflowItem wi) throws SQLException { String myrequest = "DELETE FROM TaskListItem WHERE workflow_id= ? "; DatabaseManager.updateQuery(c, myrequest, wi.getID()); } // send notices of curation activity public static void notifyOfCuration(Context c, WorkflowItem wi, EPerson[] epa, String taskName, String action, String message) throws SQLException, IOException { try { // Get the item title String title = getItemTitle(wi); // Get the submitter's name String submitter = getSubmitterName(wi); // Get the collection Collection coll = wi.getCollection(); for (int i = 0; i < epa.length; i++) { Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "flowtask_notify")); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(submitter); email.addArgument(taskName); email.addArgument(message); email.addArgument(action); email.addRecipient(epa[i].getEmail()); email.send(); } } catch (MessagingException e) { log.warn(LogManager.getHeader(c, "notifyOfCuration", "cannot email users" + " of workflow_item_id" + wi.getID())); } } private static void notifyGroupOfTask(Context c, WorkflowItem wi, Group mygroup, EPerson[] epa) throws SQLException, IOException { // check to see if notification is turned off // and only do it once - delete key after notification has // been suppressed for the first time Integer myID = Integer.valueOf(wi.getItem().getID()); if (noEMail.containsKey(myID)) { // suppress email, and delete key noEMail.remove(myID); } else { try { // Get the item title String title = getItemTitle(wi); // Get the submitter's name String submitter = getSubmitterName(wi); // Get the collection Collection coll = wi.getCollection(); String message = ""; for (int i = 0; i < epa.length; i++) { Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task")); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(submitter); ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale); switch (wi.getState()) { case WFSTATE_STEP1POOL: message = messages.getString("org.dspace.workflow.WorkflowManager.step1"); break; case WFSTATE_STEP2POOL: message = messages.getString("org.dspace.workflow.WorkflowManager.step2"); break; case WFSTATE_STEP3POOL: message = messages.getString("org.dspace.workflow.WorkflowManager.step3"); break; } email.addArgument(message); email.addArgument(getMyDSpaceLink()); email.addRecipient(epa[i].getEmail()); email.send(); } } catch (MessagingException e) { String gid = (mygroup != null) ? String.valueOf(mygroup.getID()) : "none"; log.warn(LogManager.getHeader(c, "notifyGroupofTask", "cannot email user" + " group_id" + gid + " workflow_item_id" + wi.getID())); } } } private static String getMyDSpaceLink() { return ConfigurationManager.getProperty("dspace.url") + "/mydspace"; } private static void notifyOfReject(Context c, WorkflowItem wi, EPerson e, String reason) { try { // Get the item title String title = getItemTitle(wi); // Get the collection Collection coll = wi.getCollection(); // Get rejector's name String rejector = getEPersonName(e); Locale supportedLocale = I18nUtil.getEPersonLocale(e); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject")); email.addRecipient(getSubmitterEPerson(wi).getEmail()); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(rejector); email.addArgument(reason); email.addArgument(getMyDSpaceLink()); email.send(); } catch (RuntimeException re) { // log this email error log.warn(LogManager.getHeader(c, "notify_of_reject", "cannot email user" + " eperson_id" + e.getID() + " eperson_email" + e.getEmail() + " workflow_item_id" + wi.getID())); throw re; } catch (Exception ex) { // log this email error log.warn(LogManager.getHeader(c, "notify_of_reject", "cannot email user" + " eperson_id" + e.getID() + " eperson_email" + e.getEmail() + " workflow_item_id" + wi.getID())); } } // FIXME - are the following methods still needed? private static EPerson getSubmitterEPerson(WorkflowItem wi) throws SQLException { EPerson e = wi.getSubmitter(); return e; } /** * get the title of the item in this workflow * * @param wi the workflow item object */ public static String getItemTitle(WorkflowItem wi) throws SQLException { Item myitem = wi.getItem(); DCValue[] titles = myitem.getDC("title", null, Item.ANY); // only return the first element, or "Untitled" if (titles.length > 0) { return titles[0].value; } else { return I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled "); } } /** * get the name of the eperson who started this workflow * * @param wi the workflow item */ public static String getSubmitterName(WorkflowItem wi) throws SQLException { EPerson e = wi.getSubmitter(); return getEPersonName(e); } private static String getEPersonName(EPerson e) throws SQLException { String submitter = e.getFullName(); submitter = submitter + " (" + e.getEmail() + ")"; return submitter; } // Record approval provenance statement private static void recordApproval(Context c, WorkflowItem wi, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = wi.getItem(); // Get user's name + email address String usersName = getEPersonName(e); // Get current date String now = DCDate.getCurrent().toString(); // Here's what happened String provDescription = "Approved for entry into archive by " + usersName + " on " + now + " (GMT) "; // add bitstream descriptions (name, size, checksums) provDescription += InstallItem.getBitstreamProvenanceMessage(item); // Add to item as a DC field item.addDC("description", "provenance", "en", provDescription); item.update(); } // Create workflow start provenance message private static void recordStart(Context c, Item myitem) throws SQLException, IOException, AuthorizeException { // get date DCDate now = DCDate.getCurrent(); // Create provenance description String provmessage = ""; if (myitem.getSubmitter() != null) { provmessage = "Submitted by " + myitem.getSubmitter().getFullName() + " (" + myitem.getSubmitter().getEmail() + ") on " + now.toString() + "\n"; } else // null submitter { provmessage = "Submitted by unknown (probably automated) on" + now.toString() + "\n"; } // add sizes and checksums of bitstreams provmessage += InstallItem.getBitstreamProvenanceMessage(myitem); // Add message to the DC myitem.addDC("description", "provenance", "en", provmessage); myitem.update(); } }
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.checker; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.log4j.Logger; import org.dspace.storage.rdbms.DatabaseManager; /** * Database Helper Class to cleanup database resources * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class DAOSupport { private static final Logger LOG = Logger.getLogger(DAOSupport.class); /** * Utility method that cleans up the statement and connection. * * @param stmt * A prepared statement to close. * @param conn * Corresponding connection to close. */ protected void cleanup(Statement stmt, Connection conn) { cleanup(stmt); if (conn != null) { DatabaseManager.freeConnection(conn); } } /** * Utility method that cleans up the statement and connection. * * @param stmt * A prepared statement to close. * @param conn * Corresponding connection to close. * @param rs * Result set to close */ protected void cleanup(Statement stmt, Connection conn, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.warn("Problem closing result set. " + e.getMessage(), e); } } cleanup(stmt); if (conn != null) { DatabaseManager.freeConnection(conn); } } protected void cleanup(Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { LOG.warn("Problem closing prepared statement. " + e.getMessage(), e); } } } protected void cleanup(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { LOG.warn(e); } } } }
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.checker; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; import java.util.GregorianCalendar; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; /** * <p> * The email reporter creates and sends emails to an administrator. This only * reports information for today's date. It is expected this will be used just * after the checksum checker has been run. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * */ public class DailyReportEmailer { /** log4j logger. */ private static Logger log = Logger.getLogger(DailyReportEmailer.class); /** * Default constructor. */ public DailyReportEmailer() { } /** * Send the report through email. * * @param attachment * the file containing the report * @param numberOfBitstreams * the number of bitstreams reported * * @throws IOException * if IO exception occurs * @throws javax.mail.MessagingException * if message cannot be sent. */ public void sendReport(File attachment, int numberOfBitstreams) throws IOException, javax.mail.MessagingException { // Get the mail configuration properties String server = ConfigurationManager.getProperty("mail.server"); // Set up properties for mail session Properties props = System.getProperties(); props.put("mail.smtp.host", server); // Get session Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); // create the first part of the email BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart .setText("This is the checksum checker report see attachment for details \n" + numberOfBitstreams + " Bitstreams found with POSSIBLE issues"); multipart.addBodyPart(messageBodyPart); // add the file messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName("checksum_checker_report.txt"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); msg.setFrom(new InternetAddress(ConfigurationManager .getProperty("mail.from.address"))); msg.addRecipient(Message.RecipientType.TO, new InternetAddress( ConfigurationManager.getProperty("mail.admin"))); msg.setSentDate(new Date()); msg.setSubject("Checksum checker Report - " + numberOfBitstreams + " Bitstreams found with POSSIBLE issues"); Transport.send(msg); } /** * Allows users to have email sent to them. The default is to send all * reports in one email * * @param args * <dl> * <dt>-h</dt> * <dd>help</dd> * <dt>-d</dt> * <dd>Select deleted bitstreams</dd> * <dt>-m</dt> * <dd>Bitstreams missing from assetstore</dd> * <dt>-c</dt> * <dd>Bitstreams whose checksums were changed</dd> * <dt>-n</dt> * <dd>Bitstreams whose checksums were changed</dd> * <dt>-a</dt> * <dd>Send all reports in one email</dd> * </dl> * */ public static void main(String[] args) { // set up command line parser CommandLineParser parser = new PosixParser(); CommandLine line = null; // create an options object and populate it Options options = new Options(); options.addOption("h", "help", false, "Help"); options .addOption("d", "Deleted", false, "Send E-mail report for all bitstreams set as deleted for today"); options .addOption("m", "Missing", false, "Send E-mail report for all bitstreams not found in assetstore for today"); options .addOption( "c", "Changed", false, "Send E-mail report for all bitstreams where checksum has been changed for today"); options.addOption("a", "All", false, "Send all E-mail reports"); options.addOption("u", "Unchecked", false, "Send the Unchecked bitstream report"); options .addOption("n", "Not Processed", false, "Send E-mail report for all bitstreams set to longer be processed for today"); try { line = parser.parse(options, args); } catch (ParseException e) { log.fatal(e); System.exit(1); } // user asks for help if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("Checksum Reporter\n", options); System.out .println("\nSend Deleted bitstream email report: DailyReportEmailer -d"); System.out .println("\nSend Missing bitstreams email report: DailyReportEmailer -m"); System.out .println("\nSend Checksum Changed email report: DailyReportEmailer -c"); System.out .println("\nSend bitstream not to be processed email report: DailyReportEmailer -n"); System.out .println("\nSend Un-checked bitstream report: DailyReportEmailer -u"); System.out.println("\nSend All email reports: DailyReportEmailer"); System.exit(0); } // create a new simple reporter SimpleReporter reporter = new SimpleReporterImpl(); DailyReportEmailer emailer = new DailyReportEmailer(); // get dates for yesterday and tomorrow GregorianCalendar calendar = new GregorianCalendar(); calendar.add(GregorianCalendar.DAY_OF_YEAR, -1); Date yesterday = calendar.getTime(); calendar.add(GregorianCalendar.DAY_OF_YEAR, 2); Date tomorrow = calendar.getTime(); File report = null; FileWriter writer = null; try { // the number of bitstreams in report int numBitstreams = 0; // create a temporary file in the log directory String dirLocation = ConfigurationManager.getProperty("log.dir"); File directory = new File(dirLocation); if (directory.exists() && directory.isDirectory()) { report = File.createTempFile("checker_report", ".txt", directory); } else { throw new IllegalStateException("directory :" + dirLocation + " does not exist"); } writer = new FileWriter(report); if ((line.hasOption("a")) || (line.getOptions().length == 0)) { writer .write("\n--------------------------------- Begin Reporting ------------------------\n\n"); numBitstreams += reporter.getDeletedBitstreamReport(yesterday, tomorrow, writer); writer .write("\n--------------------------------- Report Spacer ---------------------------\n\n"); numBitstreams += reporter.getChangedChecksumReport(yesterday, tomorrow, writer); writer .write("\n--------------------------------- Report Spacer ---------------------------\n\n"); numBitstreams += reporter.getBitstreamNotFoundReport(yesterday, tomorrow, writer); writer .write("\n--------------------------------- Report Spacer ---------------------------\n\n"); numBitstreams += reporter.getNotToBeProcessedReport(yesterday, tomorrow, writer); writer .write("\n--------------------------------- Report Spacer ---------------------------\n\n"); numBitstreams += reporter.getUncheckedBitstreamsReport(writer); writer .write("\n--------------------------------- End Report ---------------------------\n\n"); writer.flush(); writer.close(); emailer.sendReport(report, numBitstreams); } else { if (line.hasOption("d")) { writer .write("\n--------------------------------- Begin Reporting ------------------------\n\n"); numBitstreams += reporter.getDeletedBitstreamReport( yesterday, tomorrow, writer); writer.flush(); writer.close(); emailer.sendReport(report, numBitstreams); } if (line.hasOption("m")) { writer .write("\n--------------------------------- Begin Reporting ------------------------\n\n"); numBitstreams += reporter.getBitstreamNotFoundReport( yesterday, tomorrow, writer); writer.flush(); writer.close(); emailer.sendReport(report, numBitstreams); } if (line.hasOption("c")) { writer .write("\n--------------------------------- Begin Reporting ------------------------\n\n"); numBitstreams += reporter.getChangedChecksumReport( yesterday, tomorrow, writer); writer.flush(); writer.close(); emailer.sendReport(report, numBitstreams); } if (line.hasOption("n")) { writer .write("\n--------------------------------- Begin Reporting ------------------------\n\n"); numBitstreams += reporter.getNotToBeProcessedReport( yesterday, tomorrow, writer); writer.flush(); writer.close(); emailer.sendReport(report, numBitstreams); } if (line.hasOption("u")) { writer .write("\n--------------------------------- Begin Reporting ------------------------\n\n"); numBitstreams += reporter .getUncheckedBitstreamsReport(writer); writer.flush(); writer.close(); emailer.sendReport(report, numBitstreams); } } } catch (MessagingException e) { log.fatal(e); } catch (IOException e) { log.fatal(e); } finally { if (writer != null) { try { writer.close(); } catch (Exception e) { log.fatal("Could not close writer", e); } } if (report != null && report.exists()) { if (!report.delete()) { log.error("Unable to delete report file"); } } } } }
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.checker; import java.util.Date; /** * <p> * A delegating dispatcher that puts a time limit on the operation of another * dispatcher. * </p> * * <p> * Unit testing this class would be possible by abstracting the system time into * an abstract clock. We decided this was not worth the candle. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class LimitedDurationDispatcher implements BitstreamDispatcher { /** * The delegate dispatcher that will actually dispatch the jobs. */ private BitstreamDispatcher delegate; /** * Milliseconds since epoch after which this dispatcher will stop returning * values. */ private long end; /** * Blanked off constructor - do not use. */ private LimitedDurationDispatcher() { end = 0L; delegate = null; } /** * Main constructor. * * @param dispatcher * Delegate dispatcher that will do the heavy lifting of the * dispatching work. * @param endTime * when this dispatcher will stop returning valid bitstream ids. */ public LimitedDurationDispatcher(BitstreamDispatcher dispatcher, Date endTime) { delegate = dispatcher; end = endTime.getTime(); } /** * @see org.dspace.checker.BitstreamDispatcher#next() */ public int next() { return (System.currentTimeMillis() > end) ? SENTINEL : delegate.next(); } }
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.checker; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.log4j.Logger; import org.dspace.core.I18nUtil; /** * <p> * Collects results from a Checksum process and outputs them to a Log4j Logger. * </p> * * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * */ public class ResultsLogger implements ChecksumResultsCollector { /** * Usual Log4J logger. */ private static final Logger LOG = Logger.getLogger(ResultsLogger.class); /** * Utility date format. */ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "MM/dd/yyyy hh:mm:ss"); /** * Date the current checking run started. */ Date startDate = null; /** * ChecksumResultDAO dependency variable. */ private ChecksumResultDAO resultDAO; /** * Blanked off, no-op constructor. Do not use. */ private ResultsLogger() { } /** * Main constructor. * * @param startDt * Date the checking run started. */ public ResultsLogger(Date startDt) { this.resultDAO = new ChecksumResultDAO(); LOG.info(msg("run-start-time") + ": " + DATE_FORMAT.format(startDt)); } /** * Get the i18N string. * * @param key * to get the message. * @return the message found. */ private String msg(String key) { return I18nUtil.getMessage("org.dspace.checker.ResultsLogger." + key); } /** * Collect a result for logging. * * @param info * the BitstreamInfo representing the result. * @see org.dspace.checker.ChecksumResultsCollector#collect(org.dspace.checker.BitstreamInfo) */ public void collect(BitstreamInfo info) { LOG.info("******************************************************"); LOG.info(msg("bitstream-id") + ": " + info.getBitstreamId()); LOG.info(msg("bitstream-info-found") + ": " + info.getInfoFound()); LOG.info(msg("bitstream-marked-deleted") + ": " + info.getDeleted()); LOG.info(msg("bitstream-found") + ": " + info.getBitstreamFound()); LOG.info(msg("to-be-processed") + ": " + info.getToBeProcessed()); LOG.info(msg("internal-id") + ": " + info.getInternalId()); LOG.info(msg("name") + ": " + info.getName()); LOG.info(msg("store-number") + ": " + info.getStoreNumber()); LOG.info(msg("size") + ": " + info.getSize()); LOG.info(msg("bitstream-format") + ": " + info.getBitstreamFormatId()); LOG.info(msg("user-format-description") + ": " + info.getUserFormatDescription()); LOG.info(msg("source") + ": " + info.getSource()); LOG .info(msg("checksum-algorithm") + ": " + info.getChecksumAlgorithm()); LOG.info(msg("previous-checksum") + ": " + info.getStoredChecksum()); LOG.info(msg("previous-checksum-date") + ": " + ((info.getProcessEndDate() != null) ? DATE_FORMAT.format(info .getProcessEndDate()) : "unknown")); LOG.info(msg("new-checksum") + ": " + info.getCalculatedChecksum()); LOG.info(msg("checksum-comparison-result") + ": " + resultDAO.getChecksumCheckStr(info.getChecksumCheckResult())); LOG.info("\n\n"); } }
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.checker; import java.util.Collections; import java.util.EmptyStackException; import java.util.List; import java.util.Stack; /** * Really simple dispatcher that just iterates over a pre-defined list of ids. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class ListDispatcher implements BitstreamDispatcher { /** * List of Integer ids. */ Stack<Integer> bitstreams = new Stack<Integer>(); /** * Blanked off, no-op constructor. Do not use. */ private ListDispatcher() { } /** * Main constructor. * * @param bitstreamIds */ public ListDispatcher(List<Integer> bitstreamIds) { Collections.reverse(bitstreamIds); bitstreams.addAll(bitstreamIds); } /** * @see org.dspace.checker.BitstreamDispatcher#next() */ public synchronized int next() { try { return bitstreams.pop().intValue(); } catch (EmptyStackException e) { return SENTINEL; } } }
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.checker; import java.util.Date; /** * An implementation of the selection strategy that selects bitstreams in the * order that they were last checked, looping endlessly. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class SimpleDispatcher implements BitstreamDispatcher { /** * Should this dispatcher keep on dispatching around the collection? */ private boolean loopContinuously = false; /** * Date this dispatcher started dispatching. */ private Date processStartTime = null; /** * Access for bitstream information */ private BitstreamInfoDAO bitstreamInfoDAO; /** * Creates a new SimpleDispatcher. * * @param startTime * timestamp for beginning of checker process * @param looping * indicates whether checker should loop infinitely through * most_recent_checksum table */ public SimpleDispatcher(BitstreamInfoDAO bitstreamInfoDAO, Date startTime, boolean looping) { this.bitstreamInfoDAO = bitstreamInfoDAO; this.processStartTime = (startTime == null ? null : new Date(startTime.getTime())); this.loopContinuously = looping; } /** * Blanked off, no-op constructor. Do not use. */ private SimpleDispatcher() { } /** * Selects the next candidate bitstream. * * @see org.dspace.checker.BitstreamDispatcher#next() */ public synchronized int next() { // should process loop infinitely through the // bitstreams in most_recent_checksum table? if (!loopContinuously && (processStartTime != null)) { return bitstreamInfoDAO.getOldestBitstream(new java.sql.Timestamp( processStartTime.getTime())); } else { return bitstreamInfoDAO.getOldestBitstream(); } } }
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.checker; import java.io.IOException; import java.io.InputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.Date; import org.apache.log4j.Logger; import org.dspace.core.Utils; /** * <p> * Main class for the checksum checker tool, which calculates checksums for each * bitstream whose ID is in the most_recent_checksum table, and compares it * against the last calculated checksum for that bitstream. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * * @todo the accessor methods are currently unused - are they useful? * @todo check for any existing resource problems */ public final class CheckerCommand { /** Usual Log4J logger. */ private static final Logger LOG = Logger.getLogger(CheckerCommand.class); /** Default digest algorithm (MD5). */ private static final String DEFAULT_DIGEST_ALGORITHM = "MD5"; /** 4 Meg byte array for reading file. */ private int BYTE_ARRAY_SIZE = 4 * 1024; /** BitstreamInfoDAO dependency. */ private BitstreamInfoDAO bitstreamInfoDAO = null; /** BitstreamDAO dependency. */ private BitstreamDAO bitstreamDAO = null; /** * Checksum history Data access object */ private ChecksumHistoryDAO checksumHistoryDAO = null; /** start time for current process. */ private Date processStartDate = null; /** * Dispatcher to be used for processing run. */ private BitstreamDispatcher dispatcher = null; /** * Container/logger with details about each bitstream and checksum results. */ private ChecksumResultsCollector collector = null; /** Report all processing */ private boolean reportVerbose = false; /** * Default constructor uses DSpace plugin manager to construct dependencies. */ public CheckerCommand() { bitstreamInfoDAO = new BitstreamInfoDAO(); bitstreamDAO = new BitstreamDAO(); checksumHistoryDAO = new ChecksumHistoryDAO(); } /** * <p> * Uses the options set up on this checker to determine a mode of execution, * and then accepts bitstream ids from the dispatcher and checks their * bitstreams against the db records. * </p> * * <p> * N.B. a valid BitstreamDispatcher must be provided using * setBitstreamDispatcher before calling this method * </p> */ public void process() { LOG.debug("Begin Checker Processing"); if (dispatcher == null) { throw new IllegalStateException("No BitstreamDispatcher provided"); } if (collector == null) { collector = new ResultsLogger(processStartDate); } // update missing bitstreams that were entered into the // bitstream table - this always done. bitstreamInfoDAO.updateMissingBitstreams(); int id = dispatcher.next(); while (id != BitstreamDispatcher.SENTINEL) { LOG.debug("Processing bitstream id = " + id); BitstreamInfo info = checkBitstream(id); if (reportVerbose || !ChecksumCheckResults.CHECKSUM_MATCH.equals(info.getChecksumCheckResult())) { collector.collect(info); } id = dispatcher.next(); } } /** * Check a specified bitstream. * * @param id * the bitstream id * * @return the information about the bitstream and its checksum data */ private BitstreamInfo checkBitstream(final int id) { // get bitstream info from bitstream table BitstreamInfo info = bitstreamInfoDAO.findByBitstreamId(id); // requested id was not found in bitstream // or most_recent_checksum table if (info == null) { // Note: this case should only occur if id is requested at // command line, since ref integrity checks should // prevent id from appearing in most_recent_checksum // but not bitstream table, or vice versa info = new BitstreamInfo(id); processNullInfoBitstream(info); } else if (!info.getToBeProcessed()) { // most_recent_checksum.to_be_processed is marked // 'false' for this bitstream id. // Do not do any db updates info .setChecksumCheckResult(ChecksumCheckResults.BITSTREAM_NOT_PROCESSED); } else if (info.getDeleted()) { // bitstream id is marked 'deleted' in bitstream table. processDeletedBitstream(info); } else { processBitstream(info); } return info; } /** * Digest the stream and get the checksum value. * * @param stream * InputStream to digest. * @param algorithm * the algorithm to use when digesting. * @todo Document the algorithm parameter * @return digest * * @throws java.security.NoSuchAlgorithmException * if the requested algorithm is not provided by the system * security provider. * @throws java.io.IOException * If an exception arises whilst reading the stream */ private String digestStream(InputStream stream, String algorithm) throws java.security.NoSuchAlgorithmException, java.io.IOException { // create the digest stream DigestInputStream dStream = new DigestInputStream(stream, MessageDigest .getInstance(algorithm)); byte[] bytes = new byte[BYTE_ARRAY_SIZE]; // make sure all the data is read by the digester int bytesRead = -1; do { bytesRead = dStream.read(bytes, 0, BYTE_ARRAY_SIZE); } while (bytesRead != -1); return Utils.toHex(dStream.getMessageDigest().digest()); } /** * Compares two checksums. * * @param checksumA * the first checksum * @param checksumB * the second checksum * * @return a result code (constants defined in Util) */ private String compareChecksums(String checksumA, String checksumB) { String result = ChecksumCheckResults.CHECKSUM_NO_MATCH; if ((checksumA == null) || (checksumB == null)) { result = ChecksumCheckResults.CHECKSUM_PREV_NOT_FOUND; } else if (checksumA.equals(checksumB)) { result = ChecksumCheckResults.CHECKSUM_MATCH; } return result; } /** * Process bitstream that was marked 'deleted' in bitstream table. A deleted * bitstream should only be checked once afterwards it should be marked * 'to_be_processed=false'. Note that to_be_processed must be manually * updated in db to allow for future processing. * * @param info * a deleted bitstream. */ private void processDeletedBitstream(BitstreamInfo info) { info.setProcessStartDate(new Date()); info .setChecksumCheckResult(ChecksumCheckResults.BITSTREAM_MARKED_DELETED); info.setProcessStartDate(new Date()); info.setProcessEndDate(new Date()); info.setToBeProcessed(false); bitstreamInfoDAO.update(info); checksumHistoryDAO.insertHistory(info); } /** * Process bitstream whose ID was not found in most_recent_checksum or * bitstream table. No updates can be done. The missing bitstream is output * to the log file. * * @param info * A not found BitStreamInfo * @todo is this method required? */ private void processNullInfoBitstream(BitstreamInfo info) { info.setInfoFound(false); info.setProcessStartDate(new Date()); info.setProcessEndDate(new Date()); info .setChecksumCheckResult(ChecksumCheckResults.BITSTREAM_INFO_NOT_FOUND); } /** * <p> * Process general case bitstream. * </p> * * <p> * Note: bitstream will have timestamp indicating it was "checked", even if * actual checksumming never took place. * </p> * * @todo Why does bitstream have a timestamp indicating it's checked if * checksumming doesn't occur? * * @param info * BitstreamInfo to handle */ private void processBitstream(BitstreamInfo info) { info.setProcessStartDate(new Date()); if (info.getChecksumAlgorithm() == null) { info.setChecksumAlgorithm(DEFAULT_DIGEST_ALGORITHM); } try { InputStream bitstream = bitstreamDAO.getBitstream(info .getBitstreamId()); info.setBitstreamFound(true); String checksum = digestStream(bitstream, info .getChecksumAlgorithm()); info.setCalculatedChecksum(checksum); // compare new checksum to previous checksum info.setChecksumCheckResult(compareChecksums(info .getStoredChecksum(), info.getCalculatedChecksum())); } catch (IOException e) { // bitstream located, but file missing from asset store info .setChecksumCheckResult(ChecksumCheckResults.BITSTREAM_NOT_FOUND); info.setToBeProcessed(false); LOG.error("Error retrieving bitstream ID " + info.getBitstreamId() + " from " + "asset store.", e); } catch (SQLException e) { // ??this code only executes if an SQL // exception occurs in *DSpace* code, probably // indicating a general db problem? info .setChecksumCheckResult(ChecksumCheckResults.BITSTREAM_INFO_NOT_FOUND); LOG.error("Error retrieving metadata for bitstream ID " + info.getBitstreamId(), e); } catch (NoSuchAlgorithmException e) { info .setChecksumCheckResult(ChecksumCheckResults.CHECKSUM_ALGORITHM_INVALID); info.setToBeProcessed(false); LOG.error("Invalid digest algorithm type for bitstream ID" + info.getBitstreamId(), e); } finally { info.setProcessEndDate(new Date()); // record new checksum and comparison result in db bitstreamInfoDAO.update(info); checksumHistoryDAO.insertHistory(info); } } /** * Get dispatcher being used by this run of the checker. * * @return the dispatcher being used by this run. */ public BitstreamDispatcher getDispatcher() { return dispatcher; } /** * Set the dispatcher to be used by this run of the checker. * * @param dispatcher * Dispatcher to use. */ public void setDispatcher(BitstreamDispatcher dispatcher) { this.dispatcher = dispatcher; } /** * Get the collector that holds/logs the results for this process run. * * @return The ChecksumResultsCollector being used. */ public ChecksumResultsCollector getCollector() { return collector; } /** * Set the collector that holds/logs the results for this process run. * * @param collector * the collector to be used for this run */ public void setCollector(ChecksumResultsCollector collector) { this.collector = collector; } /** * Get time at which checker process began. * * @return start time */ public Date getProcessStartDate() { return processStartDate == null ? null : new Date(processStartDate.getTime()); } /** * Set time at which checker process began. * * @param startDate * start time */ public void setProcessStartDate(Date startDate) { processStartDate = startDate == null ? null : new Date(startDate.getTime()); } /** * Determine if any errors are reported * * @return true if only errors reported */ public boolean isReportVerbose() { return reportVerbose; } /** * Set report errors only * * @param reportVerbose * true to report only errors in the logs. */ public void setReportVerbose(boolean reportVerbose) { this.reportVerbose = reportVerbose; } }
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.checker; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Date; /** * * Simple Reporting Class which can return several different reports. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public interface SimpleReporter { /** * Returns the bitstreams set found to be deleted for the specified date * range. * * @param startDate * the start date range * @param endDate * the end date range * @param osw * the output stream writer to write to * * @return number of bitstreams found * * @throws IOException * if io error occurs */ public int getDeletedBitstreamReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException; /** * The a report of bitstreams found where the checksum has been changed * since the last check for the specified date range. * * @param startDate * the start date range. * @param endDate * then end date range. * @param osw * the output stream writer to write to * * @return number of bitstreams found * * @throws IOException * if io error occurs */ public int getChangedChecksumReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException; /** * The report of bitstreams for the specified date range where it was * determined the bitstreams can no longer be found. * * @param startDate * the start date range. * @param endDate * the end date range. * @param osw * the output stream writer to write to * * @return number of bitstreams found * * @throws IOException * if io error occurs */ public int getBitstreamNotFoundReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException; /** * The bitstreams that were set to not be processed report for the specified * date range. * * @param startDate * the start date range. * @param endDate * the end date range. * @param osw * the output stream writer to write to * * @throws IOException * if io error occurs * */ public int getNotToBeProcessedReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException; /** * The bitstreams that are not known to the checksum checker. This means * they are in the bitstream table but not in the most recent checksum table * * @param osw * the output stream writer to write to * * @return number of bitstreams found * * @throws IOException * if io error occurs * */ public int getUncheckedBitstreamsReport(OutputStreamWriter osw) throws IOException; }
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.checker; import org.apache.log4j.Logger; import org.dspace.core.Context; import org.dspace.event.Consumer; import org.dspace.event.Event; /** * Class for removing Checker data for a Bitstreams based on deletion events. * * @version $Revision: 5844 $ */ public class CheckerConsumer implements Consumer { /** log4j logger */ private static Logger log = Logger.getLogger(CheckerConsumer.class); private BitstreamInfoDAO bitstreamInfoDAO = new BitstreamInfoDAO(); /** * Initialize - allocate any resources required to operate. * Called at the start of ANY sequence of event consume() calls. */ public void initialize() throws Exception { // no-op } /** * Consume an event * * @param ctx the execution context object * * @param event the content event */ public void consume(Context ctx, Event event) throws Exception { if (event.getEventType() == Event.DELETE) { log.debug("Attempting to remove Checker Info"); bitstreamInfoDAO.deleteBitstreamInfoWithHistory(event.getSubjectID()); log.debug("Completed removing Checker Info"); } } /** * Signal that there are no more events queued in this * event stream. */ public void end(Context ctx) throws Exception { // no-op } /** * Finish - free any allocated resources. * Called when consumer is being released */ public void finish(Context ctx) throws Exception { // no-op } }
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.checker; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.ParseException; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; import org.dspace.core.Utils; /** * Manages the deletion of results from the checksum history. It uses the * dspace.cfg file as the default configuration file for the deletion settings * and can use a different configuration file if it is passed in. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * */ public final class ResultsPruner { /** * Default logger. */ private static final Logger LOG = Logger.getLogger(ResultsPruner.class); /** * Factory method for the default results pruner configuration using * dspace.cfg * * @return a ResultsPruner that represent the default retention policy */ public static ResultsPruner getDefaultPruner() { try { return getPruner(ConfigurationManager.getProperties()); } catch (FileNotFoundException e) { throw new IllegalStateException( "VeryExceptionalException - config file not there! ", e); } } /** * Factory method for ResultsPruners * * @param propsFile * to configure the results pruner. * @return the configured results pruner. * @throws FileNotFoundException * it the configuration file cannot be found. */ public static ResultsPruner getPruner(String propsFile) throws FileNotFoundException { Properties props = new Properties(); FileInputStream fin = null; try { fin = new FileInputStream(propsFile); props.load(fin); return getPruner(props); } catch (IOException e) { throw new IllegalStateException("Problem loading properties file: " + e.getMessage(), e); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { LOG.warn(e); } } } } /** * Factory method for ResultsPruners (used to load ConfigurationManager * properties. * * @param props * @return * @throws FileNotFoundException */ public static ResultsPruner getPruner(Properties props) throws FileNotFoundException { ResultsPruner rp = new ResultsPruner(); Pattern retentionPattern = Pattern .compile("checker\\.retention\\.(.*)"); for (Enumeration<String> en = (Enumeration<String>)props.propertyNames(); en.hasMoreElements();) { String name = en.nextElement(); Matcher matcher = retentionPattern.matcher(name); if (!matcher.matches()) { continue; } String resultCode = matcher.group(1); long duration; try { duration = Utils.parseDuration(props.getProperty(name)); } catch (ParseException e) { throw new IllegalStateException("Problem parsing duration: " + e.getMessage(), e); } if ("default".equals(resultCode)) { rp.setDefaultDuration(duration); } else { rp.addInterested(resultCode, duration); } } return rp; } /** Ten years */ private long defaultDuration = 31536000000L; /** * Map of retention durations, keyed by result code name */ Map<String, Long> interests = new HashMap<String, Long>(); /** * Checksum results database Data access */ private ChecksumResultDAO checksumResultDAO = null; /** * Checksum history database data access. */ private ChecksumHistoryDAO checksumHistoryDAO = null; /** * Default Constructor */ public ResultsPruner() { checksumResultDAO = new ChecksumResultDAO(); checksumHistoryDAO = new ChecksumHistoryDAO(); } /** * Add a result and the length of time before the history with this type of * result is removed from the database. * * @param result * code in the database. * * @param duration * before bitstreams with the specified result type in the * checksum history is removed. */ public void addInterested(String result, long duration) { interests.put(result, Long.valueOf(duration)); } /** * Add a result and the length of time before it is removed from the * checksum history table. * * @param result * code in the database. * * @param duration * before bitstreams with the specified result type in the * checksum history is removed. * * @throws ParseException * if the duration cannot be parsed into a long value. */ public void addInterested(String result, String duration) throws ParseException { addInterested(result, Utils.parseDuration(duration)); } /** * The default amount of time before a result is removed. * * @return the default duration. */ public long getDefaultDuration() { return defaultDuration; } /** * Prunes the results retaining results as configured by the interests * registered with this object. * * @return number of results removed. */ public int prune() { List<String> codes = checksumResultDAO.listAllCodes(); for (String code : codes) { if (!interests.containsKey(code)) { interests.put(code, Long.valueOf(defaultDuration)); } } return checksumHistoryDAO.prune(interests); } /** * The default duration before records are removed from the checksum history * table. * * @param defaultDuration * used before records are removed from the checksum history. */ public void setDefaultDuration(long defaultDuration) { this.defaultDuration = defaultDuration; } }
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.checker; /** * <p> * BitstreamDispatchers are strategy objects that hand bitstream ids out to * workers. Implementations must be threadsafe. * </p> * * <p> * The rationale behind the use of the Sentinel pattern (rather than the more * traditional iterator pattern or a cursor c.f. java.sql.ResultSet): - * </p> * <ol> * <li>To make it easy to make implementations thread safe - multithreaded * invocation of the dispatchers is seen as a next step use case. In simple * terms, this requires that a single method does all the work.</li> * <li>Shouldn't an exception as the sentinel, as reaching the end of a loop is * not an exceptional condition.</li> * </ol> * * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public interface BitstreamDispatcher { /** * This value should be returned by <code>next()</code> to indicate that * there are no more values. */ public static int SENTINEL = -1; /** * Returns the next id for checking, or a sentinel value if there are no * more to check. * * @return the next bitstream id, or BitstreamDispatcher.SENTINEL if there * isn't another value * */ public int next(); }
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.checker; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; import org.dspace.storage.rdbms.DatabaseManager; /** * This class will report information on the checksum checker process. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * */ public class ReporterDAO extends DAOSupport { /** * Select the most recent bitstream information for a given date range with * the specified status. This select is from the checksum history and * checksum results tables. */ public static final String DATE_RANGE_BITSTREAMS = "select bitstream_id, last_process_start_date, last_process_end_date, " + "expected_checksum, current_checksum, result_description " + "from most_recent_checksum, checksum_results " + "where most_recent_checksum.result = checksum_results.result_code " + "and most_recent_checksum.result= ? " + "and most_recent_checksum.last_process_start_date >= ? " + "and most_recent_checksum.last_process_start_date < ? " + "order by bitstream_id"; /** * * Find all bitstreams that were set to not be processed for the specified * date range. * */ public static final String DATE_RANGE_NOT_PROCESSED_BITSTREAMS = "select most_recent_checksum.bitstream_id, " + "most_recent_checksum.last_process_start_date, most_recent_checksum.last_process_end_date, " + "most_recent_checksum.expected_checksum, most_recent_checksum.current_checksum, " + "result_description " + "from checksum_results, most_recent_checksum " + "where most_recent_checksum.to_be_processed = false " + "and most_recent_checksum.result = checksum_results.result_code " + "and most_recent_checksum.last_process_start_date >= ? " + "and most_recent_checksum.last_process_start_date < ? " + "order by most_recent_checksum.bitstream_id"; public static final String DATE_RANGE_NOT_PROCESSED_BITSTREAMS_ORACLE = "select most_recent_checksum.bitstream_id, " + "most_recent_checksum.last_process_start_date, most_recent_checksum.last_process_end_date, " + "most_recent_checksum.expected_checksum, most_recent_checksum.current_checksum, " + "result_description " + "from checksum_results, most_recent_checksum " + "where most_recent_checksum.to_be_processed = 0 " + "and most_recent_checksum.result = checksum_results.result_code " + "and most_recent_checksum.last_process_start_date >= ? " + "and most_recent_checksum.last_process_start_date < ? " + "order by most_recent_checksum.bitstream_id"; /** * Find all bitstreams that the checksum checker is unaware of */ public static final String FIND_UNKNOWN_BITSTREAMS = "select bitstream.deleted, bitstream.store_number, bitstream.size_bytes, " + "bitstreamformatregistry.short_description, bitstream.bitstream_id, " + "bitstream.user_format_description, bitstream.internal_id, " + "bitstream.source, bitstream.checksum_algorithm, bitstream.checksum, " + "bitstream.name, bitstream.description " + "from bitstream left outer join bitstreamformatregistry on " + "bitstream.bitstream_format_id = bitstreamformatregistry.bitstream_format_id " + "where not exists( select 'x' from most_recent_checksum " + "where most_recent_checksum.bitstream_id = bitstream.bitstream_id )"; /** * Usual Log4J Logger. */ private static final Logger LOG = Logger.getLogger(ReporterDAO.class); /** * Default constructor */ public ReporterDAO() { } /** * Select the most recent bitstream for a given date range with the * specified status. * * @param startDate * the start date range * @param endDate * the end date range. * @param resultCode * the result code * * @return a list of BitstreamHistoryInfo objects */ public List<ChecksumHistory> getBitstreamResultTypeReport(Date startDate, Date endDate, String resultCode) { List<ChecksumHistory> bitstreamHistory = new LinkedList<ChecksumHistory>(); Connection conn = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { // create the connection and execute the statement conn = DatabaseManager.getConnection(); prepStmt = conn.prepareStatement(DATE_RANGE_BITSTREAMS); prepStmt.setString(1, resultCode); prepStmt.setDate(2, new java.sql.Date(startDate.getTime())); prepStmt.setDate(3, new java.sql.Date(endDate.getTime())); rs = prepStmt.executeQuery(); // add the bitstream history objects while (rs.next()) { bitstreamHistory.add(new ChecksumHistory(rs .getInt("bitstream_id"), rs .getTimestamp("last_process_start_date"), rs .getTimestamp("last_process_end_date"), rs .getString("expected_checksum"), rs .getString("current_checksum"), rs .getString("result_description"))); } } catch (SQLException e) { LOG.warn("Bitstream history could not be found for specified type " + e.getMessage(), e); } finally { cleanup(prepStmt, conn, rs); } return bitstreamHistory; } /** * Find all bitstreams that were set to not be processed for the specified * date range. * * @param startDate * the start of the date range * @param endDate * the end of the date range * @return a list of BitstreamHistoryInfo objects */ public List<ChecksumHistory> getNotProcessedBitstreamsReport(Date startDate, Date endDate) { List<ChecksumHistory> bitstreamHistory = new LinkedList<ChecksumHistory>(); Connection conn = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { // create the connection and execute the statement conn = DatabaseManager.getConnection(); if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { prepStmt = conn.prepareStatement(DATE_RANGE_NOT_PROCESSED_BITSTREAMS_ORACLE); } else { prepStmt = conn.prepareStatement(DATE_RANGE_NOT_PROCESSED_BITSTREAMS); } prepStmt.setDate(1, new java.sql.Date(startDate.getTime())); prepStmt.setDate(2, new java.sql.Date(endDate.getTime())); rs = prepStmt.executeQuery(); // add the bitstream history objects while (rs.next()) { bitstreamHistory.add(new ChecksumHistory(rs .getInt("bitstream_id"), rs .getTimestamp("last_process_start_date"), rs .getTimestamp("last_process_end_date"), rs .getString("expected_checksum"), rs .getString("current_checksum"), rs .getString("result_description"))); } } catch (SQLException e) { LOG.warn("Bitstream history could not be found for specified type " + e.getMessage(), e); } finally { cleanup(prepStmt, conn, rs); } return bitstreamHistory; } /** * Find all bitstreams that the checksum checker is currently not aware of * * @return a List of DSpaceBitstreamInfo objects */ public List<DSpaceBitstreamInfo> getUnknownBitstreams() { List<DSpaceBitstreamInfo> unknownBitstreams = new LinkedList<DSpaceBitstreamInfo>(); Connection conn = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { // create the connection and execute the statement conn = DatabaseManager.getConnection(); prepStmt = conn.prepareStatement(FIND_UNKNOWN_BITSTREAMS); rs = prepStmt.executeQuery(); // add the bitstream history objects while (rs.next()) { unknownBitstreams.add(new DSpaceBitstreamInfo(rs .getBoolean("deleted"), rs.getInt("store_number"), rs .getInt("size_bytes"), rs .getString("short_description"), rs .getInt("bitstream_id"), rs .getString("user_format_description"), rs .getString("internal_id"), rs.getString("source"), rs .getString("checksum_algorithm"), rs .getString("checksum"), rs.getString("name"), rs .getString("description"))); } } catch (SQLException e) { LOG.warn("Bitstream history could not be found for specified type " + e.getMessage(), e); } finally { cleanup(prepStmt, conn, rs); } return unknownBitstreams; } }
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.checker; import java.util.Date; /** * <p> * Represents a history record for the bitstream. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class ChecksumHistory { /** Unique bitstream id. */ private int bitstreamId; /** Date the process started. */ private Date processStartDate; /** Date the process ended. */ private Date processEndDate; /** The expected checksum. */ private String checksumExpected; /** The checksum calculated. */ private String checksumCalculated; /** The string result. */ private String result; public ChecksumHistory() { } /** * Minimal Constructor. * * @param bitstreamId * bitstream id in the database */ public ChecksumHistory(int bitstreamId) { this.bitstreamId = bitstreamId; } /** * * Full history info Constructor. * * @param bitstrmId * bitstream Id. * @param startDate * process start date * @param endDate * process end date * @param checksumExpted * expected checksum * @param checksumCalc * calculated checksum * @param inResult * result information */ public ChecksumHistory(int bitstrmId, Date startDate, Date endDate, String checksumExpted, String checksumCalc, String inResult) { this.bitstreamId = bitstrmId; this.processStartDate = (startDate == null ? null : new Date(startDate.getTime())); this.processEndDate = (endDate == null ? null : new Date(endDate.getTime())); this.checksumExpected = checksumExpted; this.checksumCalculated = checksumCalc; this.result = inResult; } /** * @return Returns the bitstreamId. */ public int getBitstreamId() { return bitstreamId; } /** * @return Returns the checksumCalculated. */ public String getChecksumCalculated() { return checksumCalculated; } /** * Set the checksum calculated. * * @param checksumCalculated * The checksumCalculated to set. */ public void setChecksumCalculated(String checksumCalculated) { this.checksumCalculated = checksumCalculated; } /** * Get the extpected checksum. * * @return Returns the checksumExpected. */ public String getChecksumExpected() { return checksumExpected; } /** * Set the expected checksum. * * @param checksumExpected * The checksumExpected to set. */ public void setChecksumExpected(String checksumExpected) { this.checksumExpected = checksumExpected; } /** * Get the process end date. This is the date and time the processing ended. * * @return Returns the processEndDate. */ public Date getProcessEndDate() { return processEndDate == null ? null : new Date(processEndDate.getTime()); } /** * Set the process end date. This is the date and time the processing ended. * * @param processEndDate * The processEndDate to set. */ public void setProcessEndDate(Date processEndDate) { this.processEndDate = (processEndDate == null ? null : new Date(processEndDate.getTime())); } /** * Get the process start date. This is the date and time the processing * started. * * @return Returns the processStartDate. */ public Date getProcessStartDate() { return processStartDate == null ? null : new Date(processStartDate.getTime()); } /** * Set the process start date. This is the date and time the processing * started. * * @param processStartDate * The processStartDate to set. */ public void setProcessStartDate(Date processStartDate) { this.processStartDate = (processStartDate == null ? null : new Date(processStartDate.getTime())); } /** * Return the processing result. * * @return */ public String getResult() { return result; } /** * Set the checksum processing result. * * @param result * The result to set. */ public void setResult(String result) { this.result = 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.checker; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.dspace.content.DSpaceObject; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.handle.HandleManager; /** * A BitstreamDispatcher that checks all the bitstreams contained within an * item, collection or community referred to by Handle. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class HandleDispatcher implements BitstreamDispatcher { /** Log 4j logger. */ private static final Logger LOG = Logger.getLogger(HandleDispatcher.class); /** Handle to retrieve bitstreams from. */ private String handle = null; /** Has the type of object the handle refers to been determined. */ private boolean init = false; /** the delegate to dispatch to. */ private ListDispatcher delegate = null; /** * Database access for retrieving bitstreams */ BitstreamInfoDAO bitstreamInfoDAO; /** * Blanked off, no-op constructor. */ private HandleDispatcher() { } /** * Main constructor. * * @param hdl * the handle to get bitstreams from. */ public HandleDispatcher(BitstreamInfoDAO bitInfoDAO, String hdl) { bitstreamInfoDAO = bitInfoDAO; handle = hdl; } /** * Private initialization routine. * * @throws SQLException * if database access fails. */ private synchronized void init() { if (!init) { Context context = null; int dsoType = -1; int id = -1; try { context = new Context(); DSpaceObject dso = HandleManager.resolveToObject(context, handle); id = dso.getID(); dsoType = dso.getType(); context.abort(); } catch (SQLException e) { LOG.error("init error " + e.getMessage(), e); throw new IllegalStateException("init error" + e.getMessage(), e); } finally { // Abort the context if it's still valid if ((context != null) && context.isValid()) { context.abort(); } } List<Integer> ids = new ArrayList<Integer>(); switch (dsoType) { case Constants.BITSTREAM: ids.add(Integer.valueOf(id)); break; case Constants.ITEM: ids = bitstreamInfoDAO.getItemBitstreams(id); break; case Constants.COLLECTION: ids = bitstreamInfoDAO.getCollectionBitstreams(id); break; case Constants.COMMUNITY: ids = bitstreamInfoDAO.getCommunityBitstreams(id); break; } delegate = new ListDispatcher(ids); init = true; } } /** * Initializes this dispatcher on first execution. * * @see org.dspace.checker.BitstreamDispatcher#next() */ public int next() { if (!init) { init(); } return delegate.next(); } }
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.checker; /** * Enumeration of ChecksumCheckResults containing constants for checksum * comparison result that must correspond to values in checksum_result table. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * * @todo Refactor these as properties of ChecksumChecker? */ public class ChecksumCheckResults { /** * Bitstream not found result. */ public static final String BITSTREAM_NOT_FOUND = "BITSTREAM_NOT_FOUND"; /** * BitstreamInfo not found result. */ public static final String BITSTREAM_INFO_NOT_FOUND = "BITSTREAM_INFO_NOT_FOUND"; /** * Bitstream not to be processed result. */ public static final String BITSTREAM_NOT_PROCESSED = "BITSTREAM_NOT_PROCESSED"; /** * Bitstream marked as deleted result. */ public static final String BITSTREAM_MARKED_DELETED = "BITSTREAM_MARKED_DELETED"; /** * Bitstream tallies with recorded checksum result. */ public static final String CHECKSUM_MATCH = "CHECKSUM_MATCH"; /** * Bitstream digest does not tally with recorded checksum result. */ public static final String CHECKSUM_NO_MATCH = "CHECKSUM_NO_MATCH"; /** * Previous checksum result not found. */ public static final String CHECKSUM_PREV_NOT_FOUND = "CHECKSUM_PREV_NOT_FOUND"; /** * No match between requested algorithm and previously used algorithm. */ public static final String CHECKSUM_ALGORITHM_INVALID = "CHECKSUM_ALGORITHM_INVALID"; }
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.checker; /** * Component that receives BitstreamInfo results from a checker. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public interface ChecksumResultsCollector { /** * Collects results. * * @param info * BitstreamInfo representing the check results. */ void collect(BitstreamInfo info); }
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.checker; import org.dspace.core.PluginManager; /** * Decorator that dispatches a specified number of bitstreams from a delegate * dispatcher. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class LimitedCountDispatcher implements BitstreamDispatcher { /** The remaining number of bitstreams to iterate through. */ private int remaining = 1; /** The dispatcher to delegate to for retrieving bitstreams. */ private BitstreamDispatcher delegate = null; /** * Default constructor uses PluginManager */ public LimitedCountDispatcher() { this((BitstreamDispatcher) PluginManager .getSinglePlugin(BitstreamDispatcher.class)); } /** * Constructor. * * @param del * The bitstream distpatcher to delegate to. * @param count * the number of bitstreams to check. */ public LimitedCountDispatcher(BitstreamDispatcher del, int count) { this(del); remaining = count; } /** * Constructor. * * @param del * The bitstream distpatcher to delegate to. */ public LimitedCountDispatcher(BitstreamDispatcher del) { delegate = del; } /** * Retreives the next bitstream to be checked. * * @return the bitstream id * @throws SQLException * if database error occurs. */ public int next() { if (remaining > 0) { remaining--; return delegate.next(); } else { return BitstreamDispatcher.SENTINEL; } } }
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.checker; /** * Value Object that holds bitstream information that will be used for dspace * bitstream. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public final class DSpaceBitstreamInfo { /** database bitstream id. */ private int bitstreamId; /** format */ private String bitstreamFormat; /** name given to the bitstream. */ private String name; /** Stored size of the bitstream. */ private long size; /** the check sum value stored in the database. */ private String storedChecksum; /** checksum algorithm (usually MD5 for now). */ private String checksumAlgorithm; /** Bitstream Format Description */ private String userFormatDescription; /** source name of the file. */ private String source; /** file location in the assetstore. */ private String internalId; /** deleted flag. */ private boolean deleted; /** store number. */ private int storeNumber; /** * Blanked off no-op default constructor. */ private DSpaceBitstreamInfo() { } /** * Minimal constructor. * * @param bid * Bitstream identifier */ public DSpaceBitstreamInfo(int bid) { deleted = false; storeNumber = -1; size = -1; bitstreamFormat = null; userFormatDescription = null; internalId = null; source = null; checksumAlgorithm = null; storedChecksum = null; name = null; this.bitstreamId = bid; } /** * Complete constructor. * * @param del * Deleted * @param storeNo * Bitstream storeNumber * @param sz * Bitstream size * @param bitstrmFmt * Bitstream format * @param bitstrmId * Bitstream id * @param usrFmtDesc * Bitstream format description * @param intrnlId * Bitstream DSpace internal id * @param src * Bitstream source * @param chksumAlgorthm * Algorithm used to check bitstream * @param chksum * Hash digest obtained * @param nm * Name of bitstream * @param desc * Bitstream description */ public DSpaceBitstreamInfo(boolean del, int storeNo, long sz, String bitstrmFmt, int bitstrmId, String usrFmtDesc, String intrnlId, String src, String chksumAlgorthm, String chksum, String nm, String desc) { this.deleted = del; this.storeNumber = storeNo; this.size = sz; this.bitstreamFormat = bitstrmFmt; this.bitstreamId = bitstrmId; this.userFormatDescription = usrFmtDesc; this.internalId = intrnlId; this.source = src; this.checksumAlgorithm = chksumAlgorthm; this.storedChecksum = chksum; this.name = nm; } /** * Get the deleted flag. * * @return boolean */ public boolean getDeleted() { return deleted; } /** * Set the deleted flag. * * @param deleted * deleted flag */ public void setDeleted(boolean deleted) { this.deleted = deleted; } /** * Get the store number. * * @return int */ public int getStoreNumber() { return storeNumber; } /** * Set the store number. * * @param storeNumber * the store number */ public void setStoreNumber(int storeNumber) { this.storeNumber = storeNumber; } /** * Get the size. * * @return int */ public long getSize() { return size; } /** * Set the size. * * @param size * the bitstream size */ public void setSize(long size) { this.size = size; } /** * Get the Bitstream Format id. * * @return int */ public String getBitstreamFormatId() { return bitstreamFormat; } /** * Set the Bitstream Format id. * * @param bitstrmFmt * id of the bitstream format */ public void setBitstreamFormatId(String bitstrmFmt) { this.bitstreamFormat = bitstrmFmt; } /** * Get the Bitstream id. * * @return int */ public int getBitstreamId() { return bitstreamId; } /** * Get the user format description. * * @return String */ public String getUserFormatDescription() { return userFormatDescription; } /** * Set the user format description. * * @param userFormatDescription * the userFormatDescription */ public void setUserFormatDescription(String userFormatDescription) { this.userFormatDescription = userFormatDescription; } /** * Get the Internal Id. * * @return String */ public String getInternalId() { return internalId; } /** * Set the Internal Id. * * @param internalId * the DSpace internal sequence id for the bitstream. */ public void setInternalId(String internalId) { this.internalId = internalId; } /** * Get the source. * * @return String */ public String getSource() { return source; } /** * Set the source. * * @param source * The bitstream source. */ public void setSource(String source) { this.source = source; } /** * Get the checksum algorithm. * * @return String */ public String getChecksumAlgorithm() { return checksumAlgorithm; } /** * Set the checksum algorithm. * * @param checksumAlgorithm * the algorithm used for checking this bitstream */ public void setChecksumAlgorithm(String checksumAlgorithm) { this.checksumAlgorithm = checksumAlgorithm; } /** * Get the checksum. * * @return String */ public String getStoredChecksum() { return storedChecksum; } /** * Set the checksum. * * @param checksum * The last stored checksum for this bitstream. */ public void setStoredChecksum(String checksum) { this.storedChecksum = checksum; } /** * Get the name of the bitstream. * * @return String */ public String getName() { return name; } /** * Set the name of the bitstream. * * @param nm * The name of this bitstream. */ public void getName(String nm) { this.name = nm; } /** * The name of the bitstream. * * @param name * The name to set. */ public void setName(String name) { this.name = name; } /** * Identity entirely dependent upon <code>bitstreamId</code>. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DSpaceBitstreamInfo)) { return false; } DSpaceBitstreamInfo other = (DSpaceBitstreamInfo) o; return (this.bitstreamId == other.bitstreamId); } /** * HashCode method uses <code>bitstreamId</code> as hashing function. * * @see java.lang.Object#hashCode() */ public int hashCode() { return bitstreamId; } /** * Describes this BitstreamInfo. * * @see java.lang.Object#toString() */ public String toString() { return new StringBuffer("DSpace Bitstream Information for id ").append( bitstreamId).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.dspace.checker; import java.util.Date; /** * <p> * Value Object that holds bitstream information that will be used for checksum * processing. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public final class BitstreamInfo { /** deleted flag. */ private boolean deleted; /** dspace bitstream information */ private DSpaceBitstreamInfo dspaceBitstream; /** * Indicates the bitstream info (metadata) was found in the database. * * @todo Is this actually used for anything? */ private boolean infoFound; /** indicates the bitstream was found in the database. */ private boolean bitstreamFound; /** the check sum value calculated by the algorithm. */ private String calculatedChecksum; /** should be processed or not? */ private boolean toBeProcessed; /** checksum comparison result code. */ private String checksumCheckResult; /** Date the object was created for processing. */ private Date processStartDate; /** Date the processing was completed. */ private Date processEndDate; /** * Blanked off no-op default constructor. */ private BitstreamInfo() { } /** * Minimal constructor. * * @param bid * Bitstream identifier */ public BitstreamInfo(int bid) { deleted = false; dspaceBitstream = new DSpaceBitstreamInfo(bid); // set default to true since it's the // case for most bitstreams infoFound = true; bitstreamFound = false; calculatedChecksum = null; processEndDate = null; toBeProcessed = false; processStartDate = new Date(); } /** * Complete constructor. * * @param del * Deleted * @param storeNo * Bitstream storeNumber * @param sz * Bitstream size * @param bitstrmFmt * Bitstream format * @param bitstrmId * Bitstream id * @param usrFmtDesc * Bitstream format description * @param intrnlId * Bitstream DSpace internal id * @param src * Bitstream source * @param chksumAlgorthm * Algorithm used to check bitstream * @param chksum * Hash digest obtained * @param nm * Name of bitstream * @param procEndDate * When the last bitstream check finished. * @param toBeProc * Whether the bitstream will be checked or skipped * @param procStartDate * When the last bitstream check started. */ public BitstreamInfo(boolean del, int storeNo, long sz, String bitstrmFmt, int bitstrmId, String usrFmtDesc, String intrnlId, String src, String chksumAlgorthm, String chksum, String nm, Date procEndDate, boolean toBeProc, Date procStartDate) { dspaceBitstream = new DSpaceBitstreamInfo(del, storeNo, sz, bitstrmFmt, bitstrmId, usrFmtDesc, intrnlId, src, chksumAlgorthm, chksum, nm, ""); this.deleted = del; this.processEndDate = (processEndDate == null ? null : new Date(procEndDate.getTime())); this.toBeProcessed = toBeProc; this.processStartDate = (processStartDate == null ? null : new Date(procStartDate.getTime())); this.infoFound = true; } /** * Get the deleted flag. * * @return true if the bitstream has been deleted */ public boolean getDeleted() { return deleted; } /** * Set the deleted flag. * * @param deleted * deleted flag */ public void setDeleted(boolean deleted) { this.deleted = deleted; } /** * Get the bitstream store number. * * @return int */ public int getStoreNumber() { return dspaceBitstream.getStoreNumber(); } /** * Set the store number. * * @param storeNumber * the store number */ public void setStoreNumber(int storeNumber) { dspaceBitstream.setStoreNumber(storeNumber); } /** * Get the size. * * @return int */ public long getSize() { return dspaceBitstream.getSize(); } /** * Set the size. * * @param size * the bitstream size */ public void setSize(int size) { dspaceBitstream.setSize(size); } /** * Get the Bitstream Format id. * * @return int */ public String getBitstreamFormatId() { return dspaceBitstream.getBitstreamFormatId(); } /** * Set the Bitstream Format id. * * @param bitstrmFmt * id of the bitstream format */ public void setBitstreamFormatId(String bitstrmFmt) { dspaceBitstream.setBitstreamFormatId(bitstrmFmt); } /** * Get the Bitstream id. * * @return int */ public int getBitstreamId() { return dspaceBitstream.getBitstreamId(); } /** * Get the user format description. * * @return String */ public String getUserFormatDescription() { return dspaceBitstream.getUserFormatDescription(); } /** * Set the user format description. * * @param userFormatDescription * the userFormatDescription */ public void setUserFormatDescription(String userFormatDescription) { dspaceBitstream.setUserFormatDescription(userFormatDescription); } /** * Get the Internal Id. * * @return String */ public String getInternalId() { return dspaceBitstream.getInternalId(); } /** * Set the Internal Id. * * @param internalId * the DSpace internal sequence id for the bitstream. */ public void setInternalId(String internalId) { dspaceBitstream.setInternalId(internalId); } /** * Get the source. * * @return String */ public String getSource() { return dspaceBitstream.getSource(); } /** * Set the source. * * @param source * The bitstream source. */ public void setSource(String source) { dspaceBitstream.setSource(source); } /** * Get the checksum algorithm. * * @return String */ public String getChecksumAlgorithm() { return dspaceBitstream.getChecksumAlgorithm(); } /** * Set the checksum algorithm. * * @param checksumAlgorithm * the algorithm used for checking this bitstream */ public void setChecksumAlgorithm(String checksumAlgorithm) { dspaceBitstream.setChecksumAlgorithm(checksumAlgorithm); } /** * Get the checksum. * * @return String */ public String getStoredChecksum() { return dspaceBitstream.getStoredChecksum(); } /** * Set the checksum. * * @param checksum * The last stored checksum for this bitstream. */ public void setStoredChecksum(String checksum) { dspaceBitstream.setStoredChecksum(checksum); } /** * Get the name of the bitstream. * * @return String */ public String getName() { return dspaceBitstream.getName(); } /** * Set the name of the bitstream. * * @param nm * The name of this bitstream. */ public void setName(String nm) { dspaceBitstream.setName(nm); } /** * calculatedChecksum accessor. * * @return Returns the calculatedChecksum. */ public String getCalculatedChecksum() { return calculatedChecksum; } /** * calculatedChecksum accessor. * * @param calculatedChecksum * The calculatedChecksum to set. */ public void setCalculatedChecksum(String calculatedChecksum) { this.calculatedChecksum = calculatedChecksum; } /** * infoFound accessor. * * @return Returns infoFound. */ public boolean getInfoFound() { return this.infoFound; } /** * infoFound accessor. * * @param found * sets infoFound. */ public void setInfoFound(boolean found) { this.infoFound = found; } /** * bitstreamFound accessor. * * @return Returns bitstreamFound. */ public boolean getBitstreamFound() { return this.bitstreamFound; } /** * sets bitstreamFound. * * @param found * value of bitstreamFound to set. */ public void setBitstreamFound(boolean found) { this.bitstreamFound = found; } /** * Identity entirely dependent upon <code>bitstreamId</code>. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BitstreamInfo)) { return false; } BitstreamInfo other = (BitstreamInfo) o; return (this.getBitstreamId() == other.getBitstreamId()); } /** * HashCode method uses <code>bitstreamId</code> as hashing function. * * @see java.lang.Object#hashCode() */ public int hashCode() { return getBitstreamId(); } /** * Describes this BitstreamInfo. * * @see java.lang.Object#toString() */ public String toString() { return new StringBuffer("ChecksumInformation for id ").append( getBitstreamId()).toString(); } /** * Sets toBeProcessed. * * @param toBeProcessed * flag from most_recent_checksum table */ public void setToBeProcessed(boolean toBeProcessed) { this.toBeProcessed = toBeProcessed; } /** * Gets toBeProcessed. * * @return value of toBeProcessed flag (from most_recent_checksum table) */ public boolean getToBeProcessed() { return this.toBeProcessed; } /** * Gets checksumCheckResult. * * @return result code for comparison of previous and current checksums */ public String getChecksumCheckResult() { return this.checksumCheckResult; } /** * Sets checksumCheckResult. * * @param resultCode * for comparison of previous and current checksums */ public void setChecksumCheckResult(String resultCode) { this.checksumCheckResult = resultCode; } /** * The start date and time this bitstream is being processed. * * @return date */ public Date getProcessStartDate() { return this.processStartDate == null ? null : new Date(this.processStartDate.getTime()); } /** * The date and time the processing started for this bitstream. * * @param startDate * date to set. */ public void setProcessStartDate(Date startDate) { this.processStartDate = startDate == null ? null : new Date(startDate.getTime()); } /** * The date and time this bitstream is finished being processed. * * @return date */ public Date getProcessEndDate() { return this.processEndDate == null ? null : new Date(this.processEndDate.getTime()); } /** * The date and time this bitstream is finished being processed. * * @param endDate * the date to set. */ public void setProcessEndDate(Date endDate) { this.processEndDate = endDate == null ? null : new Date(endDate.getTime()); } }
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.checker; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import org.dspace.core.Context; import org.dspace.storage.bitstore.BitstreamStorageManager; /** * <p> * Data Access Object for Bitstreams. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public class BitstreamDAO { /** * Default Constructor */ public BitstreamDAO() { } /** * Retrieves the bitstream from the bitstore. * * @param id * the bitstream id. * * @return Bitstream as an InputStream * * @throws IOException * Rethrown from BitstreamStorageManager * @throws SQLException * Rethrown from BitstreamStorageManager * * @see org.dspace.storage.bitstore.BitstreamStorageManager#retrieve(Context, * int) */ public InputStream getBitstream(int id) throws IOException, SQLException { Context context = null; InputStream is = null; try { context = new Context(); is = BitstreamStorageManager.retrieve(context, id); } finally { context.abort(); } return is; } }
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.checker; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; import org.dspace.storage.rdbms.DatabaseManager; /** * <p> * Database Access Object for bitstream information (metadata). Also performs * the needed insert/update/delete commands on the database for the checksum * checker. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public final class BitstreamInfoDAO extends DAOSupport { /** * This value should be returned by <code>next()</code> to indicate that * there are no more values. */ public static final int SENTINEL = -1; /** Query that gets bitstream information for a specified ID. */ private static final String FIND_BY_BITSTREAM_ID = "select bitstream.deleted, bitstream.store_number, bitstream.size_bytes, " + "bitstreamformatregistry.short_description, bitstream.bitstream_id, " + "bitstream.user_format_description, bitstream.internal_id, " + "bitstream.source, bitstream.checksum_algorithm, bitstream.checksum, " + "bitstream.name, most_recent_checksum.last_process_end_date," + "most_recent_checksum.to_be_processed " + "from bitstream left outer join bitstreamformatregistry on " + "bitstream.bitstream_format_id = bitstreamformatregistry.bitstream_format_id, " + "most_recent_checksum " + "where bitstream.bitstream_id = ? " + "and bitstream.bitstream_id = most_recent_checksum.bitstream_id"; /** * Query that selects bitstream IDs from bitstream table that are not yet in * the most_recent_checksum table, and inserts them into * most_recent_checksum. */ private static final String INSERT_MISSING_CHECKSUM_BITSTREAMS = "insert into most_recent_checksum ( " + "bitstream_id, to_be_processed, expected_checksum, current_checksum, " + "last_process_start_date, last_process_end_date, " + "checksum_algorithm, matched_prev_checksum, result ) " + "select bitstream.bitstream_id, " + "CASE WHEN bitstream.deleted = false THEN true ELSE false END, " + "CASE WHEN bitstream.checksum IS NULL THEN '' ELSE bitstream.checksum END, " + "CASE WHEN bitstream.checksum IS NULL THEN '' ELSE bitstream.checksum END, " + "?, ?, CASE WHEN bitstream.checksum_algorithm IS NULL " + "THEN 'MD5' ELSE bitstream.checksum_algorithm END, true, " + "CASE WHEN bitstream.deleted = true THEN 'BITSTREAM_MARKED_DELETED' else 'CHECKSUM_MATCH' END " + "from bitstream where not exists( " + "select 'x' from most_recent_checksum " + "where most_recent_checksum.bitstream_id = bitstream.bitstream_id )"; private static final String INSERT_MISSING_CHECKSUM_BITSTREAMS_ORACLE = "insert into most_recent_checksum ( " + "bitstream_id, to_be_processed, expected_checksum, current_checksum, " + "last_process_start_date, last_process_end_date, " + "checksum_algorithm, matched_prev_checksum, result ) " + "select bitstream.bitstream_id, " + "CASE WHEN bitstream.deleted = 0 THEN 1 ELSE 0 END, " + "CASE WHEN bitstream.checksum IS NULL THEN '' ELSE bitstream.checksum END, " + "CASE WHEN bitstream.checksum IS NULL THEN '' ELSE bitstream.checksum END, " + "? AS last_process_start_date, ? AS last_process_end_date, CASE WHEN bitstream.checksum_algorithm IS NULL " + "THEN 'MD5' ELSE bitstream.checksum_algorithm END, 1, " + "CASE WHEN bitstream.deleted = 1 THEN 'BITSTREAM_MARKED_DELETED' else 'CHECKSUM_MATCH' END " + "from bitstream where not exists( " + "select 'x' from most_recent_checksum " + "where most_recent_checksum.bitstream_id = bitstream.bitstream_id )"; /** * Query that updates most_recent_checksum table with checksum result for * specified bitstream ID. */ private static final String UPDATE_CHECKSUM = "UPDATE most_recent_checksum " + "SET current_checksum = ?, expected_checksum = ?, matched_prev_checksum = ?, to_be_processed= ?, " + "last_process_start_date=?, last_process_end_date=?, result=? WHERE bitstream_id = ? "; /** * Deletes from the most_recent_checksum where the bitstream id is found */ private static final String DELETE_BITSTREAM_INFO = "Delete from most_recent_checksum " + "where bitstream_id = ?"; /** * This selects the next bitstream in order of last processing end date. The * timestamp is truncated to milliseconds this is because the Date for java * does not support nanoseconds and milliseconds were considered accurate * enough */ public static final String GET_OLDEST_BITSTREAM = "select bitstream_id " + "from most_recent_checksum " + "where to_be_processed = true " + "order by date_trunc('milliseconds', last_process_end_date), " + "bitstream_id " + "ASC LIMIT 1"; public static final String GET_OLDEST_BITSTREAM_ORACLE = "SELECT bitstream_id FROM (select bitstream_id " + "from most_recent_checksum " + "where to_be_processed = 1 " + "order by trunc(last_process_end_date, 'mi'), " + "bitstream_id " + "ASC) WHERE rownum=1"; /** * Selects the next bitstream in order of last processing end date, ensuring * that no bitstream is checked more than once since the date parameter * used. */ public static final String GET_OLDEST_BITSTREAM_DATE = "select bitstream_id " + "from most_recent_checksum " + "where to_be_processed = true " + "and last_process_start_date < ? " + "order by date_trunc('milliseconds', last_process_end_date), " + "bitstream_id " + "ASC LIMIT 1"; public static final String GET_OLDEST_BITSTREAM_DATE_ORACLE = "SELECT bitstream_id FROM (select bitstream_id " + "from most_recent_checksum " + "where to_be_processed = 1 " + "and last_process_start_date < ? " + "order by trunc(last_process_end_date, 'mi'), " + "bitstream_id " + "ASC) WHERE rownum=1"; /** SQL query to retrieve bitstreams for a given item. */ private static final String ITEM_BITSTREAMS = "SELECT b2b.bitstream_id " + "FROM bundle2bitstream b2b, item2bundle i2b WHERE " + "b2b.bundle_id=i2b.bundle_id AND i2b.item_id=?"; /** SQL query to retrieve bitstreams for a given collection. */ private static final String COLLECTION_BITSTREAMS = "SELECT b2b.bitstream_id " + "FROM bundle2bitstream b2b, item2bundle i2b, collection2item c2i WHERE " + "b2b.bundle_id=i2b.bundle_id AND c2i.item_id=i2b.item_id AND c2i.collection_id=?"; /** SQL query to retrieve bitstreams for a given community. */ private static final String COMMUNITY_BITSTREAMS = "SELECT b2b.bitstream_id FROM bundle2bitstream b2b, item2bundle i2b, collection2item c2i, community2collection c2c WHERE b2b.bundle_id=i2b.bundle_id AND c2i.item_id=i2b.item_id AND c2c.collection_id=c2i.collection_id AND c2c.community_id=?"; /** Standard Log4J logger. */ private static final Logger LOG = Logger.getLogger(BitstreamInfoDAO.class); /** * History data access object for checksum_history table */ private ChecksumHistoryDAO checksumHistoryDAO; /** * Default constructor */ public BitstreamInfoDAO() { checksumHistoryDAO = new ChecksumHistoryDAO(); } /** * Updates most_recent_checksum with latest checksum and result of * comparison with previous checksum. * * @param info * The BitstreamInfo to update. * * @throws IllegalArgumentException * if the BitstreamInfo given is null. */ public void update(BitstreamInfo info) { if (info == null) { throw new IllegalArgumentException( "BitstreamInfo parameter may not be null"); } Connection conn = null; PreparedStatement stmt = null; try { conn = DatabaseManager.getConnection(); stmt = conn.prepareStatement(UPDATE_CHECKSUM); stmt.setString(1, (info.getCalculatedChecksum() != null) ? info .getCalculatedChecksum() : ""); stmt.setString(2, info.getStoredChecksum()); stmt.setBoolean(3, ChecksumCheckResults.CHECKSUM_MATCH.equals(info .getChecksumCheckResult())); stmt.setBoolean(4, info.getToBeProcessed()); stmt.setTimestamp(5, new Timestamp(info.getProcessStartDate() .getTime())); stmt.setTimestamp(6, new Timestamp(info.getProcessEndDate() .getTime())); stmt.setString(7, info.getChecksumCheckResult()); stmt.setInt(8, info.getBitstreamId()); stmt.executeUpdate(); conn.commit(); } catch (SQLException e) { LOG.error("Problem updating checksum row. " + e.getMessage(), e); throw new IllegalStateException("Problem updating checksum row. " + e.getMessage(), e); } finally { cleanup(stmt, conn); } } /** * Find a bitstream by its id. * * @param id * the bitstream id * * @return the bitstream information needed for checksum validation. Returns * null if bitstream info isn't found. */ public BitstreamInfo findByBitstreamId(int id) { Connection conn = null; BitstreamInfo info = null; PreparedStatement prepStmt = null; try { // create the connection and execute the statement conn = DatabaseManager.getConnection(); prepStmt = conn.prepareStatement(FIND_BY_BITSTREAM_ID); prepStmt.setInt(1, id); ResultSet rs = prepStmt.executeQuery(); // if the bitstream is found return it if (rs.next()) { info = new BitstreamInfo(rs.getBoolean("deleted"), rs .getInt("store_number"), rs.getLong("size_bytes"), rs .getString("short_description"), rs .getInt("bitstream_id"), rs .getString("user_format_description"), rs .getString("internal_id"), rs.getString("source"), rs .getString("checksum_algorithm"), rs .getString("checksum"), rs.getString("name"), rs .getTimestamp("last_process_end_date"), rs .getBoolean("to_be_processed"), new Date()); } } catch (SQLException e) { LOG.warn("Bitstream metadata could not be retrieved. " + e.getMessage(), e); } finally { cleanup(prepStmt, conn); } return info; } /** * Queries the bitstream table for bitstream IDs that are not yet in the * most_recent_checksum table, and inserts them into the * most_recent_checksum and checksum_history tables. */ public void updateMissingBitstreams() { Connection conn = null; PreparedStatement stmt = null; try { LOG.debug("updating missing bitstreams"); conn = DatabaseManager.getConnection(); if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { stmt = conn.prepareStatement(INSERT_MISSING_CHECKSUM_BITSTREAMS_ORACLE); } else { stmt = conn.prepareStatement(INSERT_MISSING_CHECKSUM_BITSTREAMS); } stmt.setTimestamp(1, new java.sql.Timestamp(new Date().getTime())); stmt.setTimestamp(2, new java.sql.Timestamp(new Date().getTime())); stmt.executeUpdate(); checksumHistoryDAO.updateMissingBitstreams(conn); conn.commit(); } catch (SQLException e) { LOG.error("Problem inserting missing bitstreams. " + e.getMessage(), e); throw new IllegalStateException("Problem inserting missing bitstreams. " + e.getMessage(), e); } finally { cleanup(stmt, conn); } } /** * Deletes the bitstream from the most_recent_checksum table if it exist. * * @param id * the bitstream id. * * @return number of records deleted */ protected int deleteBitstreamInfo(int id, Connection conn) { PreparedStatement stmt = null; int numDeleted = 0; try { stmt = conn.prepareStatement(DELETE_BITSTREAM_INFO); stmt.setInt(1, id); numDeleted = stmt.executeUpdate(); if (numDeleted > 1) { conn.rollback(); throw new IllegalStateException( "Too many rows deleted! Number of rows deleted: " + numDeleted + " only one row should be deleted for bitstream id " + id); } } catch (SQLException e) { LOG.error("Problem deleting bitstream. " + e.getMessage(), e); throw new IllegalStateException("Problem deleting bitstream. " + e.getMessage(), e); } finally { cleanup(stmt); } return numDeleted; } public int deleteBitstreamInfoWithHistory(int id) { Connection conn = null; int numDeleted = 0; try { conn = DatabaseManager.getConnection(); deleteBitstreamInfo(id, conn); checksumHistoryDAO.deleteHistoryForBitstreamInfo(id, conn); conn.commit(); } catch (SQLException e) { LOG.error("Problem deleting bitstream. " + e.getMessage(), e); throw new IllegalStateException("Problem deleting bitstream. " + e.getMessage(), e); } finally { cleanup(conn); } return numDeleted; } /** * Get the oldest bitstream in the most recent checksum table. If more than * one found the first one in the result set is returned. * * @return the bitstream id or -1 if the no bitstreams are found * */ public int getOldestBitstream() { Connection conn = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { conn = DatabaseManager.getConnection(); if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { prepStmt = conn.prepareStatement(GET_OLDEST_BITSTREAM_ORACLE); } else { prepStmt = conn.prepareStatement(GET_OLDEST_BITSTREAM); } rs = prepStmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } else { return SENTINEL; } } catch (SQLException e) { LOG.error("Problem with get oldest bitstream " + e.getMessage(), e); throw new IllegalStateException("Oldest bitstream error. " + e.getMessage(), e); } finally { cleanup(prepStmt, conn); } } /** * Returns the oldest bistream that in the set of bitstreams that are less * than the specified date. If no bitstreams are found -1 is returned. * * @param lessThanDate * @return id of olded bitstream or -1 if not bistreams are found */ public int getOldestBitstream(Timestamp lessThanDate) { Connection conn = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { conn = DatabaseManager.getConnection(); if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { prepStmt = conn.prepareStatement(GET_OLDEST_BITSTREAM_DATE_ORACLE); } else { prepStmt = conn.prepareStatement(GET_OLDEST_BITSTREAM_DATE); } prepStmt.setTimestamp(1, lessThanDate); rs = prepStmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } else { return SENTINEL; } } catch (SQLException e) { LOG.error("get oldest bitstream less than date " + e.getMessage(), e); throw new IllegalStateException("get oldest bitstream less than date. " + e.getMessage(), e); } finally { cleanup(prepStmt, conn); } } /** * Get the bitstream ids for a given Item * * @param itemId * @return the list of bitstream ids for this item */ public List<Integer> getItemBitstreams(int itemId) { List<Integer> ids = new ArrayList<Integer>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = DatabaseManager.getConnection(); ps = conn.prepareStatement(ITEM_BITSTREAMS); ps.setInt(1, itemId); rs = ps.executeQuery(); while (rs.next()) { ids.add(Integer.valueOf(rs.getInt(1))); } } catch (SQLException e) { LOG.error("get item bitstreams " + e.getMessage(), e); throw new IllegalStateException("get item bitstreams. " + e.getMessage(), e); } finally { cleanup(ps, conn, rs); } return ids; } /** * Get the bitstream ids for a given collection * * @param collectionId The id of the collection * @return the list of bitstream ids for this item */ public List<Integer> getCollectionBitstreams(int collectionId) { List<Integer> ids = new ArrayList<Integer>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = DatabaseManager.getConnection(); ps = conn.prepareStatement(COLLECTION_BITSTREAMS); ps.setInt(1, collectionId); rs = ps.executeQuery(); while (rs.next()) { ids.add(Integer.valueOf(rs.getInt(1))); } } catch (SQLException e) { LOG.error("get item bitstreams " + e.getMessage(), e); throw new IllegalStateException("get item bitstreams. " + e.getMessage(), e); } finally { cleanup(ps, conn, rs); } return ids; } /** * Get the bitstream ids for a given community * * @param communityId the community id * @return the list of bitstream ids for this item */ public List<Integer> getCommunityBitstreams(int communityId) { List<Integer> ids = new ArrayList<Integer>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = DatabaseManager.getConnection(); ps = conn.prepareStatement(COMMUNITY_BITSTREAMS); ps.setInt(1, communityId); rs = ps.executeQuery(); while (rs.next()) { ids.add(Integer.valueOf(rs.getInt(1))); } } catch (SQLException e) { LOG.error("get item bitstreams " + e.getMessage(), e); throw new IllegalStateException("get item bitstreams. " + e.getMessage(), e); } finally { cleanup(ps, conn, rs); } return ids; } }
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.checker; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.dspace.storage.rdbms.DatabaseManager; /** * <p> * Database Access for the checksum results information. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * */ public final class ChecksumResultDAO extends DAOSupport { /** * Find a specified description. */ private static final String FIND_CHECK_STRING = "select result_description " + "from checksum_results where result_code = ?"; /** * Usual Log4J Logger. */ private static final Logger LOG = Logger.getLogger(ChecksumResultDAO.class); /** * Default constructor */ public ChecksumResultDAO() { } /** * Get the result description for the given result code * * @param code * to get the description for. * @return the found description. */ public String getChecksumCheckStr(String code) { String description = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DatabaseManager.getConnection(); stmt = conn.prepareStatement(FIND_CHECK_STRING); stmt.setString(1, code); rs = stmt.executeQuery(); if (rs.next()) { description = rs.getString(1); } } catch (SQLException e) { LOG.error("Problem selecting checker result description. " + e.getMessage(), e); throw new IllegalStateException("selecting checker result description. " + e.getMessage(), e); } finally { cleanup(stmt, conn, rs); } return description; } /** * Get a list of all the possible result codes. * * @return a list of all the result codes */ public List<String> listAllCodes() { Connection conn = null; Statement stmt = null; ResultSet rs = null; List<String> codes = new ArrayList<String>(); try { conn = DatabaseManager.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT result_code FROM checksum_results"); while (rs.next()) { String code = rs.getString("result_code"); codes.add(code); } return codes; } catch (SQLException e) { LOG.error("Problem listing checksum results codes: " + e.getMessage(), e); throw new IllegalStateException("Problem listing checksum results codes: " + e.getMessage(), e); } finally { cleanup(stmt, conn, rs); } } }
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.checker; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import org.dspace.core.I18nUtil; /** * * Simple Reporter implementation. * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * @todo estimate string buffer sizes. */ public class SimpleReporterImpl implements SimpleReporter { /** The reporter access object to be used. */ private ReporterDAO reporter = null; private String msg(String key) { return I18nUtil.getMessage("org.dspace.checker.SimpleReporterImpl." + key); } /** * Main Constructor. */ public SimpleReporterImpl() { this.reporter = new ReporterDAO(); } /** * Sends the Deleted bitstream report to an administrator. for the * specified date range. * * @param startDate * the start date for the range * @param endDate * the end date for the range * @param osw * the output stream writer to write to. * * @return number of bitstreams found * * @throws IOException * if io error occurs */ public int getDeletedBitstreamReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException { // get all the bitstreams marked deleted for today List<ChecksumHistory> history = reporter.getBitstreamResultTypeReport(startDate, endDate, ChecksumCheckResults.BITSTREAM_MARKED_DELETED); osw.write("\n"); osw.write(msg("deleted-bitstream-intro")); osw.write(applyDateFormatShort(startDate)); osw.write(" "); osw.write(msg("date-range-to")); osw.write(" "); osw.write(applyDateFormatShort(endDate)); osw.write("\n\n\n"); if (history.size() == 0) { osw.write("\n\n"); osw.write(msg("no-bitstreams-to-delete")); osw.write("\n"); } else { printHistoryRecords(history, osw); } return history.size(); } /** * Send the checksum changed report for the specified date range. * * @param startDate * the start date for the range * @param endDate * the end date for the range * @param osw * the output stream writer to write to. * * @return number of bitstreams found * * @throws IOException * if io error occurs */ public int getChangedChecksumReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException { // get all the bitstreams marked deleted for today List<ChecksumHistory> history = reporter.getBitstreamResultTypeReport(startDate, endDate, ChecksumCheckResults.CHECKSUM_NO_MATCH); osw.write("\n"); osw.write(msg("checksum-did-not-match")); osw.write(" "); osw.write("\n"); osw.write(applyDateFormatShort(startDate)); osw.write(" "); osw.write(msg("date-range-to")); osw.write(" "); osw.write(applyDateFormatShort(endDate)); osw.write("\n\n\n"); if (history.size() == 0) { osw.write("\n\n"); osw.write(msg("no-changed-bitstreams")); osw.write("\n"); } else { printHistoryRecords(history, osw); } return history.size(); } /** * Send the bitstream not found report for the specified date range. * * @param startDate * the start date for the range. * @param endDate * the end date for the range. * @param osw * the output stream writer to write to. * * @return number of bitstreams found * * @throws IOException * if io error occurs */ public int getBitstreamNotFoundReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException { // get all the bitstreams marked deleted for today List<ChecksumHistory> history = reporter.getBitstreamResultTypeReport(startDate, endDate, ChecksumCheckResults.BITSTREAM_NOT_FOUND); osw.write("\n"); osw.write(msg("bitstream-not-found-report")); osw.write(applyDateFormatShort(startDate)); osw.write(" "); osw.write(msg("date-range-to")); osw.write(" "); osw.write(applyDateFormatShort(endDate)); osw.write("\n\n\n"); if (history.size() == 0) { osw.write("\n\n"); osw.write(msg("no-bitstreams-changed")); osw.write("\n"); } else { printHistoryRecords(history, osw); } return history.size(); } /** * Send the bitstreams that were set to not be processed report for the * specified date range. * * @param startDate * the start date for the range * @param endDate * the end date for the range * @param osw * the output stream writer to write to. * * @return number of bitstreams found * * @throws IOException * if io error occurs */ public int getNotToBeProcessedReport(Date startDate, Date endDate, OutputStreamWriter osw) throws IOException { // get all the bitstreams marked deleted for today List<ChecksumHistory> history = reporter.getNotProcessedBitstreamsReport(startDate, endDate); osw.write("\n"); osw.write(msg("bitstream-will-no-longer-be-processed")); osw.write(" "); osw.write(applyDateFormatShort(startDate)); osw.write(" "); osw.write(msg("date-range-to")); osw.write(" "); osw.write(applyDateFormatShort(endDate)); osw.write("\n\n\n"); if (history.size() == 0) { osw.write("\n\n"); osw.write(msg("no-bitstreams-to-no-longer-be-processed")); osw.write("\n"); } else { printHistoryRecords(history, osw); } return history.size(); } /** * Get any bitstreams that are not checked by the checksum checker. * * @param osw * the OutputStreamWriter to write to * * @return the number of unchecked bitstreams * * @throws IOException * if io error occurs */ public int getUncheckedBitstreamsReport(OutputStreamWriter osw) throws IOException { // get all the bitstreams marked deleted for today List<DSpaceBitstreamInfo> bitstreams = reporter.getUnknownBitstreams(); osw.write("\n"); osw.write(msg("unchecked-bitstream-report")); osw.write(applyDateFormatShort(new Date())); osw.write("\n\n\n"); if (bitstreams.size() == 0) { osw.write("\n\n"); osw.write(msg("no-unchecked-bitstreams")); osw.write("\n"); } else { osw.write(msg("howto-add-unchecked-bitstreams")); osw.write("\n\n\n"); this.printDSpaceInfoRecords(bitstreams, osw); } return bitstreams.size(); } /** * Create a list of the found history records. * * @param history * the list of history records to be iterated over. * @param osw * the output stream writer to write to. * * @throws IOException * if io error occurs */ private void printHistoryRecords(List<ChecksumHistory> history, OutputStreamWriter osw) throws IOException { Iterator<ChecksumHistory> iter = history.iterator(); while (iter.hasNext()) { ChecksumHistory historyInfo = iter.next(); StringBuffer buf = new StringBuffer(1000); buf.append("------------------------------------------------ \n"); buf.append(msg("bitstream-id")).append(" = ").append( historyInfo.getBitstreamId()).append("\n"); buf.append(msg("process-start-date")).append(" = ").append( applyDateFormatLong(historyInfo.getProcessStartDate())) .append("\n"); buf.append(msg("process-end-date")).append(" = ").append( applyDateFormatLong(historyInfo.getProcessEndDate())) .append("\n"); buf.append(msg("checksum-expected")).append(" = ").append( historyInfo.getChecksumExpected()).append("\n"); buf.append(msg("checksum-calculated")).append(" = ").append( historyInfo.getChecksumCalculated()).append("\n"); buf.append(msg("result")).append(" = ").append( historyInfo.getResult()).append("\n"); buf.append("----------------------------------------------- \n\n"); osw.write(buf.toString()); } } /** * Create a list of the found history records. * * @param bitstreams * the list of history records to be iterated over. * @param osw * the output stream to write to. * * @throws IOException * if io error occurs */ private void printDSpaceInfoRecords(List<DSpaceBitstreamInfo> bitstreams, OutputStreamWriter osw) throws IOException { Iterator<DSpaceBitstreamInfo> iter = bitstreams.iterator(); while (iter.hasNext()) { DSpaceBitstreamInfo info = iter.next(); StringBuffer buf = new StringBuffer(1000); buf.append("------------------------------------------------ \n"); buf.append(msg("format-id")).append(" = ").append( info.getBitstreamFormatId()).append("\n"); buf.append(msg("deleted")).append(" = ").append(info.getDeleted()) .append("\n"); buf.append(msg("bitstream-id")).append(" = ").append( info.getBitstreamId()).append("\n"); buf.append(msg("checksum-algorithm")).append(" = ").append( info.getChecksumAlgorithm()).append("\n"); buf.append(msg("internal-id")).append(" = ").append( info.getInternalId()).append("\n"); buf.append(msg("name")).append(" = ").append(info.getName()) .append("\n"); buf.append(msg("size")).append(" = ").append(info.getSize()) .append("\n"); buf.append(msg("source")).append(" = ").append(info.getSource()) .append("\n"); buf.append(msg("checksum")).append(" = ").append( info.getStoredChecksum()).append("\n"); buf.append(msg("store-number")).append(" = ").append( info.getStoreNumber()).append("\n"); buf.append(msg("description")).append(" = ").append( info.getUserFormatDescription()).append("\n"); buf.append("----------------------------------------------- \n\n"); osw.write(buf.toString()); } } private String applyDateFormatLong(Date thisDate) { return DateFormat.getDateInstance(DateFormat.MEDIUM).format(thisDate); } private String applyDateFormatShort(Date thisDate) { return DateFormat.getDateInstance(DateFormat.SHORT).format(thisDate); } }
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.checker; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import java.util.Map; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; import org.dspace.storage.rdbms.DatabaseManager; /** * <p> * This is the data access for the checksum history information. All * update,insert and delete database operations should go through this class for * checksum history operations. * </p> * * @author Jim Downing * @author Grace Carpenter * @author Nathan Sarr * * */ public class ChecksumHistoryDAO extends DAOSupport { /** * Query that selects bitstream IDs from most_recent_checksum table that are * not yet in the checksum_history table, and inserts them into * checksum_history. */ private static final String INSERT_MISSING_HISTORY_BITSTREAMS = "insert into checksum_history ( " + "bitstream_id, process_start_date, " + "process_end_date, checksum_expected, " + "checksum_calculated, result ) " + "select most_recent_checksum.bitstream_id, " + "most_recent_checksum.last_process_start_date, " + "most_recent_checksum.last_process_end_date, " + "most_recent_checksum.expected_checksum, most_recent_checksum.expected_checksum, " + "CASE WHEN bitstream.deleted = true THEN 'BITSTREAM_MARKED_DELETED' else 'CHECKSUM_MATCH' END " + "from most_recent_checksum, bitstream where " + "not exists( select 'x' from checksum_history where " + "most_recent_checksum.bitstream_id = checksum_history.bitstream_id ) " + "and most_recent_checksum.bitstream_id = bitstream.bitstream_id"; private static final String INSERT_MISSING_HISTORY_BITSTREAMS_ORACLE = "insert into checksum_history ( " + "check_id, bitstream_id, process_start_date, " + "process_end_date, checksum_expected, " + "checksum_calculated, result ) " + "select checksum_history_seq.nextval, most_recent_checksum.bitstream_id, " + "most_recent_checksum.last_process_start_date, " + "most_recent_checksum.last_process_end_date, " + "most_recent_checksum.expected_checksum, most_recent_checksum.expected_checksum, " + "CASE WHEN bitstream.deleted = 1 THEN 'BITSTREAM_MARKED_DELETED' else 'CHECKSUM_MATCH' END " + "from most_recent_checksum, bitstream where " + "not exists( select 'x' from checksum_history where " + "most_recent_checksum.bitstream_id = checksum_history.bitstream_id ) " + "and most_recent_checksum.bitstream_id = bitstream.bitstream_id"; /** Query that inserts results of recent check into the history table. */ private static final String INSERT_HISTORY = "insert into checksum_history ( bitstream_id, process_start_date, " + " process_end_date, checksum_expected, checksum_calculated, result ) " + " values ( ?, ?, ?, ?, ?, ?)"; private static final String INSERT_HISTORY_ORACLE = "insert into checksum_history ( check_id, bitstream_id, process_start_date, " + " process_end_date, checksum_expected, checksum_calculated, result ) " + " values ( checksum_history_seq.nextval, ?, ?, ?, ?, ?, ?)"; /** * Deletes from the most_recent_checksum where the bitstream id is found */ private static final String DELETE_BITSTREAM_HISTORY = "Delete from checksum_history " + "where bitstream_id = ?"; /** * Logger for the checksum history DAO. */ private static final Logger LOG = Logger .getLogger(ChecksumHistoryDAO.class); /** * Inserts results of checksum check into checksum_history table for a given * bitstream. * * @param info * the BitstreamInfo representing a checksum check. * * @throws IllegalArgumentException * if the <code>BitstreamInfo</code> is null. */ public void insertHistory(BitstreamInfo info) { if (info == null) { throw new IllegalArgumentException( "BitstreamInfo parameter may not be null"); } Connection conn = null; PreparedStatement stmt = null; try { conn = DatabaseManager.getConnection(); if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { stmt = conn.prepareStatement(INSERT_HISTORY_ORACLE); } else { stmt = conn.prepareStatement(INSERT_HISTORY); } stmt.setInt(1, info.getBitstreamId()); stmt.setTimestamp(2, new java.sql.Timestamp(info.getProcessStartDate().getTime())); stmt.setTimestamp(3, new java.sql.Timestamp(info.getProcessEndDate().getTime())); stmt.setString(4, info.getStoredChecksum()); stmt.setString(5, info.getCalculatedChecksum()); stmt.setString(6, info.getChecksumCheckResult()); stmt.executeUpdate(); conn.commit(); } catch (SQLException e) { LOG.error("Problem updating checksum row. " + e.getMessage(), e); throw new IllegalStateException("Problem updating checksum row. " + e.getMessage(), e); } finally { cleanup(stmt, conn); } } /** * Deletes the bitstream from the bitstream_history table if it exist. * * @param id * the bitstream id. * * @return number of records deleted */ protected int deleteHistoryForBitstreamInfo(int id, Connection conn) { PreparedStatement stmt = null; int numDeleted = 0; try { conn = DatabaseManager.getConnection(); stmt = conn.prepareStatement(DELETE_BITSTREAM_HISTORY); stmt.setInt(1, id); numDeleted = stmt.executeUpdate(); conn.commit(); } catch (SQLException e) { LOG.error("Problem with inserting missing bitstream. " + e.getMessage(), e); throw new IllegalStateException("Problem inserting missing bitstream. " + e.getMessage(), e); } finally { cleanup(stmt, conn); } return numDeleted; } /** * @param conn */ protected void updateMissingBitstreams(Connection conn) throws SQLException { PreparedStatement stmt = null; try { if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { stmt = conn.prepareStatement(INSERT_MISSING_HISTORY_BITSTREAMS_ORACLE); } else { stmt = conn.prepareStatement(INSERT_MISSING_HISTORY_BITSTREAMS); } stmt.executeUpdate(); } catch (SQLException e) { LOG.error("Problem updating missing history. " + e.getMessage(), e); throw new IllegalStateException("Problem updating missing history. " + e.getMessage(), e); } finally { cleanup(stmt); } } /** * Delete the history records from the database. * * @param retentionDate * any records older than this data are deleted. * @param result * result code records must have for them to be deleted. * @param conn * database connection. * @return number of records deleted. * @throws SQLException * if database error occurs. */ protected int deleteHistoryByDateAndCode(Date retentionDate, String result, Connection conn) throws SQLException { PreparedStatement update = null; try { update = conn.prepareStatement("DELETE FROM checksum_history WHERE process_end_date<? AND result=?"); update.setTimestamp(1, new Timestamp(retentionDate.getTime())); update.setString(2, result); return update.executeUpdate(); } finally { cleanup(update); } } /** * Prune the history records from the database. * * @param interests * set of results and the duration of time before they are * removed from the database * * @return number of bitstreams deleted */ public int prune(Map<String, Long> interests) { Connection conn = null; try { conn = DatabaseManager.getConnection(); long now = System.currentTimeMillis(); int count = 0; for (Map.Entry<String, Long> interest : interests.entrySet()) { count += deleteHistoryByDateAndCode(new Date(now - interest.getValue().longValue()), interest.getKey(), conn); conn.commit(); } return count; } catch (SQLException e) { LOG.error("Problem pruning results: " + e.getMessage(), e); throw new IllegalStateException("Problem pruning results: " + e.getMessage(), e); } finally { DatabaseManager.freeConnection(conn); } } }
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.browse; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.*; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.handle.HandleManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Entity class to represent an item that is being used to generate Browse * results. This behaves in many was similar to the Item object, but its * metadata handling has been further optimised for performance in both * reading and writing, and it does not deal with other objects related to * items * * FIXME: this class violates some of the encapsulation of the Item, but there is * unfortunately no way around this until DAOs and an interface are provided * for the Item class. * * @author Richard Jones * */ public class BrowseItem extends DSpaceObject { /** Logger */ private static Logger log = Logger.getLogger(BrowseItem.class); /** DSpace context */ private Context context; /** a List of all the metadata */ private List<DCValue> metadata = new ArrayList<DCValue>(); /** database id of the item */ private int id = -1; /** is the item in the archive */ private boolean in_archive = true; /** is the item withdrawn */ private boolean withdrawn = false; /** item handle */ private String handle = null; /** * Construct a new browse item with the given context and the database id * * @param context the DSpace context * @param id the database id of the item * @param in_archive * @param withdrawn */ public BrowseItem(Context context, int id, boolean in_archive, boolean withdrawn) { this.context = context; this.id = id; this.in_archive = in_archive; this.withdrawn = withdrawn; } /** * Get String array of metadata values matching the given parameters * * @param schema metadata schema * @param element metadata element * @param qualifier metadata qualifier * @param lang metadata language * @return array of matching values * @throws SQLException */ public DCValue[] getMetadata(String schema, String element, String qualifier, String lang) throws SQLException { try { BrowseItemDAO dao = BrowseDAOFactory.getItemInstance(context); // if the qualifier is a wildcard, we have to get it out of the // database if (Item.ANY.equals(qualifier)) { return dao.queryMetadata(id, schema, element, qualifier, lang); } if (!metadata.isEmpty()) { List<DCValue> values = new ArrayList<DCValue>(); Iterator<DCValue> i = metadata.iterator(); while (i.hasNext()) { DCValue dcv = i.next(); if (match(schema, element, qualifier, lang, dcv)) { values.add(dcv); } } if (values.isEmpty()) { DCValue[] dcvs = dao.queryMetadata(id, schema, element, qualifier, lang); if (dcvs != null) { Collections.addAll(metadata, dcvs); } return dcvs; } // else, Create an array of matching values DCValue[] valueArray = new DCValue[values.size()]; valueArray = (DCValue[]) values.toArray(valueArray); return valueArray; } else { DCValue[] dcvs = dao.queryMetadata(id, schema, element, qualifier, lang); if (dcvs != null) { Collections.addAll(metadata, dcvs); } return dcvs; } } catch (BrowseException be) { log.error("caught exception: ", be); return null; } } /** * Get the type of object. This object masquerades as an Item, so this * returns the value of Constants.ITEM * *@return Constants.ITEM */ public int getType() { return Constants.ITEM; } /** * @deprecated * @param real * @return */ public int getType(boolean real) { if (!real) { return Constants.ITEM; } else { return getType(); } } /** * get the database id of the item * * @return database id of item */ public int getID() { return id; } /** * Set the database id of the item * * @param id the database id of the item */ public void setID(int id) { this.id = id; } /** * Utility method for pattern-matching metadata elements. This * method will return <code>true</code> if the given schema, * element, qualifier and language match the schema, element, * qualifier and language of the <code>DCValue</code> object passed * in. Any or all of the element, qualifier and language passed * in can be the <code>Item.ANY</code> wildcard. * * @param schema * the schema for the metadata field. <em>Must</em> match * the <code>name</code> of an existing metadata schema. * @param element * the element to match, or <code>Item.ANY</code> * @param qualifier * the qualifier to match, or <code>Item.ANY</code> * @param language * the language to match, or <code>Item.ANY</code> * @param dcv * the Dublin Core value * @return <code>true</code> if there is a match */ private boolean match(String schema, String element, String qualifier, String language, DCValue dcv) { // We will attempt to disprove a match - if we can't we have a match if (!element.equals(Item.ANY) && !element.equals(dcv.element)) { // Elements do not match, no wildcard return false; } if (qualifier == null) { // Value must be unqualified if (dcv.qualifier != null) { // Value is qualified, so no match return false; } } else if (!qualifier.equals(Item.ANY)) { // Not a wildcard, so qualifier must match exactly if (!qualifier.equals(dcv.qualifier)) { return false; } } if (language == null) { // Value must be null language to match if (dcv.language != null) { // Value is qualified, so no match return false; } } else if (!language.equals(Item.ANY)) { // Not a wildcard, so language must match exactly if (!language.equals(dcv.language)) { return false; } } else if (!schema.equals(Item.ANY)) { if (dcv.schema != null && !dcv.schema.equals(schema)) { // The namespace doesn't match return false; } } // If we get this far, we have a match return true; } /* (non-Javadoc) * @see org.dspace.content.DSpaceObject#getHandle() */ public String getHandle() { // Get our Handle if any if (this.handle == null) { try { this.handle = HandleManager.findHandle(context, this); } catch (SQLException e) { log.error("caught exception: ", e); } } return this.handle; } /** * Get a thumbnail object out of the item. * * Warning: using this method actually instantiates an Item, which has a * corresponding performance hit on the database during browse listing * rendering. That's your own fault for wanting to put images on your * browse page! * * @return * @throws SQLException */ public Thumbnail getThumbnail() throws SQLException { // instantiate an item for this one. Not nice. Item item = Item.find(context, id); if (item == null) { return null; } // now go sort out the thumbnail // if there's no original, there is no thumbnail Bundle[] original = item.getBundles("ORIGINAL"); if (original.length == 0) { return null; } // if multiple bitstreams, check if the primary one is HTML boolean html = false; if (original[0].getBitstreams().length > 1) { Bitstream[] bitstreams = original[0].getBitstreams(); for (int i = 0; (i < bitstreams.length) && !html; i++) { if (bitstreams[i].getID() == original[0].getPrimaryBitstreamID()) { html = bitstreams[i].getFormat().getMIMEType().equals("text/html"); } } } // now actually pull out the thumbnail (ouch!) Bundle[] thumbs = item.getBundles("THUMBNAIL"); // if there are thumbs and we're not dealing with an HTML item // then show the thumbnail if ((thumbs.length > 0) && !html) { Bitstream thumbnailBitstream; Bitstream originalBitstream; if ((original[0].getBitstreams().length > 1) && (original[0].getPrimaryBitstreamID() > -1)) { originalBitstream = Bitstream.find(context, original[0].getPrimaryBitstreamID()); thumbnailBitstream = thumbs[0].getBitstreamByName(originalBitstream.getName() + ".jpg"); } else { originalBitstream = original[0].getBitstreams()[0]; thumbnailBitstream = thumbs[0].getBitstreams()[0]; } if ((thumbnailBitstream != null) && (AuthorizeManager.authorizeActionBoolean(context, thumbnailBitstream, Constants.READ))) { return new Thumbnail(thumbnailBitstream, originalBitstream); } } return null; } public String getName() { // FIXME: there is an exception handling problem here try { DCValue t[] = getMetadata("dc", "title", null, Item.ANY); return (t.length >= 1) ? t[0].value : null; } catch (SQLException sqle) { log.error("caught exception: ", sqle); return null; } } public boolean isArchived() { return in_archive; } public boolean isWithdrawn() { return withdrawn; } }
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.browse; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.dspace.core.Context; import org.dspace.core.ConfigurationManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * This class implements the BrowseCreateDAO interface for the Oracle database * as associated with the default DSpace installation. This class should not be * instantiated directly, but should be obtained via the BrowseDAOFactory: * * <code> * Context context = new Context(); * BrowseCreateDAO dao = BrowseDAOFactory.getCreateInstance(context); * </code> * * This class will then be loaded if the appropriate configuration is made. * * @author Graham Triggs */ public class BrowseCreateDAOOracle implements BrowseCreateDAO { /** Log4j logger */ private static Logger log = Logger.getLogger(BrowseCreateDAOOracle.class); /** * internal copy of the current DSpace context (including the database * connection) */ private Context context; /** Database specific set of utils used when prepping the database */ private BrowseDAOUtils utils; /** * Required constructor for classes implementing the BrowseCreateDAO * interface. Takes a DSpace context to use to connect to the database with. * * @param context * the DSpace context */ public BrowseCreateDAOOracle(Context context) throws BrowseException { this.context = context; // obtain the relevant Utils for this class utils = BrowseDAOFactory.getUtils(context); } /* * (non-Javadoc) * * @see org.dspace.browse.BrowseCreateDAO#createCollectionView(java.lang.String, * java.lang.String, boolean) */ public String createCollectionView(String table, String view, boolean execute) throws BrowseException { try { String createColView = "CREATE VIEW " + view + " AS " + "SELECT Collection2Item.collection_id, " + table + ".* " + "FROM " + table + ", Collection2Item " + "WHERE " + table + ".item_id = Collection2Item.item_id"; if (execute) { DatabaseManager.updateQuery(context, createColView); } return createColView + ";"; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createCommunityView(java.lang.String, java.lang.String, boolean) */ public String createCommunityView(String table, String view, boolean execute) throws BrowseException { try { String createComView = "CREATE VIEW " + view + " AS " + "SELECT Communities2Item.community_id, " + table + ".* " + "FROM " + table + ", Communities2Item " + "WHERE " + table + ".item_id = Communities2Item.item_id"; if (execute) { DatabaseManager.updateQuery(context, createComView); } return createComView + ";"; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDatabaseIndices(java.lang.String, boolean) */ public String[] createDatabaseIndices(String table, List<Integer> sortCols, boolean value, boolean execute) throws BrowseException { try { ArrayList<String> array = new ArrayList<String>(); array.add("CREATE INDEX " + table + "_item_id_idx ON " + table + "(item_id)"); if (value) { array.add("CREATE INDEX " + table + "_value_idx ON " + table + "(sort_value)"); } for (Integer i : sortCols) { array.add("CREATE INDEX " + table + "_s" + i + "_idx ON " + table + "(sort_" + i + ")"); } if (execute) { for (String query : array) { DatabaseManager.updateQuery(context, query); } } String[] arr = new String[array.size()]; return array.toArray(arr); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDatabaseIndices(java.lang.String, boolean) */ public String[] createMapIndices(String disTable, String mapTable, boolean execute) throws BrowseException { try { String[] arr = new String[5]; arr[0] = "CREATE INDEX " + disTable + "_svalue_idx ON " + disTable + "(sort_value)"; arr[1] = "CREATE INDEX " + disTable + "_value_idx ON " + disTable + "(value)"; arr[2] = "CREATE INDEX " + disTable + "_uvalue_idx ON " + disTable + "(UPPER(value))"; arr[3] = "CREATE INDEX " + mapTable + "_item_id_idx ON " + mapTable + "(item_id)"; arr[4] = "CREATE INDEX " + mapTable + "_dist_idx ON " + mapTable + "(distinct_id)"; if (execute) { for (String query : arr) { DatabaseManager.updateQuery(context, query); } } return arr; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDistinctMap(java.lang.String, java.lang.String, boolean) */ public String createDistinctMap(String table, String map, boolean execute) throws BrowseException { try { String create = "CREATE TABLE " + map + " (" + "map_id NUMBER PRIMARY KEY, " + "item_id NUMBER REFERENCES item(item_id), " + "distinct_id NUMBER REFERENCES " + table + "(id)" + ")"; if (execute) { DatabaseManager.updateQuery(context, create); } return create + ";"; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#updateDistinctMapping(java.lang.String, int, int) */ public MappingResults updateDistinctMappings(String table, int itemID, Set<Integer> distinctIDs) throws BrowseException { BrowseMappingResults results = new BrowseMappingResults(); try { Set<Integer> addDistinctIDs = null; // Find all existing mappings for this item TableRowIterator tri = DatabaseManager.queryTable(context, table, "SELECT * FROM " + table + " WHERE item_id=?", itemID); if (tri != null) { addDistinctIDs = (Set<Integer>)((HashSet<Integer>)distinctIDs).clone(); try { while (tri.hasNext()) { TableRow tr = tri.next(); // Check the item mappings to see if it contains this mapping boolean itemIsMapped = false; int trDistinctID = tr.getIntColumn("distinct_id"); if (distinctIDs.contains(trDistinctID)) { // Found this mapping results.addRetainedDistinctId(trDistinctID); // Flag it, and remove (-1) from the item mappings itemIsMapped = true; addDistinctIDs.remove(trDistinctID); } // The item is no longer mapped to this community, so remove the database record if (!itemIsMapped) { results.addRemovedDistinctId(trDistinctID); DatabaseManager.delete(context, tr); } } } finally { tri.close(); } } else { addDistinctIDs = distinctIDs; } // Any remaining mappings need to be added to the database for (int distinctID : addDistinctIDs) { if (distinctID > -1) { TableRow row = DatabaseManager.row(table); row.setColumn("item_id", itemID); row.setColumn("distinct_id", distinctID); DatabaseManager.insert(context, row); results.addAddedDistinctId(distinctID); } } } catch (SQLException e) { log.error("caught exception: ", e); String msg = "problem updating distinct mappings: table=" + table + ",item-id=" + itemID; throw new BrowseException(msg, e); } return results; } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDistinctTable(java.lang.String, boolean) */ public String createDistinctTable(String table, boolean execute) throws BrowseException { try { String create = "CREATE TABLE " + table + " (" + "id INTEGER PRIMARY KEY, " + "authority VARCHAR2(100), " + "value " + getValueColumnDefinition() + ", " + "sort_value " + getSortColumnDefinition() + ")"; if (execute) { DatabaseManager.updateQuery(context, create); } return create + ";"; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } public String createPrimaryTable(String table, List<Integer> sortCols, boolean execute) throws BrowseException { try { StringBuffer sb = new StringBuffer(); Iterator itr = sortCols.iterator(); while (itr.hasNext()) { Integer no = (Integer) itr.next(); sb.append(", sort_"); sb.append(no.toString()); sb.append(getSortColumnDefinition()); } String createTable = "CREATE TABLE " + table + " (" + "id INTEGER PRIMARY KEY," + "item_id INTEGER REFERENCES item(item_id)" + sb.toString() + ")"; if (execute) { DatabaseManager.updateQuery(context, createTable); } return createTable; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createSequence(java.lang.String, boolean) */ public String createSequence(String sequence, boolean execute) throws BrowseException { try { String create = "CREATE SEQUENCE " + sequence; if (execute) { DatabaseManager.updateQuery(context, create); } return create + ";"; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#deleteByItemID(java.lang.String, int) */ public void deleteByItemID(String table, int itemID) throws BrowseException { try { Object[] params = { Integer.valueOf(itemID) }; String dquery = "DELETE FROM " + table + " WHERE item_id=?"; DatabaseManager.updateQuery(context, dquery, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#deleteCommunityMappings(java.lang.String, int) */ public void deleteCommunityMappings(int itemID) throws BrowseException { try { Object[] params = { Integer.valueOf(itemID) }; String dquery = "DELETE FROM Communities2Item WHERE item_id = ?"; DatabaseManager.updateQuery(context, dquery, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#dropIndexAndRelated(java.lang.String, boolean) */ public String dropIndexAndRelated(String table, boolean execute) throws BrowseException { try { String dropper = "DROP TABLE " + table + " CASCADE CONSTRAINTS"; if (execute) { DatabaseManager.updateQuery(context, dropper); } return dropper + ";"; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#dropSequence(java.lang.String, boolean) */ public String dropSequence(String sequence, boolean execute) throws BrowseException { try { String dropSeq = "DROP SEQUENCE " + sequence; if (execute) { DatabaseManager.updateQuery(context, dropSeq); } return dropSeq + ";"; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#dropView(java.lang.String, boolean) */ public String dropView(String view, boolean execute) throws BrowseException { if (view != null && !"".equals(view)) { try { String dropView = "DROP VIEW " + view + " CASCADE CONSTRAINTS"; if (execute) { DatabaseManager.updateQuery(context, dropView); } return dropView + ";"; } catch (SQLException e) { log.error("caught exception: ", e); // We can't guarantee a test for existence, or force Oracle // not to complain if it isn't there, so we just catch the exception // and pretend nothing is wrong } } return ""; } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#getDistinctID(java.lang.String, java.lang.String, java.lang.String) */ public int getDistinctID(String table, String value, String authority, String sortValue) throws BrowseException { TableRowIterator tri = null; if (log.isDebugEnabled()) { log.debug("getDistinctID: table=" + table + ",value=" + value + ",authority=" + authority + ",sortValue=" + sortValue); } try { Object[] params; String select = "SELECT id FROM " + table; if (ConfigurationManager.getBooleanProperty("webui.browse.metadata.case-insensitive", false)) { if (isValueColumnClob()) { select = select + " WHERE UPPER(TO_CHAR(value))=UPPER(?)"; } else { select = select + " WHERE UPPER(value)=UPPER(?)"; } } else { if (isValueColumnClob()) { select = select + " WHERE TO_CHAR(value)=?"; } else { select = select + " WHERE value=?"; } } if (authority != null) { select += " AND authority = ?"; params = new Object[]{ value, authority }; } else { select += " AND authority IS NULL"; params = new Object[]{ value }; } tri = DatabaseManager.query(context, select, params); int distinctID = -1; if (!tri.hasNext()) { distinctID = insertDistinctRecord(table, value, authority, sortValue); } else { distinctID = tri.next().getIntColumn("id"); } if (log.isDebugEnabled()) { log.debug("getDistinctID: return=" + distinctID); } return distinctID; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#updateCommunityMappings(int) */ public void updateCommunityMappings(int itemID) throws BrowseException { try { // Get all the communities for this item int[] commID = getAllCommunityIDs(itemID); // Remove (set to -1) any duplicate communities for (int i = 0; i < commID.length; i++) { if (!isFirstOccurrence(commID, i)) { commID[i] = -1; } } // Find all existing mappings for this item TableRowIterator tri = DatabaseManager.queryTable(context, "Communities2Item", "SELECT * FROM Communities2Item WHERE item_id=?", itemID); if (tri != null) { try { while (tri.hasNext()) { TableRow tr = tri.next(); // Check the item mappings to see if it contains this community mapping boolean itemIsMapped = false; int trCommID = tr.getIntColumn("community_id"); for (int i = 0; i < commID.length; i++) { // Found this community if (commID[i] == trCommID) { // Flag it, and remove (-1) from the item mappings itemIsMapped = true; commID[i] = -1; } } // The item is no longer mapped to this community, so remove the database record if (!itemIsMapped) { DatabaseManager.delete(context, tr); } } } finally { tri.close(); } } // Any remaining mappings need to be added to the database for (int i = 0; i < commID.length; i++) { if (commID[i] > -1) { TableRow row = DatabaseManager.row("Communities2Item"); row.setColumn("item_id", itemID); row.setColumn("community_id", commID[i]); DatabaseManager.insert(context, row); } } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#insertDistinctRecord(java.lang.String, java.lang.String, java.lang.String) */ public int insertDistinctRecord(String table, String value, String authority, String sortValue) throws BrowseException { if (log.isDebugEnabled()) { log.debug("insertDistinctRecord: table=" + table + ",value=" + value+ ",sortValue=" + sortValue); } try { TableRow dr = DatabaseManager.row(table); dr.setColumn("value", utils.truncateValue(value)); dr.setColumn("sort_value", utils.truncateSortValue(sortValue)); if (authority != null) { dr.setColumn("authority", utils.truncateValue(authority,100)); } DatabaseManager.insert(context, dr); int distinctID = dr.getIntColumn("id"); log.debug("insertDistinctRecord: return=" + distinctID); return distinctID; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } public void insertIndex(String table, int itemID, Map<Integer, String> sortCols) throws BrowseException { try { // create us a row in the index TableRow row = DatabaseManager.row(table); // set the primary information for the index row.setColumn("item_id", itemID); // now set the columns for the other sort values for (Map.Entry<Integer, String> sortCol : sortCols.entrySet()) { row.setColumn("sort_" + sortCol.getKey().toString(), utils.truncateSortValue(sortCol.getValue())); } DatabaseManager.insert(context, row); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#updateIndex(java.lang.String, int, java.util.Map) */ public boolean updateIndex(String table, int itemID, Map<Integer, String> sortCols) throws BrowseException { try { boolean rowUpdated = false; TableRow row = DatabaseManager.findByUnique(context, table, "item_id", itemID); // If the item does not exist in the table, return that it couldn't be found if (row == null) { return false; } // Iterate through all the sort values for (Map.Entry<Integer, String> sortCol : sortCols.entrySet()) { // Generate the appropriate column name String column = "sort_" + sortCol.getKey().toString(); // Create the value that will be written in to the column String newValue = utils.truncateSortValue( sortCol.getValue() ); // Check the column exists - if it doesn't, something has gone seriously wrong if (!row.hasColumn(column)) { throw new BrowseException("Column '" + column + "' does not exist in table " + table); } // Get the existing value from the column String oldValue = row.getStringColumn(column); // If the new value differs from the old value, update the column and flag that the row has changed if (oldValue != null && !oldValue.equals(newValue)) { row.setColumn(column, newValue); rowUpdated = true; } else if (newValue != null && !newValue.equals(oldValue)) { row.setColumn(column, newValue); rowUpdated = true; } } // We've updated the row, so save it back to the database if (rowUpdated) { DatabaseManager.update(context, row); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } // Return that the original record was found return true; } public List<Integer> deleteMappingsByItemID(String mapTable, int itemID) throws BrowseException { List<Integer> distinctIds = new ArrayList<Integer>(); TableRowIterator tri = null; try { tri = DatabaseManager.queryTable(context, mapTable, "SELECT * FROM " + mapTable + " WHERE item_id=?", itemID); if (tri != null) { while (tri.hasNext()) { TableRow tr = tri.next(); distinctIds.add(tr.getIntColumn("distinct_id")); DatabaseManager.delete(context, tr); } } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } return distinctIds; } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#pruneDistinct(java.lang.String, java.lang.String) */ public void pruneDistinct(String table, String map, List<Integer> distinctIds) throws BrowseException { try { StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(table).append(" WHERE NOT EXISTS (SELECT 1 FROM "); query.append(map).append(" WHERE ").append(map).append(".distinct_id = ").append(table).append(".id)"); if (distinctIds != null && distinctIds.size() > 0) { query.append(" AND ").append(table).append(".id=?"); PreparedStatement stmt = null; try { stmt = context.getDBConnection().prepareStatement(query.toString()); for (Integer distinctId : distinctIds) { stmt.setInt(1, distinctId); stmt.execute(); stmt.clearParameters(); } } finally { if (stmt != null) { stmt.close(); } } } else { DatabaseManager.updateQuery(context, query.toString()); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#pruneExcess(java.lang.String, boolean) */ public void pruneExcess(String table, boolean withdrawn) throws BrowseException { try { StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(table).append(" WHERE NOT EXISTS (SELECT 1 FROM item WHERE item.item_id="); query.append(table).append(".item_id AND "); if (withdrawn) { query.append("item.withdrawn = 1"); } else { query.append("item.in_archive = 1 AND item.withdrawn = 0"); } query.append(")"); DatabaseManager.updateQuery(context, query.toString()); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#pruneMapExcess(java.lang.String, boolean) */ public void pruneMapExcess(String map, boolean withdrawn, List<Integer> distinctIds) throws BrowseException { try { StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(map).append(" WHERE NOT EXISTS (SELECT 1 FROM item WHERE item.item_id="); query.append(map).append(".item_id AND "); if (withdrawn) { query.append("item.withdrawn = 1"); } else { query.append("item.in_archive = 1 AND item.withdrawn = 0"); } query.append(")"); if (distinctIds != null && distinctIds.size() > 0) { query.append(" AND ").append(map).append(".distinct_id=?"); PreparedStatement stmt = null; try { stmt = context.getDBConnection().prepareStatement(query.toString()); for (Integer distinctId : distinctIds) { stmt.setInt(1, distinctId); stmt.execute(); stmt.clearParameters(); } } finally { if (stmt != null) { stmt.close(); } } } else { DatabaseManager.updateQuery(context, query.toString()); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#testTableExistence(java.lang.String) */ public boolean testTableExistence(String table) throws BrowseException { // this method can kill the db connection, so we start up // our own private context to do it Context c = null; try { c = new Context(); String testQuery = "SELECT * FROM " + table + " WHERE ROWNUM=1"; DatabaseManager.query(c, testQuery); return true; } catch (SQLException e) { return false; } finally { if (c != null) { c.abort(); } } } /** * Get the definition of the value column - CLOB if the size is greater than 4000 bytes * otherwise a VARCHAR2. * * @return */ private String getValueColumnDefinition() { if (getValueColumnMaxBytes() < 1 || getValueColumnMaxBytes() > 4000) { return " CLOB "; } return " VARCHAR2(" + getValueColumnMaxBytes() + ") "; } /** * Get the definition of the sort_value column - always a VARCHAR2 * (required for ordering) * * @return */ private String getSortColumnDefinition() { return " VARCHAR2(" + getSortColumnMaxBytes() + ") "; } /** * Get the size in bytes of the value columns. * * As the size is configured in chars, double the number of bytes * (to account for UTF-8) * * @return */ private int getValueColumnMaxBytes() { int chars = utils.getValueColumnMaxChars(); if (chars > 2000 || chars < 1) { return 4000; } return chars * 2; } /** * Get the size in bytes of the sort columns. * MUST return a value between 1 and 4000. * * As the size is configured in chars, double the number of bytes * (to account for UTF-8) * * @return */ private int getSortColumnMaxBytes() { int chars = utils.getSortColumnMaxChars(); if (chars > 2000 || chars < 1) { return 4000; } return chars * 2; } /** * If getValueColumnDefinition() is returning a CLOB definition, * then this must return true. * * @return */ private boolean isValueColumnClob() { if (getValueColumnMaxBytes() < 1) { return true; } return false; } /** * perform a database query to get all the communities that this item belongs to, * including all mapped communities, and ancestors * * this is done here instead of using the Item api, because for reindexing we may * not have Item objects, and in any case this is *much* faster * * @param itemId * @return * @throws SQLException */ private int[] getAllCommunityIDs(int itemId) throws SQLException { List<Integer> commIdList = new ArrayList<Integer>(); TableRowIterator tri = null; try { tri = DatabaseManager.queryTable(context, "Community2Item", "SELECT * FROM Community2Item WHERE item_id=?", itemId); while (tri.hasNext()) { TableRow row = tri.next(); int commId = row.getIntColumn("community_id"); commIdList.add(commId); // Get the parent community, and continue to get all ancestors Integer parentId = getParentCommunityID(commId); while (parentId != null) { commIdList.add(parentId); parentId = getParentCommunityID(parentId); } } } finally { if (tri != null) { tri.close(); } } // Need to iterate the array as toArray will produce an array Integers, // not ints as we need. int[] cIds = new int[commIdList.size()]; for (int i = 0; i < commIdList.size(); i++) { cIds[i] = commIdList.get(i); } return cIds; } /** * Get the id of the parent community. Returns Integer, as null is used to * signify that there are no parents (ie. top-level). * * @param commId * @return * @throws SQLException */ private Integer getParentCommunityID(int commId) throws SQLException { TableRowIterator tri = null; try { tri = DatabaseManager.queryTable(context, "Community2Community", "SELECT * FROM Community2Community WHERE child_comm_id=?", commId); if (tri.hasNext()) { return tri.next().getIntColumn("parent_comm_id"); } } finally { if (tri != null) { tri.close(); } } return null; } /** * Check to see if the integer at pos is the first occurrence of that value * in the array. * * @param ids * @param pos * @return */ private boolean isFirstOccurrence(int[] ids, int pos) { if (pos < 0 || pos >= ids.length) { return false; } int id = ids[pos]; for (int i = 0; i < pos; i++) { if (id == ids[i]) { return false; } } return true; } private static class BrowseMappingResults implements MappingResults { private List<Integer> addedDistinctIds = new ArrayList<Integer>(); private List<Integer> retainedDistinctIds = new ArrayList<Integer>(); private List<Integer> removedDistinctIds = new ArrayList<Integer>(); private void addAddedDistinctId(int id) { addedDistinctIds.add(id); } private void addRetainedDistinctId(int id) { retainedDistinctIds.add(id); } private void addRemovedDistinctId(int id) { removedDistinctIds.add(id); } public List<Integer> getAddedDistinctIds() { return addedDistinctIds; } public List<Integer> getRetainedDistinctIds() { return retainedDistinctIds; } public List<Integer> getRemovedDistinctIds() { return Collections.unmodifiableList(removedDistinctIds); } } }
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.browse; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * This class is the Oracle driver class for reading information from the Browse * tables. It implements the BrowseDAO interface, and also has a constructor of * the form: * * BrowseDAOOracle(Context context) * * As required by BrowseDAOFactory. This class should only ever be loaded by * that Factory object. * * @author Graham Triggs * */ public class BrowseDAOOracle implements BrowseDAO { /** Log4j log */ private static Logger log = Logger.getLogger(BrowseDAOOracle.class); /** The DSpace context */ private Context context; /** Database specific set of utils used when prepping the database */ private BrowseDAOUtils utils; // SQL query related attributes for this class /** the values to place in the SELECT --- FROM bit */ private String[] selectValues = { "*" }; /** the values to place in the SELECT COUNT(---) bit */ private String[] countValues; /** table(s) to select from */ private String table = null; private String tableDis = null; private String tableMap = null; /** field to look for focus value in */ private String focusField = null; /** value to start browse from in focus field */ private String focusValue = null; /** field to look for value in */ private String valueField = null; /** value to restrict browse to (e.g. author name) */ private String value = null; private String authority = null; /** exact or partial matching of the value */ private boolean valuePartial = false; /** the table that defines the mapping for the relevant container */ private String containerTable = null; /** the name of the field which contains the container id (e.g. collection_id) */ private String containerIDField = null; /** the database id of the container we are constraining to */ private int containerID = -1; /** the column that we are sorting results by */ private String orderField = null; /** whether to sort results ascending or descending */ private boolean ascending = true; /** the limit of number of results to return */ private int limit = -1; /** the offset of the start point */ private int offset = 0; /** whether to use the equals comparator in value comparisons */ private boolean equalsComparator = true; /** whether this is a distinct browse or not */ private boolean distinct = false; // administrative attributes for this class /** a cache of the actual query to be executed */ private String querySql = ""; private List<Serializable> queryParams = new ArrayList<Serializable>(); private String whereClauseOperator = ""; /** whether the query (above) needs to be regenerated */ private boolean rebuildQuery = true; // FIXME Would be better to join to item table and get the correct values /** flags for what the items represent */ private boolean itemsInArchive = true; private boolean itemsWithdrawn = false; public BrowseDAOOracle(Context context) throws BrowseException { this.context = context; // obtain the relevant Utils for this class utils = BrowseDAOFactory.getUtils(context); } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doCountQuery() */ public int doCountQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "executing_count_query", "query=" + query)); } TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); if (tri.hasNext()) { TableRow row = tri.next(); return (int) row.getLongColumn("num"); } else { return 0; } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doMaxQuery(java.lang.String, java.lang.String, int) */ public String doMaxQuery(String column, String table, int itemID) throws BrowseException { TableRowIterator tri = null; try { String query = "SELECT MAX(" + column + ") AS max_value FROM " + table + " WHERE item_id=?"; Object[] params = { Integer.valueOf(itemID) }; tri = DatabaseManager.query(context, query, params); TableRow row; if (tri.hasNext()) { row = tri.next(); return row.getStringColumn("max_value"); } else { return null; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doOffsetQuery(java.lang.String, java.lang.String, java.lang.String) */ public int doOffsetQuery(String column, String value, boolean isAscending) throws BrowseException { TableRowIterator tri = null; if (column == null || value == null) { return 0; } try { List<Serializable> paramsList = new ArrayList<Serializable>(); StringBuffer queryBuf = new StringBuffer(); queryBuf.append("COUNT(").append(column).append(") AS offset "); buildSelectStatement(queryBuf, paramsList); if (isAscending) { queryBuf.append(" WHERE ").append(column).append("<?"); paramsList.add(value); } else { queryBuf.append(" WHERE ").append(column).append(">?"); paramsList.add(value + Character.MAX_VALUE); } if (containerTable != null || (value != null && valueField != null && tableDis != null && tableMap != null)) { queryBuf.append(" AND ").append("mappings.item_id="); queryBuf.append(table).append(".item_id"); } tri = DatabaseManager.query(context, queryBuf.toString(), paramsList.toArray()); TableRow row; if (tri.hasNext()) { row = tri.next(); return row.getIntColumn("offset"); } else { return 0; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doDistinctOffsetQuery(java.lang.String, java.lang.String, java.lang.String) */ public int doDistinctOffsetQuery(String column, String value, boolean isAscending) throws BrowseException { TableRowIterator tri = null; try { List<Serializable> paramsList = new ArrayList<Serializable>(); StringBuffer queryBuf = new StringBuffer(); queryBuf.append("COUNT(").append(column).append(") AS offset "); buildSelectStatementDistinct(queryBuf, paramsList); if (isAscending) { queryBuf.append(" WHERE ").append(column).append("<?"); paramsList.add(value); } else { queryBuf.append(" WHERE ").append(column).append(">?"); paramsList.add(value + Character.MAX_VALUE); } if (containerTable != null && tableMap != null) { queryBuf.append(" AND ").append("mappings.distinct_id="); queryBuf.append(table).append(".id"); } tri = DatabaseManager.query(context, queryBuf.toString(), paramsList.toArray()); TableRow row; if (tri.hasNext()) { row = tri.next(); return row.getIntColumn("offset"); } else { return 0; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doQuery() */ public List<BrowseItem> doQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "executing_full_query", "query=" + query)); } TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); // go over the query results and process List<BrowseItem> results = new ArrayList<BrowseItem>(); while (tri.hasNext()) { TableRow row = tri.next(); BrowseItem browseItem = new BrowseItem(context, row.getIntColumn("item_id"), itemsInArchive, itemsWithdrawn); results.add(browseItem); } return results; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException("problem with query: " + query, e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doValueQuery() */ public List<String[]> doValueQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "executing_value_query", "query=" + query)); } TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); // go over the query results and process List<String[]> results = new ArrayList<String[]>(); while (tri.hasNext()) { TableRow row = tri.next(); String valueResult = row.getStringColumn("value"); String authorityResult = row.getStringColumn("authority"); results.add(new String[]{valueResult,authorityResult}); } return results; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getContainerID() */ public int getContainerID() { return containerID; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getContainerIDField() */ public String getContainerIDField() { return containerIDField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getContainerTable() */ public String getContainerTable() { return containerTable; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getCountValues() */ public String[] getCountValues() { return (String[]) ArrayUtils.clone(this.countValues); } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getFocusField() */ public String getJumpToField() { return focusField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getFocusValue() */ public String getJumpToValue() { return focusValue; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getLimit() */ public int getLimit() { return limit; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getOffset() */ public int getOffset() { return offset; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getOrderField() */ public String getOrderField() { return orderField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getSelectValues() */ public String[] getSelectValues() { return (String[]) ArrayUtils.clone(selectValues); } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getTable() */ public String getTable() { return table; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getValue() */ public String getFilterValue() { return value; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getValueField() */ public String getFilterValueField() { return valueField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#isAscending() */ public boolean isAscending() { return ascending; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#isDistinct() */ public boolean isDistinct() { return this.distinct; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setAscending(boolean) */ public void setAscending(boolean ascending) { this.ascending = ascending; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setContainerID(int) */ public void setContainerID(int containerID) { this.containerID = containerID; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setContainerIDField(java.lang.String) */ public void setContainerIDField(String containerIDField) { this.containerIDField = containerIDField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setContainerTable(java.lang.String) */ public void setContainerTable(String containerTable) { this.containerTable = containerTable; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setCountValues(java.lang.String[]) */ public void setCountValues(String[] fields) { this.countValues = (String[]) ArrayUtils.clone(fields); this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setDistinct(boolean) */ public void setDistinct(boolean bool) { this.distinct = bool; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setEqualsComparator(boolean) */ public void setEqualsComparator(boolean equalsComparator) { this.equalsComparator = equalsComparator; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setFocusField(java.lang.String) */ public void setJumpToField(String focusField) { this.focusField = focusField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setFocusValue(java.lang.String) */ public void setJumpToValue(String focusValue) { this.focusValue = focusValue; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setLimit(int) */ public void setLimit(int limit) { this.limit = limit; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setOffset(int) */ public void setOffset(int offset) { this.offset = offset; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setOrderField(java.lang.String) */ public void setOrderField(String orderField) { this.orderField = orderField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setSelectValues(java.lang.String[]) */ public void setSelectValues(String[] selectValues) { this.selectValues = (String[]) ArrayUtils.clone(selectValues); this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setTable(java.lang.String) */ public void setTable(String table) { this.table = table; // FIXME Rather than assume from the browse table, join the query to item to get the correct values // Check to see if this is the withdrawn browse index - if it is, // we need to set the flags appropriately for when we create the BrowseItems if (table.equals(BrowseIndex.getWithdrawnBrowseIndex().getTableName())) { itemsInArchive = false; itemsWithdrawn = true; } else { itemsInArchive = true; itemsWithdrawn = false; } this.rebuildQuery = true; } public void setFilterMappingTables(String tableDis, String tableMap) { this.tableDis = tableDis; this.tableMap = tableMap; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setValue(java.lang.String) */ public void setFilterValue(String value) { this.value = value; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setFilterValuePartial(boolean) */ public void setFilterValuePartial(boolean part) { this.valuePartial = part; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setValueField(java.lang.String) */ public void setFilterValueField(String valueField) { this.valueField = valueField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#useEqualsComparator() */ public boolean useEqualsComparator() { return equalsComparator; } // PRIVATE METHODS /** * Build the query that will be used for a distinct select. This incorporates * only the parts of the parameters that are actually useful for this type * of browse * * @return the query to be executed * @throws BrowseException */ private String buildDistinctQuery(List<Serializable> params) throws BrowseException { StringBuffer queryBuf = new StringBuffer(); if (!buildSelectListCount(queryBuf)) { if (!buildSelectListValues(queryBuf)) { throw new BrowseException("No arguments for SELECT statement"); } } buildSelectStatementDistinct(queryBuf, params); buildWhereClauseOpReset(); // assemble the focus clase if we are to have one // it will look like one of the following, for example // sort_value <= myvalue // sort_1 >= myvalue buildWhereClauseJumpTo(queryBuf, params); // assemble the where clause out of the two possible value clauses // and include container support buildWhereClauseDistinctConstraints(queryBuf, params); // assemble the order by field buildOrderBy(queryBuf); // prepare the limit and offset clauses buildRowLimitAndOffset(queryBuf, params); return queryBuf.toString(); } /** * Build the query that will be used for a full browse. * * @return the query to be executed * @throws BrowseException */ private String buildQuery(List<Serializable> params) throws BrowseException { StringBuffer queryBuf = new StringBuffer(); if (!buildSelectListCount(queryBuf)) { if (!buildSelectListValues(queryBuf)) { throw new BrowseException("No arguments for SELECT statement"); } } buildSelectStatement(queryBuf, params); buildWhereClauseOpReset(); // assemble the focus clase if we are to have one // it will look like one of the following, for example // sort_value <= myvalue // sort_1 >= myvalue buildWhereClauseJumpTo(queryBuf, params); // assemble the value clause if we are to have one buildWhereClauseFilterValue(queryBuf, params); // assemble the where clause out of the two possible value clauses // and include container support buildWhereClauseFullConstraints(queryBuf, params); // assemble the order by field buildOrderBy(queryBuf); // prepare the limit and offset clauses buildRowLimitAndOffset(queryBuf, params); return queryBuf.toString(); } /** * Get the clause to perform search result ordering. This will * return something of the form: * * <code> * ORDER BY [order field] (ASC | DESC) * </code> */ private void buildOrderBy(StringBuffer queryBuf) { if (orderField != null) { queryBuf.append(" ORDER BY "); queryBuf.append(orderField); if (isAscending()) { queryBuf.append(" ASC "); } else { queryBuf.append(" DESC "); } } } /** * Get the limit clause to perform search result truncation. Will return * something of the form: * * <code> * LIMIT [limit] * </code> */ private void buildRowLimitAndOffset(StringBuffer queryBuf, List<Serializable> params) { // prepare the LIMIT clause if (limit > 0 || offset > 0) { queryBuf.insert(0, "SELECT /*+ FIRST_ROWS(n) */ rec.*, ROWNUM rnum FROM ("); queryBuf.append(") "); } if (limit > 0) { queryBuf.append("rec WHERE rownum<=? "); if (offset > 0) { params.add(Integer.valueOf(limit + offset)); } else { params.add(Integer.valueOf(limit)); } } if (offset > 0) { queryBuf.insert(0, "SELECT * FROM ("); queryBuf.append(") WHERE rnum>?"); params.add(Integer.valueOf(offset)); } } /** * Build the clauses required for the view used in focused or scoped queries. * * @param queryBuf * @param params */ private void buildFocusedSelectClauses(StringBuffer queryBuf, List<Serializable> params) { if (tableMap != null && tableDis != null) { queryBuf.append(tableMap).append(".distinct_id=").append(tableDis).append(".id"); queryBuf.append(" AND "); if (authority == null) { queryBuf.append(tableDis).append(".authority IS NULL"); queryBuf.append(" AND "); queryBuf.append(tableDis).append(".").append(valueField); if (valuePartial) { queryBuf.append(" LIKE ? "); if (valueField.startsWith("sort_")) { params.add("%" + utils.truncateSortValue(value) + "%"); } else { params.add("%" + utils.truncateValue(value) + "%"); } } else { queryBuf.append("=? "); if (valueField.startsWith("sort_")) { params.add(utils.truncateSortValue(value)); } else { params.add(utils.truncateValue(value)); } } } else { queryBuf.append(tableDis).append(".authority=?"); params.add(utils.truncateValue(authority,100)); } } if (containerTable != null && containerIDField != null && containerID != -1) { if (tableMap != null) { if (tableDis != null) { queryBuf.append(" AND "); } queryBuf.append(tableMap).append(".item_id=") .append(containerTable).append(".item_id AND "); } queryBuf.append(containerTable).append(".").append(containerIDField); queryBuf.append("=? "); params.add(Integer.valueOf(containerID)); } } /** * Build the table list for the view used in focused or scoped queries. * * @param queryBuf */ private void buildFocusedSelectTables(StringBuffer queryBuf) { if (containerTable != null) { queryBuf.append(containerTable); } if (tableMap != null) { if (containerTable != null) { queryBuf.append(", "); } queryBuf.append(tableMap); if (tableDis != null) { queryBuf.append(", ").append(tableDis); } } } /** * Build a clause for counting results. Will return something of the form: * * <code> * COUNT( [value 1], [value 2] ) AS number * </code> * * @return the count clause */ private boolean buildSelectListCount(StringBuffer queryBuf) { if (countValues != null && countValues.length > 0) { queryBuf.append(" COUNT("); if ("*".equals(countValues[0])) { queryBuf.append(countValues[0]); } else { queryBuf.append(table).append(".").append(countValues[0]); } for (int i = 1; i < countValues.length; i++) { queryBuf.append(", "); if ("*".equals(countValues[i])) { queryBuf.append(countValues[i]); } else { queryBuf.append(table).append(".").append(countValues[i]); } } queryBuf.append(") AS num"); return true; } return false; } /** * Prepare the list of values to be selected on. Will return something of the form: * * <code> * [value 1], [value 2] * </code> * * @return the select value list */ private boolean buildSelectListValues(StringBuffer queryBuf) { if (selectValues != null && selectValues.length > 0) { queryBuf.append(table).append(".").append(selectValues[0]); for (int i = 1; i < selectValues.length; i++) { queryBuf.append(", "); queryBuf.append(table).append(".").append(selectValues[i]); } return true; } return false; } /** * Prepare the select clause using the pre-prepared arguments. This will produce something * of the form: * * <code> * SELECT [arguments] FROM [table] * </code> */ private void buildSelectStatement(StringBuffer queryBuf, List<Serializable> params) throws BrowseException { if (queryBuf.length() == 0) { throw new BrowseException("No arguments for SELECT statement"); } if (table == null || "".equals(table)) { throw new BrowseException("No table for SELECT statement"); } // queryBuf already contains what we are selecting, // so insert the statement at the beginning queryBuf.insert(0, "SELECT "); // Then append the table queryBuf.append(" FROM "); queryBuf.append(table); if (containerTable != null || (value != null && valueField != null && tableDis != null && tableMap != null)) { queryBuf.append(", (SELECT "); if (containerTable != null) { queryBuf.append(containerTable).append(".item_id"); } else { queryBuf.append("DISTINCT ").append(tableMap).append(".item_id"); } queryBuf.append(" FROM "); buildFocusedSelectTables(queryBuf); queryBuf.append(" WHERE "); buildFocusedSelectClauses(queryBuf, params); queryBuf.append(") mappings"); } queryBuf.append(" "); } /** * Prepare the select clause using the pre-prepared arguments. This will produce something * of the form: * * <code> * SELECT [arguments] FROM [table] * </code> * * @param queryBuf the string value obtained from distinctClause, countClause or selectValues * @return the SELECT part of the query */ private void buildSelectStatementDistinct(StringBuffer queryBuf, List<Serializable> params) throws BrowseException { if (queryBuf.length() == 0) { throw new BrowseException("No arguments for SELECT statement"); } if (table == null || "".equals(table)) { throw new BrowseException("No table for SELECT statement"); } // queryBuf already contains what we are selecting, // so insert the statement at the beginning queryBuf.insert(0, "SELECT "); // Then append the table queryBuf.append(" FROM "); queryBuf.append(table); if (containerTable != null && tableMap != null) { queryBuf.append(", (SELECT DISTINCT ").append(tableMap).append(".distinct_id "); queryBuf.append(" FROM "); buildFocusedSelectTables(queryBuf); queryBuf.append(" WHERE "); buildFocusedSelectClauses(queryBuf, params); queryBuf.append(") mappings"); } queryBuf.append(" "); } /** * assemble a WHERE clause with the given constraints. This will return something * of the form: * * <code> * WHERE [focus clause] [AND] [value clause] [AND] [container constraint] * </code> * * The container constraint is described in one of either getFullConstraint or * getDistinctConstraint, and the form of that section of the query can be * found in their documentation. * * If either of focusClause or valueClause is null, they will be duly omitted from * the WHERE clause. */ private void buildWhereClauseDistinctConstraints(StringBuffer queryBuf, List<Serializable> params) { // add the constraint to community or collection if necessary // and desired if (containerIDField != null && containerID != -1 && containerTable != null) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" ").append(table).append(".id=mappings.distinct_id "); } } /** * assemble a WHERE clause with the given constraints. This will return something * of the form: * * <code> * WHERE [focus clause] [AND] [value clause] [AND] [container constraint] * </code> * * The container constraint is described in one of either getFullConstraint or * getDistinctConstraint, and the form of that section of the query can be * found in their documentation. * * If either of focusClause or valueClause is null, they will be duly omitted from * the WHERE clause. */ private void buildWhereClauseFullConstraints(StringBuffer queryBuf, List<Serializable> params) { // add the constraint to community or collection if necessary // and desired if (tableDis == null || tableMap == null) { if (containerIDField != null && containerID != -1) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" ").append(table).append(".item_id=mappings.item_id "); } } } /** * Get the clause to get the browse to start from a given focus value. * Will return something of the form: * * <code> * [field] (<[=] | >[=]) '[value]' * </code> * * such as: * * <code> * sort_value <= 'my text' * </code> */ private void buildWhereClauseJumpTo(StringBuffer queryBuf, List<Serializable> params) { // get the operator (<[=] | >[=]) which the focus of the browse will // be matched using String focusComparator = getFocusComparator(); // assemble the focus clase if we are to have one // it will look like one of the following // - sort_value <= myvalue // - sort_1 >= myvalue if (focusField != null && focusValue != null) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" "); queryBuf.append(focusField); queryBuf.append(focusComparator); queryBuf.append("? "); if (focusField.startsWith("sort_")) { params.add(utils.truncateSortValue(focusValue)); } else { params.add(utils.truncateValue(focusValue)); } } } /** * Return the clause to constrain the browse to a specific value. * Will return something of the form: * * <code> * [field] = '[value]' * </code> * * such as: * * <code> * sort_value = 'some author' * </code> */ private void buildWhereClauseFilterValue(StringBuffer queryBuf, List<Serializable> params) { // assemble the value clause if we are to have one if (value != null && valueField != null) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" "); if (tableDis != null && tableMap != null) { queryBuf.append(table).append(".item_id=mappings.item_id "); } else { queryBuf.append(valueField); if (valuePartial) { queryBuf.append(" LIKE ? "); if (valueField.startsWith("sort_")) { params.add("%" + utils.truncateSortValue(value) + "%"); } else { params.add("%" + utils.truncateValue(value) + "%"); } } else { queryBuf.append("=? "); if (valueField.startsWith("sort_")) { params.add(utils.truncateSortValue(value)); } else { params.add(utils.truncateValue(value)); } } } } } /** * Insert an operator into the where clause, and reset to ' AND ' */ private void buildWhereClauseOpInsert(StringBuffer queryBuf) { queryBuf.append(whereClauseOperator); whereClauseOperator = " AND "; } /** * Reset the where clause operator for initial use */ private void buildWhereClauseOpReset() { // Use sneaky trick to insert the WHERE by defining it as the first operator whereClauseOperator = " WHERE "; } /** * Get the comparator which should be used to compare focus values * with values in the database. This will return one of the 4 following * possible values: <, >, <=, >= * * @return the focus comparator */ private String getFocusComparator() { // now decide whether we will use an equals comparator; String equals = "="; if (!useEqualsComparator()) { equals = ""; } // get the comparator for the match of the browsable index value // the rule is: if the scope has a value, then the comparator is always "=" // if, the order is set to ascending then we want to use // WHERE sort_value > <the value> // and when the order is descending then we want to use // WHERE sort_value < <the value> String focusComparator = ""; if (isAscending()) { focusComparator = ">" + equals; } else { focusComparator = "<" + equals; } return focusComparator; } /** * Return a string representation (the SQL) of the query that would be executed * using one of doCountQuery, doValueQuery, doMaxQuery or doQuery * * @return String representation of the query (SQL) * @throws BrowseException */ private String getQuery() throws BrowseException { if ("".equals(querySql) || rebuildQuery) { queryParams.clear(); if (this.isDistinct()) { querySql = buildDistinctQuery(queryParams); } else { querySql = buildQuery(queryParams); } this.rebuildQuery = false; } return querySql; } /** * Return the parameters to be bound to the query * * @return Object[] query parameters * @throws BrowseException */ private Object[] getQueryParams() throws BrowseException { // Ensure that the query has been built if ("".equals(querySql) || rebuildQuery) { getQuery(); } return queryParams.toArray(); } public void setAuthorityValue(String value) { authority = value; } public String getAuthorityValue() { return authority; } }
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.browse; import java.util.List; import java.util.Map; import java.util.Set; /** * Interface for any class wishing to provide a browse storage later. This particular * Data Access Object deals with building and destroying the database, and inserting and * removing content from it. There is an alternative class BrowseDAO which deals with * Read-Only operations. * * If you implement this class, and you wish it to be loaded via the BrowseDAOFactory * you must supply a constructor of the form: * * public BrowseCreateDAOImpl(Context context) {} * * Where Context is the DSpace Context object * * Where tables are referred to in this class, they can be obtained from the BrowseIndex * class, which will answer queries given the context of the request on which table * is the relevant target. * * @author Richard Jones * */ public interface BrowseCreateDAO { // this must have a constructor which takes a DSpace Context as // an argument, thus: // // public BrowseCreateDAO(Context context) /** * Delete the record for the given item id from the specified table. * * Table names can be obtained from the BrowseIndex class * * @param table the browse table to remove the index from * @param itemID the database id of the item to remove the index for * @throws BrowseException */ public void deleteByItemID(String table, int itemID) throws BrowseException; public void deleteCommunityMappings(int itemID) throws BrowseException; public void updateCommunityMappings(int itemID) throws BrowseException; /** * Insert an index record into the given table for the given item id. The Map should contain * key value pairs representing the sort column integer representation and the normalised * value for that field. * * For example, the caller might do as follows: * * <code> * Map map = new HashMap(); * map.put(new Integer(1), "the title"); * map.put(new Integer(2), "the subject"); * * BrowseCreateDAO dao = BrowseDAOFactory.getCreateInstance(); * dao.insertIndex("index_1", 21, map); * </code> * * @param table the browse table to insert the index in * @param itemID the database id of the item being indexed * @param sortCols an Integer-String map of sort column numbers and values * @throws BrowseException */ public void insertIndex(String table, int itemID, Map<Integer, String> sortCols) throws BrowseException; /** * Updates an index record into the given table for the given item id. The Map should contain * key value pairs representing the sort column integer representation and the normalised * value for that field. * * For example, the caller might do as follows: * * <code> * Map map = new HashMap(); * map.put(new Integer(1), "the title"); * map.put(new Integer(2), "the subject"); * * BrowseCreateDAO dao = BrowseDAOFactory.getCreateInstance(); * dao.updateIndex("index_1", 21, map); * </code> * * @param table the browse table to insert the index in * @param itemID the database id of the item being indexed * @param sortCols an Integer-String map of sort column numbers and values * @return true if the record is updated, false if not found * @throws BrowseException */ public boolean updateIndex(String table, int itemID, Map<Integer, String> sortCols) throws BrowseException; /** * Get the browse index's internal id for the location of the given string * and sort value in the given table. This method should always return a * positive integer, as if no existing ID is available for the given value * then one should be inserted using the data supplied, and the ID returned. * * Generally this method is used in conjunction with createDistinctMapping thus: * * <code> * BrowseCreateDAO dao = BrowseDAOFactory.getCreateInstance(); * dao.createDistinctMapping("index_1_distinct_map", 21, * dao.getDistinctID("index_1_distinct", "Human Readable", "human readable")); * </code> * * When it creates a distinct record, it would usually do so through insertDistinctRecord * defined below. * * @param table the table in which to look for/create the id * @param value the value on which to search * @param sortValue the sort value to use in case of the need to create * @return the database id of the distinct record * @throws BrowseException */ public int getDistinctID(String table, String value, String authority, String sortValue) throws BrowseException; /** * Insert the given value and sort value into the distinct index table. This * returns an integer which represents the database id of the created record, so * that it can be used, for example in createDistinctMapping thus: * * <code> * BrowseCreateDAO dao = BrowseDAOFactory.getCreateInstance(); * dao.createDistinctMapping("index_1_distinct_map", 21, * dao.insertDistinctRecord("index_1_distinct", "Human Readable", "human readable")); * </code> * * This is less good than using getDistinctID defined above, as if there is * already a distinct value in the table it may throw an exception * * @param table the table into which to insert the record * @param value the value to insert * @param sortValue the sort value to insert * @return the database id of the created record * @throws BrowseException */ public int insertDistinctRecord(String table, String value, String authority, String sortValue) throws BrowseException; /** * Update a mapping between an item id and a distinct metadata field such as an author, * who can appear in multiple items. To get the id of the distinct record you should * use either getDistinctID or insertDistinctRecord as defined above. * * @param table the mapping table * @param itemID the item id * @param distinctIDs the id of the distinct record * @return the ids of any distinct records that have been unmapped * @throws BrowseException */ public MappingResults updateDistinctMappings(String table, int itemID, Set<Integer> distinctIDs) throws BrowseException; /** * Find out of a given table exists. * * @param table the table to test * @return true if exists, false if not * @throws BrowseException */ public boolean testTableExistence(String table) throws BrowseException; /** * Drop the given table name, and all other resources that are attached to it. In normal * relational database land this will include constraints and views. If the boolean execute * is true this operation should be carried out, and if it is false it should not. The returned * string should contain the SQL (if relevant) that the caller can do with what they like * (for example, output to the screen). * * @param table The table to drop * @param execute Whether to action the removal or not * @return The instructions (SQL) that effect the removal * @throws BrowseException */ public String dropIndexAndRelated(String table, boolean execute) throws BrowseException; /** * Drop the given sequence name. This is relevant to most forms of database, but not all. * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen) * * @param sequence the sequence to drop * @param execute whether to action the removal or not * @return The instructions (SQL) that effect the removal * @throws BrowseException */ public String dropSequence(String sequence, boolean execute) throws BrowseException; /** * Drop the given view name. This is relevant to most forms of database, but not all. * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen) * * @param view the view to drop * @param execute whether to action the removal or not * @return The instructions (SQL) that effect the removal * @throws BrowseException */ public String dropView(String view, boolean execute) throws BrowseException; /** * Create the sequence with the given name. This is relevant to most forms of database, but not all. * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen) * * @param sequence the sequence to create * @param execute whether to action the create or not * @return the instructions (SQL) that effect the creation * @throws BrowseException */ public String createSequence(String sequence, boolean execute) throws BrowseException; /** * Create the main index table. This is the one which will contain a single row per * item. If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen) * * This form is used for the primary item browse tables * * This should be used, for example, like this: * * <code> * List list = new ArrayList(); * list.add(new Integer(1)); * list.add(new Integer(2)); * * BrowseCreateDAO dao = BrowseDAOFactory.getCreateInstance(); * dao.createPrimaryTable("index_1", list, true); * </code> * * @param table the raw table to create * @param sortCols a List of Integers numbering the sort columns required * @param execute whether to action the create or not * @return the instructions (SQL) that effect the creation * @throws BrowseException */ public String createPrimaryTable(String table, List<Integer> sortCols, boolean execute) throws BrowseException; /** * Create any indices that the implementing DAO sees fit to maximise performance. * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string array should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen). It's an array so that * you can return each bit of SQL as an element if you want. * * @param table the table upon which to create indices * @param sortCols TODO * @param execute whether to action the create or not * @return the instructions (SQL) that effect the indices * @throws BrowseException */ public String[] createDatabaseIndices(String table, List<Integer> sortCols, boolean value, boolean execute) throws BrowseException; /** * Create any indices that the implementing DAO sees fit to maximise performance. * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string array should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen). It's an array so that * you can return each bit of SQL as an element if you want. * * @param disTable the distinct table upon which to create indices * @param mapTable the mapping table upon which to create indices * @param execute whether to action the create or not * @return the instructions (SQL) that effect the indices * @throws BrowseException */ public String[] createMapIndices(String disTable, String mapTable, boolean execute) throws BrowseException; /** * Create the View of the full item index as seen from a collection. * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string array should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen). * * @param table the table to create the view on * @param view the name of the view to create * @param execute whether to action the create or not * @return the instructions (SQL) that effects the create * @throws BrowseException */ public String createCollectionView(String table, String view, boolean execute) throws BrowseException; /** * Create the View of the full item index as seen from a community * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string array should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen). * * @param table the table to create the view on * @param view the name of the view to create * @param execute whether to action the create or not * @return the instructions (SQL) that effects the create * @throws BrowseException */ public String createCommunityView(String table, String view, boolean execute) throws BrowseException; public List<Integer> deleteMappingsByItemID(String mapTable, int itemID) throws BrowseException; /** * Create the table which will hold the distinct metadata values that appear in multiple * items. For example, this table may hold a list of unique authors, each name in the * metadata for the entire system appearing only once. Or for subject classifications. * If the boolean execute is true this operation should be carried out, and if it is false * it should not. The returned string array should contain the SQL (if relevant) that the caller * can do with what they like (for example, output to the screen). * * @param table the table to create * @param execute whether to action the create or not * @return the instructions (SQL) that effects the create * @throws BrowseException */ public String createDistinctTable(String table, boolean execute) throws BrowseException; /** * Create a table to hold a mapping between an item and a distinct metadata value that can appear * across multiple items (for example, author names). If the boolean execute is true this * operation should be carried out, and if it is false it should not. * * @param table the name of the distinct table which holds the target of the mapping * @param map the name of the mapping table itself * @param execute whether to execute the query or not * @return * @throws BrowseException */ public String createDistinctMap(String table, String map, boolean execute) throws BrowseException; /** * So that any left over indices for items which have been deleted can be assured to have * been removed, this method checks for indices for items which are not in the item table. * If it finds an index which does not have an associated item it removes it. * * @param table the index table to check * @param withdrawn TODO * @throws BrowseException */ public void pruneExcess(String table, boolean withdrawn) throws BrowseException; /** * So that any left over indices for items which have been deleted can be assured to have * been removed, this method checks for indices for items which are not in the item table. * If it finds an index which does not have an associated item it removes it. * * @param map the name of the associated distinct mapping table * @param withdrawn TODO * @throws BrowseException */ public void pruneMapExcess(String map, boolean withdrawn, List<Integer> distinctIds) throws BrowseException; /** * So that there are no distinct values indexed which are no longer referenced from the * map table, this method checks for values which are not referenced from the map, * and removes them. * * @param table the name of the distinct index table * @param map the name of the associated distinct mapping table. * @throws BrowseException */ public void pruneDistinct(String table, String map, List<Integer> distinctIds) throws BrowseException; }
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.browse; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; /** * Utility class to provide a wrapper for the various output possibilities from * the IndexBrowse class. It can output to the screen and to file, and it can be * verbose or not verbose. * * @author Richard Jones * */ public class BrowseOutput { /** be verbose? */ private boolean verbose = false; /** print to the screen? */ private boolean print = false; /** write to file? */ private boolean file = false; /** append to file, or overwrite? */ private boolean append = true; /** name of file to write to */ private String fileName; /** * Constructor. */ public BrowseOutput() { } /** * @return Returns the append. */ public boolean isAppend() { return append; } /** * @param append * The append to set. */ public void setAppend(boolean append) { this.append = append; } /** * @return Returns the fileName. */ public String getFileName() { return fileName; } /** * @param fileName * The fileName to set. */ public void setFileName(String fileName) { this.fileName = fileName; setAppend(false); } /** * @return Returns the file. */ public boolean isFile() { return file; } /** * @param file * The file to set. */ public void setFile(boolean file) { this.file = file; } /** * @return Returns the print. */ public boolean isPrint() { return print; } /** * @param print * The print to set. */ public void setPrint(boolean print) { this.print = print; } /** * @return Returns the verbose. */ public boolean isVerbose() { return verbose; } /** * @param verbose * The verbose to set. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Pass in a message to be processed. If the setting is verbose * then this will be output to System.out * * @param message the message to set */ public void message(String message) { if (isVerbose()) { System.out.println(message); } } /** * Pass in a message that must be displayed to the user, irrespective * of the verbosity. Will be displayed to System.out * * @param message the urgent message */ public void urgent(String message) { System.out.println(message); } /** * Pass in some SQL. If print is set to true this will output to the * screen. If file is set to true, this will write to the file specified. * * @param sql * @throws BrowseException */ public void sql(String sql) throws BrowseException { if (isPrint()) { System.out.println(sql); } if (isFile()) { try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName, isAppend())); out.write(sql + "\n"); out.close(); setAppend(true); } catch (IOException e) { throw new BrowseException(e); } } } }
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.browse; import org.apache.log4j.Logger; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Context; import org.dspace.storage.rdbms.TableRowIterator; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.DatabaseManager; import java.sql.SQLException; /** * Postgres driver implementing ItemCountDAO interface to cache item * count information in communities and collections * * @author Richard Jones * */ public class ItemCountDAOPostgres implements ItemCountDAO { /** Log4j logger */ private static Logger log = Logger.getLogger(ItemCountDAOPostgres.class); /** DSpace context */ private Context context; /** SQL to select on a collection id */ private String collectionSelect = "SELECT * FROM collection_item_count WHERE collection_id = ?"; /** SQL to insert a new collection record */ private String collectionInsert = "INSERT INTO collection_item_count (collection_id, count) VALUES (?, ?)"; /** SQL to update an existing collection record */ private String collectionUpdate = "UPDATE collection_item_count SET count = ? WHERE collection_id = ?"; /** SQL to remove a collection record */ private String collectionRemove = "DELETE FROM collection_item_count WHERE collection_id = ?"; /** SQL to select on a community id */ private String communitySelect = "SELECT * FROM community_item_count WHERE community_id = ?"; /** SQL to insert a new community record */ private String communityInsert = "INSERT INTO community_item_count (community_id, count) VALUES (?, ?)"; /** SQL to update an existing community record */ private String communityUpdate = "UPDATE community_item_count SET count = ? WHERE community_id = ?"; /** SQL to remove a community record */ private String communityRemove = "DELETE FROM community_item_count WHERE community_id = ?"; /** * Store the count of the given collection * * @param collection * @param count * @throws ItemCountException */ public void collectionCount(Collection collection, int count) throws ItemCountException { TableRowIterator tri = null; try { // first find out if we have a record Object[] sparams = { Integer.valueOf(collection.getID()) }; tri = DatabaseManager.query(context, collectionSelect, sparams); if (tri.hasNext()) { Object[] params = { Integer.valueOf(count), Integer.valueOf(collection.getID()) }; DatabaseManager.updateQuery(context, collectionUpdate, params); } else { Object[] params = { Integer.valueOf(collection.getID()), Integer.valueOf(count) }; DatabaseManager.updateQuery(context, collectionInsert, params); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } /** * Store the count of the given community * * @param community * @param count * @throws ItemCountException */ public void communityCount(Community community, int count) throws ItemCountException { TableRowIterator tri = null; try { // first find out if we have a record Object[] sparams = { Integer.valueOf(community.getID()) }; tri = DatabaseManager.query(context, communitySelect, sparams); if (tri.hasNext()) { Object[] params = { Integer.valueOf(count), Integer.valueOf(community.getID()) }; DatabaseManager.updateQuery(context, communityUpdate, params); } else { Object[] params = { Integer.valueOf(community.getID()), Integer.valueOf(count) }; DatabaseManager.updateQuery(context, communityInsert, params); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } /** * Set the dspace context to use * * @param context * @throws ItemCountException */ public void setContext(Context context) throws ItemCountException { this.context = context; } /** * get the count of the items in the given container * * @param dso * @return * @throws ItemCountException */ public int getCount(DSpaceObject dso) throws ItemCountException { if (dso instanceof Collection) { return getCollectionCount((Collection) dso); } else if (dso instanceof Community) { return getCommunityCount((Community) dso); } else { throw new ItemCountException("We can only count items in Communities or Collections"); } } /** * remove the cache for the given container * * @param dso * @throws ItemCountException */ public void remove(DSpaceObject dso) throws ItemCountException { if (dso instanceof Collection) { removeCollection((Collection) dso); } else if (dso instanceof Community) { removeCommunity((Community) dso); } else { throw new ItemCountException("We can only delete count of items from Communities or Collections"); } } /** * remove the cache for the given collection * * @param collection * @throws ItemCountException */ private void removeCollection(Collection collection) throws ItemCountException { try { Object[] params = { Integer.valueOf(collection.getID()) }; DatabaseManager.updateQuery(context, collectionRemove, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Remove the cache for the given community * * @param community * @throws ItemCountException */ private void removeCommunity(Community community) throws ItemCountException { try { Object[] params = { Integer.valueOf(community.getID()) }; DatabaseManager.updateQuery(context, communityRemove, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Get the count for the given collection * * @param collection * @return * @throws ItemCountException */ private int getCollectionCount(Collection collection) throws ItemCountException { TableRowIterator tri = null; try { Object[] params = { Integer.valueOf(collection.getID()) }; tri = DatabaseManager.query(context, collectionSelect, params); if (!tri.hasNext()) { return 0; } TableRow tr = tri.next(); if (tri.hasNext()) { throw new ItemCountException("More than one count row in the database"); } return tr.getIntColumn("count"); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } /** * get the count for the given community * * @param community * @return * @throws ItemCountException */ private int getCommunityCount(Community community) throws ItemCountException { TableRowIterator tri = null; try { Object[] params = { Integer.valueOf(community.getID()) }; tri = DatabaseManager.query(context, communitySelect, params); if (!tri.hasNext()) { return 0; } TableRow tr = tri.next(); if (tri.hasNext()) { throw new ItemCountException("More than one count row in the database"); } return tr.getIntColumn("count"); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } }
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.browse; import org.apache.log4j.Logger; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Context; import org.dspace.storage.rdbms.TableRowIterator; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.DatabaseManager; import java.sql.SQLException; /** * Oracle driver implementing ItemCountDAO interface to cache item * count information in communities and collections * * @author Richard Jones * */ public class ItemCountDAOOracle implements ItemCountDAO { /** Log4j logger */ private static Logger log = Logger.getLogger(ItemCountDAOOracle.class); /** DSpace context */ private Context context; /** SQL to select on a collection id */ private String collectionSelect = "SELECT * FROM collection_item_count WHERE collection_id = ?"; /** SQL to insert a new collection record */ private String collectionInsert = "INSERT INTO collection_item_count (collection_id, count) VALUES (?, ?)"; /** SQL to update an existing collection record */ private String collectionUpdate = "UPDATE collection_item_count SET count = ? WHERE collection_id = ?"; /** SQL to remove a collection record */ private String collectionRemove = "DELETE FROM collection_item_count WHERE collection_id = ?"; /** SQL to select on a community id */ private String communitySelect = "SELECT * FROM community_item_count WHERE community_id = ?"; /** SQL to insert a new community record */ private String communityInsert = "INSERT INTO community_item_count (community_id, count) VALUES (?, ?)"; /** SQL to update an existing community record */ private String communityUpdate = "UPDATE community_item_count SET count = ? WHERE community_id = ?"; /** SQL to remove a community record */ private String communityRemove = "DELETE FROM community_item_count WHERE community_id = ?"; /** * Store the count of the given collection * * @param collection * @param count * @throws ItemCountException */ public void collectionCount(Collection collection, int count) throws ItemCountException { TableRowIterator tri = null; try { // first find out if we have a record Object[] sparams = { Integer.valueOf(collection.getID()) }; tri = DatabaseManager.query(context, collectionSelect, sparams); if (tri.hasNext()) { Object[] params = { Integer.valueOf(count), Integer.valueOf(collection.getID()) }; DatabaseManager.updateQuery(context, collectionUpdate, params); } else { Object[] params = { Integer.valueOf(collection.getID()), Integer.valueOf(count) }; DatabaseManager.updateQuery(context, collectionInsert, params); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } /** * Store the count of the given community * * @param community * @param count * @throws ItemCountException */ public void communityCount(Community community, int count) throws ItemCountException { TableRowIterator tri = null; try { // first find out if we have a record Object[] sparams = { Integer.valueOf(community.getID()) }; tri = DatabaseManager.query(context, communitySelect, sparams); if (tri.hasNext()) { Object[] params = { Integer.valueOf(count), Integer.valueOf(community.getID()) }; DatabaseManager.updateQuery(context, communityUpdate, params); } else { Object[] params = { Integer.valueOf(community.getID()), Integer.valueOf(count) }; DatabaseManager.updateQuery(context, communityInsert, params); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } /** * Set the dspace context to use * * @param context * @throws ItemCountException */ public void setContext(Context context) throws ItemCountException { this.context = context; } /** * get the count of the items in the given container * * @param dso * @return * @throws ItemCountException */ public int getCount(DSpaceObject dso) throws ItemCountException { if (dso instanceof Collection) { return getCollectionCount((Collection) dso); } else if (dso instanceof Community) { return getCommunityCount((Community) dso); } else { throw new ItemCountException("We can only count items in Communities or Collections"); } } /** * remove the cache for the given container * * @param dso * @throws ItemCountException */ public void remove(DSpaceObject dso) throws ItemCountException { if (dso instanceof Collection) { removeCollection((Collection) dso); } else if (dso instanceof Community) { removeCommunity((Community) dso); } else { throw new ItemCountException("We can only delete count of items from Communities or Collections"); } } /** * remove the cache for the given collection * * @param collection * @throws ItemCountException */ private void removeCollection(Collection collection) throws ItemCountException { try { Object[] params = { Integer.valueOf(collection.getID()) }; DatabaseManager.updateQuery(context, collectionRemove, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Remove the cache for the given community * * @param community * @throws ItemCountException */ private void removeCommunity(Community community) throws ItemCountException { try { Object[] params = { Integer.valueOf(community.getID()) }; DatabaseManager.updateQuery(context, communityRemove, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Get the count for the given collection * * @param collection * @return * @throws ItemCountException */ private int getCollectionCount(Collection collection) throws ItemCountException { TableRowIterator tri = null; try { Object[] params = { Integer.valueOf(collection.getID()) }; tri = DatabaseManager.query(context, collectionSelect, params); if (!tri.hasNext()) { return 0; } TableRow tr = tri.next(); if (tri.hasNext()) { throw new ItemCountException("More than one count row in the database"); } return tr.getIntColumn("count"); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } /** * get the count for the given community * * @param community * @return * @throws ItemCountException */ private int getCommunityCount(Community community) throws ItemCountException { TableRowIterator tri = null; try { Object[] params = { Integer.valueOf(community.getID()) }; tri = DatabaseManager.query(context, communitySelect, params); if (!tri.hasNext()) { return 0; } TableRow tr = tri.next(); if (tri.hasNext()) { throw new ItemCountException("More than one count row in the database"); } return tr.getIntColumn("count"); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } finally { if (tri != null) { tri.close(); } } } }
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.browse; import org.dspace.core.Context; import org.dspace.core.ConfigurationManager; /** * Factory class to allow us to load the correct DAO for registering * item count information * * @author Richard Jones * */ public class ItemCountDAOFactory { /** * Get an instance of ItemCountDAO which supports the correct database * for the specific DSpace instance. * * @param context * @return * @throws ItemCountException */ public static ItemCountDAO getInstance(Context context) throws ItemCountException { String db = ConfigurationManager.getProperty("db.name"); ItemCountDAO dao; if ("postgres".equals(db)) { dao = new ItemCountDAOPostgres(); } else if ("oracle".equals(db)) { dao = new ItemCountDAOOracle(); } else { throw new ItemCountException("Database type: " + db + " is not currently supported"); } dao.setContext(context); return dao; } }
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.browse; import java.util.Locale; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; import org.dspace.text.filter.TextFilter; import com.ibm.icu.text.CollationElementIterator; import com.ibm.icu.text.Collator; import com.ibm.icu.text.RuleBasedCollator; /** * Makes a sort string that is Locale dependent. * Uses the same Locale for all items, regardless of source language. * * You can set the Locale to use by setting 'webui.browse.sort.locale' * in the dspace.cfg to an ISO code. * * If you do not specify a Locale, then it defaults to Locale.ENGLISH. * * IMPORTANT: The strings that this generates are NOT human readable. * Also, you will not be able to meaningfully apply any filters *after* this, * however, you can apply other filters before. * * @author Graham Triggs */ public class LocaleOrderingFilter implements TextFilter { private static Logger log = Logger.getLogger(LocaleOrderingFilter.class); /** * Uses a Locale dependent Collator to generate a sort string * @param str The string to parse * @return String the sort ordering text */ public String filter(String str) { RuleBasedCollator collator = getCollator(); // Have we got a collator? if (collator != null) { int element; StringBuffer buf = new StringBuffer(); // Iterate through the elements of the collator CollationElementIterator iter = collator.getCollationElementIterator(str); while ((element = iter.next()) != CollationElementIterator.NULLORDER) { // Generate a hexadecimal string representation of the Collation element // This can then be compared in a text sort ;-) String test = Integer.toString(element, 16); buf.append(test); } return buf.toString(); } return str; } /** * We don't need to use the language parameter, so map this to * the standard sort string filter */ public String filter(String str, String lang) { return filter(str); } /** * Get a Locale dependent collator * * @return The collator to use */ private static RuleBasedCollator getCollator() { // Get the Locale to use Locale locale = getSortLocale(); if (locale != null) { // Get collator for the supplied Locale RuleBasedCollator collator = (RuleBasedCollator)Collator.getInstance(locale); if (collator != null) { return collator; } } return null; } /** * Get a Locale to use for the sorting * * @return The Locale to use */ private static Locale getSortLocale() { Locale theLocale = null; // Get a Locale configuration from the dspace.cfg String locale = ConfigurationManager.getProperty("webui.browse.sort.locale"); if (locale != null) { // Attempt to create Locale for the configured value String[] localeArr = locale.split("_"); if (localeArr.length > 1) { theLocale = new Locale(localeArr[0], localeArr[1]); } else { theLocale = new Locale(locale); } // Return the configured locale, or English default if (theLocale == null) { log.warn("Could not create the supplied Locale: webui.browse.sort.locale=" + locale); return Locale.ENGLISH; } } else { return Locale.ENGLISH; } return theLocale; } }
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.browse; /** * Utility class for retrieving the size of the columns to be used in the browse tables, * and applying truncation to the strings that will be inserted into the tables. * * Can be configured in dspace.cfg, with the following entries: * * webui.browse.value_columns.max * - the maximum number of characters in 'value' columns * (0 is unlimited) * * webui.browse.sort_columns.max * - the maximum number of characters in 'sort' columns * (0 is unlimited) * * webui.browse.value_columns.omission_mark * - a string to append to truncated values that will be entered into * the value columns (ie. '...') * * By default, the column sizes are '0' (unlimited), and no truncation is applied, * EXCEPT for Oracle, where we have to truncate the columns for it to work! (in which * case, both value and sort columns are by default limited to 2000 characters). * * @author Graham Triggs * @author Richard Jones */ public interface BrowseDAOUtils { /** * Get the size to use for the 'value' columns in characters * * @return */ public int getValueColumnMaxChars(); /** * Get the size to use for the sort columns in characters * * @return */ public int getSortColumnMaxChars(); /** * Truncate strings that are to be used for the 'value' columns * * @param value * @return */ public String truncateValue(String value); /** * Truncate strings that are to be used for sorting * * @param value * @return */ public String truncateSortValue(String value); /** * Truncate strings that are to be used for the 'value' columns. * Characters is the maximum number of characters to allow. * Actual truncation applied will be the SMALLER of the passed * value, or that read from the configuration. * * @param value * @param chars * @return * @deprecated */ public String truncateValue(String value, int chars); /** * Truncate strings that are to be used for the sorting * Characters is the maximum number of characters to allow. * Actual truncation applied will be the SMALLER of the passed * value, or that read from the configuration. * * @param value * @param chars * @return * @deprecated */ public String truncateSortValue(String value, int chars); }
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.browse; import java.util.HashMap; import java.util.Map; import org.dspace.core.ConfigurationManager; /** * Class to represent the configuration of the cross-linking between browse * pages (for example, between the author name in one full listing to the * author's list of publications). * * @author Richard Jones * */ public class CrossLinks { /** a map of the desired links */ private Map<String, String> links = new HashMap<String, String>(); /** * Construct a new object which will obtain the configuration for itself * * @throws BrowseException */ public CrossLinks() throws BrowseException { int i = 1; while (true) { String field = "webui.browse.link." + i; String config = ConfigurationManager.getProperty(field); if (config == null) { break; } String[] parts = config.split(":"); if (parts.length != 2) { throw new BrowseException("Invalid configuration for " + field + ": " + config); } links.put(parts[1], parts[0]); i++; } } /** * Is there a link for the given canonical form of metadata (i.e. schema.element.qualifier) * * @param metadata the metadata to check for a link on * @return */ public boolean hasLink(String metadata) { return links.containsKey(metadata); } /** * get the type of link that the bit of metadata has * * @param metadata the metadata to get the link type for * @return */ public String getLinkType(String metadata) { return links.get(metadata); } }
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.browse; import org.dspace.storage.rdbms.TableRowIterator; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.core.Context; import org.dspace.content.DCValue; import org.dspace.content.Item; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BrowseItemDAOPostgres implements BrowseItemDAO { /** query to obtain all the items from the database */ private String findAll = "SELECT item_id, in_archive, withdrawn FROM item WHERE in_archive = true OR withdrawn = true"; /** query to get the text value of a metadata element only (qualifier is NULL) */ private String getByMetadataElement = "SELECT authority, confidence, text_value,text_lang,element,qualifier FROM metadatavalue, metadatafieldregistry, metadataschemaregistry " + "WHERE metadatavalue.item_id = ? " + " AND metadatavalue.metadata_field_id = metadatafieldregistry.metadata_field_id " + " AND metadatafieldregistry.element = ? " + " AND metadatafieldregistry.qualifier IS NULL " + " AND metadatafieldregistry.metadata_schema_id=metadataschemaregistry.metadata_schema_id " + " AND metadataschemaregistry.short_id = ? " + " ORDER BY metadatavalue.metadata_field_id, metadatavalue.place"; /** query to get the text value of a metadata element and qualifier */ private String getByMetadata = "SELECT authority, confidence, text_value,text_lang,element,qualifier FROM metadatavalue, metadatafieldregistry, metadataschemaregistry " + "WHERE metadatavalue.item_id = ? " + " AND metadatavalue.metadata_field_id = metadatafieldregistry.metadata_field_id " + " AND metadatafieldregistry.element = ? " + " AND metadatafieldregistry.qualifier = ? " + " AND metadatafieldregistry.metadata_schema_id=metadataschemaregistry.metadata_schema_id " + " AND metadataschemaregistry.short_id = ? " + " ORDER BY metadatavalue.metadata_field_id, metadatavalue.place"; /** query to get the text value of a metadata element with the wildcard qualifier (*) */ private String getByMetadataAnyQualifier = "SELECT authority, confidence, text_value,text_lang,element,qualifier FROM metadatavalue, metadatafieldregistry, metadataschemaregistry " + "WHERE metadatavalue.item_id = ? " + " AND metadatavalue.metadata_field_id = metadatafieldregistry.metadata_field_id " + " AND metadatafieldregistry.element = ? " + " AND metadatafieldregistry.metadata_schema_id=metadataschemaregistry.metadata_schema_id " + " AND metadataschemaregistry.short_id = ? " + " ORDER BY metadatavalue.metadata_field_id, metadatavalue.place"; /** DSpace context */ private Context context; public BrowseItemDAOPostgres(Context context) throws BrowseException { this.context = context; } public BrowseItem[] findAll() throws SQLException { TableRowIterator tri = null; List<BrowseItem> items = new ArrayList<BrowseItem>(); try { tri = DatabaseManager.query(context, findAll); while (tri.hasNext()) { TableRow row = tri.next(); items.add(new BrowseItem(context, row.getIntColumn("item_id"), row.getBooleanColumn("in_archive"), row.getBooleanColumn("withdrawn"))); } } finally { if (tri != null) { tri.close(); } } BrowseItem[] bis = new BrowseItem[items.size()]; return items.toArray(bis); } public DCValue[] queryMetadata(int itemId, String schema, String element, String qualifier, String lang) throws SQLException { List<DCValue> values = new ArrayList<DCValue>(); TableRowIterator tri = null; try { if (qualifier == null) { Object[] params = { Integer.valueOf(itemId), element, schema }; tri = DatabaseManager.query(context, getByMetadataElement, params); } else if (Item.ANY.equals(qualifier)) { Object[] params = { Integer.valueOf(itemId), element, schema }; tri = DatabaseManager.query(context, getByMetadataAnyQualifier, params); } else { Object[] params = { Integer.valueOf(itemId), element, qualifier, schema }; tri = DatabaseManager.query(context, getByMetadata, params); } if (!tri.hasNext()) { return new DCValue[0]; } while (tri.hasNext()) { TableRow tr = tri.next(); DCValue dcv = new DCValue(); dcv.schema = schema; dcv.element = tr.getStringColumn("element"); dcv.qualifier = tr.getStringColumn("qualifier"); dcv.language = tr.getStringColumn("text_lang"); dcv.value = tr.getStringColumn("text_value"); dcv.authority = tr.getStringColumn("authority"); dcv.confidence = tr.getIntColumn("confidence"); values.add(dcv); } } finally { if (tri != null) { tri.close(); } } DCValue[] dcvs = new DCValue[values.size()]; return values.toArray(dcvs); } }
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.browse; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.dspace.core.ConfigurationManager; import org.dspace.sort.SortOption; import org.dspace.sort.SortException; /** * This class holds all the information about a specifically configured * BrowseIndex. It is responsible for parsing the configuration, understanding * about what sort options are available, and what the names of the database * tables that hold all the information are actually called. * * @author Richard Jones */ public final class BrowseIndex { /** the configuration number, as specified in the config */ /** used for single metadata browse tables for generating the table name */ private int number; /** the name of the browse index, as specified in the config */ private String name; /** the SortOption for this index (only valid for item indexes) */ private SortOption sortOption; /** the value of the metadata, as specified in the config */ private String metadataAll; /** the metadata fields, as an array */ private String[] metadata; /** the datatype of the index, as specified in the config */ private String datatype; /** the display type of the metadata, as specified in the config */ private String displayType; /** base name for tables, sequences */ private String tableBaseName; /** a three part array of the metadata bits (e.g. dc.contributor.author) */ private String[][] mdBits; /** default order (asc / desc) for this index */ private String defaultOrder = SortOption.ASCENDING; /** additional 'internal' tables that are always defined */ private static BrowseIndex itemIndex = new BrowseIndex("bi_item"); private static BrowseIndex withdrawnIndex = new BrowseIndex("bi_withdrawn"); /** * Ensure no one else can create these */ private BrowseIndex() { } /** * Constructor for creating generic / internal index objects * @param baseName The base of the table name */ private BrowseIndex(String baseName) { try { number = -1; tableBaseName = baseName; displayType = "item"; sortOption = SortOption.getDefaultSortOption(); } catch (SortException se) { // FIXME Exception handling } } /** * Create a new BrowseIndex object using the definition from the configuration, * and the number of the configuration option. The definition should be of * the form: * * <code> * [name]:[metadata]:[data type]:[display type] * </code> * * [name] is a freetext name for the field * [metadata] is the usual format of the metadata such as dc.contributor.author * [data type] must be either "title", "date" or "text" * [display type] must be either "single" or "full" * * @param definition the configuration definition of this index * @param number the configuration number of this index * @throws BrowseException */ private BrowseIndex(String definition, int number) throws BrowseException { try { boolean valid = true; this.defaultOrder = SortOption.ASCENDING; this.number = number; String rx = "(\\w+):(\\w+):([\\w\\.\\*,]+):?(\\w*):?(\\w*)"; Pattern pattern = Pattern.compile(rx); Matcher matcher = pattern.matcher(definition); if (matcher.matches()) { name = matcher.group(1); displayType = matcher.group(2); if (isMetadataIndex()) { metadataAll = matcher.group(3); datatype = matcher.group(4); if (metadataAll != null) { metadata = metadataAll.split(","); } if (metadata == null || metadata.length == 0) { valid = false; } if (datatype == null || datatype.equals("")) { valid = false; } // If an optional ordering configuration is supplied, // set the defaultOrder appropriately (asc or desc) if (matcher.groupCount() > 4) { String order = matcher.group(5); if (SortOption.DESCENDING.equalsIgnoreCase(order)) { this.defaultOrder = SortOption.DESCENDING; } } tableBaseName = getItemBrowseIndex().tableBaseName; } else if (isItemIndex()) { String sortName = matcher.group(3); for (SortOption so : SortOption.getSortOptions()) { if (so.getName().equals(sortName)) { sortOption = so; } } if (sortOption == null) { valid = false; } // If an optional ordering configuration is supplied, // set the defaultOrder appropriately (asc or desc) if (matcher.groupCount() > 3) { String order = matcher.group(4); if (SortOption.DESCENDING.equalsIgnoreCase(order)) { this.defaultOrder = SortOption.DESCENDING; } } tableBaseName = getItemBrowseIndex().tableBaseName; } else { valid = false; } } else { valid = false; } if (!valid) { throw new BrowseException("Browse Index configuration is not valid: webui.browse.index." + number + " = " + definition); } } catch (SortException se) { throw new BrowseException("Error in SortOptions", se); } } /** * @return Default order for this index, null if not specified */ public String getDefaultOrder() { return defaultOrder; } /** * @return Returns the datatype. */ public String getDataType() { if (sortOption != null) { return sortOption.getType(); } return datatype; } /** * @return Returns the displayType. */ public String getDisplayType() { return displayType; } /** * @return Returns the number of metadata fields for this index */ public int getMetadataCount() { if (isMetadataIndex()) { return metadata.length; } return 0; } /** * @return Returns the mdBits. */ public String[] getMdBits(int idx) { if (isMetadataIndex()) { return mdBits[idx]; } return null; } /** * @return Returns the metadata. */ public String getMetadata() { return metadataAll; } public String getMetadata(int idx) { return metadata[idx]; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ // public void setName(String name) // { // this.name = name; // } /** * Get the SortOption associated with this index. */ public SortOption getSortOption() { return sortOption; } /** * Populate the internal array containing the bits of metadata, for * ease of use later */ public void generateMdBits() { try { if (isMetadataIndex()) { mdBits = new String[metadata.length][]; for (int i = 0; i < metadata.length; i++) { mdBits[i] = interpretField(metadata[i], null); } } } catch(IOException e) { // it's not obvious what we really ought to do here //log.error("caught exception: ", e); } } /** * Get the name of the sequence that will be used in the given circumstances * * @param isDistinct is a distinct table * @param isMap is a map table * @return the name of the sequence */ public String getSequenceName(boolean isDistinct, boolean isMap) { if (isDistinct || isMap) { return BrowseIndex.getSequenceName(number, isDistinct, isMap); } return BrowseIndex.getSequenceName(tableBaseName, isDistinct, isMap); } /** * Get the name of the sequence that will be used in the given circumstances * * @param number the index configuration number * @param isDistinct is a distinct table * @param isMap is a map table * @return the name of the sequence */ public static String getSequenceName(int number, boolean isDistinct, boolean isMap) { return BrowseIndex.getSequenceName(makeTableBaseName(number), isDistinct, isMap); } /** * Generate a sequence name from the given base * @param baseName * @param isDistinct * @param isMap * @return */ private static String getSequenceName(String baseName, boolean isDistinct, boolean isMap) { if (isDistinct) { baseName = baseName + "_dis"; } else if (isMap) { baseName = baseName + "_dmap"; } baseName = baseName + "_seq"; return baseName; } /** * Get the name of the table for the given set of circumstances * This is provided solely for cleaning the database, where you are * trying to create table names that may not be reflected in the current index * * @param number the index configuration number * @param isCommunity whether this is a community constrained index (view) * @param isCollection whether this is a collection constrained index (view) * @param isDistinct whether this is a distinct table * @param isMap whether this is a distinct map table * @return the name of the table * @deprecated 1.5 */ public static String getTableName(int number, boolean isCommunity, boolean isCollection, boolean isDistinct, boolean isMap) { return BrowseIndex.getTableName(makeTableBaseName(number), isCommunity, isCollection, isDistinct, isMap); } /** * Generate a table name from the given base * @param baseName * @param isCommunity * @param isCollection * @param isDistinct * @param isMap * @return */ private static String getTableName(String baseName, boolean isCommunity, boolean isCollection, boolean isDistinct, boolean isMap) { // isDistinct is meaningless in relation to isCommunity and isCollection // so we bounce that back first, ignoring other arguments if (isDistinct) { return baseName + "_dis"; } // isCommunity and isCollection are mutually exclusive if (isCommunity) { baseName = baseName + "_com"; } else if (isCollection) { baseName = baseName + "_col"; } // isMap is additive to isCommunity and isCollection if (isMap) { baseName = baseName + "_dmap"; } return baseName; } /** * Get the name of the table in the given circumstances * * @param isCommunity whether this is a community constrained index (view) * @param isCollection whether this is a collection constrained index (view) * @param isDistinct whether this is a distinct table * @param isMap whether this is a distinct map table * @return the name of the table * @deprecated 1.5 */ public String getTableName(boolean isCommunity, boolean isCollection, boolean isDistinct, boolean isMap) { if (isDistinct || isMap) { return BrowseIndex.getTableName(number, isCommunity, isCollection, isDistinct, isMap); } return BrowseIndex.getTableName(tableBaseName, isCommunity, isCollection, isDistinct, isMap); } /** * Get the name of the table in the given circumstances. This is the same as calling * * <code> * getTableName(isCommunity, isCollection, false, false); * </code> * * @param isCommunity whether this is a community constrained index (view) * @param isCollection whether this is a collection constrained index (view) * @return the name of the table * @deprecated 1.5 */ public String getTableName(boolean isCommunity, boolean isCollection) { return getTableName(isCommunity, isCollection, false, false); } /** * Get the default index table name. This is the same as calling * * <code> * getTableName(false, false, false, false); * </code> * * @return */ public String getTableName() { return getTableName(false, false, false, false); } /** * Get the table name for the given set of circumstances * * This is the same as calling: * * <code> * getTableName(isCommunity, isCollection, isDistinct, false); * </code> * * @param isDistinct is this a distinct table * @param isCommunity * @param isCollection * @return * @deprecated 1.5 */ public String getTableName(boolean isDistinct, boolean isCommunity, boolean isCollection) { return getTableName(isCommunity, isCollection, isDistinct, false); } /** * Get the default name of the distinct map table. This is the same as calling * * <code> * getTableName(false, false, false, true); * </code> * * @return */ public String getMapTableName() { return getTableName(false, false, false, true); } /** * Get the default name of the distinct table. This is the same as calling * * <code> * getTableName(false, false, true, false); * </code> * * @return */ public String getDistinctTableName() { return getTableName(false, false, true, false); } /** * Get the name of the column that is used to store the default value column * * @return the name of the value column */ public String getValueColumn() { if (!isDate()) { return "sort_text_value"; } else { return "text_value"; } } /** * Get the name of the primary key index column * * @return the name of the primary key index column */ public String getIndexColumn() { return "id"; } /** * Is this browse index type for a title? * * @return true if title type, false if not */ // public boolean isTitle() // { // return "title".equals(getDataType()); // } /** * Is the browse index type for a date? * * @return true if date type, false if not */ public boolean isDate() { return "date".equals(getDataType()); } /** * Is the browse index type for a plain text type? * * @return true if plain text type, false if not */ // public boolean isText() // { // return "text".equals(getDataType()); // } /** * Is the browse index of display type single? * * @return true if singe, false if not */ public boolean isMetadataIndex() { return displayType != null && displayType.startsWith("metadata"); } /** * Is the browse index authority value? * * @return true if authority, false if not */ public boolean isAuthorityIndex() { return "metadataAuthority".equals(displayType); } /** * Is the browse index of display type full? * * @return true if full, false if not */ public boolean isItemIndex() { return "item".equals(displayType); } /** * Get the field for sorting associated with this index * @return * @throws BrowseException */ public String getSortField(boolean isSecondLevel) throws BrowseException { String focusField; if (isMetadataIndex() && !isSecondLevel) { focusField = "sort_value"; } else { if (sortOption != null) { focusField = "sort_" + sortOption.getNumber(); } else { focusField = "sort_1"; // Use the first sort column } } return focusField; } /** * @deprecated * @return * @throws BrowseException */ public static String[] tables() throws BrowseException { BrowseIndex[] bis = getBrowseIndices(); String[] returnTables = new String[bis.length]; for (int i = 0; i < bis.length; i++) { returnTables[i] = bis[i].getTableName(); } return returnTables; } /** * Get an array of all the browse indices for the current configuration * * @return an array of all the current browse indices * @throws BrowseException */ public static BrowseIndex[] getBrowseIndices() throws BrowseException { int idx = 1; String definition; ArrayList<BrowseIndex> browseIndices = new ArrayList<BrowseIndex>(); while ( ((definition = ConfigurationManager.getProperty("webui.browse.index." + idx))) != null) { BrowseIndex bi = new BrowseIndex(definition, idx); browseIndices.add(bi); idx++; } BrowseIndex[] bis = new BrowseIndex[browseIndices.size()]; bis = browseIndices.toArray(bis); return bis; } /** * Get the browse index from configuration with the specified name. * The name is the first part of the browse configuration * * @param name the name to retrieve * @return the specified browse index * @throws BrowseException */ public static BrowseIndex getBrowseIndex(String name) throws BrowseException { for (BrowseIndex bix : BrowseIndex.getBrowseIndices()) { if (bix.getName().equals(name)) { return bix; } } return null; } /** * Get the configured browse index that is defined to use this sort option * * @param so * @return * @throws BrowseException */ public static BrowseIndex getBrowseIndex(SortOption so) throws BrowseException { for (BrowseIndex bix : BrowseIndex.getBrowseIndices()) { if (bix.getSortOption() == so) { return bix; } } return null; } /** * Get the internally defined browse index for archived items * * @return */ public static BrowseIndex getItemBrowseIndex() { return BrowseIndex.itemIndex; } /** * Get the internally defined browse index for withdrawn items * @return */ public static BrowseIndex getWithdrawnBrowseIndex() { return BrowseIndex.withdrawnIndex; } /** * Take a string representation of a metadata field, and return it as an array. * This is just a convenient utility method to basically break the metadata * representation up by its delimiter (.), and stick it in an array, inserting * the value of the init parameter when there is no metadata field part. * * @param mfield the string representation of the metadata * @param init the default value of the array elements * @return a three element array with schema, element and qualifier respectively */ public String[] interpretField(String mfield, String init) throws IOException { StringTokenizer sta = new StringTokenizer(mfield, "."); String[] field = {init, init, init}; int i = 0; while (sta.hasMoreTokens()) { field[i++] = sta.nextToken(); } // error checks to make sure we have at least a schema and qualifier for both if (field[0] == null || field[1] == null) { throw new IOException("at least a schema and element be " + "specified in configuration. You supplied: " + mfield); } return field; } /** * Does this browse index represent one of the internal item indexes * * @return */ public boolean isInternalIndex() { return (this == itemIndex || this == withdrawnIndex); } /** * Generate a base table name * @param number * @return */ private static String makeTableBaseName(int number) { return "bi_" + Integer.toString(number); } }
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.browse; import org.dspace.storage.rdbms.TableRowIterator; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.core.Context; import org.dspace.content.DCValue; import org.dspace.content.Item; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BrowseItemDAOOracle implements BrowseItemDAO { /** query to obtain all the items from the database */ private String findAll = "SELECT item_id, in_archive, withdrawn FROM item WHERE in_archive = 1 OR withdrawn = 1"; /** query to get the text value of a metadata element only (qualifier is NULL) */ private String getByMetadataElement = "SELECT authority, confidence, text_value,text_lang,element,qualifier FROM metadatavalue, metadatafieldregistry, metadataschemaregistry " + "WHERE metadatavalue.item_id = ? " + " AND metadatavalue.metadata_field_id = metadatafieldregistry.metadata_field_id " + " AND metadatafieldregistry.element = ? " + " AND metadatafieldregistry.qualifier IS NULL " + " AND metadatafieldregistry.metadata_schema_id=metadataschemaregistry.metadata_schema_id " + " AND metadataschemaregistry.short_id = ? " + " ORDER BY metadatavalue.metadata_field_id, metadatavalue.place"; /** query to get the text value of a metadata element and qualifier */ private String getByMetadata = "SELECT authority, confidence, text_value,text_lang,element,qualifier FROM metadatavalue, metadatafieldregistry, metadataschemaregistry " + "WHERE metadatavalue.item_id = ? " + " AND metadatavalue.metadata_field_id = metadatafieldregistry.metadata_field_id " + " AND metadatafieldregistry.element = ? " + " AND metadatafieldregistry.qualifier = ? " + " AND metadatafieldregistry.metadata_schema_id=metadataschemaregistry.metadata_schema_id " + " AND metadataschemaregistry.short_id = ? " + " ORDER BY metadatavalue.metadata_field_id, metadatavalue.place"; /** query to get the text value of a metadata element with the wildcard qualifier (*) */ private String getByMetadataAnyQualifier = "SELECT authority, confidence, text_value,text_lang,element,qualifier FROM metadatavalue, metadatafieldregistry, metadataschemaregistry " + "WHERE metadatavalue.item_id = ? " + " AND metadatavalue.metadata_field_id = metadatafieldregistry.metadata_field_id " + " AND metadatafieldregistry.element = ? " + " AND metadatafieldregistry.metadata_schema_id=metadataschemaregistry.metadata_schema_id " + " AND metadataschemaregistry.short_id = ? " + " ORDER BY metadatavalue.metadata_field_id, metadatavalue.place"; /** DSpace context */ private Context context; public BrowseItemDAOOracle(Context context) throws BrowseException { this.context = context; } public BrowseItem[] findAll() throws SQLException { TableRowIterator tri = null; List<BrowseItem> items = new ArrayList<BrowseItem>(); try { tri = DatabaseManager.query(context, findAll); while (tri.hasNext()) { TableRow row = tri.next(); items.add(new BrowseItem(context, row.getIntColumn("item_id"), row.getBooleanColumn("in_archive"), row.getBooleanColumn("withdrawn"))); } } finally { if (tri != null) { tri.close(); } } BrowseItem[] bis = new BrowseItem[items.size()]; return items.toArray(bis); } public DCValue[] queryMetadata(int itemId, String schema, String element, String qualifier, String lang) throws SQLException { List<DCValue> values = new ArrayList<DCValue>(); TableRowIterator tri = null; try { if (qualifier == null) { Object[] params = { Integer.valueOf(itemId), element, schema }; tri = DatabaseManager.query(context, getByMetadataElement, params); } else if (Item.ANY.equals(qualifier)) { Object[] params = { Integer.valueOf(itemId), element, schema }; tri = DatabaseManager.query(context, getByMetadataAnyQualifier, params); } else { Object[] params = { Integer.valueOf(itemId), element, qualifier, schema }; tri = DatabaseManager.query(context, getByMetadata, params); } if (!tri.hasNext()) { return new DCValue[0]; } while (tri.hasNext()) { TableRow tr = tri.next(); DCValue dcv = new DCValue(); dcv.schema = schema; dcv.element = tr.getStringColumn("element"); dcv.qualifier = tr.getStringColumn("qualifier"); dcv.language = tr.getStringColumn("text_lang"); dcv.value = tr.getStringColumn("text_value"); dcv.authority = tr.getStringColumn("authority"); dcv.confidence = tr.getIntColumn("confidence"); values.add(dcv); } } finally { if (tri != null) { tri.close(); } } DCValue[] dcvs = new DCValue[values.size()]; return values.toArray(dcvs); } }
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.browse; /** * Exception type to handle item count specific problems * * @author Richard Jones * */ public class ItemCountException extends Exception { public ItemCountException() { } public ItemCountException(String message) { super(message); } public ItemCountException(Throwable cause) { super(cause); } public ItemCountException(String message, Throwable 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/ */ package org.dspace.browse; /** * Just a quick BrowseException class to give us the relevant data type * * @author Richard Jones */ public class BrowseException extends Exception { public BrowseException() { super(); } public BrowseException(String message) { super(message); } public BrowseException(String message, Throwable cause) { super(message, cause); } public BrowseException(Throwable cause) { super(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/ */ package org.dspace.browse; import org.apache.log4j.Logger; import org.dspace.content.Community; import org.dspace.content.Collection; import org.dspace.core.Context; import org.dspace.content.DSpaceObject; import org.dspace.core.ConfigurationManager; import java.sql.SQLException; /** * This class provides a standard interface to all item counting * operations for communities and collections. It can be run from the * command line to prepare the cached data if desired, simply by * running: * * java org.dspace.browse.ItemCounter * * It can also be invoked via its standard API. In the event that * the data cache is not being used, this class will return direct * real time counts of content. * * @author Richard Jones * */ public class ItemCounter { /** Log4j logger */ private static Logger log = Logger.getLogger(ItemCounter.class); /** DAO to use to store and retrieve data */ private ItemCountDAO dao; /** DSpace Context */ private Context context; /** * method invoked by CLI which will result in the number of items * in each community and collection being cached. These counts will * not update themselves until this is run again. * * @param args */ public static void main(String[] args) throws ItemCountException, SQLException { Context context = new Context(); ItemCounter ic = new ItemCounter(context); ic.buildItemCounts(); context.complete(); } /** * Construct a new item counter which will use the give DSpace Context * * @param context * @throws ItemCountException */ public ItemCounter(Context context) throws ItemCountException { this.context = context; this.dao = ItemCountDAOFactory.getInstance(this.context); } /** * This method does the grunt work of drilling through and iterating * over all of the communities and collections in the system and * obtaining and caching the item counts for each one. * * @throws ItemCountException */ public void buildItemCounts() throws ItemCountException { try { Community[] tlc = Community.findAllTop(context); for (int i = 0; i < tlc.length; i++) { count(tlc[i]); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Get the count of the items in the given container. If the configuration * value webui.strengths.cache is equal to 'true' this will return the * cached value if it exists. If it is equal to 'false' it will count * the number of items in the container in real time * * @param dso * @return * @throws ItemCountException * @throws SQLException */ public int getCount(DSpaceObject dso) throws ItemCountException { boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); if (useCache) { return dao.getCount(dso); } // if we make it this far, we need to manually count if (dso instanceof Collection) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } if (dso instanceof Community) { try { return ((Community) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } return 0; } /** * Remove any cached data for the given container * * @param dso * @throws ItemCountException */ public void remove(DSpaceObject dso) throws ItemCountException { dao.remove(dso); } /** * count and cache the number of items in the community. This * will include all sub-communities and collections in the * community. It will also recurse into sub-communities and * collections and call count() on them also. * * Therefore, the count the contents of the entire system, it is * necessary just to call this method on each top level community * * @param community * @throws ItemCountException */ private void count(Community community) throws ItemCountException { try { // first count the community we are in int count = community.countItems(); dao.communityCount(community, count); // now get the sub-communities Community[] scs = community.getSubcommunities(); for (int i = 0; i < scs.length; i++) { count(scs[i]); } // now get the collections Collection[] cols = community.getCollections(); for (int i = 0; i < cols.length; i++) { count(cols[i]); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * count and cache the number of items in the given collection * * @param collection * @throws ItemCountException */ private void count(Collection collection) throws ItemCountException { try { int ccount = collection.countItems(); dao.collectionCount(collection, ccount); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } }
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.browse; import java.sql.SQLException; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCValue; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.core.Context; import org.dspace.sort.SortOption; /** * The results of a Browse, including all the contextual information about * the query, as well as the results and associated information to create * pageable navigation. * * @author Richard Jones */ public class BrowseInfo { /** * The results of the browse. * FIXME: Unable to generify due to mixed usage */ private List results; /** * The position of the first element of results within the Browse index. * Positions begin with 0. */ private int overallPosition; /** * The position of the requested object within the results. Offsets begin * with 0. */ private int offset; /** * The total number of items in the browse index. */ private int total; /** * True if this browse was cached. */ private boolean cached; /** the browse index to which this pertains */ private BrowseIndex browseIndex; /** the sort option being used */ private SortOption sortOption; /** is the browse ascending or descending */ private boolean ascending; /** what level of browse are we in? full and single front pages are 0, single value browse is 1 */ private int level = 0; /** the value browsed upon */ private String value; /** the authority key browsed upon */ private String authority; /** is this a "starts_with" browse? */ private boolean startsWith = false; /** Collection we are constrained to */ private Collection collection; /** Community we are constrained to */ private Community community; /** offset of the item at the top of the next page */ private int nextOffset = -1; /** offset of the item at the top of the previous page */ private int prevOffset = -1; /** the value upon which we are focusing */ private String focus; /** number of results to display per page */ private int resultsPerPage = -1; /** database id of the item upon which we are focusing */ private int focusItem = -1; /** number of metadata elements to display before truncating using "et al" */ private int etAl = -1; /** * Constructor * FIXME: Unable to generify due to mixed usage * * @param results * A List of Browse results * @param overallPosition * The position of the first returned item in the overall index * @param total * The total number of items in the index * @param offset * The position of the requested item in the set of results */ public BrowseInfo(List results, int overallPosition, int total, int offset) { if (results == null) { throw new IllegalArgumentException("Null result list not allowed"); } this.results = Collections.unmodifiableList(results); this.overallPosition = overallPosition; this.total = total; this.offset = offset; } /** * @return the number of metadata fields at which to truncate with "et al" */ public int getEtAl() { return etAl; } /** * set the number of metadata fields at which to truncate with "et al" * * @param etAl */ public void setEtAl(int etAl) { this.etAl = etAl; } /** * @return Returns the focusItem. */ public int getFocusItem() { return focusItem; } /** * @param focusItem The focusItem to set. */ public void setFocusItem(int focusItem) { this.focusItem = focusItem; } /** * Does this browse have an item focus (as opposed to one of: no focus, * a value focus) * * @return true if item focus, false if not */ public boolean hasItemFocus() { if (focusItem == -1) { return false; } return true; } /** * @return Returns the resultsPerPage. */ public int getResultsPerPage() { return resultsPerPage; } /** * @param resultsPerPage The resultsPerPage to set. */ public void setResultsPerPage(int resultsPerPage) { this.resultsPerPage = resultsPerPage; } /** * Is there a value associated with this browse * * @return true if a value, false if not */ public boolean hasValue() { if (this.value != null) { return true; } return false; } /** * Is there an authority key associated with this browse * * @return true if an authority key, false if not */ public boolean hasAuthority() { if (this.authority != null) { return true; } return false; } /** * Are there results for this browse, or was the result set empty? * * @return true if results, false if not */ public boolean hasResults() { if (results.size() > 0) { return true; } return false; } /** * @param focus the value to focus the browse around */ public void setFocus(String focus) { this.focus = focus; } /** * @return the value to focus the browse around */ public String getFocus() { return this.focus; } /** * Set the DSpaceObject that is the container for this browse. If this * is not of type Collection or Community, this method will throw an * exception * * @param dso the container object; a Community or Collection * @throws BrowseException */ public void setBrowseContainer(DSpaceObject dso) throws BrowseException { if (dso instanceof Collection) { this.collection = (Collection) dso; } else if (dso instanceof Community) { this.community = (Community) dso; } else { throw new BrowseException("The container must be a community or a collection"); } } /** * Obtain a DSpaceObject that represents the container object. This will be * a Community or a Collection * * @return A DSpaceObject representing a Community or a Collection */ public DSpaceObject getBrowseContainer() { if (this.collection != null) { return this.collection; } if (this.community != null) { return this.community; } return null; } /** * @param level the browse level */ public void setBrowseLevel(int level) { this.level = level; } /** * @return the browse level */ public int getBrowseLevel() { return this.level; } /** * @param offset the database id of the item at the top of the next page */ public void setNextOffset(int offset) { this.nextOffset = offset; } /** * @return the database id of the item at the top of the next page */ public int getNextOffset() { return this.nextOffset; } /** * @return Returns the ascending. */ public boolean isAscending() { return ascending; } /** * @param ascending The ascending to set. */ public void setAscending(boolean ascending) { this.ascending = ascending; } /** * @return Returns the browseIndex. */ public BrowseIndex getBrowseIndex() { return browseIndex; } /** * @param browseIndex The browseIndex to set. */ public void setBrowseIndex(BrowseIndex browseIndex) { this.browseIndex = browseIndex; } /** * @return Returns the prevItem. */ public int getPrevOffset() { return prevOffset > -1 ? prevOffset : 0; } /** * @param prevOffset The prevOffset to set. */ public void setPrevOffset(int prevOffset) { this.prevOffset = prevOffset; } /** * @return Returns the sortOption. */ public SortOption getSortOption() { return sortOption; } /** * @param sortOption The sortOption to set. */ public void setSortOption(SortOption sortOption) { this.sortOption = sortOption; } /** * @return Returns the startsWith. */ public boolean isStartsWith() { return startsWith; } /** * @param startsWith The startsWith to set. */ public void setStartsWith(boolean startsWith) { this.startsWith = startsWith; } /** * @return Returns the value. */ public String getValue() { return value; } /** * @param value The value to set. */ public void setValue(String value) { this.value = value; } /** * @return Returns the authority key. */ public String getAuthority() { return authority; } /** * @param authority The authority key to set. */ public void setAuthority(String authority) { this.authority = authority; } /** * is this a top level (0) browse? Examples of this are a full item * browse or a single browse. Other browse types are considered * second level (1) * * @return true if top level, false if not */ public boolean isTopLevel() { if (this.level == 0) { return true; } return false; } /** * Is this a second level (1) browse? Examples of this are a single * value browse (e.g. all items by a given author) * * @return true if second level, false if not */ public boolean isSecondLevel() { if (this.level == 1) { return true; } return false; } /** * The results of the Browse. Each member of the list is either a String array * (for the authors browse: first element the value, second element the authority key) * or an {@link org.dspace.content.Item}(for the * other browses). * * @return Result list. This list cannot be modified. */ public List getResults() { return results; } /** * Return the results of the Browse as an array of String array. * The first element (i.e. index 0) is the value, the second is the authority key * * @return The results of the Browse as a String array. */ public String[][] getStringResults() { return (String[][]) results.toArray(new String[results.size()][2]); } /** * @deprecated * @return */ public Item[] getItemResults() { return new Item[0]; } /** * Return the results of the Browse as an Item array. * * @return The results of the Browse as an Item array. */ public Item[] getItemResults(Context context) throws BrowseException { try { BrowseItem[] bis = getBrowseItemResults(); Item[] items = new Item[bis.length]; for (int i = 0; i < bis.length; i++) { items[i] = Item.find(context, bis[i].getID()); } return items; } catch (SQLException e) { throw new BrowseException(e); } } /** * Return the results of the Browse as a BrowseItem array * * @return the results of the browse as a BrowseItem array */ public BrowseItem[] getBrowseItemResults() { return (BrowseItem[]) results.toArray(new BrowseItem[results.size()]); } /** * Return the number of results. * * @return The number of results. */ public int getResultCount() { return results.size(); } /** * Return the position of the results in index being browsed. This is 0 for * the start of the index. * * @return The position of the results in index being browsed. */ public int getOverallPosition() { return overallPosition; } /** * Return the total number of items in the index. * * @return The total number of items in the index. */ public int getTotal() { return total; } /** * Return the position of the requested item or value in the set of results. * * @return The position of the requested item or value in the set of results */ public int getOffset() { return offset; } /** * True if there are no previous results from the browse. * * @return True if there are no previous results from the browse */ public boolean isFirst() { return overallPosition == 0; } /** * True if these are the last results from the browse. * * @return True if these are the last results from the browse */ public boolean isLast() { return (overallPosition + getResultCount()) == total; } /** * True if this browse was cached. */ public boolean wasCached() { return cached; } /** * Set whether this browse was cached. */ void setCached(boolean cached) { this.cached = cached; } /** * are we browsing within a Community container? * * @return true if in community, false if not */ public boolean inCommunity() { if (this.community != null) { return true; } return false; } /** * are we browsing within a Collection container * * @return true if in collection, false if not */ public boolean inCollection() { if (this.collection != null) { return true; } return false; } /** * Are there further results for the browse that haven't been returned yet? * * @return true if next page, false if not */ public boolean hasNextPage() { if (nextOffset > -1) { return true; } return false; } /** * Are there results prior to these that haven't been returned here? * * @return true if previous page, false if not */ public boolean hasPrevPage() { if (offset > 0) { return true; } return false; } /** * Does this browse have a focus? * * @return true if focus, false if not */ public boolean hasFocus() { if ("".equals(focus) || focus == null) { return false; } return true; } /** * Get an integer representing the number within the total set of results which * marks the position of the first result in the current sub-set * * @return the start point of the browse page */ public int getStart() { return overallPosition + 1; } /** * Get an integer representing the number within the total set of results which * marks the position of the last result in the current sub-set * * @return the end point of the browse page */ public int getFinish() { return overallPosition + results.size(); } /** * Utility method for obtaining a string representation of the browse. This is * useful only for debug */ public String toString() { try { StringBuffer sb = new StringBuffer(); // calculate the range for display String from = Integer.toString(overallPosition + 1); String to = Integer.toString(overallPosition + results.size()); String of = Integer.toString(total); // report on the positional information of the browse sb.append("BrowseInfo String Representation: "); sb.append("Browsing " + from + " to " + to + " of " + of + " "); // insert the information about which index sb.append("in index: " + browseIndex.getName() + " (data type: " + browseIndex.getDataType() + ", display type: " + browseIndex.getDisplayType() + ") "); sb.append("||"); // report on the browse scope container String container = "all of DSpace"; DSpaceObject theContainer = null; if (inCollection()) { container = "collection"; theContainer = this.collection; } else if (inCommunity()) { container = "community"; theContainer = this.community; } String containerID = "no id available/necessary"; if (theContainer != null) { containerID = Integer.toString(theContainer.getID()) + " (" + theContainer.getHandle() + ")"; } sb.append("Browsing in " + container + ": " + containerID); sb.append("||"); // load the item list display configuration ItemListConfig config = new ItemListConfig(); // some information about the columns to be displayed if (browseIndex.isItemIndex()) { sb.append("Listing over " + Integer.toString(config.numCols()) + " columns: "); for (int k = 1; k <= config.numCols(); k++) { if (k > 1) { sb.append(","); } String[] meta = config.getMetadata(k); sb.append(meta[0] + "." + meta[1] + "." + meta[2]); } if (value != null) { sb.append(" on value: ").append(value); } if (isStartsWith()) { sb.append(" sort column starting with: ").append(focus); } else if (hasFocus()) { sb.append(" sort column focus: ").append(focus); } } else if (browseIndex.isMetadataIndex()) { sb.append("Listing single column: ").append(browseIndex.getMetadata()); if (isStartsWith()) { sb.append(" sort column starting with: ").append(focus); } else if (hasFocus()) { sb.append(" sort column focus: ").append(focus); } } sb.append("||"); // some information about how the data is sorted String direction = (ascending ? "ASC" : "DESC"); sb.append("Sorting by: " + sortOption.getMetadata() + " " + direction + " (option " + Integer.toString(sortOption.getNumber()) + ")"); sb.append("||"); // output the results if (browseIndex.isMetadataIndex() && !isSecondLevel()) { sb.append(valueListingString()); } else if (browseIndex.isItemIndex() || isSecondLevel()) { sb.append(fullListingString(config)); } sb.append("||"); // tell us what the next and previous values are going to be sb.append("Top of next page: "); if (hasNextPage()) { sb.append("offset: ").append(Integer.toString(this.nextOffset)); } else { sb.append("n/a"); } sb.append(";"); sb.append("Top of previous page: "); if (hasPrevPage()) { sb.append("offset: ").append(Integer.toString(this.prevOffset)); } else { sb.append("n/a"); } sb.append("||"); return sb.toString(); } catch (SQLException e) { return e.getMessage(); } catch (BrowseException e) { return e.getMessage(); } } /** * A utility method for generating a string to represent a single item's * entry in the browse * * @param config * @return * @throws SQLException */ private String fullListingString(ItemListConfig config) throws SQLException { // report on all the results contained herein StringBuffer sb = new StringBuffer(); Iterator itr = results.iterator(); while (itr.hasNext()) { BrowseItem bi = (BrowseItem) itr.next(); if (bi == null) { sb.append("{{ NULL ITEM }}"); break; } sb.append("{{Item ID: " + Integer.toString(bi.getID()) + " :: "); for (int j = 1; j <= config.numCols(); j++) { String[] md = config.getMetadata(j); if (md == null) { sb.append("{{ NULL METADATA }}"); break; } DCValue[] values = bi.getMetadata(md[0], md[1], md[2], Item.ANY); StringBuffer value = new StringBuffer(); if (values != null) { for (int i = 0; i < values.length; i++) { if (i > 0) { value.append(","); } value.append(values[i].value); } } else { value.append("-"); } String metadata = "[" + md[0] + "." + md[1] + "." + md[2] + ":" + value.toString() + "]"; sb.append(metadata); } sb.append("}}"); } return sb.toString(); } /** * A utility method for representing a single value in the browse * * @return */ private String valueListingString() { // report on all the results contained herein StringBuffer sb = new StringBuffer(); Iterator itr = results.iterator(); while (itr.hasNext()) { String theValue = (String) itr.next(); if (theValue == null) { sb.append("{{ NULL VALUE }}"); break; } sb.append("{{Value: " + theValue + "}}"); } return sb.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.dspace.browse; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.event.Consumer; import org.dspace.event.Event; /** * Class for updating browse system from content events. * Prototype: only Item events recognized. * * XXX FIXME NOTE: The Browse Consumer is INCOMPLETE because the * deletion of an Item CANNOT be implemented as an event consumer: * When an Item is deleted, the browse tables must be updated * immediately, within the same transaction, to maintain referential * consistency. It cannot be handled in an Event consumer since by * definition that runs after the transaction is committed. * Perhaps this can be addressed if the Browse system is replaced. * * To handle create/modify events: accumulate Sets of Items to be added * and updated out of the event stream. Process them in endEvents() * filter out update requests for Items that were just created. * * Recommended filter: Item+Create|Modify|Modify_Metadata:Collection+Add|Remove * * @version $Revision: 5844 $ */ public class BrowseConsumer implements Consumer { /** log4j logger */ private static Logger log = Logger.getLogger(BrowseConsumer.class); // items to be updated in browse index private Map<Integer, ItemHolder> toUpdate = null; public void initialize() throws Exception { } public void consume(Context ctx, Event event) throws Exception { if(toUpdate == null) { toUpdate = new HashMap<Integer, ItemHolder>(); } log.debug("consume() evaluating event: " + event.toString()); int st = event.getSubjectType(); int et = event.getEventType(); switch (st) { // If an Item is created or its metadata is modified.. case Constants.ITEM: if (et == Event.MODIFY_METADATA || et == Event.CREATE) { Item subj = (Item)event.getSubject(ctx); if (subj != null) { log.debug("consume() adding event to update queue: " + event.toString()); if (et == Event.CREATE || !toUpdate.containsKey(subj.getID())) { toUpdate.put(subj.getID(), new ItemHolder(subj, et == Event.CREATE)); } } } break; // track ADD and REMOVE from collections, that changes browse index. case Constants.COLLECTION: if (event.getObjectType() == Constants.ITEM && (et == Event.ADD || et == Event.REMOVE)) { Item obj = (Item)event.getObject(ctx); if (obj != null) { log.debug("consume() adding event to update queue: " + event.toString()); if (!toUpdate.containsKey(obj.getID())) { toUpdate.put(obj.getID(), new ItemHolder(obj, false)); } } } break; default: log.debug("consume() ignoring event: " + event.toString()); } } public void end(Context ctx) throws Exception { if (toUpdate != null) { // Update/Add items for (ItemHolder i : toUpdate.values()) { // FIXME: there is an exception handling problem here try { // Update browse indices ctx.turnOffAuthorisationSystem(); IndexBrowse ib = new IndexBrowse(ctx); ib.indexItem(i.item, i.createEvent); ctx.restoreAuthSystemState(); } catch (BrowseException e) { log.error("caught exception: ", e); //throw new SQLException(e.getMessage()); } if (log.isDebugEnabled()) { log.debug("Updated browse indices for Item id=" + String.valueOf(i.item.getID()) + ", hdl=" + i.item.getHandle()); } } // NOTE: Removed items are necessarily handled inline (ugh). // browse updates wrote to the DB, so we have to commit. ctx.getDBConnection().commit(); } // clean out toUpdate toUpdate = null; } public void finish(Context ctx) { } private final class ItemHolder { private Item item; private boolean createEvent; ItemHolder(Item pItem, boolean pCreateEvent) { item = pItem; createEvent = pCreateEvent; } } }
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.browse; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import org.dspace.core.ConfigurationManager; /** * Class to mediate with the item list configuration * * @author Richard Jones * */ public class ItemListConfig { /** a map of column number to metadata value */ private Map<Integer, String[]> metadata = new HashMap<Integer, String[]>(); /** a map of column number to data type */ private Map<Integer, Integer> types = new HashMap<Integer, Integer>(); /** constant for a DATE column */ private static final int DATE = 1; /** constant for a TEXT column */ private static final int TEXT = 2; /** * Create a new instance of the Item list configuration. This loads * all the required information from configuration * * @throws BrowseException */ public ItemListConfig() throws BrowseException { try { String configLine = ConfigurationManager.getProperty("webui.itemlist.columns"); if (configLine == null || "".equals(configLine)) { throw new BrowseException("There is no configuration for webui.itemlist.columns"); } // parse the config StringTokenizer st = new StringTokenizer(configLine, ","); int i = 1; while (st.hasMoreTokens()) { Integer key = Integer.valueOf(i); String token = st.nextToken(); // find out if the field is a date if (token.indexOf("(date)") > 0) { token = token.replaceAll("\\(date\\)", ""); types.put(key, Integer.valueOf(ItemListConfig.DATE)); } else { types.put(key, Integer.valueOf(ItemListConfig.TEXT)); } String[] mdBits = interpretField(token.trim(), null); metadata.put(key, mdBits); // don't forget to increment the key counter i++; } } catch (IOException e) { throw new BrowseException(e); } } /** * how many columns are there? * * @return the number of columns */ public int numCols() { return metadata.size(); } /** * what metadata is to go in the given column number * * @param col * @return */ public String[] getMetadata(int col) { return metadata.get(Integer.valueOf(col)); } /** * Take a string representation of a metadata field, and return it as an array. * This is just a convenient utility method to basically break the metadata * representation up by its delimiter (.), and stick it in an array, inserting * the value of the init parameter when there is no metadata field part. * * @param mfield the string representation of the metadata * @param init the default value of the array elements * @return a three element array with schema, element and qualifier respectively */ public final String[] interpretField(String mfield, String init) throws IOException { StringTokenizer sta = new StringTokenizer(mfield, "."); String[] field = {init, init, init}; int i = 0; while (sta.hasMoreTokens()) { field[i++] = sta.nextToken(); } // error checks to make sure we have at least a schema and qualifier for both if (field[0] == null || field[1] == null) { throw new IOException("at least a schema and element be " + "specified in configuration. You supplied: " + mfield); } return field; } }
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.browse; import org.dspace.core.ConfigurationManager; /** * Utility class for retrieving the size of the columns to be used in the browse tables, * and applying truncation to the strings that will be inserted into the tables. * * Can be configured in dspace.cfg, with the following entries: * * webui.browse.value_columns.max * - the maximum number of characters in 'value' columns * (0 is unlimited) * * webui.browse.sort_columns.max * - the maximum number of characters in 'sort' columns * (0 is unlimited) * * webui.browse.value_columns.omission_mark * - a string to append to truncated values that will be entered into * the value columns (ie. '...') * * By default, the column sizes are '0' (unlimited), and no truncation is applied, * EXCEPT for Oracle, where we have to truncate the columns for it to work! (in which * case, both value and sort columns are by default limited to 2000 characters). * * @author Richard Jones * @author Graham Triggs */ public class BrowseDAOUtilsOracle extends BrowseDAOUtilsDefault { /** * Create a new instance of the Oracle specific set of utilities. This * enforces a limit of 2000 characters on the value and sort columns * in the database. Any configuration which falls outside this boundary * will be automatically brought within it. * */ public BrowseDAOUtilsOracle() { valueColumnMaxChars = 2000; sortColumnMaxChars = 2000; if (ConfigurationManager.getProperty("webui.browse.value_columns.max") != null) { valueColumnMaxChars = ConfigurationManager.getIntProperty("webui.browse.value_columns.max"); } if (ConfigurationManager.getProperty("webui.browse.sort_columns.max") != null) { sortColumnMaxChars = ConfigurationManager.getIntProperty("webui.browse.sort_columns.max"); } // For Oracle, force the sort column to be no more than 2000 characters, // even if explicitly configured (have to deal with limitation of using VARCHAR2) if (sortColumnMaxChars < 1 || sortColumnMaxChars > 2000) { sortColumnMaxChars = 2000; } valueColumnOmissionMark = ConfigurationManager.getProperty("webui.browse.value_columns.omission_mark"); if (valueColumnOmissionMark == null) { valueColumnOmissionMark = "..."; } } }
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.browse; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.dspace.core.Context; import org.dspace.core.ConfigurationManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * This class implements the BrowseCreateDAO interface for the PostgreSQL database * as associated with the default DSpace installation. This class should not * be instantiated directly, but should be obtained via the BrowseDAOFactory: * * <code> * Context context = new Context(); * BrowseCreateDAO dao = BrowseDAOFactory.getCreateInstance(context); * </code> * * This class will then be loaded if the appropriate configuration is made. * * @author Richard Jones * @author Graham Triggs */ public class BrowseCreateDAOPostgres implements BrowseCreateDAO { /** Log4j logger */ private static Logger log = Logger.getLogger(BrowseCreateDAOPostgres.class); /** internal copy of the current DSpace context (including the database connection) */ private Context context; /** Database specific set of utils used when prepping the database */ private BrowseDAOUtils utils; /** * Required constructor for classes implementing the BrowseCreateDAO interface. * Takes a DSpace context to use to connect to the database with. * * @param context the DSpace context */ public BrowseCreateDAOPostgres(Context context) throws BrowseException { this.context = context; // obtain the relevant Utils for this class utils = BrowseDAOFactory.getUtils(context); } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createCollectionView(java.lang.String, java.lang.String, boolean) */ public String createCollectionView(String table, String view, boolean execute) throws BrowseException { try { String createColView = "CREATE VIEW " + view + " as " + "SELECT Collection2Item.collection_id, " + table + ".* " + "FROM " + table + ", Collection2Item " + "WHERE " + table + ".item_id = Collection2Item.item_id;"; if (execute) { DatabaseManager.updateQuery(context, createColView); } return createColView; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createCommunityView(java.lang.String, java.lang.String, boolean) */ public String createCommunityView(String table, String view, boolean execute) throws BrowseException { try { String createComView = "CREATE VIEW " + view + " as " + "SELECT Communities2Item.community_id, " + table + ".* " + "FROM " + table + ", Communities2Item " + "WHERE " + table + ".item_id = Communities2Item.item_id;"; if (execute) { DatabaseManager.updateQuery(context, createComView); } return createComView; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDatabaseIndices(java.lang.String, boolean) */ public String[] createDatabaseIndices(String table, List<Integer> sortCols, boolean value, boolean execute) throws BrowseException { try { ArrayList<String> array = new ArrayList<String>(); array.add("CREATE INDEX " + table + "_item_id_idx ON " + table + "(item_id);"); if (value) { array.add("CREATE INDEX " + table + "_value_idx ON " + table + "(sort_value);"); } for (Integer i : sortCols) { array.add("CREATE INDEX " + table + "_s" + i + "_idx ON " + table + "(sort_" + i + ");"); } if (execute) { for (String query : array) { DatabaseManager.updateQuery(context, query); } } String[] arr = new String[array.size()]; return array.toArray(arr); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDatabaseIndices(java.lang.String, boolean) */ public String[] createMapIndices(String disTable, String mapTable, boolean execute) throws BrowseException { try { String[] arr = new String[5]; arr[0] = "CREATE INDEX " + disTable + "_svalue_idx ON " + disTable + "(sort_value)"; arr[1] = "CREATE INDEX " + disTable + "_value_idx ON " + disTable + "(value)"; arr[2] = "CREATE INDEX " + disTable + "_uvalue_idx ON " + disTable + "(UPPER(value))"; arr[3] = "CREATE INDEX " + mapTable + "_item_id_idx ON " + mapTable + "(item_id)"; arr[4] = "CREATE INDEX " + mapTable + "_dist_idx ON " + mapTable + "(distinct_id)"; if (execute) { for (String query : arr) { DatabaseManager.updateQuery(context, query); } } return arr; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDistinctMap(java.lang.String, java.lang.String, boolean) */ public String createDistinctMap(String table, String map, boolean execute) throws BrowseException { try { String create = "CREATE TABLE " + map + " (" + "map_id integer primary key, " + "item_id integer references item(item_id), " + "distinct_id integer references " + table + "(id)" + ");"; if (execute) { DatabaseManager.updateQuery(context, create); } return create; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#updateDistinctMapping(java.lang.String, int, int) */ public MappingResults updateDistinctMappings(String table, int itemID, Set<Integer> distinctIDs) throws BrowseException { BrowseMappingResults results = new BrowseMappingResults(); try { Set<Integer> addDistinctIDs = null; // Find all existing mappings for this item TableRowIterator tri = DatabaseManager.queryTable(context, table, "SELECT * FROM " + table + " WHERE item_id=?", itemID); if (tri != null) { addDistinctIDs = (Set<Integer>)((HashSet<Integer>)distinctIDs).clone(); try { while (tri.hasNext()) { TableRow tr = tri.next(); // Check the item mappings to see if it contains this mapping boolean itemIsMapped = false; int trDistinctID = tr.getIntColumn("distinct_id"); if (distinctIDs.contains(trDistinctID)) { // Found this mapping results.addRetainedDistinctId(trDistinctID); // Flag it, and remove (-1) from the item mappings itemIsMapped = true; addDistinctIDs.remove(trDistinctID); } // The item is no longer mapped to this community, so remove the database record if (!itemIsMapped) { results.addRemovedDistinctId(trDistinctID); DatabaseManager.delete(context, tr); } } } finally { tri.close(); } } else { addDistinctIDs = distinctIDs; } // Any remaining mappings need to be added to the database for (int distinctID : addDistinctIDs) { if (distinctID > -1) { TableRow row = DatabaseManager.row(table); row.setColumn("item_id", itemID); row.setColumn("distinct_id", distinctID); DatabaseManager.insert(context, row); results.addAddedDistinctId(distinctID); } } } catch (SQLException e) { log.error("caught exception: ", e); String msg = "problem updating distinct mappings: table=" + table + ",item-id=" + itemID; throw new BrowseException(msg, e); } return results; } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createDistinctTable(java.lang.String, boolean) */ public String createDistinctTable(String table, boolean execute) throws BrowseException { try { String create = "CREATE TABLE " + table + " (" + "id integer primary key, " + "authority VARCHAR(100), " + "value " + getValueColumnDefinition() + ", " + "sort_value " + getSortColumnDefinition() + ");"; if (execute) { DatabaseManager.updateQuery(context, create); } return create; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createPrimaryTable(java.lang.String, java.util.List, boolean) */ public String createPrimaryTable(String table, List<Integer> sortCols, boolean execute) throws BrowseException { try { StringBuffer sb = new StringBuffer(); Iterator itr = sortCols.iterator(); while (itr.hasNext()) { Integer no = (Integer) itr.next(); sb.append(", sort_"); sb.append(no.toString()); sb.append(getSortColumnDefinition()); } String createTable = "CREATE TABLE " + table + " (" + "id integer primary key," + "item_id integer references item(item_id)" + sb.toString() + ");"; if (execute) { DatabaseManager.updateQuery(context, createTable); } return createTable; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#createSequence(java.lang.String, boolean) */ public String createSequence(String sequence, boolean execute) throws BrowseException { try { String create = "CREATE SEQUENCE " + sequence + ";"; if (execute) { DatabaseManager.updateQuery(context, create); } return create; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#deleteByItemID(java.lang.String, int) */ public void deleteByItemID(String table, int itemID) throws BrowseException { try { Object[] params = { Integer.valueOf(itemID) }; String dquery = "DELETE FROM " + table + " WHERE item_id = ?"; DatabaseManager.updateQuery(context, dquery, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#deleteCommunityMappings(java.lang.String, int) */ public void deleteCommunityMappings(int itemID) throws BrowseException { try { Object[] params = { Integer.valueOf(itemID) }; String dquery = "DELETE FROM Communities2Item WHERE item_id = ?"; DatabaseManager.updateQuery(context, dquery, params); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#dropIndexAndRelated(java.lang.String, boolean) */ public String dropIndexAndRelated(String table, boolean execute) throws BrowseException { try { String dropper = "DROP TABLE " + table + " CASCADE;"; if (execute) { DatabaseManager.updateQuery(context, dropper); } return dropper; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#dropSequence(java.lang.String, boolean) */ public String dropSequence(String sequence, boolean execute) throws BrowseException { try { String dropSeq = "DROP SEQUENCE " + sequence + ";"; if (execute) { DatabaseManager.updateQuery(context, dropSeq); } return dropSeq; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#dropView(java.lang.String, boolean) */ public String dropView(String view, boolean execute) throws BrowseException { /* Postgres VIEWs are dropped along with the main index if (view != null && !"".equals(view)) { try { String dropView = "DROP VIEW " + view + " CASCADE;"; if (execute) { DatabaseManager.updateQuery(context, dropView); } return dropView; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } */ return ""; } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#getDistinctID(java.lang.String, java.lang.String, java.lang.String) */ public int getDistinctID(String table, String value, String authority, String sortValue) throws BrowseException { TableRowIterator tri = null; if (log.isDebugEnabled()) { log.debug("getDistinctID: table=" + table + ",value=" + value + ",sortValue=" + sortValue); } try { Object[] params; String select; if (authority != null) { params = new Object[]{ value, authority }; } else { params = new Object[]{ value }; } if (ConfigurationManager.getBooleanProperty("webui.browse.metadata.case-insensitive", false)) { if (authority != null) { select = "SELECT id FROM " + table + " WHERE UPPER(value) = UPPER(?) and authority = ?"; } else { select = "SELECT id FROM " + table + " WHERE UPPER(value) = UPPER(?) and authority IS NULL"; } } else { if (authority != null) { select = "SELECT id FROM " + table + " WHERE value = ? and authority = ?"; } else { select = "SELECT id FROM " + table + " WHERE value = ? and authority IS NULL"; } } tri = DatabaseManager.query(context, select, params); int distinctID = -1; if (!tri.hasNext()) { distinctID = insertDistinctRecord(table, value, authority, sortValue); } else { distinctID = tri.next().getIntColumn("id"); } if (log.isDebugEnabled()) { log.debug("getDistinctID: return=" + distinctID); } return distinctID; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#updateCommunityMappings(int) */ public void updateCommunityMappings(int itemID) throws BrowseException { try { // Get all the communities for this item int[] commID = getAllCommunityIDs(itemID); // Remove (set to -1) any duplicate communities for (int i = 0; i < commID.length; i++) { if (!isFirstOccurrence(commID, i)) { commID[i] = -1; } } // Find all existing mappings for this item TableRowIterator tri = DatabaseManager.queryTable(context, "Communities2Item", "SELECT * FROM Communities2Item WHERE item_id=?", itemID); if (tri != null) { try { while (tri.hasNext()) { TableRow tr = tri.next(); // Check the item mappings to see if it contains this community mapping boolean itemIsMapped = false; int trCommID = tr.getIntColumn("community_id"); for (int i = 0; i < commID.length; i++) { // Found this community if (commID[i] == trCommID) { // Flag it, and remove (-1) from the item mappings itemIsMapped = true; commID[i] = -1; } } // The item is no longer mapped to this community, so remove the database record if (!itemIsMapped) { DatabaseManager.delete(context, tr); } } } finally { tri.close(); } } // Any remaining mappings need to be added to the database for (int i = 0; i < commID.length; i++) { if (commID[i] > -1) { TableRow row = DatabaseManager.row("Communities2Item"); row.setColumn("item_id", itemID); row.setColumn("community_id", commID[i]); DatabaseManager.insert(context, row); } } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#insertDistinctRecord(java.lang.String, java.lang.String, java.lang.String) */ public int insertDistinctRecord(String table, String value, String authority, String sortValue) throws BrowseException { log.debug("insertDistinctRecord: table=" + table + ",value=" + value+ ",authority=" + authority+",sortValue=" + sortValue); try { TableRow dr = DatabaseManager.row(table); if (authority != null) { dr.setColumn("authority", utils.truncateValue(authority,100)); } dr.setColumn("value", utils.truncateValue(value)); dr.setColumn("sort_value", utils.truncateSortValue(sortValue)); DatabaseManager.insert(context, dr); int distinctID = dr.getIntColumn("id"); log.debug("insertDistinctRecord: return=" + distinctID); return distinctID; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#insertIndex(java.lang.String, int, java.lang.String, java.lang.String, java.util.Map) */ public void insertIndex(String table, int itemID, Map<Integer, String> sortCols) throws BrowseException { try { // create us a row in the index TableRow row = DatabaseManager.row(table); // set the primary information for the index row.setColumn("item_id", itemID); // now set the columns for the other sort values for (Map.Entry<Integer, String> sortCol : sortCols.entrySet()) { row.setColumn("sort_" + sortCol.getKey().toString(), utils.truncateSortValue(sortCol.getValue())); } DatabaseManager.insert(context, row); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#updateIndex(java.lang.String, int, java.util.Map) */ public boolean updateIndex(String table, int itemID, Map<Integer, String> sortCols) throws BrowseException { try { boolean rowUpdated = false; TableRow row = DatabaseManager.findByUnique(context, table, "item_id", itemID); // If the item does not exist in the table, return that it couldn't be found if (row == null) { return false; } // Iterate through all the sort values for (Map.Entry<Integer, String> sortCol : sortCols.entrySet()) { // Generate the appropriate column name String column = "sort_" + sortCol.getKey().toString(); // Create the value that will be written in to the column String newValue = utils.truncateSortValue( sortCol.getValue() ); // Check the column exists - if it doesn't, something has gone seriously wrong if (!row.hasColumn(column)) { throw new BrowseException("Column '" + column + "' does not exist in table " + table); } // Get the existing value from the column String oldValue = row.getStringColumn(column); // If the new value differs from the old value, update the column and flag that the row has changed if (oldValue != null && !oldValue.equals(newValue)) { row.setColumn(column, newValue); rowUpdated = true; } else if (newValue != null && !newValue.equals(oldValue)) { row.setColumn(column, newValue); rowUpdated = true; } } // We've updated the row, so save it back to the database if (rowUpdated) { DatabaseManager.update(context, row); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } // Return that the original record was found return true; } public List<Integer> deleteMappingsByItemID(String mapTable, int itemID) throws BrowseException { List<Integer> distinctIds = new ArrayList<Integer>(); TableRowIterator tri = null; try { tri = DatabaseManager.queryTable(context, mapTable, "SELECT * FROM " + mapTable + " WHERE item_id=?", itemID); if (tri != null) { while (tri.hasNext()) { TableRow tr = tri.next(); distinctIds.add(tr.getIntColumn("distinct_id")); DatabaseManager.delete(context, tr); } } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } return distinctIds; } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#pruneDistinct(java.lang.String, java.lang.String) */ public void pruneDistinct(String table, String map, List<Integer> distinctIds) throws BrowseException { try { StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(table).append(" WHERE NOT EXISTS (SELECT 1 FROM "); query.append(map).append(" WHERE ").append(map).append(".distinct_id = ").append(table).append(".id)"); if (distinctIds != null && distinctIds.size() > 0) { query.append(" AND ").append(table).append(".id=?"); PreparedStatement stmt = null; try { stmt = context.getDBConnection().prepareStatement(query.toString()); for (Integer distinctId : distinctIds) { stmt.setInt(1, distinctId); stmt.execute(); stmt.clearParameters(); } } finally { if (stmt != null) { stmt.close(); } } } else { DatabaseManager.updateQuery(context, query.toString()); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#pruneExcess(java.lang.String, boolean) */ public void pruneExcess(String table, boolean withdrawn) throws BrowseException { try { StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(table).append(" WHERE NOT EXISTS (SELECT 1 FROM item WHERE item.item_id="); query.append(table).append(".item_id AND "); if (withdrawn) { query.append("item.withdrawn = true"); } else { query.append("item.in_archive = true AND item.withdrawn = false"); } query.append(")"); DatabaseManager.updateQuery(context, query.toString()); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } try { String itemCriteria = withdrawn ? "item.withdrawn = true" : "item.in_archive = true AND item.withdrawn = false"; String delete = "DELETE FROM " + table + " WHERE NOT EXISTS (SELECT 1 FROM item WHERE item.item_id=" + table + ".item_id AND " + itemCriteria + ")"; DatabaseManager.updateQuery(context, delete); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#pruneMapExcess(java.lang.String, boolean) */ public void pruneMapExcess(String map, boolean withdrawn, List<Integer> distinctIds) throws BrowseException { try { StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(map).append(" WHERE NOT EXISTS (SELECT 1 FROM item WHERE item.item_id="); query.append(map).append(".item_id AND "); if (withdrawn) { query.append("item.withdrawn = true"); } else { query.append("item.in_archive = true AND item.withdrawn = false"); } query.append(")"); if (distinctIds != null && distinctIds.size() > 0) { query.append(" AND ").append(map).append(".distinct_id=?"); PreparedStatement stmt = null; try { stmt = context.getDBConnection().prepareStatement(query.toString()); for (Integer distinctId : distinctIds) { stmt.setInt(1, distinctId); stmt.execute(); stmt.clearParameters(); } } finally { if (stmt != null) { stmt.close(); } } } else { DatabaseManager.updateQuery(context, query.toString()); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /* (non-Javadoc) * @see org.dspace.browse.BrowseCreateDAO#testTableExistence(java.lang.String) */ public boolean testTableExistence(String table) throws BrowseException { // this method can kill the db connection, so we start up // our own private context to do it Context c = null; try { c = new Context(); String testQuery = "SELECT * FROM " + table + " LIMIT 1"; DatabaseManager.query(c, testQuery); return true; } catch (SQLException e) { return false; } finally { if (c != null) { c.abort(); } } } /** * Get the definition of the sort_value column - always a VARCHAR2 * (required for ordering) * * @return */ private String getSortColumnDefinition() { int size = utils.getSortColumnMaxChars(); if (size < 1) { return " TEXT "; } return " VARCHAR(" + size + ") "; } /** * Get the definition of the value column - TEXT if the size is greater than 4000 bytes * otherwise a VARCHAR2. * * @return */ private String getValueColumnDefinition() { int size = utils.getValueColumnMaxChars(); if (size < 1) { return " TEXT "; } return " VARCHAR(" + size + ") "; } /** * perform a database query to get all the communities that this item belongs to, * including all mapped communities, and ancestors * * this is done here instead of using the Item api, because for reindexing we may * not have Item objects, and in any case this is *much* faster * * @param itemId * @return * @throws SQLException */ private int[] getAllCommunityIDs(int itemId) throws SQLException { List<Integer> commIdList = new ArrayList<Integer>(); TableRowIterator tri = null; try { tri = DatabaseManager.queryTable(context, "Community2Item", "SELECT * FROM Community2Item WHERE item_id=?", itemId); while (tri.hasNext()) { TableRow row = tri.next(); int commId = row.getIntColumn("community_id"); commIdList.add(commId); // Get the parent community, and continue to get all ancestors Integer parentId = getParentCommunityID(commId); while (parentId != null) { commIdList.add(parentId); parentId = getParentCommunityID(parentId); } } } finally { if (tri != null) { tri.close(); } } // Need to iterate the array as toArray will produce an array Integers, // not ints as we need. int[] cIds = new int[commIdList.size()]; for (int i = 0; i < commIdList.size(); i++) { cIds[i] = commIdList.get(i); } return cIds; } /** * Get the id of the parent community. Returns Integer, as null is used to * signify that there are no parents (ie. top-level). * * @param commId * @return * @throws SQLException */ private Integer getParentCommunityID(int commId) throws SQLException { TableRowIterator tri = null; try { tri = DatabaseManager.queryTable(context, "Community2Community", "SELECT * FROM Community2Community WHERE child_comm_id=?", commId); if (tri.hasNext()) { return tri.next().getIntColumn("parent_comm_id"); } } finally { if (tri != null) { tri.close(); } } return null; } /** * Check to see if the integer at pos is the first occurrence of that value * in the array. * * @param ids * @param pos * @return */ private boolean isFirstOccurrence(int[] ids, int pos) { if (pos < 0 || pos >= ids.length) { return false; } int id = ids[pos]; for (int i = 0; i < pos; i++) { if (id == ids[i]) { return false; } } return true; } private static class BrowseMappingResults implements MappingResults { private List<Integer> addedDistinctIds = new ArrayList<Integer>(); private List<Integer> retainedDistinctIds = new ArrayList<Integer>(); private List<Integer> removedDistinctIds = new ArrayList<Integer>(); private void addAddedDistinctId(int id) { addedDistinctIds.add(id); } private void addRetainedDistinctId(int id) { retainedDistinctIds.add(id); } private void addRemovedDistinctId(int id) { removedDistinctIds.add(id); } public List<Integer> getAddedDistinctIds() { return addedDistinctIds; } public List<Integer> getRetainedDistinctIds() { return retainedDistinctIds; } public List<Integer> getRemovedDistinctIds() { return Collections.unmodifiableList(removedDistinctIds); } } }
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.browse; import java.util.List; interface MappingResults { List<Integer> getAddedDistinctIds(); List<Integer> getRetainedDistinctIds(); List<Integer> getRemovedDistinctIds(); }
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.browse; import org.dspace.core.ConfigurationManager; /** * Utility class for retrieving the size of the columns to be used in the browse tables, * and applying truncation to the strings that will be inserted into the tables. * * Can be configured in dspace.cfg, with the following entries: * * webui.browse.value_columns.max * - the maximum number of characters in 'value' columns * (0 is unlimited) * * webui.browse.sort_columns.max * - the maximum number of characters in 'sort' columns * (0 is unlimited) * * webui.browse.value_columns.omission_mark * - a string to append to truncated values that will be entered into * the value columns (ie. '...') * * By default, the column sizes are '0' (unlimited), and no truncation is applied, * EXCEPT for Oracle, where we have to truncate the columns for it to work! (in which * case, both value and sort columns are by default limited to 2000 characters). * * @author Graham Triggs * @author Richard Jones */ public class BrowseDAOUtilsDefault implements BrowseDAOUtils { /** Maximum number of characters for value columns */ public int valueColumnMaxChars; /** Maximum number of characters for sort columns */ public int sortColumnMaxChars; /** string to insert where omissions have been made */ public String valueColumnOmissionMark; /** * Create a new instance of the Default set of utils to use with the database. * This represents the most likely case with a database, in that it does not * require the fields to be truncated. Other databases, such as Oracle, require * a set limit for their VARCHAR fields, and will therefore have a slightly * different implementation * * Other database implementations should extend this class for typing and * future proofing purposes * */ public BrowseDAOUtilsDefault() { // Default for all other databases is unlimited valueColumnMaxChars = 0; sortColumnMaxChars = 0; if (ConfigurationManager.getProperty("webui.browse.value_columns.max") != null) { valueColumnMaxChars = ConfigurationManager.getIntProperty("webui.browse.value_columns.max"); } if (ConfigurationManager.getProperty("webui.browse.sort_columns.max") != null) { sortColumnMaxChars = ConfigurationManager.getIntProperty("webui.browse.sort_columns.max"); } valueColumnOmissionMark = ConfigurationManager.getProperty("webui.browse.value_columns.omission_mark"); if (valueColumnOmissionMark == null) { valueColumnOmissionMark = "..."; } } /** * Get the size to use for the 'value' columns in characters * * @return */ public int getValueColumnMaxChars() { return this.valueColumnMaxChars; } /** * Get the size to use for the sort columns in characters * * @return */ public int getSortColumnMaxChars() { return this.sortColumnMaxChars; } /** * Truncate strings that are to be used for the 'value' columns * * @param value * @return */ public String truncateValue(String value) { return this.trunctateString(value, this.valueColumnMaxChars, valueColumnOmissionMark); } /** * Truncate strings that are to be used for sorting * * @param value * @return */ public String truncateSortValue(String value) { return this.trunctateString(value, this.sortColumnMaxChars, null); } /** * Truncate strings that are to be used for the 'value' columns. * Characters is the maximum number of characters to allow. * Actual truncation applied will be the SMALLER of the passed * value, or that read from the configuration. * * @param value * @param chars * @return * @deprecated */ public String truncateValue(String value, int chars) { return this.trunctateString(value, Math.min(chars, this.valueColumnMaxChars), valueColumnOmissionMark); } /** * Truncate strings that are to be used for the sorting * Characters is the maximum number of characters to allow. * Actual truncation applied will be the SMALLER of the passed * value, or that read from the configuration. * * @param value * @param chars * @return * @deprecated */ public String truncateSortValue(String value, int chars) { return this.trunctateString(value, Math.min(chars, this.sortColumnMaxChars), null); } /** * Internal method to apply the truncation. * * @param value * @param maxChars * @param omissionMark * @return */ private String trunctateString(String value, int maxChars, String omissionMark) { if (value == null || maxChars < 1) { return value; } if (maxChars > value.length()) { return value; } if (omissionMark != null && omissionMark.length() > 0) { return value.substring(0, maxChars - omissionMark.length()) + omissionMark; } return value.substring(0, maxChars); } }
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.browse; import org.dspace.content.DCValue; import java.sql.SQLException; public interface BrowseItemDAO { /** * Get an array of all the items in the database * * @return array of items * @throws java.sql.SQLException */ public BrowseItem[] findAll() throws SQLException; /** * perform a database query to obtain the string array of values corresponding to * the passed parameters. In general you should use: * * <code> * getMetadata(schema, element, qualifier, lang); * </code> * * As this will obtain the value from cache if available first. * * @param itemId * @param schema * @param element * @param qualifier * @param lang * @return * @throws SQLException */ public DCValue[] queryMetadata(int itemId, String schema, String element, String qualifier, String lang) throws SQLException; }
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.browse; import java.sql.SQLException; import java.util.List; import java.util.ArrayList; import org.apache.log4j.Logger; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.sort.SortOption; import org.dspace.sort.OrderFormat; /** * This class does most of the actual grunt work of preparing a browse * result. It takes in to a couple of available methods (depending on your * desired browse type) a BrowserScope object, and uses this to produce a * BrowseInfo object which is sufficient to describe to the User Interface * the results of the requested browse * * @author Richard Jones * */ public class BrowseEngine { /** the logger for this class */ private static Logger log = Logger.getLogger(BrowseEngine.class); /** the browse scope which is the basis for our browse */ private BrowserScope scope; /** the DSpace context */ private Context context; /** The Data Access Object for the browse tables */ private BrowseDAO dao; /** The Browse Index associated with the Browse Scope */ private BrowseIndex browseIndex; /** * Create a new instance of the Browse engine, using the given DSpace * Context object. This will automatically assign a Data Access Object * for the Browse Engine, based on the dspace.cfg setting for db.name * * @param context the DSpace context * @throws BrowseException */ public BrowseEngine(Context context) throws BrowseException { // set the context this.context = context; // prepare the data access object dao = BrowseDAOFactory.getInstance(context); } /** * Perform a standard browse, which will return a BrowseInfo * object that represents the results for the current page, the * total number of results, the range, and information to construct * previous and next links on any web page * * @param bs the scope of the browse * @return the results of the browse * @throws BrowseException */ public BrowseInfo browse(BrowserScope bs) throws BrowseException { log.debug(LogManager.getHeader(context, "browse", "")); // first, load the browse scope into the object this.scope = bs; // since we use it so much, get the browse index out of the // scope and store as a member browseIndex = scope.getBrowseIndex(); // now make the decision as to how to browse if (browseIndex.isMetadataIndex() && !scope.isSecondLevel()) { // this is a single value browse type that has not gone to // the second level (i.e. authors, not items by a given author) return browseByValue(scope); } else { // this is the full browse type or a browse that has gone to // the second level return browseByItem(scope); } } /** * Perform a limited browse, which only returns the results requested, * without any extraneous information. To perform a full browse, use * BrowseEngine.browse() above. This supports Item browse only, and does * not currently support focus or values. This method is used, for example, * to generate the Recently Submitted Items results. * * @param bs the scope of the browse * @return the results of the browse */ public BrowseInfo browseMini(BrowserScope bs) throws BrowseException { log.info(LogManager.getHeader(context, "browse_mini", "")); // load the scope into the object this.scope = bs; // since we use it so much, get the browse index out of the // scope and store as a member browseIndex = scope.getBrowseIndex(); // get the table name that we are going to be getting our data from dao.setTable(browseIndex.getTableName()); // tell the browse query whether we are ascending or descending on the value dao.setAscending(scope.isAscending()); // define a clause for the WHERE clause which will allow us to constrain // our browse to a specified community or collection if (scope.inCollection() || scope.inCommunity()) { if (scope.inCollection()) { Collection col = (Collection) scope.getBrowseContainer(); dao.setContainerTable("collection2item"); dao.setContainerIDField("collection_id"); dao.setContainerID(col.getID()); } else if (scope.inCommunity()) { Community com = (Community) scope.getBrowseContainer(); dao.setContainerTable("communities2item"); dao.setContainerIDField("community_id"); dao.setContainerID(com.getID()); } } dao.setOffset(scope.getOffset()); dao.setLimit(scope.getResultsPerPage()); // assemble the ORDER BY clause String orderBy = browseIndex.getSortField(scope.isSecondLevel()); if (scope.getSortBy() > 0) { orderBy = "sort_" + Integer.toString(scope.getSortBy()); } dao.setOrderField(orderBy); // now run the query List<BrowseItem> results = dao.doQuery(); // construct the mostly empty BrowseInfo object to pass back BrowseInfo browseInfo = new BrowseInfo(results, 0, scope.getResultsPerPage(), 0); // add the browse index to the Browse Info browseInfo.setBrowseIndex(browseIndex); // set the sort option for the Browse Info browseInfo.setSortOption(scope.getSortOption()); // tell the Browse Info which way we are sorting browseInfo.setAscending(scope.isAscending()); // tell the browse info what the container for the browse was if (scope.inCollection() || scope.inCommunity()) { browseInfo.setBrowseContainer(scope.getBrowseContainer()); } browseInfo.setResultsPerPage(scope.getResultsPerPage()); browseInfo.setEtAl(scope.getEtAl()); return browseInfo; } /** * Browse the archive by the full item browse mechanism. This produces a * BrowseInfo object which contains full BrowseItem objects as its result * set. * * @param bs the scope of the browse * @return the results of the browse * @throws BrowseException */ private BrowseInfo browseByItem(BrowserScope bs) throws BrowseException { log.info(LogManager.getHeader(context, "browse_by_item", "")); try { // get the table name that we are going to be getting our data from dao.setTable(browseIndex.getTableName()); // tell the browse query whether we are ascending or descending on the value dao.setAscending(scope.isAscending()); // assemble the value clause String rawValue = null; if (scope.hasFilterValue() && scope.isSecondLevel()) { String value = scope.getFilterValue(); rawValue = value; // make sure the incoming value is normalised value = OrderFormat.makeSortString(value, scope.getFilterValueLang(), scope.getBrowseIndex().getDataType()); dao.setAuthorityValue(scope.getAuthorityValue()); // set the values in the Browse Query if (scope.isSecondLevel()) { dao.setFilterValueField("value"); dao.setFilterValue(rawValue); } else { dao.setFilterValueField("sort_value"); dao.setFilterValue(value); } dao.setFilterValuePartial(scope.getFilterValuePartial()); // to apply the filtering, we need the distinct and map tables for the index dao.setFilterMappingTables(browseIndex.getDistinctTableName(), browseIndex.getMapTableName()); } // define a clause for the WHERE clause which will allow us to constrain // our browse to a specified community or collection if (scope.inCollection() || scope.inCommunity()) { if (scope.inCollection()) { Collection col = (Collection) scope.getBrowseContainer(); dao.setContainerTable("collection2item"); dao.setContainerIDField("collection_id"); dao.setContainerID(col.getID()); } else if (scope.inCommunity()) { Community com = (Community) scope.getBrowseContainer(); dao.setContainerTable("communities2item"); dao.setContainerIDField("community_id"); dao.setContainerID(com.getID()); } } // this is the total number of results in answer to the query int total = getTotalResults(); // assemble the ORDER BY clause String orderBy = browseIndex.getSortField(scope.isSecondLevel()); if (scope.getSortBy() > 0) { orderBy = "sort_" + Integer.toString(scope.getSortBy()); } dao.setOrderField(orderBy); int offset = scope.getOffset(); String rawFocusValue = null; if (offset < 1 && (scope.hasJumpToItem() || scope.hasJumpToValue() || scope.hasStartsWith())) { // We need to convert these to an offset for the actual browse query. // First, get a value that we can look up in the ordering field rawFocusValue = getJumpToValue(); // make sure the incoming value is normalised String focusValue = normalizeJumpToValue(rawFocusValue); log.debug("browsing using focus: " + focusValue); // Convert the focus value into an offset offset = getOffsetForValue(focusValue); } dao.setOffset(offset); // assemble the LIMIT clause dao.setLimit(scope.getResultsPerPage()); // Holder for the results List<BrowseItem> results = null; // Does this browse have any contents? if (total > 0) { // now run the query results = dao.doQuery(); // now, if we don't have any results, we are at the end of the browse. This will // be because a starts_with value has been supplied for which we don't have // any items. if (results.size() == 0) { // In this case, we will calculate a new offset for the last page of results offset = total - scope.getResultsPerPage(); if (offset < 0) { offset = 0; } // And rerun the query dao.setOffset(offset); results = dao.doQuery(); } } else { // No records, so make an empty list results = new ArrayList<BrowseItem>(); } // construct the BrowseInfo object to pass back // BrowseInfo browseInfo = new BrowseInfo(results, position, total, offset); BrowseInfo browseInfo = new BrowseInfo(results, offset, total, offset); if (offset + scope.getResultsPerPage() < total) { browseInfo.setNextOffset(offset + scope.getResultsPerPage()); } if (offset - scope.getResultsPerPage() > -1) { browseInfo.setPrevOffset(offset - scope.getResultsPerPage()); } // add the browse index to the Browse Info browseInfo.setBrowseIndex(browseIndex); // set the sort option for the Browse Info browseInfo.setSortOption(scope.getSortOption()); // tell the Browse Info which way we are sorting browseInfo.setAscending(scope.isAscending()); // tell the Browse Info which level of browse we are at browseInfo.setBrowseLevel(scope.getBrowseLevel()); // set the browse value if there is one browseInfo.setValue(rawValue); // set the browse authority key if there is one browseInfo.setAuthority(scope.getAuthorityValue()); // set the focus value if there is one browseInfo.setFocus(rawFocusValue); if (scope.hasJumpToItem()) { browseInfo.setFocusItem(scope.getJumpToItem()); } // tell the browse info if it is working from a starts with parameter browseInfo.setStartsWith(scope.hasStartsWith()); // tell the browse info what the container for the browse was if (scope.inCollection() || scope.inCommunity()) { browseInfo.setBrowseContainer(scope.getBrowseContainer()); } browseInfo.setResultsPerPage(scope.getResultsPerPage()); browseInfo.setEtAl(scope.getEtAl()); return browseInfo; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /** * Browse the archive by single values (such as the name of an author). This * produces a BrowseInfo object that contains Strings as the results of * the browse * * @param bs the scope of the browse * @return the results of the browse * @throws BrowseException */ private BrowseInfo browseByValue(BrowserScope bs) throws BrowseException { log.info(LogManager.getHeader(context, "browse_by_value", "focus=" + bs.getJumpToValue())); try { // get the table name that we are going to be getting our data from // this is the distinct table constrained to either community or collection dao.setTable(browseIndex.getDistinctTableName()); // remind the DAO that this is a distinct value browse, so it knows what sort // of query to build dao.setDistinct(true); // tell the browse query whether we are ascending or descending on the value dao.setAscending(scope.isAscending()); // set our constraints on community or collection if (scope.inCollection() || scope.inCommunity()) { // Scoped browsing of distinct metadata requires the mapping // table to be specified. dao.setFilterMappingTables(null, browseIndex.getMapTableName()); if (scope.inCollection()) { Collection col = (Collection) scope.getBrowseContainer(); dao.setContainerTable("collection2item"); dao.setContainerIDField("collection_id"); dao.setContainerID(col.getID()); } else if (scope.inCommunity()) { Community com = (Community) scope.getBrowseContainer(); dao.setContainerTable("communities2item"); dao.setContainerIDField("community_id"); dao.setContainerID(com.getID()); } } // this is the total number of results in answer to the query int total = getTotalResults(true); // set the ordering field (there is only one option) dao.setOrderField("sort_value"); // assemble the focus clause if we are to have one // it will look like one of the following // - sort_value < myvalue // = sort_1 > myvalue dao.setJumpToField("sort_value"); int offset = scope.getOffset(); String rawFocusValue = null; if (offset < 1 && scope.hasJumpToValue() || scope.hasStartsWith()) { String focusValue = getJumpToValue(); // store the value to tell the Browse Info object which value we are browsing on rawFocusValue = focusValue; // make sure the incoming value is normalised focusValue = normalizeJumpToValue(focusValue); offset = getOffsetForDistinctValue(focusValue); } // assemble the offset and limit dao.setOffset(offset); dao.setLimit(scope.getResultsPerPage()); // Holder for the results List<String[]> results = null; // Does this browse have any contents? if (total > 0) { // now run the query results = dao.doValueQuery(); // now, if we don't have any results, we are at the end of the browse. This will // be because a starts_with value has been supplied for which we don't have // any items. if (results.size() == 0) { // In this case, we will calculate a new offset for the last page of results offset = total - scope.getResultsPerPage(); if (offset < 0) { offset = 0; } // And rerun the query dao.setOffset(offset); results = dao.doValueQuery(); } } else { // No records, so make an empty list results = new ArrayList<String[]>(); } // construct the BrowseInfo object to pass back BrowseInfo browseInfo = new BrowseInfo(results, offset, total, offset); if (offset + scope.getResultsPerPage() < total) { browseInfo.setNextOffset(offset + scope.getResultsPerPage()); } if (offset - scope.getResultsPerPage() > -1) { browseInfo.setPrevOffset(offset - scope.getResultsPerPage()); } // add the browse index to the Browse Info browseInfo.setBrowseIndex(browseIndex); // set the sort option for the Browse Info browseInfo.setSortOption(scope.getSortOption()); // tell the Browse Info which way we are sorting browseInfo.setAscending(scope.isAscending()); // tell the Browse Info which level of browse we are at browseInfo.setBrowseLevel(scope.getBrowseLevel()); // set the browse value if there is one browseInfo.setFocus(rawFocusValue); // tell the browse info if it is working from a starts with parameter browseInfo.setStartsWith(scope.hasStartsWith()); // tell the browse info what the container for the browse was if (scope.inCollection() || scope.inCommunity()) { browseInfo.setBrowseContainer(scope.getBrowseContainer()); } browseInfo.setResultsPerPage(scope.getResultsPerPage()); return browseInfo; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /** * Return the focus value. * * @return the focus value to use * @throws BrowseException */ private String getJumpToValue() throws BrowseException { log.debug(LogManager.getHeader(context, "get_focus_value", "")); // if the focus is by value, just return it if (scope.hasJumpToValue()) { log.debug(LogManager.getHeader(context, "get_focus_value_return", "return=" + scope.getJumpToValue())); return scope.getJumpToValue(); } // if the focus is to start with, then we need to return the value of the starts with if (scope.hasStartsWith()) { log.debug(LogManager.getHeader(context, "get_focus_value_return", "return=" + scope.getStartsWith())); return scope.getStartsWith(); } // since the focus is not by value, we need to obtain it // get the id of the item to focus on int id = scope.getJumpToItem(); // get the table name. We don't really need to care about whether we are in a // community or collection at this point. This is only for full or second // level browse, so there is no need to worry about distinct value browsing String tableName = browseIndex.getTableName(); // we need to make sure that we select from the correct column. If the sort option // is the 0th option then we use sort_value, but if it is one of the others we have // to select from that column instead. Otherwise, we end up missing the focus value // to do comparisons in other columns. The use of the focus value needs to be consistent // across the browse SortOption so = scope.getSortOption(); if (so == null || so.getNumber() == 0) { if (browseIndex.getSortOption() != null) { so = browseIndex.getSortOption(); } } String col = "sort_1"; if (so.getNumber() > 0) { col = "sort_" + Integer.toString(so.getNumber()); } // now get the DAO to do the query for us, returning the highest // string value in the given column in the given table for the // item (I think) String max = dao.doMaxQuery(col, tableName, id); log.debug(LogManager.getHeader(context, "get_focus_value_return", "return=" + max)); return max; } /** * Convert the value into an offset into the table for this browse * * @return the focus value to use * @throws BrowseException */ private int getOffsetForValue(String value) throws BrowseException { // we need to make sure that we select from the correct column. If the sort option // is the 0th option then we use sort_value, but if it is one of the others we have // to select from that column instead. Otherwise, we end up missing the focus value // to do comparisons in other columns. The use of the focus value needs to be consistent // across the browse SortOption so = scope.getSortOption(); if (so == null || so.getNumber() == 0) { if (browseIndex.getSortOption() != null) { so = browseIndex.getSortOption(); } } String col = "sort_1"; if (so.getNumber() > 0) { col = "sort_" + Integer.toString(so.getNumber()); } // now get the DAO to do the query for us, returning the highest // string value in the given column in the given table for the // item (I think) return dao.doOffsetQuery(col, value, scope.isAscending()); } /** * Convert the value into an offset into the table for this browse * * @return the focus value to use * @throws BrowseException */ private int getOffsetForDistinctValue(String value) throws BrowseException { if (!browseIndex.isMetadataIndex()) { throw new IllegalArgumentException("getOffsetForDistinctValue called when not a metadata index"); } // now get the DAO to do the query for us, returning the highest // string value in the given column in the given table for the // item (I think) return dao.doDistinctOffsetQuery("sort_value", value, scope.isAscending()); } /** * Return a normalized focus value. If there is no normalization that can be performed, * return the focus value that is passed in. * * @param value a focus value to normalize * @return the normalized focus value * @throws BrowseException */ private String normalizeJumpToValue(String value) throws BrowseException { // If the scope has a focus value (focus by value) if (scope.hasJumpToValue()) { // Normalize it based on the specified language as appropriate for this index return OrderFormat.makeSortString(scope.getJumpToValue(), scope.getJumpToValueLang(), scope.getBrowseIndex().getDataType()); } else if (scope.hasStartsWith()) { // Scope has a starts with, so normalize that instead return OrderFormat.makeSortString(scope.getStartsWith(), null, scope.getBrowseIndex().getDataType()); } // No focus value on the scope (ie. focus by id), so just return the passed focus value // This is useful in cases where we have pulled a focus value from the index // which will already be normalized, and avoids another DB lookup return value; } /** * Get the total number of results for the browse. This is the same as * calling getTotalResults(false) * * @return * @throws SQLException * @throws BrowseException */ private int getTotalResults() throws SQLException, BrowseException { return getTotalResults(false); } /** * Get the total number of results. The argument determines whether this is a distinct * browse or not as this has an impact on how results are counted * * @param distinct is this a distinct browse or not * @return the total number of results available in this type of browse * @throws SQLException * @throws BrowseException */ private int getTotalResults(boolean distinct) throws SQLException, BrowseException { log.debug(LogManager.getHeader(context, "get_total_results", "distinct=" + distinct)); // tell the browse query whether we are distinct dao.setDistinct(distinct); // ensure that the select is set to "*" String[] select = { "*" }; dao.setCountValues(select); // FIXME: it would be nice to have a good way of doing this in the DAO // now reset all of the fields that we don't want to have constraining // our count, storing them locally to reinstate later String focusField = dao.getJumpToField(); String focusValue = dao.getJumpToValue(); String orderField = dao.getOrderField(); int limit = dao.getLimit(); int offset = dao.getOffset(); dao.setJumpToField(null); dao.setJumpToValue(null); dao.setOrderField(null); dao.setLimit(-1); dao.setOffset(-1); // perform the query and get the result int count = dao.doCountQuery(); // now put back the values we removed for this method dao.setJumpToField(focusField); dao.setJumpToValue(focusValue); dao.setOrderField(orderField); dao.setLimit(limit); dao.setOffset(offset); dao.setCountValues(null); log.debug(LogManager.getHeader(context, "get_total_results_return", "return=" + count)); return count; } }
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.browse; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Context; import org.dspace.sort.SortOption; import org.dspace.sort.SortException; /** * A class which represents the initial request to the browse system. * When passed into the BrowseEngine, this will cause the creation * of a BrowseInfo object * * @author Richard Jones * */ public class BrowserScope { /** the DSpace context */ private Context context; /** the current browse index */ private BrowseIndex browseIndex; /** the order in which to display results */ private String order; /** the field upon which to sort */ private int sortBy; /** the value to restrict the browse to */ private String filterValue; /** exact or partial matching of the value */ private boolean filterValuePartial = false; /** the language of the value to restrict the browse to */ private String filterValueLang; /** the item id focus of the browse */ private int jumpItemId = -1; /** the string value to start with */ private String startsWith; /** the number of results per page to display */ private int resultsPerPage = 20; /** the Collection to which to restrict */ private Collection collection; /** the Community to which to restrict */ private Community community; /** the sort option being used */ private SortOption sortOption; /** the value upon which to focus */ private String jumpValue; /** the language of the value upon which to focus */ private String jumpValueLang; /** the browse level */ private int level = 0; /** the number of authors to display in the results */ private int etAl = 0; /** the number of items to offset into the result ie. 0 = 1st record */ private int offset = 0; private String authority = null; /** * Construct a new BrowserScope using the given Context * * @param context the DSpace Context */ public BrowserScope(Context context) { this.context = context; } /** * Set the DSpaceObject that is the container for this browse. If this * is not of type Collection or Community, this method will throw an * exception * * @param dso the container object; a Community or Collection * @throws BrowseException */ public void setBrowseContainer(DSpaceObject dso) throws BrowseException { if (dso instanceof Collection) { this.collection = (Collection) dso; } else if (dso instanceof Community) { this.community = (Community) dso; } else { throw new BrowseException("The container must be a community or a collection"); } } /** * Obtain a DSpaceObject that represents the container object. This will be * a Community or a Collection * * @return A DSpaceObject representing a Community or a Collection */ public DSpaceObject getBrowseContainer() { if (this.collection != null) { return this.collection; } if (this.community != null) { return this.community; } return null; } /** * @param level the browse level */ public void setBrowseLevel(int level) { this.level = level; } /** * @return the browse level */ public int getBrowseLevel() { return this.level; } /** * @return true if top level browse, false if not */ public boolean isTopLevel() { if (this.level == 0) { return true; } return false; } /** * @return true if second level browse, false if not */ public boolean isSecondLevel() { if (this.level == 1) { return true; } return false; } /** * @return Returns the browseIndex. */ public BrowseIndex getBrowseIndex() { return browseIndex; } /** * @param browseIndex The browseIndex to set. */ public void setBrowseIndex(BrowseIndex browseIndex) throws BrowseException { this.browseIndex = browseIndex; } /** * @return Returns the author limit. */ public int getEtAl() { return etAl; } /** * @param etAl the author limit */ public void setEtAl(int etAl) { this.etAl = etAl; } /** * @return Returns the collection. */ public Collection getCollection() { return collection; } /** * @param collection The collection to set. */ public void setCollection(Collection collection) { this.collection = collection; } /** * @return Returns the community. */ public Community getCommunity() { return community; } /** * @param community The community to set. */ public void setCommunity(Community community) { this.community = community; } /** * @return Returns the context. */ public Context getContext() { return context; } /** * @param context The context to set. */ public void setContext(Context context) { this.context = context; } /** * @return Returns the focus. */ public int getJumpToItem() { return jumpItemId; } /** * @param itemId The focus to set. */ public void setJumpToItem(int itemId) { this.jumpItemId = itemId; } /** * @return the value to focus on */ public String getJumpToValue() { return jumpValue; } /** * @param value the value to focus on */ public void setJumpToValue(String value) { this.jumpValue = value; } /** * @return the language of the value to focus on */ public String getJumpToValueLang() { return jumpValueLang; } /** * @param valueLang the language of the value to focus on */ public void setJumpToValueLang(String valueLang) { this.jumpValueLang = valueLang; } /** * @return Returns the order. */ public String getOrder() { if (order != null) { return order; } BrowseIndex bi = getBrowseIndex(); if (bi != null) { return bi.getDefaultOrder(); } return SortOption.ASCENDING; } /** * @param order The order to set. */ public void setOrder(String order) { if (order == null) { this.order = null; } else if (SortOption.ASCENDING.equalsIgnoreCase(order)) { this.order = SortOption.ASCENDING; } else if (SortOption.DESCENDING.equalsIgnoreCase(order)) { this.order = SortOption.DESCENDING; } } /** * @return Returns the resultsPerPage. */ public int getResultsPerPage() { return resultsPerPage; } /** * @param resultsPerPage The resultsPerPage to set. */ public void setResultsPerPage(int resultsPerPage) { if (resultsPerPage > -1) { this.resultsPerPage = resultsPerPage; } } /** * @return Returns the sortBy. */ public int getSortBy() { return sortBy; } /** * @param sortBy The sortBy to set. */ public void setSortBy(int sortBy) throws BrowseException { this.sortBy = sortBy; } /** * @return returns the offset for the browse */ public int getOffset() { return offset; } /** * @param offset the offset to use for this scope */ public void setOffset(int offset) { this.offset = offset; } /** * Obtain the sort option * * @return the sort option * @throws BrowseException */ public SortOption getSortOption() throws BrowseException { try { // If a sortOption hasn't been set, work out the default, providing we have an index if (sortOption == null && browseIndex != null) { // If a sorting hasn't been specified, and it's a metadata browse if (sortBy <= 0 && browseIndex.isMetadataIndex()) { // Create a dummy sortOption for the metadata sort String dataType = browseIndex.getDataType(); String type = ("date".equals(dataType) ? "date" : "text"); sortOption = new SortOption(0, browseIndex.getName(), browseIndex.getMetadata(0), type); } else { // If a sorting hasn't been specified if (sortBy <= 0) { // Get the sort option from the index sortOption = browseIndex.getSortOption(); if (sortOption == null) { // No sort option, so default to the first one defined in the config for (SortOption so : SortOption.getSortOptions()) { sortOption = so; break; } } } else { // A sorting has been specified, so get it from the configured sort columns for (SortOption so : SortOption.getSortOptions()) { if (so.getNumber() == sortBy) { sortOption = so; } } } } } return sortOption; } catch (SortException se) { throw new BrowseException("Error in SortOptions", se); } } /** * @return Returns the startsWith. */ public String getStartsWith() { return startsWith; } /** * @param startsWith The startsWith to set. */ public void setStartsWith(String startsWith) { this.startsWith = startsWith; } /** * Used for second-level item browses, * to only display items that match the value * @return Returns the value. */ public String getFilterValue() { return filterValue; } /** * Used for second-level item browses, * to only display items that match the value * @param value The value to set. */ public void setFilterValue(String value) { this.filterValue = value; } /** * Should the filter value be treated as partial, or exact * @return true if partial, false if exact */ public boolean getFilterValuePartial() { return filterValuePartial; } /** * Should the filter value be treated as partial, or exact * @param filterValuePartial true if partial, false if exact */ public void setFilterValuePartial(boolean filterValuePartial) { this.filterValuePartial = filterValuePartial; } /** * @return Returns the language. */ public String getFilterValueLang() { return filterValueLang; } /** * @param lang The language to set. */ public void setFilterValueLang(String lang) { this.filterValueLang = lang; } /** * @return true if in community, false if not */ public boolean inCommunity() { if (this.community != null) { return true; } return false; } /** * @return true if in collection, false if not */ public boolean inCollection() { if (this.collection != null) { return true; } return false; } /** * @return true if ascending, false if not - or not set */ public boolean isAscending() { if (SortOption.ASCENDING.equalsIgnoreCase(order)) { return true; } if (SortOption.DESCENDING.equalsIgnoreCase(order)) { return false; } BrowseIndex bi = getBrowseIndex(); if (bi != null && SortOption.DESCENDING.equalsIgnoreCase(bi.getDefaultOrder())) { return false; } return true; } /** * @return true if has value, false if not */ public boolean hasFilterValue() { if (filterValue == null || "".equals(filterValue)) { return false; } return true; } /** * @return true if has item focus, false if not */ public boolean hasJumpToItem() { if (jumpItemId == -1) { return false; } return true; } /** * @return true if has value focus, false if not */ public boolean hasJumpToValue() { if (this.jumpValue != null) { return true; } return false; } /** * @return true if has starts with value, false if not */ public boolean hasStartsWith() { if (this.startsWith != null) { return true; } return false; } public String getAuthorityValue() { return authority; } public void setAuthorityValue(String value) { authority = value; } }
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.browse; import java.util.List; /** * Interface for any class wishing to interact with the Browse storage layer for * Read Only operations. If you wish to modify the contents of the browse indices * or create and destroy index tables you should look at implementations for * BrowseCreateDAO. * * If you implement this class, and you wish it to be loaded via the BrowseDAOFactory * you must supply a constructor of the form: * * public BrowseDAOImpl(Context context) {} * * Where Context is the DSpace Context object * * Where tables are referred to in this class, they can be obtained from the BrowseIndex * class, which will answer queries given the context of the request on which table * is the relevant target. * * @author Richard Jones * */ public interface BrowseDAO { // Objects implementing this interface should also include // a constructor which takes the DSpace Context as an argument // // public BrowseDAOImpl(Context context) ... /** * This executes a query which will count the number of results for the * parameters you set. * * @return the integer value of the number of results found * @throws BrowseException */ public int doCountQuery() throws BrowseException; /** * This executes a query which returns a List object containing String * values which represent the results of a single value browse (for * example, the list of all subject headings). This is most * commonly used with a Distinct browse type. * * @return List of Strings representing the single value query results * @throws BrowseException */ public List<String[]> doValueQuery() throws BrowseException; /** * This executes a query which returns a List object containing BrowseItem objects * representing the results of a full item browse. * * @return List of BrowseItem objects * @throws BrowseException */ public List<BrowseItem> doQuery() throws BrowseException; /** * This executes a query which returns the value of the "highest" (max) value * in the given table's column for the given item id. * * @param column the column to interrogate * @param table the table to query * @param itemID the item id * @return String representing the max value in the given column * @throws BrowseException */ public String doMaxQuery(String column, String table, int itemID) throws BrowseException; /** * This executes a query which returns the offset where the value (or nearest greater * equivalent) can be found in the specified table ordered by the column. * * @param column the column to interrogate * @param value the item id * @param isAscending browsing in ascending or descending order * @return the offset into the table * @throws BrowseException */ public int doOffsetQuery(String column, String value, boolean isAscending) throws BrowseException; /** * This executes a query which returns the offset where the value (or nearest greater * equivalent) can be found in the specified table ordered by the column. * * @param column the column to interrogate * @param value the item id * @param isAscending browsing in ascending or descending order * @return the offset into the table * @throws BrowseException */ public int doDistinctOffsetQuery(String column, String value, boolean isAscending) throws BrowseException; /** * Does the query use the equals comparator when doing less than or greater than * comparisons. @see setEqualsComparator * * Default value is true * * @return true if using it, false if not */ public boolean useEqualsComparator(); /** * Set whether the query should use an equals comparator when doing less than or * greater than comparisons. That is, if true then comparisons will be made * using the equivalent of "<=" and ">=", while if false it will use the * equivalent of "<" and ">" * * @param equalsComparator true to use, false to not. */ public void setEqualsComparator(boolean equalsComparator); /** * Is the sort order ascending or descending? * * Default value is true * * @return true for ascending, false for descending */ public boolean isAscending(); /** * Set whether the results should be sorted in ascending order (on the given sort column) * or descending order. * * @param ascending true to ascend, false to descend */ public void setAscending(boolean ascending); /** * Get the database ID of the container object. The container object will be a * Community or a Collection. * * @return the database id of the container, or -1 if none is set */ public int getContainerID(); /** * Set the database id of the container object. This should be the id of a * Community or Collection. This will constrain the results of the browse * to only items or values within items that appear in the given container. * * @param containerID */ public void setContainerID(int containerID); /** * get the name of the field in which to look for the container id. This is * principally for use internal to the DAO. * * @return the name of the container id field. For example "collection_id" or * "community_id" */ public String getContainerIDField(); /** * set the name of the field in which to look for the container id. * * @param containerIDField the name of the container id field. * For example "collection_id" or "community_id" */ public void setContainerIDField(String containerIDField); /** * Get the field in which we will match a focus value from which to start * the browse. This will either be the "sort_value" field or one of the * additional sort fields defined by configuration * * @return the name of the focus field */ public String getJumpToField(); /** * Set the focus field upon which we will match a value from which to start * the browse. This will either be the "sort_value" field or one of the * additional sort fields defined by configuration * * param focusField the name of the focus field */ public void setJumpToField(String focusField); /** * Get the value at which the browse will start. The value supplied here will * be the top result on the page of results. * * @return the value to start browsing on */ public String getJumpToValue(); /** * Set the value upon which to start the browse from. The value supplied here * will be the top result on the page of results * * @param focusValue the value in the focus field on which to start browsing */ public void setJumpToValue(String focusValue); /** * get the integer number which is the limit of the results that will be returned * by any query. The default is -1, which means unlimited results. * * @return the maximum possible number of results allowed to be returned */ public int getLimit(); /** * Set the limit for how many results should be returned. This is generally * for use in paging or limiting the number of items be be displayed. The default * is -1, meaning unlimited results. Note that if the number of results of the * query is less than this number, the size of the result set will be smaller * than this limit. * * @param limit the maximum number of results to return. */ public void setLimit(int limit); /** * Get the offset from the first result from which to return results. This * functionality is present for backwards compatibility, but is ill advised. All * normal browse operations can be completed without it. The default is -1, which * means do not offset. * * @return the offset */ public int getOffset(); /** * Get the offset from the first result from which to return results. This * functionality is present for backwards compatibility, but is ill advised. All * normal browse operations can be completed without it. The default is -1, which * means do not offset. * * @param offset */ public void setOffset(int offset); /** * Get the database field which will be used to do the sorting of result sets on. * * @return the field by which results will be sorted */ public String getOrderField(); /** * Set the database field which will be used to sort result sets on * * @param orderField the field by which results will be sorted */ public void setOrderField(String orderField); /** * Get the array of values that we will be selecting on. The default is * to select all of the values from a given table * * @return an array of values to select on */ public String[] getSelectValues(); /** * Set the array of values to select on. This should be a list of the columns * available in the target table, or the SQL wildcards. The default is * single element array with the standard wildcard (*) * * @param selectValues the values to select on */ public void setSelectValues(String[] selectValues); /** * Get the array of fields that we will be counting on. * * @return an array of fields to be counted over */ public String[] getCountValues(); /** * Set the array of columns that we will be counting over. In general, the * wildcard (*) will suffice * * @param fields an array of fields to be counted over */ public void setCountValues(String[] fields); /** * get the name of the table that we are querying * * @return the name of the table */ public String getTable(); /** * Set the name of the table to query * * @param table the name of the table */ public void setTable(String table); /** * Set the name of the mapping tables to use for filtering * @param tableDis the name of the table holding the distinct values * @param tableMap the name of the table holding the mappings */ public void setFilterMappingTables(String tableDis, String tableMap); /** * Get the value which we are constraining all our browse results to contain. * * @return the value to which to constrain results */ public String getFilterValue(); /** * Set the value to which all our browse results should be constrained. For * example, if you are listing all of the publications by a single author * your value would be the author name. * * @param value the value to which to constrain results */ public void setFilterValue(String value); /** * Sets whether we will treat the filter value as partial (like match), or exact * * @param part true if partial, false if exact */ public void setFilterValuePartial(boolean part); /** * Get the name of the field in which the value to constrain results is * contained * * @return the name of the field */ public String getFilterValueField(); /** * Set he name of the field in which the value to constrain results is * contained * * @param valueField the name of the field */ public void setFilterValueField(String valueField); /** * Set whether this is a distinct value browse or not * * @param bool true if distinct value, false if not */ public void setDistinct(boolean bool); /** * Is this a distinct value browse? * * @return true if distinct, false if not */ public boolean isDistinct(); /** * If we have specified a container id and container field, we must also specify * a container table. This is the name of the table that maps the item onto * the distinct value. Since we are in a container, this value will actually be * the view which allows us to select only items which are within a given container * * @param containerTable the name of the container table mapping */ public void setContainerTable(String containerTable); /** * Get the name of the container table that is being used to map items to distinct * values when in a container constrained browse * * @return the name of the table */ public String getContainerTable(); public void setAuthorityValue(String value); public String getAuthorityValue(); }
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.browse; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; /** * Factory class to generate DAOs based on the configuration * * @author Richard Jones * */ public class BrowseDAOFactory { /** * Get an instance of the relevant Read Only DAO class, which will * conform to the BrowseDAO interface * * @param context the DSpace context * @return the relevant DAO * @throws BrowseException */ public static BrowseDAO getInstance(Context context) throws BrowseException { String db = ConfigurationManager.getProperty("db.name"); if ("postgres".equals(db)) { return new BrowseDAOPostgres(context); } else if ("oracle".equals(db)) { return new BrowseDAOOracle(context); } else { throw new BrowseException("The configuration for db.name is either invalid, or contains an unrecognised database"); } } /** * Get an instance of the relevant Write Only DAO class, which will * conform to the BrowseCreateDAO interface * * @param context the DSpace context * @return the relevant DAO * @throws BrowseException */ public static BrowseCreateDAO getCreateInstance(Context context) throws BrowseException { String db = ConfigurationManager.getProperty("db.name"); if ("postgres".equals(db)) { return new BrowseCreateDAOPostgres(context); } else if ("oracle".equals(db)) { return new BrowseCreateDAOOracle(context); } else { throw new BrowseException("The configuration for db.name is either invalid, or contains an unrecognised database"); } } /** * Get an instance of the relevant Read Only DAO class, which will * conform to the BrowseItemDAO interface * * @param context the DSpace context * @return the relevant DAO * @throws BrowseException */ public static BrowseItemDAO getItemInstance(Context context) throws BrowseException { String db = ConfigurationManager.getProperty("db.name"); if ("postgres".equals(db)) { return new BrowseItemDAOPostgres(context); } else if ("oracle".equals(db)) { return new BrowseItemDAOOracle(context); } else { throw new BrowseException("The configuration for db.name is either invalid, or contains an unrecognised database"); } } /** * Get an instance of the relevant DAO Utilities class, which will * conform to the BrowseDAOUtils interface * * @param context the DSpace context * @return the relevant DAO * @throws BrowseException */ public static BrowseDAOUtils getUtils(Context context) throws BrowseException { String db = ConfigurationManager.getProperty("db.name"); if ("postgres".equals(db)) { return new BrowseDAOUtilsPostgres(); } else if ("oracle".equals(db)) { return new BrowseDAOUtilsOracle(); } else { throw new BrowseException("The configuration for db.name is either invalid, or contains an unrecognised database"); } } }
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.browse; /** * Utility class for retrieving the size of the columns to be used in the browse tables, * and applying truncation to the strings that will be inserted into the tables. * * Can be configured in dspace.cfg, with the following entries: * * webui.browse.value_columns.max * - the maximum number of characters in 'value' columns * (0 is unlimited) * * webui.browse.sort_columns.max * - the maximum number of characters in 'sort' columns * (0 is unlimited) * * webui.browse.value_columns.omission_mark * - a string to append to truncated values that will be entered into * the value columns (ie. '...') * * By default, the column sizes are '0' (unlimited), and no truncation is applied, * EXCEPT for Oracle, where we have to truncate the columns for it to work! (in which * case, both value and sort columns are by default limited to 2000 characters). * * @author Richard Jones */ public class BrowseDAOUtilsPostgres extends BrowseDAOUtilsDefault { /** * This is really just a type cast at the moment so we have a Postgres * specific set of utils. In reality, this is identical to the * Default class which it extends. * */ public BrowseDAOUtilsPostgres() { super(); } }
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.browse; import org.dspace.content.Community; import org.dspace.content.Collection; import org.dspace.core.Context; import org.dspace.content.DSpaceObject; /** * Interface for data access of cached community and collection item count * information * * @author Richard Jones * */ public interface ItemCountDAO { /** * Set the DSpace Context to use during data access * * @param context * @throws ItemCountException */ public void setContext(Context context) throws ItemCountException; /** * Set the given count as the number of items in the given community * * @param community * @param count * @throws ItemCountException */ public void communityCount(Community community, int count) throws ItemCountException; /** * Set the given count as the number of items in the given collection * * @param collection * @param count * @throws ItemCountException */ public void collectionCount(Collection collection, int count) throws ItemCountException; /** * Get the number of items in the given DSpaceObject container. This method will * only succeed if the DSpaceObject is an instance of either a Community or a * Collection. Otherwise it will throw an exception * * @param dso * @return * @throws ItemCountException */ public int getCount(DSpaceObject dso) throws ItemCountException; /** * Remove any cached data regarding the given DSpaceObject container. This method will * only succeed if the DSpaceObject is an instance of either a Community or a * Collection. Otherwise it will throw an exception * * @param dso * @throws ItemCountException */ public void remove(DSpaceObject dso) throws ItemCountException; }
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.browse; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.content.authority.ChoiceAuthorityManager; import org.dspace.content.authority.MetadataAuthorityManager; import org.dspace.core.Context; import org.dspace.sort.SortOption; import org.dspace.sort.SortException; import org.dspace.sort.OrderFormat; /** * Tool to create Browse indexes. This class is used from the command line to * create and destroy the browse indices from configuration, and also from within * the application to add and remove content from those tables. * * To see a full definition of the usage of this class just run it without any * arguments, and you will get the help message. * * @author Richard Jones */ public class IndexBrowse { /** logger */ private static Logger log = Logger.getLogger(IndexBrowse.class); /** DSpace context */ private Context context; /** whether to destroy and rebuild the database */ private boolean rebuild = false; /** whether to destroy the database */ private boolean delete = false; /** the index number to start working from (for debug only) */ private int start = 1; /** whether to execute the commands generated against the database */ private boolean execute = false; /** whether there is an output file into which to write SQL */ private boolean fileOut = false; /** whether the output should be written to the standadr out */ private boolean stdOut = false; /** the name of the output file */ private String outFile = null; /** should the operations be verbose */ private boolean verbose = false; /** the configured browse indices */ private BrowseIndex[] bis; /** the DAO for write operations on the database */ private BrowseCreateDAO dao; /** the outputter class */ private BrowseOutput output; /** * Construct a new index browse. If done this way, an internal * DSpace context will be created. Better instead to call * * <code> * new IndexBrowse(context); * </code> * * with your desired context (when using with the application) * * @throws SQLException * @throws BrowseException */ public IndexBrowse() throws SQLException, BrowseException { this(new Context()); } /** * Create a new IndexBrowse object. This will ignore any authorisations * applied to the Context * * @param context * @throws SQLException * @throws BrowseException */ public IndexBrowse(Context context) throws SQLException, BrowseException { this.context = context; // get the browse indices, and ensure that // we have all the relevant tables prepped this.bis = BrowseIndex.getBrowseIndices(); checkConfig(); // get the DAO for the create operations dao = BrowseDAOFactory.getCreateInstance(context); // set the outputter output = new BrowseOutput(); // then generate all the metadata bits that we // are going to use for (int k = 0; k < bis.length; k++) { bis[k].generateMdBits(); } } /** * @return Returns the verbose. */ public boolean isVerbose() { return verbose; } /** * @param verbose The verbose to set. */ public void setVerbose(boolean verbose) { this.verbose = verbose; output.setVerbose(verbose); } /** * @return true if to rebuild the database, false if not */ public boolean rebuild() { return rebuild; } /** * @param bool whether to rebuild the database or not */ public void setRebuild(boolean bool) { this.rebuild = bool; } /** * @return true if to delete the database, false if not */ public boolean delete() { return delete; } /** * @param bool whetehr to delete the database or not */ public void setDelete(boolean bool) { this.delete = bool; } /** * @param start the index to start working up from */ public void setStart(int start) { this.start = start; } /** * @return the index to start working up from */ public int getStart() { return this.start; } /** * @param bool whether to execute the database commands or not */ public void setExecute(boolean bool) { this.execute = bool; } /** * @return true if to execute database commands, false if not */ public boolean execute() { return this.execute; } /** * @param bool whether to use an output file */ public void setFileOut(boolean bool) { this.fileOut = bool; output.setFile(bool); } /** * @return true if using an output file, false if not */ public boolean isFileOut() { return this.fileOut; } /** * @param bool whether to write to standard out */ public void setStdOut(boolean bool) { this.stdOut = bool; output.setPrint(bool); } /** * @return true if to write to standard out, false if not */ public boolean toStdOut() { return this.stdOut; } /** * @param file the name of the output file */ public void setOutFile(String file) { this.outFile = file; output.setFileName(file); } /** * @return the name of the output file */ public String getOutFile() { return this.outFile; } /** * Prune indexes - called from the public interfaces or at the end of a batch indexing process */ private void pruneIndexes() throws BrowseException { // go over the indices and prune for (int i = 0; i < bis.length; i++) { if (bis[i].isMetadataIndex()) { log.debug("Pruning metadata index: " + bis[i].getTableName()); pruneDistinctIndex(bis[i], null); } } dao.pruneExcess(BrowseIndex.getItemBrowseIndex().getTableName(), false); dao.pruneExcess(BrowseIndex.getWithdrawnBrowseIndex().getTableName(), true); } private void pruneDistinctIndex(BrowseIndex bi, List<Integer> removedIds) throws BrowseException { dao.pruneMapExcess(bi.getMapTableName(), false, removedIds); dao.pruneDistinct(bi.getDistinctTableName(), bi.getMapTableName(), removedIds); } /** * Index the given item * * @param item the item to index * @throws BrowseException */ public void indexItem(Item item) throws BrowseException { indexItem(item, false); } void indexItem(Item item, boolean addingNewItem) throws BrowseException { // If the item is not archived AND has not been withdrawn // we can assume that it has *never* been archived - in that case, // there won't be anything in the browse index, so we can just skip processing. // If it is either archived or withdrawn, then there may be something in the browse // tables, so we *must* process it. // Caveat: an Item.update() that changes isArchived() from TRUE to FALSE, whilst leaving // isWithdrawn() as FALSE, may result in stale data in the browse tables. // Such an update should never occur though, and if it does, probably indicates a major // problem with the code updating the Item. if (item.isArchived()) { indexItem(new ItemMetadataProxy(item), addingNewItem); } else if (item.isWithdrawn()) { indexItem(new ItemMetadataProxy(item), false); } } /** * Index the given item * * @param item the item to index * @throws BrowseException */ private void indexItem(ItemMetadataProxy item, boolean addingNewItem) throws BrowseException { // Map to store the metadata from the Item // so that we don't grab it multiple times Map<String, String> itemMDMap = new HashMap<String, String>(); try { boolean reqCommunityMappings = false; Map<Integer, String> sortMap = getSortValues(item, itemMDMap); if (item.isArchived() && !item.isWithdrawn()) { // Try to update an existing record in the item index if (!dao.updateIndex(BrowseIndex.getItemBrowseIndex().getTableName(), item.getID(), sortMap)) { // Record doesn't exist - ensure that it doesn't exist in the withdrawn index, // and add it to the archived item index dao.deleteByItemID(BrowseIndex.getWithdrawnBrowseIndex().getTableName(), item.getID()); dao.insertIndex(BrowseIndex.getItemBrowseIndex().getTableName(), item.getID(), sortMap); } reqCommunityMappings = true; } else if (item.isWithdrawn()) { // Try to update an existing record in the withdrawn index if (!dao.updateIndex(BrowseIndex.getWithdrawnBrowseIndex().getTableName(), item.getID(), sortMap)) { // Record doesn't exist - ensure that it doesn't exist in the item index, // and add it to the withdrawn item index dao.deleteByItemID(BrowseIndex.getItemBrowseIndex().getTableName(), item.getID()); dao.insertIndex(BrowseIndex.getWithdrawnBrowseIndex().getTableName(), item.getID(), sortMap); } } else { // This item shouldn't exist in either index - ensure that it is removed dao.deleteByItemID(BrowseIndex.getItemBrowseIndex().getTableName(), item.getID()); dao.deleteByItemID(BrowseIndex.getWithdrawnBrowseIndex().getTableName(), item.getID()); } // Update the community mappings if they are required, or remove them if they aren't if (reqCommunityMappings) { dao.updateCommunityMappings(item.getID()); } else { dao.deleteCommunityMappings(item.getID()); } // Now update the metadata indexes for (int i = 0; i < bis.length; i++) { if (bis[i].isMetadataIndex()) { log.debug("Indexing for item " + item.getID() + ", for index: " + bis[i].getTableName()); Set<Integer> distIDSet = new HashSet<Integer>(); // now index the new details - but only if it's archived and not withdrawn if (item.isArchived() && !item.isWithdrawn()) { // get the metadata from the item for (int mdIdx = 0; mdIdx < bis[i].getMetadataCount(); mdIdx++) { String[] md = bis[i].getMdBits(mdIdx); DCValue[] values = item.getMetadata(md[0], md[1], md[2], Item.ANY); // if we have values to index on, then do so if (values != null && values.length > 0) { int minConfidence = MetadataAuthorityManager.getManager() .getMinConfidence(values[0].schema, values[0].element, values[0].qualifier); for (DCValue value : values) { // Ensure that there is a value to index before inserting it if (StringUtils.isEmpty(value.value)) { log.error("Null metadata value for item " + item.getID() + ", field: " + value.schema + "." + value.element + (value.qualifier == null ? "" : "." + value.qualifier)); } else { if (bis[i].isAuthorityIndex() && (value.authority == null || value.confidence < minConfidence)) { // skip to next value in this authority field if value is not authoritative log.debug("Skipping non-authoritative value: " + item.getID() + ", field=" + value.schema + "." + value.element + "." + value.qualifier + ", value=" + value.value + ", authority=" + value.authority + ", confidence=" + value.confidence + " (BAD AUTHORITY)"); continue; } // is there any valid (with appropriate confidence) authority key? if (value.authority != null && value.confidence >= minConfidence) { boolean isValueInVariants = false; // Are there variants of this value List<String> variants = ChoiceAuthorityManager.getManager() .getVariants(value.schema, value.element, value.qualifier, value.authority, value.language); // If we have variants, index them if (variants != null) { for (String var : variants) { String nVal = OrderFormat.makeSortString(var, value.language, bis[i].getDataType()); distIDSet.add(dao.getDistinctID(bis[i].getDistinctTableName(), var, value.authority, nVal)); if (var.equals(value.value)) { isValueInVariants = true; } } } // If we didn't index the value as one of the variants, add it now if (!isValueInVariants) { // get the normalised version of the value String nVal = OrderFormat.makeSortString(value.value, value.language, bis[i].getDataType()); distIDSet.add(dao.getDistinctID(bis[i].getDistinctTableName(), value.value, value.authority, nVal)); } } else // put it in the browse index as if it hasn't have an authority key { // get the normalised version of the value String nVal = OrderFormat.makeSortString(value.value, value.language, bis[i].getDataType()); distIDSet.add(dao.getDistinctID(bis[i].getDistinctTableName(), value.value, null, nVal)); } } } } } } // Do we have any mappings? if (distIDSet.isEmpty()) { if (!addingNewItem) { // remove any old mappings List<Integer> distinctIds = dao.deleteMappingsByItemID(bis[i].getMapTableName(), item.getID()); if (distinctIds != null && distinctIds.size() > 0) { dao.pruneDistinct(bis[i].getDistinctTableName(), bis[i].getMapTableName(), distinctIds); } } } else { // Update the existing mappings MappingResults results = dao.updateDistinctMappings(bis[i].getMapTableName(), item.getID(), distIDSet); if (results.getRemovedDistinctIds() != null && results.getRemovedDistinctIds().size() > 0) { pruneDistinctIndex(bis[i], results.getRemovedDistinctIds()); } } } } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /** * Get the normalised values for each of the sort columns * @param item * @param itemMDMap * @return * @throws BrowseException * @throws SQLException */ private Map<Integer, String> getSortValues(ItemMetadataProxy item, Map itemMDMap) throws BrowseException, SQLException { try { // now obtain the sort order values that we will use Map<Integer, String> sortMap = new HashMap<Integer, String>(); for (SortOption so : SortOption.getSortOptions()) { Integer key = Integer.valueOf(so.getNumber()); String metadata = so.getMetadata(); // If we've already used the metadata for this Item // it will be cached in the map DCValue value = null; if (itemMDMap != null) { value = (DCValue) itemMDMap.get(metadata); } // We haven't used this metadata before, so grab it from the item if (value == null) { String[] somd = so.getMdBits(); DCValue[] dcv = item.getMetadata(somd[0], somd[1], somd[2], Item.ANY); if (dcv == null) { continue; } // we only use the first dc value if (dcv.length > 0) { // Set it as the current metadata value to use // and add it to the map value = dcv[0]; if (itemMDMap != null) { itemMDMap.put(metadata, dcv[0]); } } } // normalise the values as we insert into the sort map if (value != null && value.value != null) { String nValue = OrderFormat.makeSortString(value.value, value.language, so.getType()); sortMap.put(key, nValue); } } return sortMap; } catch (SortException se) { throw new BrowseException("Error in SortOptions", se); } } /** * remove all the indices for the given item * * @param item the item to be removed * @return * @throws BrowseException */ public boolean itemRemoved(Item item) throws BrowseException { return itemRemoved(item.getID()); } public boolean itemRemoved(int itemID) throws BrowseException { // go over the indices and index the item for (int i = 0; i < bis.length; i++) { if (bis[i].isMetadataIndex()) { log.debug("Removing indexing for removed item " + itemID + ", for index: " + bis[i].getTableName()); dao.deleteByItemID(bis[i].getMapTableName(), itemID); } } // Remove from the item indexes (archive and withdrawn) dao.deleteByItemID(BrowseIndex.getItemBrowseIndex().getTableName(), itemID); dao.deleteByItemID(BrowseIndex.getWithdrawnBrowseIndex().getTableName(), itemID); dao.deleteCommunityMappings(itemID); return true; } /** * Creates Browse indexes, destroying the old ones. * * @param argv * Command-line arguments */ public static void main(String[] argv) throws SQLException, BrowseException, ParseException { Date startTime = new Date(); try { Context context = new Context(); context.turnOffAuthorisationSystem(); IndexBrowse indexer = new IndexBrowse(context); // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); // these are mutually exclusive, and represent the primary actions options.addOption("t", "tables", false, "create the tables only, do not attempt to index. Mutually exclusive with -f and -i"); options.addOption("i", "index", false, "actually do the indexing. Mutually exclusive with -t and -f"); options.addOption("f", "full", false, "make the tables, and do the indexing. This forces -x. Mutually exclusive with -t and -i"); // these options can be specified only with the -f option options.addOption("r", "rebuild", false, "should we rebuild all the indices, which removes old index tables and creates new ones. For use with -f. Mutually exclusive with -d"); options.addOption("d", "delete", false, "delete all the indices, but don't create new ones. For use with -f. This is mutually exclusive with -r"); // these options can be specified only with the -t and -f options options.addOption("o", "out", true, "[-o <filename>] write the remove and create SQL to the given file. For use with -t and -f"); // FIXME: not currently working options.addOption("p", "print", false, "write the remove and create SQL to the stdout. For use with -t and -f"); options.addOption("x", "execute", false, "execute all the remove and create SQL against the database. For use with -t and -f"); options.addOption("s", "start", true, "[-s <int>] start from this index number and work upward (mostly only useful for debugging). For use with -t and -f"); // this option can be used with any argument options.addOption("v", "verbose", false, "print extra information to the stdout. If used in conjunction with -p, you cannot use the stdout to generate your database structure"); // display the help. If this is spefified, it trumps all other arguments options.addOption("h", "help", false, "show this help documentation. Overrides all other arguments"); CommandLine line = parser.parse(options, argv); // display the help if (line.hasOption("h")) { indexer.usage(options); return; } if (line.hasOption("v")) { indexer.setVerbose(true); } if (line.hasOption("i")) { indexer.createIndex(); return; } if (line.hasOption("f")) { if (line.hasOption('r')) { indexer.setRebuild(true); } else if (line.hasOption("d")) { indexer.setDelete(true); } } if (line.hasOption("f") || line.hasOption("t")) { if (line.hasOption("s")) { indexer.setStart(Integer.parseInt(line.getOptionValue("s"))); } if (line.hasOption("x")) { indexer.setExecute(true); } if (line.hasOption("p")) { indexer.setStdOut(true); } if (line.hasOption("o")) { indexer.setFileOut(true); indexer.setOutFile(line.getOptionValue("o")); } } if (line.hasOption("t")) { indexer.prepTables(); return; } if (line.hasOption("f")) { indexer.setExecute(true); indexer.initBrowse(); return; } indexer.usage(options); context.complete(); } finally { Date endTime = new Date(); System.out.println("Started: " + startTime.getTime()); System.out.println("Ended: " + endTime.getTime()); System.out.println("Elapsed time: " + ((endTime.getTime() - startTime.getTime()) / 1000) + " secs (" + (endTime.getTime() - startTime.getTime()) + " msecs)"); } } /** * output the usage information * * @param options */ private void usage(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("IndexBrowse", options); } /** * Prepare the tables for the browse indices * * @throws BrowseException */ private void prepTables() throws BrowseException { try { // first, erase the existing indexes clearDatabase(); createItemTables(); // for each current browse index, make all the relevant tables for (int i = 0; i < bis.length; i++) { createTables(bis[i]); // prepare some CLI output StringBuilder logMe = new StringBuilder(); for (SortOption so : SortOption.getSortOptions()) { logMe.append(" ").append(so.getMetadata()).append(" "); } output.message("Creating browse index " + bis[i].getName() + ": index by " + bis[i].getMetadata() + " sortable by: " + logMe.toString()); } } catch (SortException se) { throw new BrowseException("Error in SortOptions", se); } } /** * delete all the existing browse tables * * @throws BrowseException */ public void clearDatabase() throws BrowseException { try { output.message("Deleting old indices"); // notice that we have to do this without reference to the BrowseIndex[] // because they do not necessarily reflect what currently exists in // the database int i = getStart(); while (true) { String tableName = BrowseIndex.getTableName(i, false, false, false, false); String distinctTableName = BrowseIndex.getTableName(i, false, false, true, false); String distinctMapName = BrowseIndex.getTableName(i, false, false, false, true); String sequence = BrowseIndex.getSequenceName(i, false, false); String mapSequence = BrowseIndex.getSequenceName(i, false, true); String distinctSequence = BrowseIndex.getSequenceName(i, true, false); // These views are no longer used, but as we are cleaning the database, // they may exist and need to be removed String colViewName = BrowseIndex.getTableName(i, false, true, false, false); String comViewName = BrowseIndex.getTableName(i, true, false, false, false); String distinctColViewName = BrowseIndex.getTableName(i, false, true, false, true); String distinctComViewName = BrowseIndex.getTableName(i, true, false, false, true); output.message("Checking for " + tableName); if (dao.testTableExistence(tableName)) { output.message("...found"); output.message("Deleting old index and associated resources: " + tableName); // prepare a statement which will delete the table and associated // resources String dropper = dao.dropIndexAndRelated(tableName, this.execute()); String dropSeq = dao.dropSequence(sequence, this.execute()); output.sql(dropper); output.sql(dropSeq); // These views are no longer used, but as we are cleaning the database, // they may exist and need to be removed String dropColView = dao.dropView( colViewName, this.execute() ); String dropComView = dao.dropView( comViewName, this.execute() ); output.sql(dropColView); output.sql(dropComView); } // NOTE: we need a secondary context to check for the existance // of the table, because if an SQLException is thrown, then // the connection is aborted, and no more transaction stuff can be // done. Therefore we use a blank context to make the requests, // not caring if it gets aborted or not output.message("Checking for " + distinctTableName); if (!dao.testTableExistence(distinctTableName)) { if (i < bis.length || i < 10) { output.message("... doesn't exist; but will carry on as there may be something that conflicts"); } else { output.message("... doesn't exist; no more tables to delete"); break; } } else { output.message("...found"); output.message("Deleting old index and associated resources: " + distinctTableName); // prepare statements that will delete the distinct value tables String dropDistinctTable = dao.dropIndexAndRelated(distinctTableName, this.execute()); String dropMap = dao.dropIndexAndRelated(distinctMapName, this.execute()); String dropDistinctMapSeq = dao.dropSequence(mapSequence, this.execute()); String dropDistinctSeq = dao.dropSequence(distinctSequence, this.execute()); output.sql(dropDistinctTable); output.sql(dropMap); output.sql(dropDistinctMapSeq); output.sql(dropDistinctSeq); // These views are no longer used, but as we are cleaning the database, // they may exist and need to be removed String dropDistinctColView = dao.dropView( distinctColViewName, this.execute() ); String dropDistinctComView = dao.dropView( distinctComViewName, this.execute() ); output.sql(dropDistinctColView); output.sql(dropDistinctComView); } i++; } dropItemTables(BrowseIndex.getItemBrowseIndex()); dropItemTables(BrowseIndex.getWithdrawnBrowseIndex()); if (execute()) { context.commit(); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /** * drop the tables and related database entries for the internal * 'item' tables * @param bix * @throws BrowseException */ private void dropItemTables(BrowseIndex bix) throws BrowseException { if (dao.testTableExistence(bix.getTableName())) { String tableName = bix.getTableName(); String dropper = dao.dropIndexAndRelated(tableName, this.execute()); String dropSeq = dao.dropSequence( bix.getSequenceName(false, false), this.execute() ); output.sql(dropper); output.sql(dropSeq); // These views are no longer used, but as we are cleaning the database, // they may exist and need to be removed String colViewName = bix.getTableName(false, true, false, false); String comViewName = bix.getTableName(true, false, false, false); String dropColView = dao.dropView( colViewName, this.execute() ); String dropComView = dao.dropView( comViewName, this.execute() ); output.sql(dropColView); output.sql(dropComView); } } /** * Create the internal full item tables * @throws BrowseException */ private void createItemTables() throws BrowseException { try { // prepare the array list of sort options List<Integer> sortCols = new ArrayList<Integer>(); for (SortOption so : SortOption.getSortOptions()) { sortCols.add(Integer.valueOf(so.getNumber())); } createItemTables(BrowseIndex.getItemBrowseIndex(), sortCols); createItemTables(BrowseIndex.getWithdrawnBrowseIndex(), sortCols); if (execute()) { context.commit(); } } catch (SortException se) { throw new BrowseException("Error in SortOptions", se); } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /** * Create the internal full item tables for a particular index * (ie. withdrawn / in archive) * @param bix * @param sortCols * @throws BrowseException */ private void createItemTables(BrowseIndex bix, List<Integer> sortCols) throws BrowseException { String tableName = bix.getTableName(); String itemSeq = dao.createSequence(bix.getSequenceName(false, false), this.execute()); String itemTable = dao.createPrimaryTable(tableName, sortCols, execute); String[] itemIndices = dao.createDatabaseIndices(tableName, sortCols, false, this.execute()); output.sql(itemSeq); output.sql(itemTable); for (int i = 0; i < itemIndices.length; i++) { output.sql(itemIndices[i]); } } /** * Create the browse tables for the given browse index * * @param bi the browse index to create * @throws BrowseException */ private void createTables(BrowseIndex bi) throws BrowseException { try { // if this is a single view, create the DISTINCT tables and views if (bi.isMetadataIndex()) { // if this is a single view, create the DISTINCT tables and views String distinctTableName = bi.getDistinctTableName(); String distinctSeq = bi.getSequenceName(true, false); String distinctMapName = bi.getMapTableName(); String mapSeq = bi.getSequenceName(false, true); // FIXME: at the moment we have not defined INDEXes for this data // add this later when necessary String distinctTableSeq = dao.createSequence(distinctSeq, this.execute()); String distinctMapSeq = dao.createSequence(mapSeq, this.execute()); String createDistinctTable = dao.createDistinctTable(distinctTableName, this.execute()); String createDistinctMap = dao.createDistinctMap(distinctTableName, distinctMapName, this.execute()); String[] mapIndices = dao.createMapIndices(distinctTableName, distinctMapName, this.execute()); output.sql(distinctTableSeq); output.sql(distinctMapSeq); output.sql(createDistinctTable); output.sql(createDistinctMap); for (int i = 0; i < mapIndices.length; i++) { output.sql(mapIndices[i]); } } if (execute()) { context.commit(); } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /** * index everything * * @throws SQLException * @throws BrowseException */ public void initBrowse() throws SQLException, BrowseException { Date localStart = new Date(); output.message("Creating browse indexes for DSpace"); Date initDate = new Date(); long init = initDate.getTime() - localStart.getTime(); output.message("init complete (" + Long.toString(init) + " ms)"); if (delete()) { output.message("Deleting browse tables"); clearDatabase(); output.message("Browse tables deleted"); return; } else if (rebuild()) { output.message("Preparing browse tables"); prepTables(); output.message("Browse tables prepared"); } Date prepDate = new Date(); long prep = prepDate.getTime() - localStart.getTime(); long prepinit = prepDate.getTime() - initDate.getTime(); output.message("tables prepped (" + Long.toString(prep) + " ms, " + Long.toString(prepinit) + " ms)"); int count = createIndex(); context.complete(); Date endDate = new Date(); long end = endDate.getTime() - localStart.getTime(); long endprep = endDate.getTime() - prepDate.getTime(); output.message("content indexed (" + Long.toString(end) + " ms, " + Long.toString(endprep) + " ms)"); output.message("Items indexed: " + Integer.toString(count)); if (count > 0) { long overall = end / count; long specific = endprep / count; output.message("Overall average time per item: " + Long.toString(overall) + " ms"); output.message("Index only average time per item: " + Long.toString(specific) + " ms"); } output.message("Browse indexing completed"); } /** * create the indices for all the items * * @return * @throws BrowseException */ private int createIndex() throws BrowseException { try { // first, pre-prepare the known metadata fields that we want to query // on for (int k = 0; k < bis.length; k++) { bis[k].generateMdBits(); } // now get the ids of ALL the items in the database BrowseItemDAO biDao = BrowseDAOFactory.getItemInstance(context); BrowseItem[] items = biDao.findAll(); // go through every item id, grab the relevant metadata // and write it into the database for (int j = 0; j < items.length; j++) { // Creating the indexes from scracth, so treat each item as if it's new indexItem(new ItemMetadataProxy(items[j].getID(), items[j]), true); // after each item we commit the context and clear the cache context.commit(); context.clearCache(); } // Make sure the deletes are written back context.commit(); return items.length; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } } /** * Currently does nothing * */ private void checkConfig() { // FIXME: exactly in what way do we want to check the config? } /** * Take a string representation of a metadata field, and return it as an array. * This is just a convenient utility method to basically break the metadata * representation up by its delimiter (.), and stick it in an array, inserting * the value of the init parameter when there is no metadata field part. * * @param mfield the string representation of the metadata * @param init the default value of the array elements * @return a three element array with schema, element and qualifier respectively */ public String[] interpretField(String mfield, String init) throws IOException { StringTokenizer sta = new StringTokenizer(mfield, "."); String[] field = {init, init, init}; int i = 0; while (sta.hasMoreTokens()) { field[i++] = sta.nextToken(); } // error checks to make sure we have at least a schema and qualifier for both if (field[0] == null || field[1] == null) { throw new IOException("at least a schema and element be " + "specified in configuration. You supplied: " + mfield); } return field; } // private inner class // Hides the Item / BrowseItem in such a way that we can remove // the duplication in indexing an item. private static class ItemMetadataProxy { private Item item; private BrowseItem browseItem; private int id; ItemMetadataProxy(Item item) { this.item = item; this.browseItem = null; this.id = 0; } ItemMetadataProxy(int id, BrowseItem browseItem) { this.item = null; this.browseItem = browseItem; this.id = id; } public DCValue[] getMetadata(String schema, String element, String qualifier, String lang) throws SQLException { if (item != null) { return item.getMetadata(schema, element, qualifier, lang); } return browseItem.getMetadata(schema, element, qualifier, lang); } public int getID() { if (item != null) { return item.getID(); } return id; } /** * Is the Item archived? * @return */ public boolean isArchived() { if (item != null) { return item.isArchived(); } return browseItem.isArchived(); } /** * Is the Item withdrawn? * @return */ public boolean isWithdrawn() { if (item != null) { return item.isWithdrawn(); } return browseItem.isWithdrawn(); } } }
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.browse; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * This class is the PostgreSQL driver class for reading information from the * Browse tables. It implements the BrowseDAO interface, and also has a * constructor of the form: * * BrowseDAOPostgres(Context context) * * As required by BrowseDAOFactory. This class should only ever be loaded by * that Factory object. * * @author Richard Jones * @author Graham Triggs */ public class BrowseDAOPostgres implements BrowseDAO { /** Log4j log */ private static Logger log = Logger.getLogger(BrowseDAOPostgres.class); /** The DSpace context */ private Context context; /** Database specific set of utils used when prepping the database */ private BrowseDAOUtils utils; // SQL query related attributes for this class /** the values to place in the SELECT --- FROM bit */ private String[] selectValues = { "*" }; /** the values to place in the SELECT COUNT(---) bit */ private String[] countValues; /** table(s) to select from */ private String table = null; private String tableDis = null; private String tableMap = null; /** field to look for focus value in */ private String focusField = null; /** value to start browse from in focus field */ private String focusValue = null; /** field to look for value in */ private String valueField = null; /** value to restrict browse to (e.g. author name) */ private String value = null; private String authority = null; /** exact or partial matching of the value */ private boolean valuePartial = false; /** the table that defines the mapping for the relevant container */ private String containerTable = null; /** the name of the field which contains the container id (e.g. collection_id) */ private String containerIDField = null; /** the database id of the container we are constraining to */ private int containerID = -1; /** the column that we are sorting results by */ private String orderField = null; /** whether to sort results ascending or descending */ private boolean ascending = true; /** the limit of number of results to return */ private int limit = -1; /** the offset of the start point */ private int offset = 0; /** whether to use the equals comparator in value comparisons */ private boolean equalsComparator = true; /** whether this is a distinct browse or not */ private boolean distinct = false; // administrative attributes for this class /** a cache of the actual query to be executed */ private String querySql = ""; private List<Serializable> queryParams = new ArrayList<Serializable>(); /** whether the query (above) needs to be regenerated */ private boolean rebuildQuery = true; private String whereClauseOperator = ""; // FIXME Would be better to join to item table and get the correct values /** flags for what the items represent */ private boolean itemsInArchive = true; private boolean itemsWithdrawn = false; /** * Required constructor for use by BrowseDAOFactory * * @param context DSpace context */ public BrowseDAOPostgres(Context context) throws BrowseException { this.context = context; // obtain the relevant Utils for this class utils = BrowseDAOFactory.getUtils(context); } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doCountQuery() */ public int doCountQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "executing_count_query", "query=" + query)); } TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); if (tri.hasNext()) { TableRow row = tri.next(); return (int) row.getLongColumn("num"); } else { return 0; } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doMaxQuery(java.lang.String, java.lang.String, int) */ public String doMaxQuery(String column, String table, int itemID) throws BrowseException { TableRowIterator tri = null; try { String query = "SELECT max(" + column + ") FROM " + table + " WHERE item_id = ?"; Object[] params = { Integer.valueOf(itemID) }; tri = DatabaseManager.query(context, query, params); TableRow row; if (tri.hasNext()) { row = tri.next(); return row.getStringColumn("max"); } else { return null; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doOffsetQuery(java.lang.String, java.lang.String, java.lang.String) */ public int doOffsetQuery(String column, String value, boolean isAscending) throws BrowseException { TableRowIterator tri = null; if (column == null || value == null) { return 0; } try { List<Serializable> paramsList = new ArrayList<Serializable>(); StringBuffer queryBuf = new StringBuffer(); queryBuf.append("COUNT(").append(column).append(") AS offset "); buildSelectStatement(queryBuf, paramsList); if (isAscending) { queryBuf.append(" WHERE ").append(column).append("<?"); paramsList.add(value); } else { queryBuf.append(" WHERE ").append(column).append(">?"); paramsList.add(value + Character.MAX_VALUE); } if (containerTable != null || (value != null && valueField != null && tableDis != null && tableMap != null)) { queryBuf.append(" AND ").append("mappings.item_id="); queryBuf.append(table).append(".item_id"); } tri = DatabaseManager.query(context, queryBuf.toString(), paramsList.toArray()); TableRow row; if (tri.hasNext()) { row = tri.next(); return (int)row.getLongColumn("offset"); } else { return 0; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doDistinctOffsetQuery(java.lang.String, java.lang.String, java.lang.String) */ public int doDistinctOffsetQuery(String column, String value, boolean isAscending) throws BrowseException { TableRowIterator tri = null; try { List<Serializable> paramsList = new ArrayList<Serializable>(); StringBuffer queryBuf = new StringBuffer(); queryBuf.append("COUNT(").append(column).append(") AS offset "); buildSelectStatementDistinct(queryBuf, paramsList); if (isAscending) { queryBuf.append(" WHERE ").append(column).append("<?"); paramsList.add(value); } else { queryBuf.append(" WHERE ").append(column).append(">?"); paramsList.add(value + Character.MAX_VALUE); } if (containerTable != null && tableMap != null) { queryBuf.append(" AND ").append("mappings.distinct_id="); queryBuf.append(table).append(".id"); } tri = DatabaseManager.query(context, queryBuf.toString(), paramsList.toArray()); TableRow row; if (tri.hasNext()) { row = tri.next(); return (int)row.getLongColumn("offset"); } else { return 0; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doQuery() */ public List<BrowseItem> doQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "executing_full_query", "query=" + query)); } TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); // go over the query results and process List<BrowseItem> results = new ArrayList<BrowseItem>(); while (tri.hasNext()) { TableRow row = tri.next(); BrowseItem browseItem = new BrowseItem(context, row.getIntColumn("item_id"), itemsInArchive, itemsWithdrawn); results.add(browseItem); } return results; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException("problem with query: " + query, e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doValueQuery() */ public List<String[]> doValueQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); log.debug(LogManager.getHeader(context, "executing_value_query", "query=" + query)); TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); // go over the query results and process List<String[]> results = new ArrayList<String[]>(); while (tri.hasNext()) { TableRow row = tri.next(); String valueResult = row.getStringColumn("value"); String authorityResult = row.getStringColumn("authority"); results.add(new String[]{valueResult,authorityResult}); } return results; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getContainerID() */ public int getContainerID() { return containerID; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getContainerIDField() */ public String getContainerIDField() { return containerIDField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getContainerTable() */ public String getContainerTable() { return containerTable; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getCountValues() */ public String[] getCountValues() { return (String[]) ArrayUtils.clone(this.countValues); } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getFocusField() */ public String getJumpToField() { return focusField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getFocusValue() */ public String getJumpToValue() { return focusValue; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getLimit() */ public int getLimit() { return limit; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getOffset() */ public int getOffset() { return offset; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getOrderField() */ public String getOrderField() { return orderField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getSelectValues() */ public String[] getSelectValues() { return (String[]) ArrayUtils.clone(selectValues); } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getTable() */ public String getTable() { return table; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getValue() */ public String getFilterValue() { return value; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getValueField() */ public String getFilterValueField() { return valueField; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#isAscending() */ public boolean isAscending() { return ascending; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#isDistinct() */ public boolean isDistinct() { return this.distinct; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setAscending(boolean) */ public void setAscending(boolean ascending) { this.ascending = ascending; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setContainerID(int) */ public void setContainerID(int containerID) { this.containerID = containerID; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setContainerIDField(java.lang.String) */ public void setContainerIDField(String containerIDField) { this.containerIDField = containerIDField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setContainerTable(java.lang.String) */ public void setContainerTable(String containerTable) { this.containerTable = containerTable; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setCountValues(java.lang.String[]) */ public void setCountValues(String[] fields) { this.countValues = (String[]) ArrayUtils.clone(fields); this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setDistinct(boolean) */ public void setDistinct(boolean bool) { this.distinct = bool; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setEqualsComparator(boolean) */ public void setEqualsComparator(boolean equalsComparator) { this.equalsComparator = equalsComparator; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setFocusField(java.lang.String) */ public void setJumpToField(String focusField) { this.focusField = focusField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setFocusValue(java.lang.String) */ public void setJumpToValue(String focusValue) { this.focusValue = focusValue; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setLimit(int) */ public void setLimit(int limit) { this.limit = limit; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setOffset(int) */ public void setOffset(int offset) { this.offset = offset; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setOrderField(java.lang.String) */ public void setOrderField(String orderField) { this.orderField = orderField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setSelectValues(java.lang.String[]) */ public void setSelectValues(String[] selectValues) { this.selectValues = (String[]) ArrayUtils.clone(selectValues); this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setTable(java.lang.String) */ public void setTable(String table) { this.table = table; // FIXME Rather than assume from the browse table, join the query to item to get the correct values // Check to see if this is the withdrawn browse index - if it is, // we need to set the flags appropriately for when we create the BrowseItems if (table.equals(BrowseIndex.getWithdrawnBrowseIndex().getTableName())) { itemsInArchive = false; itemsWithdrawn = true; } else { itemsInArchive = true; itemsWithdrawn = false; } this.rebuildQuery = true; } public void setFilterMappingTables(String tableDis, String tableMap) { this.tableDis = tableDis; this.tableMap = tableMap; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setValue(java.lang.String) */ public void setFilterValue(String value) { this.value = value; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setFilterValuePartial(boolean) */ public void setFilterValuePartial(boolean part) { this.valuePartial = part; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#setValueField(java.lang.String) */ public void setFilterValueField(String valueField) { this.valueField = valueField; this.rebuildQuery = true; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#useEqualsComparator() */ public boolean useEqualsComparator() { return equalsComparator; } // PRIVATE METHODS /** * Build the query that will be used for a distinct select. This incorporates * only the parts of the parameters that are actually useful for this type * of browse * * @return the query to be executed * @throws BrowseException */ private String buildDistinctQuery(List<Serializable> params) throws BrowseException { StringBuffer queryBuf = new StringBuffer(); if (!buildSelectListCount(queryBuf)) { if (!buildSelectListValues(queryBuf)) { throw new BrowseException("No arguments for SELECT statement"); } } buildSelectStatementDistinct(queryBuf, params); buildWhereClauseOpReset(); // assemble the focus clause if we are to have one // it will look like one of the following, for example // sort_value <= myvalue // sort_1 >= myvalue buildWhereClauseJumpTo(queryBuf, params); // assemble the where clause out of the two possible value clauses // and include container support buildWhereClauseDistinctConstraints(queryBuf, params); // assemble the order by field buildOrderBy(queryBuf); // prepare the limit and offset clauses buildRowLimitAndOffset(queryBuf, params); return queryBuf.toString(); } /** * Build the query that will be used for a full browse. * * @return the query to be executed * @throws BrowseException */ private String buildQuery(List<Serializable> params) throws BrowseException { StringBuffer queryBuf = new StringBuffer(); if (!buildSelectListCount(queryBuf)) { if (!buildSelectListValues(queryBuf)) { throw new BrowseException("No arguments for SELECT statement"); } } buildSelectStatement(queryBuf, params); buildWhereClauseOpReset(); // assemble the focus clause if we are to have one // it will look like one of the following, for example // sort_value <= myvalue // sort_1 >= myvalue buildWhereClauseJumpTo(queryBuf, params); // assemble the value clause if we are to have one buildWhereClauseFilterValue(queryBuf, params); // assemble the where clause out of the two possible value clauses // and include container support buildWhereClauseFullConstraints(queryBuf, params); // assemble the order by field buildOrderBy(queryBuf); // prepare the limit and offset clauses buildRowLimitAndOffset(queryBuf, params); return queryBuf.toString(); } /** * Get the clause to perform search result ordering. This will * return something of the form: * * <code> * ORDER BY [order field] (ASC | DESC) * </code> * * @return the ORDER BY clause */ private void buildOrderBy(StringBuffer queryBuf) { if (orderField != null) { queryBuf.append(" ORDER BY "); queryBuf.append(orderField); if (isAscending()) { queryBuf.append(" ASC "); } else { queryBuf.append(" DESC "); } } } /** * Get the limit clause to perform search result truncation. Will return * something of the form: * * <code> * LIMIT [limit] * </code> * * @return the limit clause */ private void buildRowLimitAndOffset(StringBuffer queryBuf, List<Serializable> params) { // prepare the LIMIT clause if (limit > 0) { queryBuf.append(" LIMIT ? "); params.add(Integer.valueOf(limit)); } // prepare the OFFSET clause if (offset > 0) { queryBuf.append(" OFFSET ? "); params.add(Integer.valueOf(offset)); } } /** * Build the clauses required for the view used in focused or scoped queries. * * @param queryBuf * @param params */ private void buildFocusedSelectClauses(StringBuffer queryBuf, List<Serializable> params) { if (tableMap != null && tableDis != null) { queryBuf.append(tableMap).append(".distinct_id=").append(tableDis).append(".id"); queryBuf.append(" AND "); if (authority == null) { queryBuf.append(tableDis).append(".authority IS NULL"); queryBuf.append(" AND "); queryBuf.append(tableDis).append(".").append(valueField); if (valuePartial) { queryBuf.append(" LIKE ? "); if (valueField.startsWith("sort_")) { params.add("%" + utils.truncateSortValue(value) + "%"); } else { params.add("%" + utils.truncateValue(value) + "%"); } } else { queryBuf.append("=? "); if (valueField.startsWith("sort_")) { params.add(utils.truncateSortValue(value)); } else { params.add(utils.truncateValue(value)); } } } else { queryBuf.append(tableDis).append(".authority=?"); params.add(utils.truncateValue(authority,100)); } } if (containerTable != null && containerIDField != null && containerID != -1) { if (tableMap != null) { if (tableDis != null) { queryBuf.append(" AND "); } queryBuf.append(tableMap).append(".item_id=") .append(containerTable).append(".item_id AND "); } queryBuf.append(containerTable).append(".").append(containerIDField); queryBuf.append("=? "); params.add(Integer.valueOf(containerID)); } } /** * Build the table list for the view used in focused or scoped queries. * * @param queryBuf */ private void buildFocusedSelectTables(StringBuffer queryBuf) { if (containerTable != null) { queryBuf.append(containerTable); } if (tableMap != null) { if (containerTable != null) { queryBuf.append(", "); } queryBuf.append(tableMap); if (tableDis != null) { queryBuf.append(", ").append(tableDis); } } } /** * Build a clause for counting results. Will return something of the form: * * <code> * COUNT( [value 1], [value 2] ) AS number * </code> * * @return the count clause */ private boolean buildSelectListCount(StringBuffer queryBuf) { if (countValues != null && countValues.length > 0) { queryBuf.append(" COUNT("); if ("*".equals(countValues[0])) { queryBuf.append(countValues[0]); } else { queryBuf.append(table).append(".").append(countValues[0]); } for (int i = 1; i < countValues.length; i++) { queryBuf.append(", "); if ("*".equals(countValues[i])) { queryBuf.append(countValues[i]); } else { queryBuf.append(table).append(".").append(countValues[i]); } } queryBuf.append(") AS num"); return true; } return false; } /** * Prepare the list of values to be selected on. Will return something of the form: * * <code> * [value 1], [value 2] * </code> * * @return the select value list */ private boolean buildSelectListValues(StringBuffer queryBuf) { if (selectValues != null && selectValues.length > 0) { queryBuf.append(table).append(".").append(selectValues[0]); for (int i = 1; i < selectValues.length; i++) { queryBuf.append(", "); queryBuf.append(table).append(".").append(selectValues[i]); } return true; } return false; } /** * Prepare the select clause using the pre-prepared arguments. This will produce something * of the form: * * <code> * SELECT [arguments] FROM [table] * </code> * * @param queryBuf the string value obtained from distinctClause, countClause or selectValues * @return the SELECT part of the query */ private void buildSelectStatement(StringBuffer queryBuf, List<Serializable> params) throws BrowseException { if (queryBuf.length() == 0) { throw new BrowseException("No arguments for SELECT statement"); } if (table == null || "".equals(table)) { throw new BrowseException("No table for SELECT statement"); } // queryBuf already contains what we are selecting, // so insert the statement at the beginning queryBuf.insert(0, "SELECT "); // Then append the table queryBuf.append(" FROM "); queryBuf.append(table); if (containerTable != null || (value != null && valueField != null && tableDis != null && tableMap != null)) { queryBuf.append(", (SELECT "); if (containerTable != null) { queryBuf.append(containerTable).append(".item_id"); } else { queryBuf.append("DISTINCT ").append(tableMap).append(".item_id"); } queryBuf.append(" FROM "); buildFocusedSelectTables(queryBuf); queryBuf.append(" WHERE "); buildFocusedSelectClauses(queryBuf, params); queryBuf.append(") mappings"); } queryBuf.append(" "); } /** * Prepare the select clause using the pre-prepared arguments. This will produce something * of the form: * * <code> * SELECT [arguments] FROM [table] * </code> * * @param queryBuf the string value obtained from distinctClause, countClause or selectValues * @return the SELECT part of the query */ private void buildSelectStatementDistinct(StringBuffer queryBuf, List<Serializable> params) throws BrowseException { if (queryBuf.length() == 0) { throw new BrowseException("No arguments for SELECT statement"); } if (table == null || "".equals(table)) { throw new BrowseException("No table for SELECT statement"); } // queryBuf already contains what we are selecting, // so insert the statement at the beginning queryBuf.insert(0, "SELECT "); // Then append the table queryBuf.append(" FROM "); queryBuf.append(table); if (containerTable != null && tableMap != null) { queryBuf.append(", (SELECT DISTINCT ").append(tableMap).append(".distinct_id "); queryBuf.append(" FROM "); buildFocusedSelectTables(queryBuf); queryBuf.append(" WHERE "); buildFocusedSelectClauses(queryBuf, params); queryBuf.append(") mappings"); } queryBuf.append(" "); } /** * Get a sub-query to obtain the ids for a distinct browse within a given * constraint. This will produce something of the form: * * <code> * id IN (SELECT distinct_id FROM [container table] WHERE [container field] = [container id]) * </code> * * This is for use inside the overall WHERE clause only * * @return the sub-query */ private void buildWhereClauseDistinctConstraints(StringBuffer queryBuf, List<Serializable> params) { // add the constraint to community or collection if necessary // and desired if (containerIDField != null && containerID != -1 && containerTable != null) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" ").append(table).append(".id=mappings.distinct_id "); } } /** * Get the clause to get the browse to start from a given focus value. * Will return something of the form: * * <code> * [field] (<[=] | >[=]) '[value]' * </code> * * such as: * * <code> * sort_value <= 'my text' * </code> * * @return the focus clause */ private void buildWhereClauseJumpTo(StringBuffer queryBuf, List<Serializable> params) { // get the operator (<[=] | >[=]) which the focus of the browse will // be matched using String focusComparator = getFocusComparator(); // assemble the focus clause if we are to have one // it will look like one of the following // - sort_value <= myvalue // - sort_1 >= myvalue if (focusField != null && focusValue != null) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" "); queryBuf.append(focusField); queryBuf.append(focusComparator); queryBuf.append("? "); if (focusField.startsWith("sort_")) { params.add(utils.truncateSortValue(focusValue)); } else { params.add(utils.truncateValue(focusValue)); } } } /** * Get a clause to obtain the ids for a full browse within a given * constraint. This will produce something of the form: * * <code> * [container field] = [container id] * </code> * * This is for use inside the overall WHERE clause only * * @return the constraint clause */ private void buildWhereClauseFullConstraints(StringBuffer queryBuf, List<Serializable> params) { // add the constraint to community or collection if necessary // and desired if (tableDis == null || tableMap == null) { if (containerIDField != null && containerID != -1) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" ").append(table).append(".item_id=mappings.item_id "); } } } /** * Return the clause to constrain the browse to a specific value. * Will return something of the form: * * <code> * [field] = '[value]' * </code> * * such as: * * <code> * sort_value = 'some author' * </code> * * @return the value clause */ private void buildWhereClauseFilterValue(StringBuffer queryBuf, List<Serializable> params) { // assemble the value clause if we are to have one if (value != null && valueField != null) { buildWhereClauseOpInsert(queryBuf); queryBuf.append(" "); if (tableDis != null && tableMap != null) { queryBuf.append(table).append(".item_id=mappings.item_id "); } else { queryBuf.append(valueField); if (valuePartial) { queryBuf.append(" LIKE ? "); if (valueField.startsWith("sort_")) { params.add("%" + utils.truncateSortValue(value) + "%"); } else { params.add("%" + utils.truncateValue(value) + "%"); } } else { queryBuf.append("=? "); if (valueField.startsWith("sort_")) { params.add(utils.truncateSortValue(value)); } else { params.add(utils.truncateValue(value)); } } } } } /** * Insert an operator into the where clause, and reset to ' AND ' */ private void buildWhereClauseOpInsert(StringBuffer queryBuf) { queryBuf.append(whereClauseOperator); whereClauseOperator = " AND "; } /** * Reset the where clause operator for initial use */ private void buildWhereClauseOpReset() { // Use sneaky trick to insert the WHERE by defining it as the first operator whereClauseOperator = " WHERE "; } /** * Get the comparator which should be used to compare focus values * with values in the database. This will return one of the 4 following * possible values: <, >, <=, >= * * @return the focus comparator */ private String getFocusComparator() { // now decide whether we will use an equals comparator; String equals = "="; if (!useEqualsComparator()) { equals = ""; } // get the comparator for the match of the browsable index value // the rule is: if the scope has a value, then the comparator is always "=" // if, the order is set to ascending then we want to use // WHERE sort_value > <the value> // and when the order is descending then we want to use // WHERE sort_value < <the value> String focusComparator = ""; if (isAscending()) { focusComparator = ">" + equals; } else { focusComparator = "<" + equals; } return focusComparator; } /* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#getQuery() */ private String getQuery() throws BrowseException { if ("".equals(querySql) || rebuildQuery) { queryParams.clear(); if (this.isDistinct()) { querySql = buildDistinctQuery(queryParams); } else { querySql = buildQuery(queryParams); } this.rebuildQuery = false; } return querySql; } /** * Return the parameters to be bound to the query * * @return Object[] query parameters * @throws BrowseException */ private Object[] getQueryParams() throws BrowseException { // Ensure that the query has been built if ("".equals(querySql) || rebuildQuery) { getQuery(); } return queryParams.toArray(); } public void setAuthorityValue(String value) { authority = value; } public String getAuthorityValue() { return authority; } }
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.authorize; import java.sql.SQLException; import org.dspace.authorize.AuthorizeException; 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.Item; import org.dspace.content.ItemIterator; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.Group; /** * Was Hack/Tool to set policies for items, bundles, and bitstreams. Now has * helpful method, setPolicies(); * * @author dstuve * @version $Revision: 5844 $ */ public class PolicySet { /** * Command line interface to setPolicies - run to see arguments */ public static void main(String[] argv) throws Exception { if (argv.length < 6) { System.out .println("Args: containerType containerID contentType actionID groupID command [filter]"); System.out.println("container=COLLECTION command = ADD|REPLACE"); return; } int containertype = Integer.parseInt(argv[0]); int containerID = Integer.parseInt(argv[1]); int contenttype = Integer.parseInt(argv[2]); int actionID = Integer.parseInt(argv[3]); int groupID = Integer.parseInt(argv[4]); boolean isReplace = false; String command = argv[5]; String filter = null; if ( argv.length == 7 ) { filter = argv[6]; } if (command.equals("REPLACE")) { isReplace = true; } Context c = new Context(); // turn off authorization c.setIgnoreAuthorization(true); ////////////////////// // carnage begins here ////////////////////// setPoliciesFilter(c, containertype, containerID, contenttype, actionID, groupID, isReplace, false, filter); c.complete(); System.exit(0); } /** * Useful policy wildcard tool. Can set entire collections' contents' * policies * * @param c * current context * @param containerType * type, Constants.ITEM or Constants.COLLECTION * @param containerID * ID of container (DB primary key) * @param contentType * type (BUNDLE, ITEM, or BITSTREAM) * @param actionID * action ID * @param groupID * group ID (database key) * @param isReplace * if <code>true</code>, existing policies are removed first, * otherwise add to existing policies * @param clearOnly * if <code>true</code>, just delete policies for matching * objects * @throws SQLException * if database problem * @throws AuthorizeException * if current user is not authorized to change these policies */ public static void setPolicies(Context c, int containerType, int containerID, int contentType, int actionID, int groupID, boolean isReplace, boolean clearOnly) throws SQLException, AuthorizeException { setPoliciesFilter(c, containerType, containerID, contentType, actionID, groupID, isReplace, clearOnly, null); } /** * Useful policy wildcard tool. Can set entire collections' contents' * policies * * @param c * current context * @param containerType * type, Constants.ITEM or Constants.COLLECTION * @param containerID * ID of container (DB primary key) * @param contentType * type (BUNDLE, ITEM, or BITSTREAM) * @param actionID * action ID * @param groupID * group ID (database key) * @param isReplace * if <code>true</code>, existing policies are removed first, * otherwise add to existing policies * @param clearOnly * if <code>true</code>, just delete policies for matching * objects * @param filter * if non-null, only process bitstreams whose names contain filter * @throws SQLException * if database problem * @throws AuthorizeException * if current user is not authorized to change these policies */ public static void setPoliciesFilter(Context c, int containerType, int containerID, int contentType, int actionID, int groupID, boolean isReplace, boolean clearOnly, String filter) throws SQLException, AuthorizeException { if (containerType == Constants.COLLECTION) { Collection collection = Collection.find(c, containerID); Group group = Group.find(c, groupID); ItemIterator i = collection.getItems(); try { if (contentType == Constants.ITEM) { // build list of all items in a collection while (i.hasNext()) { Item myitem = i.next(); // is this a replace? delete policies first if (isReplace || clearOnly) { AuthorizeManager.removeAllPolicies(c, myitem); } if (!clearOnly) { // now add the policy ResourcePolicy rp = ResourcePolicy.create(c); rp.setResource(myitem); rp.setAction(actionID); rp.setGroup(group); rp.update(); } } } else if (contentType == Constants.BUNDLE) { // build list of all items in a collection // build list of all bundles in those items while (i.hasNext()) { Item myitem = i.next(); Bundle[] bundles = myitem.getBundles(); for (int j = 0; j < bundles.length; j++) { Bundle t = bundles[j]; // t for target // is this a replace? delete policies first if (isReplace || clearOnly) { AuthorizeManager.removeAllPolicies(c, t); } if (!clearOnly) { // now add the policy ResourcePolicy rp = ResourcePolicy.create(c); rp.setResource(t); rp.setAction(actionID); rp.setGroup(group); rp.update(); } } } } else if (contentType == Constants.BITSTREAM) { // build list of all bitstreams in a collection // iterate over items, bundles, get bitstreams while (i.hasNext()) { Item myitem = i.next(); System.out.println("Item " + myitem.getID()); Bundle[] bundles = myitem.getBundles(); for (int j = 0; j < bundles.length; j++) { System.out.println("Bundle " + bundles[j].getID()); Bitstream[] bitstreams = bundles[j].getBitstreams(); for (int k = 0; k < bitstreams.length; k++) { Bitstream t = bitstreams[k]; // t for target if ( filter == null || t.getName().indexOf( filter ) != -1 ) { // is this a replace? delete policies first if (isReplace || clearOnly) { AuthorizeManager.removeAllPolicies(c, t); } if (!clearOnly) { // now add the policy ResourcePolicy rp = ResourcePolicy.create(c); rp.setResource(t); rp.setAction(actionID); rp.setGroup(group); rp.update(); } } } } } } } finally { if (i != null) { i.close(); } } } } }
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.authorize; //import org.dspace.browse.Browse; import java.sql.SQLException; import java.util.List; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.Group; /** * Command line tool to locate collections without default item and bitstream * read policies, and assign them some. (They must be there for submitted items * to inherit.) * * @author dstuve * @version $Revision: 5844 $ */ public class FixDefaultPolicies { /** * Command line interface to setPolicies - run to see arguments */ public static void main(String[] argv) throws Exception { Context c = new Context(); // turn off authorization c.setIgnoreAuthorization(true); ////////////////////// // carnage begins here ////////////////////// Collection[] collections = Collection.findAll(c); for (int i = 0; i < collections.length; i++) { Collection t = collections[i]; System.out.println("Collection " + t + " " + t.getMetadata("name")); // check for READ if (checkForPolicy(c, t, Constants.READ)) { System.out.println("\tFound READ policies!"); } else { System.out.println("\tNo READ policy found, adding anonymous."); addAnonymousPolicy(c, t, Constants.READ); } if (checkForPolicy(c, t, Constants.DEFAULT_ITEM_READ)) { System.out.println("\tFound DEFAULT_ITEM_READ policies!"); } else { System.out .println("\tNo DEFAULT_ITEM_READ policy found, adding anonymous."); addAnonymousPolicy(c, t, Constants.DEFAULT_ITEM_READ); } if (checkForPolicy(c, t, Constants.DEFAULT_BITSTREAM_READ)) { System.out.println("\tFound DEFAULT_BITSTREAM_READ policies!"); } else { System.out .println("\tNo DEFAULT_BITSTREAM_READ policy found, adding anonymous."); addAnonymousPolicy(c, t, Constants.DEFAULT_BITSTREAM_READ); } } // now ensure communities have READ policies Community[] communities = Community.findAll(c); for (int i = 0; i < communities.length; i++) { Community t = communities[i]; System.out.println("Community " + t + " " + t.getMetadata("name")); // check for READ if (checkForPolicy(c, t, Constants.READ)) { System.out.println("\tFound READ policies!"); } else { System.out.println("\tNo READ policy found, adding anonymous."); addAnonymousPolicy(c, t, Constants.READ); } } c.complete(); System.exit(0); } /** * check to see if a collection has any policies for a given action */ private static boolean checkForPolicy(Context c, DSpaceObject t, int myaction) throws SQLException { // check to see if any policies exist for this action List<ResourcePolicy> policies = AuthorizeManager.getPoliciesActionFilter(c, t, myaction); return policies.size() > 0; } /** * add an anonymous group permission policy to the collection for this * action */ private static void addAnonymousPolicy(Context c, DSpaceObject t, int myaction) throws SQLException, AuthorizeException { // group 0 is the anonymous group! Group anonymousGroup = Group.find(c, 0); // now create the default policies for submitted items ResourcePolicy myPolicy = ResourcePolicy.create(c); myPolicy.setResource(t); myPolicy.setAction(myaction); myPolicy.setGroup(anonymousGroup); myPolicy.update(); } }
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.authorize; import org.dspace.core.ConfigurationManager; /** * This class is responsible to provide access to the configuration of the * Authorization System * * @author bollini * */ public class AuthorizeConfiguration { private static boolean can_communityAdmin_group = ConfigurationManager .getBooleanProperty("core.authorization.community-admin.group", true); // subcommunities and collections private static boolean can_communityAdmin_createSubelement = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.create-subelement", true); private static boolean can_communityAdmin_deleteSubelement = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.delete-subelement", true); private static boolean can_communityAdmin_policies = ConfigurationManager .getBooleanProperty("core.authorization.community-admin.policies", true); private static boolean can_communityAdmin_adminGroup = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.admin-group", true); private static boolean can_communityAdmin_collectionPolicies = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.collection.policies", true); private static boolean can_communityAdmin_collectionTemplateItem = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.collection.template-item", true); private static boolean can_communityAdmin_collectionSubmitters = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.collection.submitters", true); private static boolean can_communityAdmin_collectionWorkflows = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.collection.workflows", true); private static boolean can_communityAdmin_collectionAdminGroup = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.collection.admin-group", true); private static boolean can_communityAdmin_itemDelete = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.item.delete", true); private static boolean can_communityAdmin_itemWithdraw = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.item.withdraw", true); private static boolean can_communityAdmin_itemReinstatiate = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.item.reinstatiate", true); private static boolean can_communityAdmin_itemPolicies = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.item.policies", true); // # also bundle private static boolean can_communityAdmin_itemCreateBitstream = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.item.create-bitstream", true); private static boolean can_communityAdmin_itemDeleteBitstream = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.item.delete-bitstream", true); private static boolean can_communityAdmin_itemAdminccLicense = ConfigurationManager .getBooleanProperty( "core.authorization.community-admin.item-admin.cc-license", true); // # COLLECTION ADMIN private static boolean can_collectionAdmin_policies = ConfigurationManager .getBooleanProperty("core.authorization.collection-admin.policies", true); private static boolean can_collectionAdmin_templateItem = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.template-item", true); private static boolean can_collectionAdmin_submitters = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.submitters", true); private static boolean can_collectionAdmin_workflows = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.workflows", true); private static boolean can_collectionAdmin_adminGroup = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.admin-group", true); private static boolean can_collectionAdmin_itemDelete = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.item.delete", true); private static boolean can_collectionAdmin_itemWithdraw = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.item.withdraw", true); private static boolean can_collectionAdmin_itemReinstatiate = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.item.reinstatiate", true); private static boolean can_collectionAdmin_itemPolicies = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.item.policies", true); // # also bundle private static boolean can_collectionAdmin_itemCreateBitstream = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.item.create-bitstream", true); private static boolean can_collectionAdmin_itemDeleteBitstream = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.item.delete-bitstream", true); private static boolean can_collectionAdmin_itemAdminccLicense = ConfigurationManager .getBooleanProperty( "core.authorization.collection-admin.item-admin.cc-license", true); // # ITEM ADMIN private static boolean can_itemAdmin_policies = ConfigurationManager .getBooleanProperty("core.authorization.item-admin.policies", true); // # also bundle private static boolean can_itemAdmin_createBitstream = ConfigurationManager .getBooleanProperty( "core.authorization.item-admin.create-bitstream", true); private static boolean can_itemAdmin_deleteBitstream = ConfigurationManager .getBooleanProperty( "core.authorization.item-admin.delete-bitstream", true); private static boolean can_itemAdmin_ccLicense = ConfigurationManager .getBooleanProperty("core.authorization.item-admin.cc-license", true); /** * Are community admins allowed to create new, not strictly community * related, group? * * @return */ public static boolean canCommunityAdminPerformGroupCreation() { return can_communityAdmin_group; } /** * Are community admins allowed to create collections or subcommunities? * * @return */ public static boolean canCommunityAdminPerformSubelementCreation() { return can_communityAdmin_createSubelement; } /** * Are community admins allowed to remove collections or subcommunities? * * @return */ public static boolean canCommunityAdminPerformSubelementDeletion() { return can_communityAdmin_deleteSubelement; } /** * Are community admins allowed to manage the community's and * subcommunities' policies? * * @return */ public static boolean canCommunityAdminManagePolicies() { return can_communityAdmin_policies; } /** * Are community admins allowed to create/edit them community's and * subcommunities' admin groups? * * @return */ public static boolean canCommunityAdminManageAdminGroup() { return can_communityAdmin_adminGroup; } /** * Are community admins allowed to create/edit the community's and * subcommunities' admin group? * * @return */ public static boolean canCommunityAdminManageCollectionPolicies() { return can_communityAdmin_collectionPolicies; } /** * Are community admins allowed to manage the item template of them * collections? * * @return */ public static boolean canCommunityAdminManageCollectionTemplateItem() { return can_communityAdmin_collectionTemplateItem; } /** * Are community admins allowed to manage (create/edit/remove) the * submitters group of them collections? * * @return */ public static boolean canCommunityAdminManageCollectionSubmitters() { return can_communityAdmin_collectionSubmitters; } /** * Are community admins allowed to manage (create/edit/remove) the workflows * group of them collections? * * @return */ public static boolean canCommunityAdminManageCollectionWorkflows() { return can_communityAdmin_collectionWorkflows; } /** * Are community admins allowed to manage (create/edit/remove) the admin * group of them collections? * * @return */ public static boolean canCommunityAdminManageCollectionAdminGroup() { return can_communityAdmin_collectionAdminGroup; } /** * Are community admins allowed to remove an item from them collections? * * @return */ public static boolean canCommunityAdminPerformItemDeletion() { return can_communityAdmin_itemDelete; } /** * Are community admins allowed to withdrawn an item from them collections? * * @return */ public static boolean canCommunityAdminPerformItemWithdrawn() { return can_communityAdmin_itemWithdraw; } /** * Are community admins allowed to reinstate an item from them * collections? * * @return */ public static boolean canCommunityAdminPerformItemReinstatiate() { return can_communityAdmin_itemReinstatiate; } /** * Are community admins allowed to manage the policies of an item owned by * one of them collections? * * @return */ public static boolean canCommunityAdminManageItemPolicies() { return can_communityAdmin_itemPolicies; } /** * Are community admins allowed to add a bitstream to an item owned by one * of them collections? * * @return */ public static boolean canCommunityAdminPerformBitstreamCreation() { return can_communityAdmin_itemCreateBitstream; } /** * Are community admins allowed to remove a bitstream from an item owned by * one of them collections? * * @return */ public static boolean canCommunityAdminPerformBitstreamDeletion() { return can_communityAdmin_itemDeleteBitstream; } /** * Are community admins allowed to perform CC License replace or addition to * an item owned by one of them collections? * * @return */ public static boolean canCommunityAdminManageCCLicense() { return can_communityAdmin_itemAdminccLicense; } /** * Are collection admins allowed to manage the collection's policies? * * @return */ public static boolean canCollectionAdminManagePolicies() { return can_collectionAdmin_policies; } /** * Are collection admins allowed to manage (create/edit/delete) the * collection's item template? * * @return */ public static boolean canCollectionAdminManageTemplateItem() { return can_collectionAdmin_templateItem; } /** * Are collection admins allowed to manage (create/edit/delete) the * collection's submitters group? * * @return */ public static boolean canCollectionAdminManageSubmitters() { return can_collectionAdmin_submitters; } /** * Are collection admins allowed to manage (create/edit/delete) the * collection's workflows group? * * @return */ public static boolean canCollectionAdminManageWorkflows() { return can_collectionAdmin_workflows; } /** * Are collection admins allowed to manage (create/edit) the collection's * admins group? * * @return */ public static boolean canCollectionAdminManageAdminGroup() { return can_collectionAdmin_adminGroup; } /** * Are collection admins allowed to remove an item from the collection? * * @return */ public static boolean canCollectionAdminPerformItemDeletion() { return can_collectionAdmin_itemDelete; } /** * Are collection admins allowed to withdrawn an item from the collection? * * @return */ public static boolean canCollectionAdminPerformItemWithdrawn() { return can_collectionAdmin_itemWithdraw; } /** * Are collection admins allowed to reinstate an item from the * collection? * * @return */ public static boolean canCollectionAdminPerformItemReinstatiate() { return can_collectionAdmin_itemReinstatiate; } /** * Are collection admins allowed to manage the policies of item owned by the * collection? * * @return */ public static boolean canCollectionAdminManageItemPolicies() { return can_collectionAdmin_itemPolicies; } /** * Are collection admins allowed to add a bitstream to an item owned by the * collections? * * @return */ public static boolean canCollectionAdminPerformBitstreamCreation() { return can_collectionAdmin_itemCreateBitstream; } /** * Are collection admins allowed to remove a bitstream from an item owned by * the collections? * * @return */ public static boolean canCollectionAdminPerformBitstreamDeletion() { return can_collectionAdmin_itemDeleteBitstream; } /** * Are collection admins allowed to replace or adding a CC License to an * item owned by the collections? * * @return */ public static boolean canCollectionAdminManageCCLicense() { return can_collectionAdmin_itemAdminccLicense; } /** * Are item admins allowed to manage the item's policies? * * @return */ public static boolean canItemAdminManagePolicies() { return can_itemAdmin_policies; } /** * Are item admins allowed to add bitstreams to the item? * * @return */ public static boolean canItemAdminPerformBitstreamCreation() { return can_itemAdmin_createBitstream; } /** * Are item admins allowed to remove bitstreams from the item? * * @return */ public static boolean canItemAdminPerformBitstreamDeletion() { return can_itemAdmin_deleteBitstream; } /** * Are item admins allowed to replace or adding CC License to the item? * * @return */ public static boolean canItemAdminManageCCLicense() { return can_itemAdmin_ccLicense; } }
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.authorize; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.dspace.content.DSpaceObject; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * AuthorizeManager handles all authorization checks for DSpace. For better * security, DSpace assumes that you do not have the right to do something * unless that permission is spelled out somewhere. That "somewhere" is the * ResourcePolicy table. The AuthorizeManager is given a user, an object, and an * action, and it then does a lookup in the ResourcePolicy table to see if there * are any policies giving the user permission to do that action. * <p> * ResourcePolicies now apply to single objects (such as submit (ADD) permission * to a collection.) * <p> * Note: If an eperson is a member of the administrator group (id 1), then they * are automatically given permission for all requests another special group is * group 0, which is anonymous - all EPeople are members of group 0. */ public class AuthorizeManager { /** * Utility method, checks that the current user of the given context can * perform all of the specified actions on the given object. An * <code>AuthorizeException</code> if all the authorizations fail. * * @param c * context with the current user * @param o * DSpace object user is attempting to perform action on * @param actions * array of action IDs from * <code>org.dspace.core.Constants</code> * @throws AuthorizeException * if any one of the specified actions cannot be performed by * the current user on the given object. * @throws SQLException * if there's a database problem */ public static void authorizeAnyOf(Context c, DSpaceObject o, int[] actions) throws AuthorizeException, SQLException { AuthorizeException ex = null; for (int i = 0; i < actions.length; i++) { try { authorizeAction(c, o, actions[i]); return; } catch (AuthorizeException e) { if (ex == null) { ex = e; } } } throw ex; } /** * Checks that the context's current user can perform the given action on * the given object. Throws an exception if the user is not authorized, * otherwise the method call does nothing. * * @param c * context * @param o * a DSpaceObject * @param action * action to perform from <code>org.dspace.core.Constants</code> * * @throws AuthorizeException * if the user is denied */ public static void authorizeAction(Context c, DSpaceObject o, int action) throws AuthorizeException, SQLException { authorizeAction(c, o, action, true); } /** * Checks that the context's current user can perform the given action on * the given object. Throws an exception if the user is not authorized, * otherwise the method call does nothing. * * @param c * context * @param o * a DSpaceObject * @param useInheritance * flag to say if ADMIN action on the current object or parent * object can be used * @param action * action to perform from <code>org.dspace.core.Constants</code> * * @throws AuthorizeException * if the user is denied */ public static void authorizeAction(Context c, DSpaceObject o, int action, boolean useInheritance) throws AuthorizeException, SQLException { if (o == null) { // action can be -1 due to a null entry String actionText; if (action == -1) { actionText = "null"; } else { actionText = Constants.actionText[action]; } EPerson e = c.getCurrentUser(); int userid; if (e == null) { userid = 0; } else { userid = e.getID(); } throw new AuthorizeException( "Authorization attempted on null DSpace object " + actionText + " by user " + userid); } if (!authorize(c, o, action, c.getCurrentUser(), useInheritance)) { // denied, assemble and throw exception int otype = o.getType(); int oid = o.getID(); int userid; EPerson e = c.getCurrentUser(); if (e == null) { userid = 0; } else { userid = e.getID(); } // AuthorizeException j = new AuthorizeException("Denied"); // j.printStackTrace(); // action can be -1 due to a null entry String actionText; if (action == -1) { actionText = "null"; } else { actionText = Constants.actionText[action]; } throw new AuthorizeException("Authorization denied for action " + actionText + " on " + Constants.typeText[otype] + ":" + oid + " by user " + userid, o, action); } } /** * same authorize, returns boolean for those who don't want to deal with * catching exceptions. * * @param c * DSpace context, containing current user * @param o * DSpaceObject * @param a * action being attempted, from * <code>org.dspace.core.Constants</code> * * @return <code>true</code> if the current user in the context is * authorized to perform the given action on the given object */ public static boolean authorizeActionBoolean(Context c, DSpaceObject o, int a) throws SQLException { return authorizeActionBoolean(c, o, a, true); } /** * same authorize, returns boolean for those who don't want to deal with * catching exceptions. * * @param c * DSpace context, containing current user * @param o * DSpaceObject * @param a * action being attempted, from * <code>org.dspace.core.Constants</code> * @param useInheritance * flag to say if ADMIN action on the current object or parent * object can be used * * @return <code>true</code> if the current user in the context is * authorized to perform the given action on the given object */ public static boolean authorizeActionBoolean(Context c, DSpaceObject o, int a, boolean useInheritance) throws SQLException { boolean isAuthorized = true; if (o == null) { return false; } try { authorizeAction(c, o, a, useInheritance); } catch (AuthorizeException e) { isAuthorized = false; } return isAuthorized; } /** * Check to see if the given user can perform the given action on the given * object. Always returns true if the ignore authorization flat is set in * the current context. * * @param c * current context. User is irrelevant; "ignore authorization" * flag is relevant * @param o * object action is being attempted on * @param action * ID of action being attempted, from * <code>org.dspace.core.Constants</code> * @param e * user attempting action * @param useInheritance * flag to say if ADMIN action on the current object or parent * object can be used * @return <code>true</code> if user is authorized to perform the given * action, <code>false</code> otherwise * @throws SQLException */ private static boolean authorize(Context c, DSpaceObject o, int action, EPerson e, boolean useInheritance) throws SQLException { // return FALSE if there is no DSpaceObject if (o == null) { return false; } // is authorization disabled for this context? if (c.ignoreAuthorization()) { return true; } // is eperson set? if not, userid = 0 (anonymous) int userid = 0; if (e != null) { userid = e.getID(); // perform isAdmin check to see // if user is an Admin on this object DSpaceObject testObject = useInheritance?o.getAdminObject(action):null; if (isAdmin(c, testObject)) { return true; } } for (ResourcePolicy rp : getPoliciesActionFilter(c, o, action)) { // check policies for date validity if (rp.isDateValid()) { if ((rp.getEPersonID() != -1) && (rp.getEPersonID() == userid)) { return true; // match } if ((rp.getGroupID() != -1) && (Group.isMember(c, rp.getGroupID()))) { // group was set, and eperson is a member // of that group return true; } } } // default authorization is denial return false; } /////////////////////////////////////////////// // admin check methods /////////////////////////////////////////////// /** * Check to see if the current user is an Administrator of a given object * within DSpace. Always return <code>true</code> if the user is a System * Admin * * @param c * current context * @param o * current DSpace Object, if <code>null</code> the call will be * equivalent to a call to the <code>isAdmin(Context c)</code> * method * * @return <code>true</code> if user has administrative privileges on the * given DSpace object */ public static boolean isAdmin(Context c, DSpaceObject o) throws SQLException { // return true if user is an Administrator if (isAdmin(c)) { return true; } if (o == null) { return false; } // is eperson set? if not, userid = 0 (anonymous) int userid = 0; EPerson e = c.getCurrentUser(); if(e != null) { userid = e.getID(); } // // First, check all Resource Policies directly on this object // List<ResourcePolicy> policies = getPoliciesActionFilter(c, o, Constants.ADMIN); for (ResourcePolicy rp : policies) { // check policies for date validity if (rp.isDateValid()) { if ((rp.getEPersonID() != -1) && (rp.getEPersonID() == userid)) { return true; // match } if ((rp.getGroupID() != -1) && (Group.isMember(c, rp.getGroupID()))) { // group was set, and eperson is a member // of that group return true; } } } // If user doesn't have specific Admin permissions on this object, // check the *parent* objects of this object. This allows Admin // permissions to be inherited automatically (e.g. Admin on Community // is also an Admin of all Collections/Items in that Community) DSpaceObject parent = o.getParentObject(); if (parent != null) { return isAdmin(c, parent); } return false; } /** * Check to see if the current user is a System Admin. Always return * <code>true</code> if c.ignoreAuthorization is set. Anonymous users * can't be Admins (EPerson set to NULL) * * @param c * current context * * @return <code>true</code> if user is an admin or ignore authorization * flag set */ public static boolean isAdmin(Context c) throws SQLException { // if we're ignoring authorization, user is member of admin if (c.ignoreAuthorization()) { return true; } EPerson e = c.getCurrentUser(); if (e == null) { return false; // anonymous users can't be admins.... } else { return Group.isMember(c, 1); } } /////////////////////////////////////////////// // policy manipulation methods /////////////////////////////////////////////// /** * Add a policy for an individual eperson * * @param c * context. Current user irrelevant * @param o * DSpaceObject to add policy to * @param actionID * ID of action from <code>org.dspace.core.Constants</code> * @param e * eperson who can perform the action * * @throws AuthorizeException * if current user in context is not authorized to add policies */ public static void addPolicy(Context c, DSpaceObject o, int actionID, EPerson e) throws SQLException, AuthorizeException { ResourcePolicy rp = ResourcePolicy.create(c); rp.setResource(o); rp.setAction(actionID); rp.setEPerson(e); rp.update(); } /** * Add a policy for a group * * @param c * current context * @param o * object to add policy for * @param actionID * ID of action from <code>org.dspace.core.Constants</code> * @param g * group to add policy for * @throws SQLException * if there's a database problem * @throws AuthorizeException * if the current user is not authorized to add this policy */ public static void addPolicy(Context c, DSpaceObject o, int actionID, Group g) throws SQLException, AuthorizeException { ResourcePolicy rp = ResourcePolicy.create(c); rp.setResource(o); rp.setAction(actionID); rp.setGroup(g); rp.update(); } /** * Return a List of the policies for an object * * @param c current context * @param o object to retrieve policies for * * @return List of <code>ResourcePolicy</code> objects */ public static List<ResourcePolicy> getPolicies(Context c, DSpaceObject o) throws SQLException { TableRowIterator tri = DatabaseManager.queryTable(c, "resourcepolicy", "SELECT * FROM resourcepolicy WHERE resource_type_id= ? AND resource_id= ? ", o.getType(),o.getID()); List<ResourcePolicy> policies = new ArrayList<ResourcePolicy>(); try { while (tri.hasNext()) { TableRow row = tri.next(); // first check the cache (FIXME: is this right?) ResourcePolicy cachepolicy = (ResourcePolicy) c.fromCache( ResourcePolicy.class, row.getIntColumn("policy_id")); if (cachepolicy != null) { policies.add(cachepolicy); } else { policies.add(new ResourcePolicy(c, row)); } } } finally { if (tri != null) { tri.close(); } } return policies; } /** * Return a List of the policies for a group * * @param c current context * @param g group to retrieve policies for * * @return List of <code>ResourcePolicy</code> objects */ public static List<ResourcePolicy> getPoliciesForGroup(Context c, Group g) throws SQLException { TableRowIterator tri = DatabaseManager.queryTable(c, "resourcepolicy", "SELECT * FROM resourcepolicy WHERE epersongroup_id= ? ", g.getID()); List<ResourcePolicy> policies = new ArrayList<ResourcePolicy>(); try { while (tri.hasNext()) { TableRow row = tri.next(); // first check the cache (FIXME: is this right?) ResourcePolicy cachepolicy = (ResourcePolicy) c.fromCache( ResourcePolicy.class, row.getIntColumn("policy_id")); if (cachepolicy != null) { policies.add(cachepolicy); } else { policies.add(new ResourcePolicy(c, row)); } } } finally { if (tri != null) { tri.close(); } } return policies; } /** * Return a list of policies for an object that match the action * * @param c * context * @param o * DSpaceObject policies relate to * @param actionID * action (defined in class Constants) * @throws SQLException * if there's a database problem */ public static List<ResourcePolicy> getPoliciesActionFilter(Context c, DSpaceObject o, int actionID) throws SQLException { TableRowIterator tri = DatabaseManager.queryTable(c, "resourcepolicy", "SELECT * FROM resourcepolicy WHERE resource_type_id= ? "+ "AND resource_id= ? AND action_id= ? ", o.getType(), o.getID(),actionID); List<ResourcePolicy> policies = new ArrayList<ResourcePolicy>(); try { while (tri.hasNext()) { TableRow row = tri.next(); // first check the cache (FIXME: is this right?) ResourcePolicy cachepolicy = (ResourcePolicy) c.fromCache( ResourcePolicy.class, row.getIntColumn("policy_id")); if (cachepolicy != null) { policies.add(cachepolicy); } else { policies.add(new ResourcePolicy(c, row)); } } } finally { if (tri != null) { tri.close(); } } return policies; } /** * Add policies to an object to match those from a previous object * * @param c context * @param src * source of policies * @param dest * destination of inherited policies * @throws SQLException * if there's a database problem * @throws AuthorizeException * if the current user is not authorized to add these policies */ public static void inheritPolicies(Context c, DSpaceObject src, DSpaceObject dest) throws SQLException, AuthorizeException { // find all policies for the source object List<ResourcePolicy> policies = getPolicies(c, src); //Only inherit non-ADMIN policies (since ADMIN policies are automatically inherited) List<ResourcePolicy> nonAdminPolicies = new ArrayList<ResourcePolicy>(); for (ResourcePolicy rp : policies) { if (rp.getAction() != Constants.ADMIN) { nonAdminPolicies.add(rp); } } addPolicies(c, nonAdminPolicies, dest); } /** * Copies policies from a list of resource policies to a given DSpaceObject * * @param c * DSpace context * @param policies * List of ResourcePolicy objects * @param dest * object to have policies added * @throws SQLException * if there's a database problem * @throws AuthorizeException * if the current user is not authorized to add these policies */ public static void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { // now add them to the destination object for (ResourcePolicy srp : policies) { ResourcePolicy drp = ResourcePolicy.create(c); // copy over values drp.setResource(dest); drp.setAction(srp.getAction()); drp.setEPerson(srp.getEPerson()); drp.setGroup(srp.getGroup()); drp.setStartDate(srp.getStartDate()); drp.setEndDate(srp.getEndDate()); // and write out new policy drp.update(); } } /** * removes ALL policies for an object. FIXME doesn't check authorization * * @param c * DSpace context * @param o * object to remove policies for * @throws SQLException * if there's a database problem */ public static void removeAllPolicies(Context c, DSpaceObject o) throws SQLException { // FIXME: authorization check? DatabaseManager.updateQuery(c, "DELETE FROM resourcepolicy WHERE " + "resource_type_id= ? AND resource_id= ? ", o.getType(), o.getID()); } /** * Remove all policies from an object that match a given action. FIXME * doesn't check authorization * * @param context * current context * @param dso * object to remove policies from * @param actionID * ID of action to match from * <code>org.dspace.core.Constants</code>, or -1=all * @throws SQLException * if there's a database problem */ public static void removePoliciesActionFilter(Context context, DSpaceObject dso, int actionID) throws SQLException { if (actionID == -1) { // remove all policies from object removeAllPolicies(context, dso); } else { DatabaseManager.updateQuery(context, "DELETE FROM resourcepolicy WHERE resource_type_id= ? AND "+ "resource_id= ? AND action_id= ? ", dso.getType(), dso.getID(), actionID); } } /** * Removes all policies relating to a particular group. FIXME doesn't check * authorization * * @param c * current context * @param groupID * ID of the group * @throws SQLException * if there's a database problem */ public static void removeGroupPolicies(Context c, int groupID) throws SQLException { DatabaseManager.updateQuery(c, "DELETE FROM resourcepolicy WHERE " + "epersongroup_id= ? ", groupID); } /** * Removes all policies from a group for a particular object that belong to * a Group. FIXME doesn't check authorization * * @param c * current context * @param o * the object * @param g * the group * @throws SQLException * if there's a database problem */ public static void removeGroupPolicies(Context c, DSpaceObject o, Group g) throws SQLException { DatabaseManager.updateQuery(c, "DELETE FROM resourcepolicy WHERE " + "resource_type_id= ? AND resource_id= ? AND epersongroup_id= ? ", o.getType(), o.getID(), g.getID()); } /** * Returns all groups authorized to perform an action on an object. Returns * empty array if no matches. * * @param c * current context * @param o * object * @param actionID * ID of action frm <code>org.dspace.core.Constants</code> * @return array of <code>Group</code>s that can perform the specified * action on the specified object * @throws java.sql.SQLException * if there's a database problem */ public static Group[] getAuthorizedGroups(Context c, DSpaceObject o, int actionID) throws java.sql.SQLException { // do query matching groups, actions, and objects TableRowIterator tri = DatabaseManager.queryTable(c, "resourcepolicy", "SELECT * FROM resourcepolicy WHERE resource_type_id= ? "+ "AND resource_id= ? AND action_id= ? ",o.getType(),o.getID(),actionID); List<Group> groups = new ArrayList<Group>(); try { while (tri.hasNext()) { TableRow row = tri.next(); // first check the cache (FIXME: is this right?) ResourcePolicy cachepolicy = (ResourcePolicy) c.fromCache( ResourcePolicy.class, row.getIntColumn("policy_id")); ResourcePolicy myPolicy = null; if (cachepolicy != null) { myPolicy = cachepolicy; } else { myPolicy = new ResourcePolicy(c, row); } // now do we have a group? Group myGroup = myPolicy.getGroup(); if (myGroup != null) { groups.add(myGroup); } } } finally { if (tri != null) { tri.close(); } } Group[] groupArray = new Group[groups.size()]; groupArray = groups.toArray(groupArray); return groupArray; } }
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.authorize; import java.sql.SQLException; import java.util.Date; import org.apache.log4j.Logger; import org.dspace.content.DSpaceObject; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; /** * Class representing a ResourcePolicy * * @author David Stuve * @version $Revision: 5844 $ */ public class ResourcePolicy { /** log4j logger */ private static Logger log = Logger.getLogger(ResourcePolicy.class); /** Our context */ private Context myContext; /** The row in the table representing this object */ private TableRow myRow; /** * Construct an ResourcePolicy * * @param context * the context this object exists in * @param row * the corresponding row in the table */ ResourcePolicy(Context context, TableRow row) { myContext = context; myRow = row; } /** * Return true if this object equals obj, false otherwise. * * @param obj * @return true if ResourcePolicy objects are equal */ @Override public boolean equals(Object obj) { try { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ResourcePolicy other = (ResourcePolicy) obj; if (this.getAction() != other.getAction()) { return false; } if (this.getEPerson() != other.getEPerson() && (this.getEPerson() == null || !this.getEPerson().equals(other.getEPerson()))) { return false; } if (this.getGroup() != other.getGroup() && (this.getGroup() == null || !this.getGroup().equals(other.getGroup()))) { return false; } if (this.getStartDate() != other.getStartDate() && (this.getStartDate() == null || !this.getStartDate().equals(other.getStartDate()))) { return false; } if (this.getEndDate() != other.getEndDate() && (this.getEndDate() == null || !this.getEndDate().equals(other.getEndDate()))) { return false; } return true; } catch (SQLException ex) { log.error("Error while comparing ResourcePolicy objects", ex); } return false; } /** * Return a hash code for this object. * * @return int hash of object */ @Override public int hashCode() { int hash = 7; try { hash = 19 * hash + this.getAction(); hash = 19 * hash + (this.getEPerson() != null? this.getEPerson().hashCode():0); hash = 19 * hash + (this.getGroup() != null? this.getGroup().hashCode():0); hash = 19 * hash + (this.getStartDate() != null? this.getStartDate().hashCode():0); hash = 19 * hash + (this.getEndDate() != null? this.getEndDate().hashCode():0); hash = 19 * hash + (this.getEPerson() != null? this.getEPerson().hashCode():0); } catch (SQLException ex) { log.error("Error generating hascode of ResourcePolicy", ex); } return hash; } /** * Get an ResourcePolicy from the database. * * @param context * DSpace context object * @param id * ID of the ResourcePolicy * * @return the ResourcePolicy format, or null if the ID is invalid. */ public static ResourcePolicy find(Context context, int id) throws SQLException { TableRow row = DatabaseManager.find(context, "ResourcePolicy", id); if (row == null) { return null; } else { return new ResourcePolicy(context, row); } } /** * Create a new ResourcePolicy * * @param context * DSpace context object */ public static ResourcePolicy create(Context context) throws SQLException, AuthorizeException { // FIXME: Check authorisation // Create a table row TableRow row = DatabaseManager.create(context, "ResourcePolicy"); return new ResourcePolicy(context, row); } /** * Delete an ResourcePolicy * */ public void delete() throws SQLException { // FIXME: authorizations // Remove ourself DatabaseManager.delete(myContext, myRow); } /** * Get the e-person's internal identifier * * @return the internal identifier */ public int getID() { return myRow.getIntColumn("policy_id"); } /** * Get the type of the objects referred to by policy * * @return type of object/resource */ public int getResourceType() { return myRow.getIntColumn("resource_type_id"); } /** * set both type and id of resource referred to by policy * */ public void setResource(DSpaceObject o) { setResourceType(o.getType()); setResourceID(o.getID()); } /** * Set the type of the resource referred to by the policy * * @param mytype * type of the resource */ public void setResourceType(int mytype) { myRow.setColumn("resource_type_id", mytype); } /** * Get the ID of a resource pointed to by the policy (is null if policy * doesn't apply to a single resource.) * * @return resource_id */ public int getResourceID() { return myRow.getIntColumn("resource_id"); } /** * If the policy refers to a single resource, this is the ID of that * resource. * * @param myid id of resource (database primary key) */ public void setResourceID(int myid) { myRow.setColumn("resource_id", myid); } /** * @return get the action this policy authorizes */ public int getAction() { return myRow.getIntColumn("action_id"); } /** * @return action text or 'null' if action row empty */ public String getActionText() { int myAction = myRow.getIntColumn("action_id"); if (myAction == -1) { return "..."; } else { return Constants.actionText[myAction]; } } /** * set the action this policy authorizes * * @param myid action ID from <code>org.dspace.core.Constants</code> */ public void setAction(int myid) { myRow.setColumn("action_id", myid); } /** * @return eperson ID, or -1 if EPerson not set */ public int getEPersonID() { return myRow.getIntColumn("eperson_id"); } /** * get EPerson this policy relates to * * @return EPerson, or null */ public EPerson getEPerson() throws SQLException { int eid = myRow.getIntColumn("eperson_id"); if (eid == -1) { return null; } return EPerson.find(myContext, eid); } /** * assign an EPerson to this policy * * @param e EPerson */ public void setEPerson(EPerson e) { if (e != null) { myRow.setColumn("eperson_id", e.getID()); } else { myRow.setColumnNull("eperson_id"); } } /** * gets ID for Group referred to by this policy * * @return groupID, or -1 if no group set */ public int getGroupID() { return myRow.getIntColumn("epersongroup_id"); } /** * gets Group for this policy * * @return Group, or -1 if no group set */ public Group getGroup() throws SQLException { int gid = myRow.getIntColumn("epersongroup_id"); if (gid == -1) { return null; } else { return Group.find(myContext, gid); } } /** * set Group for this policy * * @param g group */ public void setGroup(Group g) { if (g != null) { myRow.setColumn("epersongroup_id", g.getID()); } else { myRow.setColumnNull("epersongroup_id"); } } /** * figures out if the date is valid for the policy * * @return true if policy has begun and hasn't expired yet (or no dates are * set) */ public boolean isDateValid() { Date sd = getStartDate(); Date ed = getEndDate(); // if no dates set, return true (most common case) if ((sd == null) && (ed == null)) { return true; } // one is set, now need to do some date math Date now = new Date(); // check start date first if (sd != null && now.before(sd)) { // start date is set, return false if we're before it return false; } // now expiration date if (ed != null && now.after(ed)) { // end date is set, return false if we're after it return false; } // if we made it this far, start < now < end return true; // date must be okay } /** * Get the start date of the policy * * @return start date, or null if there is no start date set (probably most * common case) */ public java.util.Date getStartDate() { return myRow.getDateColumn("start_date"); } /** * Set the start date for the policy * * @param d * date, or null for no start date */ public void setStartDate(java.util.Date d) { myRow.setColumn("start_date", d); } /** * Get end date for the policy * * @return end date or null for no end date */ public java.util.Date getEndDate() { return myRow.getDateColumn("end_date"); } /** * Set end date for the policy * * @param d * end date, or null */ public void setEndDate(java.util.Date d) { myRow.setColumn("end_date", d); } /** * Update the ResourcePolicy */ public void update() throws SQLException { // FIXME: Check authorisation DatabaseManager.update(myContext, myRow); } }
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.authorize; import org.dspace.content.DSpaceObject; /** * Exception indicating the current user of the context does not have permission * to perform a particular action. * * @author David Stuve * @version $Revision: 5844 $ */ public class AuthorizeException extends Exception { private int myaction; // action attempted, or -1 private DSpaceObject myobject; // object action attempted on or null /** * Create an empty authorize exception */ public AuthorizeException() { super(); myaction = -1; myobject = null; } /** * create an exception with only a message * * @param message */ public AuthorizeException(String message) { super(message); myaction = -1; myobject = null; } /** * Create an authorize exception with a message * * @param message * the message */ public AuthorizeException(String message, DSpaceObject o, int a) { super(message); myobject = o; myaction = a; } public int getAction() { return myaction; } public DSpaceObject getObject() { return myobject; } }
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.storage.bitstore; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.log4j.Logger; /** * Cleans up asset store. * * @author Peter Breton * @version $Revision: 5844 $ */ public class Cleanup { /** log4j log */ private static Logger log = Logger.getLogger(Cleanup.class); /** * Cleans up asset store. * * @param argv - * Command-line arguments */ public static void main(String[] argv) { try { log.info("Cleaning up asset store"); // set up command line parser CommandLineParser parser = new PosixParser(); CommandLine line = null; // create an options object and populate it Options options = new Options(); options.addOption("l", "leave", false, "Leave database records but delete file from assetstore"); options.addOption("v", "verbose", false, "Provide verbose output"); options.addOption("h", "help", false, "Help"); try { line = parser.parse(options, argv); } catch (ParseException e) { log.fatal(e); System.exit(1); } // user asks for help if (line.hasOption('h')) { printHelp(options); System.exit(0); } boolean deleteDbRecords = true; // Prune stage if (line.hasOption('l')) { log.debug("option l used setting flag to leave db records"); deleteDbRecords = false; } log.debug("leave db records = " + deleteDbRecords); BitstreamStorageManager.cleanup(deleteDbRecords, line.hasOption('v')); System.exit(0); } catch (Exception e) { log.fatal("Caught exception:", e); System.exit(1); } } private static void printHelp(Options options) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("Cleanup\n", 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.dspace.storage.bitstore; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.dspace.checker.BitstreamInfoDAO; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.Utils; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import edu.sdsc.grid.io.FileFactory; import edu.sdsc.grid.io.GeneralFile; import edu.sdsc.grid.io.GeneralFileOutputStream; import edu.sdsc.grid.io.local.LocalFile; import edu.sdsc.grid.io.srb.SRBAccount; import edu.sdsc.grid.io.srb.SRBFile; import edu.sdsc.grid.io.srb.SRBFileSystem; /** * <P> * Stores, retrieves and deletes bitstreams. * </P> * * <P> * Presently, asset stores are specified in <code>dspace.cfg</code>. Since * Java does not offer a way of detecting free disk space, the asset store to * use for new bitstreams is also specified in a configuration property. The * drawbacks to this are that the administrators are responsible for monitoring * available space in the asset stores, and DSpace (Tomcat) has to be restarted * when the asset store for new ('incoming') bitstreams is changed. * </P> * * <P> * Mods by David Little, UCSD Libraries 12/21/04 to allow the registration of * files (bitstreams) into DSpace. * </P> * * <p>Cleanup integration with checker package by Nate Sarr 2006-01. N.B. The * dependency on the checker package isn't ideal - a Listener pattern would be * better but was considered overkill for the purposes of integrating the checker. * It would be worth re-considering a Listener pattern if another package needs to * be notified of BitstreamStorageManager actions.</p> * * @author Peter Breton, Robert Tansley, David Little, Nathan Sarr * @version $Revision: 5844 $ */ public class BitstreamStorageManager { /** log4j log */ private static Logger log = Logger.getLogger(BitstreamStorageManager.class); /** * The asset store locations. The information for each GeneralFile in the * array comes from dspace.cfg, so see the comments in that file. * * If an array element refers to a conventional (non_SRB) asset store, the * element will be a LocalFile object (similar to a java.io.File object) * referencing a local directory under which the bitstreams are stored. * * If an array element refers to an SRB asset store, the element will be an * SRBFile object referencing an SRB 'collection' (directory) under which * the bitstreams are stored. * * An SRBFile object is obtained by (1) using dspace.cfg properties to * create an SRBAccount object (2) using the account to create an * SRBFileSystem object (similar to a connection) (3) using the * SRBFileSystem object to create an SRBFile object */ private static GeneralFile[] assetStores; /** The asset store to use for new bitstreams */ private static int incoming; // These settings control the way an identifier is hashed into // directory and file names // // With digitsPerLevel 2 and directoryLevels 3, an identifier // like 12345678901234567890 turns into the relative name // /12/34/56/12345678901234567890. // // You should not change these settings if you have data in the // asset store, as the BitstreamStorageManager will be unable // to find your existing data. private static final int digitsPerLevel = 2; private static final int directoryLevels = 3; /** * This prefix string marks registered bitstreams in internal_id */ private static final String REGISTERED_FLAG = "-R"; /* Read in the asset stores from the config. */ static { List<Object> stores = new ArrayList<Object>(); // 'assetstore.dir' is always store number 0 String sAssetstoreDir = ConfigurationManager .getProperty("assetstore.dir"); // see if conventional assetstore or srb if (sAssetstoreDir != null) { stores.add(sAssetstoreDir); // conventional (non-srb) } else if (ConfigurationManager.getProperty("srb.host") != null) { stores.add(new SRBAccount( // srb ConfigurationManager.getProperty("srb.host"), ConfigurationManager.getIntProperty("srb.port"), ConfigurationManager.getProperty("srb.username"), ConfigurationManager.getProperty("srb.password"), ConfigurationManager.getProperty("srb.homedirectory"), ConfigurationManager.getProperty("srb.mdasdomainname"), ConfigurationManager .getProperty("srb.defaultstorageresource"), ConfigurationManager.getProperty("srb.mcatzone"))); } else { log.error("No default assetstore"); } // read in assetstores .1, .2, .... for (int i = 1;; i++) { // i == 0 is default above sAssetstoreDir = ConfigurationManager.getProperty("assetstore.dir." + i); // see if 'i' conventional assetstore or srb if (sAssetstoreDir != null) { // conventional (non-srb) stores.add(sAssetstoreDir); } else if (ConfigurationManager.getProperty("srb.host." + i) != null) { // srb stores.add(new SRBAccount( ConfigurationManager.getProperty("srb.host." + i), ConfigurationManager.getIntProperty("srb.port." + i), ConfigurationManager.getProperty("srb.username." + i), ConfigurationManager.getProperty("srb.password." + i), ConfigurationManager .getProperty("srb.homedirectory." + i), ConfigurationManager .getProperty("srb.mdasdomainname." + i), ConfigurationManager .getProperty("srb.defaultstorageresource." + i), ConfigurationManager.getProperty("srb.mcatzone." + i))); } else { break; // must be at the end of the assetstores } } // convert list to array // the elements (objects) in the list are class // (1) String - conventional non-srb assetstore // (2) SRBAccount - srb assetstore assetStores = new GeneralFile[stores.size()]; for (int i = 0; i < stores.size(); i++) { Object o = stores.get(i); if (o == null) { // I don't know if this can occur log.error("Problem with assetstore " + i); } if (o instanceof String) { assetStores[i] = new LocalFile((String) o); } else if (o instanceof SRBAccount) { SRBFileSystem srbFileSystem = null; try { srbFileSystem = new SRBFileSystem((SRBAccount) o); } catch (NullPointerException e) { log.error("No SRBAccount for assetstore " + i); } catch (IOException e) { log.error("Problem getting SRBFileSystem for assetstore" + i); } if (srbFileSystem == null) { log.error("SRB FileSystem is null for assetstore " + i); } String sSRBAssetstore = null; if (i == 0) { // the zero (default) assetstore has no suffix sSRBAssetstore = ConfigurationManager .getProperty("srb.parentdir"); } else { sSRBAssetstore = ConfigurationManager .getProperty("srb.parentdir." + i); } if (sSRBAssetstore == null) { log.error("srb.parentdir is undefined for assetstore " + i); } assetStores[i] = new SRBFile(srbFileSystem, sSRBAssetstore); } else { log.error("Unexpected " + o.getClass().toString() + " with assetstore " + i); } } // Read asset store to put new files in. Default is 0. incoming = ConfigurationManager.getIntProperty("assetstore.incoming"); } /** * Store a stream of bits. * * <p> * If this method returns successfully, the bits have been stored, and RDBMS * metadata entries are in place (the context still needs to be completed to * finalize the transaction). * </p> * * <p> * If this method returns successfully and the context is aborted, then the * bits will be stored in the asset store and the RDBMS metadata entries * will exist, but with the deleted flag set. * </p> * * If this method throws an exception, then any of the following may be * true: * * <ul> * <li>Neither bits nor RDBMS metadata entries have been stored. * <li>RDBMS metadata entries with the deleted flag set have been stored, * but no bits. * <li>RDBMS metadata entries with the deleted flag set have been stored, * and some or all of the bits have also been stored. * </ul> * * @param context * The current context * @param is * The stream of bits to store * @exception IOException * If a problem occurs while storing the bits * @exception SQLException * If a problem occurs accessing the RDBMS * * @return The ID of the stored bitstream */ public static int store(Context context, InputStream is) throws SQLException, IOException { // Create internal ID String id = Utils.generateKey(); // Create a deleted bitstream row, using a separate DB connection TableRow bitstream; Context tempContext = null; try { tempContext = new Context(); bitstream = DatabaseManager.row("Bitstream"); bitstream.setColumn("deleted", true); bitstream.setColumn("internal_id", id); /* * Set the store number of the new bitstream If you want to use some * other method of working out where to put a new bitstream, here's * where it should go */ bitstream.setColumn("store_number", incoming); DatabaseManager.insert(tempContext, bitstream); tempContext.complete(); } catch (SQLException sqle) { if (tempContext != null) { tempContext.abort(); } throw sqle; } // Where on the file system will this new bitstream go? GeneralFile file = getFile(bitstream); // Make the parent dirs if necessary GeneralFile parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } //Create the corresponding file and open it file.createNewFile(); GeneralFileOutputStream fos = FileFactory.newFileOutputStream(file); // Read through a digest input stream that will work out the MD5 DigestInputStream dis = null; try { dis = new DigestInputStream(is, MessageDigest.getInstance("MD5")); } // Should never happen catch (NoSuchAlgorithmException nsae) { log.warn("Caught NoSuchAlgorithmException", nsae); } Utils.bufferedCopy(dis, fos); fos.close(); is.close(); bitstream.setColumn("size_bytes", file.length()); if (dis != null) { bitstream.setColumn("checksum", Utils.toHex(dis.getMessageDigest() .digest())); bitstream.setColumn("checksum_algorithm", "MD5"); } bitstream.setColumn("deleted", false); DatabaseManager.update(context, bitstream); int bitstreamId = bitstream.getIntColumn("bitstream_id"); if (log.isDebugEnabled()) { log.debug("Stored bitstream " + bitstreamId + " in file " + file.getAbsolutePath()); } return bitstreamId; } /** * Register a bitstream already in storage. * * @param context * The current context * @param assetstore The assetstore number for the bitstream to be * registered * @param bitstreamPath The relative path of the bitstream to be registered. * The path is relative to the path of ths assetstore. * @return The ID of the registered bitstream * @exception SQLException * If a problem occurs accessing the RDBMS * @throws IOException */ public static int register(Context context, int assetstore, String bitstreamPath) throws SQLException, IOException { // mark this bitstream as a registered bitstream String sInternalId = REGISTERED_FLAG + bitstreamPath; // Create a deleted bitstream row, using a separate DB connection TableRow bitstream; Context tempContext = null; try { tempContext = new Context(); bitstream = DatabaseManager.row("Bitstream"); bitstream.setColumn("deleted", true); bitstream.setColumn("internal_id", sInternalId); bitstream.setColumn("store_number", assetstore); DatabaseManager.insert(tempContext, bitstream); tempContext.complete(); } catch (SQLException sqle) { if (tempContext != null) { tempContext.abort(); } throw sqle; } // get a reference to the file GeneralFile file = getFile(bitstream); // read through a DigestInputStream that will work out the MD5 // // DSpace refers to checksum, writes it in METS, and uses it as an // AIP filename (!), but never seems to validate with it. Furthermore, // DSpace appears to hardcode the algorithm to MD5 in some places--see // METSExport.java. // // To remain compatible with DSpace we calculate an MD5 checksum on // LOCAL registered files. But for REMOTE (e.g. SRB) files we // calculate an MD5 on just the fileNAME. The reasoning is that in the // case of a remote file, calculating an MD5 on the file itself will // generate network traffic to read the file's bytes. In this case it // would be better have a proxy process calculate MD5 and store it as // an SRB metadata attribute so it can be retrieved simply from SRB. // // TODO set this up as a proxy server process so no net activity // FIXME this is a first class HACK! for the reasons described above if (file instanceof LocalFile) { // get MD5 on the file for local file DigestInputStream dis = null; try { dis = new DigestInputStream(FileFactory.newFileInputStream(file), MessageDigest.getInstance("MD5")); } catch (NoSuchAlgorithmException e) { log.warn("Caught NoSuchAlgorithmException", e); throw new IOException("Invalid checksum algorithm", e); } catch (IOException e) { log.error("File: " + file.getAbsolutePath() + " to be registered cannot be opened - is it " + "really there?"); throw e; } final int BUFFER_SIZE = 1024 * 4; final byte[] buffer = new byte[BUFFER_SIZE]; while (true) { final int count = dis.read(buffer, 0, BUFFER_SIZE); if (count == -1) { break; } } bitstream.setColumn("checksum", Utils.toHex(dis.getMessageDigest() .digest())); dis.close(); } else if (file instanceof SRBFile) { if (!file.exists()) { log.error("File: " + file.getAbsolutePath() + " is not in SRB MCAT"); throw new IOException("File is not in SRB MCAT"); } // get MD5 on just the filename (!) for SRB file int iLastSlash = bitstreamPath.lastIndexOf('/'); String sFilename = bitstreamPath.substring(iLastSlash + 1); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Caught NoSuchAlgorithmException", e); throw new IOException("Invalid checksum algorithm", e); } bitstream.setColumn("checksum", Utils.toHex(md.digest(sFilename.getBytes()))); } else { throw new IOException("Unrecognized file type - " + "not local, not SRB"); } bitstream.setColumn("checksum_algorithm", "MD5"); bitstream.setColumn("size_bytes", file.length()); bitstream.setColumn("deleted", false); DatabaseManager.update(context, bitstream); int bitstreamId = bitstream.getIntColumn("bitstream_id"); if (log.isDebugEnabled()) { log.debug("Stored bitstream " + bitstreamId + " in file " + file.getAbsolutePath()); } return bitstreamId; } /** * Does the internal_id column in the bitstream row indicate the bitstream * is a registered file * * @param internalId the value of the internal_id column * @return true if the bitstream is a registered file */ public static boolean isRegisteredBitstream(String internalId) { if (internalId.substring(0, REGISTERED_FLAG.length()) .equals(REGISTERED_FLAG)) { return true; } return false; } /** * Retrieve the bits for the bitstream with ID. If the bitstream does not * exist, or is marked deleted, returns null. * * @param context * The current context * @param id * The ID of the bitstream to retrieve * @exception IOException * If a problem occurs while retrieving the bits * @exception SQLException * If a problem occurs accessing the RDBMS * * @return The stream of bits, or null */ public static InputStream retrieve(Context context, int id) throws SQLException, IOException { TableRow bitstream = DatabaseManager.find(context, "bitstream", id); GeneralFile file = getFile(bitstream); return (file != null) ? FileFactory.newFileInputStream(file) : null; } /** * <p> * Remove a bitstream from the asset store. This method does not delete any * bits, but simply marks the bitstreams as deleted (the context still needs * to be completed to finalize the transaction). * </p> * * <p> * If the context is aborted, the bitstreams deletion status remains * unchanged. * </p> * * @param context * The current context * @param id * The ID of the bitstream to delete * @exception SQLException * If a problem occurs accessing the RDBMS */ public static void delete(Context context, int id) throws SQLException { DatabaseManager.updateQuery(context, "update Bundle set primary_bitstream_id=null where primary_bitstream_id = ? ", id); DatabaseManager.updateQuery(context, "update Bitstream set deleted = '1' where bitstream_id = ? ", id); } /** * Clean up the bitstream storage area. This method deletes any bitstreams * which are more than 1 hour old and marked deleted. The deletions cannot * be undone. * * @param deleteDbRecords if true deletes the database records otherwise it * only deletes the files and directories in the assetstore * @exception IOException * If a problem occurs while cleaning up * @exception SQLException * If a problem occurs accessing the RDBMS */ public static void cleanup(boolean deleteDbRecords, boolean verbose) throws SQLException, IOException { Context context = null; BitstreamInfoDAO bitstreamInfoDAO = new BitstreamInfoDAO(); int commitCounter = 0; try { context = new Context(); String myQuery = "select * from Bitstream where deleted = '1'"; List<TableRow> storage = DatabaseManager.queryTable(context, "Bitstream", myQuery) .toList(); for (Iterator<TableRow> iterator = storage.iterator(); iterator.hasNext();) { TableRow row = iterator.next(); int bid = row.getIntColumn("bitstream_id"); GeneralFile file = getFile(row); // Make sure entries which do not exist are removed if (file == null || !file.exists()) { log.debug("file is null"); if (deleteDbRecords) { log.debug("deleting record"); if (verbose) { System.out.println(" - Deleting bitstream information (ID: " + bid + ")"); } bitstreamInfoDAO.deleteBitstreamInfoWithHistory(bid); if (verbose) { System.out.println(" - Deleting bitstream record from database (ID: " + bid + ")"); } DatabaseManager.delete(context, "Bitstream", bid); } continue; } // This is a small chance that this is a file which is // being stored -- get it next time. if (isRecent(file)) { log.debug("file is recent"); continue; } if (deleteDbRecords) { log.debug("deleting db record"); if (verbose) { System.out.println(" - Deleting bitstream information (ID: " + bid + ")"); } bitstreamInfoDAO.deleteBitstreamInfoWithHistory(bid); if (verbose) { System.out.println(" - Deleting bitstream record from database (ID: " + bid + ")"); } DatabaseManager.delete(context, "Bitstream", bid); } if (isRegisteredBitstream(row.getStringColumn("internal_id"))) { continue; // do not delete registered bitstreams } boolean success = file.delete(); String message = ("Deleted bitstream " + bid + " (file " + file.getAbsolutePath() + ") with result " + success); if (log.isDebugEnabled()) { log.debug(message); } if (verbose) { System.out.println(message); } // if the file was deleted then // try deleting the parents // Otherwise the cleanup script is set to // leave the db records then the file // and directories have already been deleted // if this is turned off then it still looks like the // file exists if( success ) { deleteParents(file); } // Make sure to commit our outstanding work every 100 // iterations. Otherwise you risk losing the entire transaction // if we hit an exception, which isn't useful at all for large // amounts of bitstreams. commitCounter++; if (commitCounter % 100 == 0) { System.out.print("Committing changes to the database..."); context.commit(); System.out.println(" Done!"); } } context.complete(); } // Aborting will leave the DB objects around, even if the // bitstreams are deleted. This is OK; deleting them next // time around will be a no-op. catch (SQLException sqle) { if (verbose) { System.err.println("Error: " + sqle.getMessage()); } context.abort(); throw sqle; } catch (IOException ioe) { if (verbose) { System.err.println("Error: " + ioe.getMessage()); } context.abort(); throw ioe; } } //////////////////////////////////////// // Internal methods //////////////////////////////////////// /** * Return true if this file is too recent to be deleted, false otherwise. * * @param file * The file to check * @return True if this file is too recent to be deleted */ private static boolean isRecent(GeneralFile file) { long lastmod = file.lastModified(); long now = new java.util.Date().getTime(); if (lastmod >= now) { return true; } // Less than one hour old return (now - lastmod) < (1 * 60 * 1000); } /** * Delete empty parent directories. * * @param file * The file with parent directories to delete */ private static synchronized void deleteParents(GeneralFile file) { if (file == null ) { return; } GeneralFile tmp = file; for (int i = 0; i < directoryLevels; i++) { GeneralFile directory = tmp.getParentFile(); GeneralFile[] files = directory.listFiles(); // Only delete empty directories if (files.length != 0) { break; } directory.delete(); tmp = directory; } } /** * Return the file corresponding to a bitstream. It's safe to pass in * <code>null</code>. * * @param bitstream * the database table row for the bitstream. Can be * <code>null</code> * * @return The corresponding file in the file system, or <code>null</code> * * @exception IOException * If a problem occurs while determining the file */ private static GeneralFile getFile(TableRow bitstream) throws IOException { // Check that bitstream is not null if (bitstream == null) { return null; } // Get the store to use int storeNumber = bitstream.getIntColumn("store_number"); // Default to zero ('assetstore.dir') for backwards compatibility if (storeNumber == -1) { storeNumber = 0; } GeneralFile assetstore = assetStores[storeNumber]; // turn the internal_id into a file path relative to the assetstore // directory String sInternalId = bitstream.getStringColumn("internal_id"); // there are 4 cases: // -conventional bitstream, conventional storage // -conventional bitstream, srb storage // -registered bitstream, conventional storage // -registered bitstream, srb storage // conventional bitstream - dspace ingested, dspace random name/path // registered bitstream - registered to dspace, any name/path String sIntermediatePath = null; if (isRegisteredBitstream(sInternalId)) { sInternalId = sInternalId.substring(REGISTERED_FLAG.length()); sIntermediatePath = ""; } else { // Sanity Check: If the internal ID contains a // pathname separator, it's probably an attempt to // make a path traversal attack, so ignore the path // prefix. The internal-ID is supposed to be just a // filename, so this will not affect normal operation. if (sInternalId.indexOf(File.separator) != -1) { sInternalId = sInternalId.substring(sInternalId.lastIndexOf(File.separator) + 1); } sIntermediatePath = getIntermediatePath(sInternalId); } StringBuffer bufFilename = new StringBuffer(); if (assetstore instanceof LocalFile) { bufFilename.append(assetstore.getCanonicalPath()); bufFilename.append(File.separator); bufFilename.append(sIntermediatePath); bufFilename.append(sInternalId); if (log.isDebugEnabled()) { log.debug("Local filename for " + sInternalId + " is " + bufFilename.toString()); } return new LocalFile(bufFilename.toString()); } if (assetstore instanceof SRBFile) { bufFilename.append(sIntermediatePath); bufFilename.append(sInternalId); if (log.isDebugEnabled()) { log.debug("SRB filename for " + sInternalId + " is " + ((SRBFile) assetstore).toString() + bufFilename.toString()); } return new SRBFile((SRBFile) assetstore, bufFilename.toString()); } return null; } /** * Return the intermediate path derived from the internal_id. This method * splits the id into groups which become subdirectories. * * @param iInternalId * The internal_id * @return The path based on the id without leading or trailing separators */ private static String getIntermediatePath(String iInternalId) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < directoryLevels; i++) { int digits = i * digitsPerLevel; if (i > 0) { buf.append(File.separator); } buf.append(iInternalId.substring(digits, digits + digitsPerLevel)); } buf.append(File.separator); return buf.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.dspace.storage.rdbms; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.apache.log4j.Logger; import org.dspace.browse.BrowseException; import org.dspace.browse.IndexBrowse; import org.dspace.core.ConfigurationManager; /** * Command-line executed class for initializing the DSpace database. This should * be invoked with a single argument, the filename of the database schema file. * * @author Robert Tansley * @version $Revision: 5844 $ */ public class InitializeDatabase { /** log4j category */ private static Logger log = Logger.getLogger(InitializeDatabase.class); public static void main(String[] argv) { // Usage checks if (argv.length != 1) { log.warn("Schema file not specified"); System.exit(1); } ConfigurationManager.loadConfig(null); log.info("Initializing Database"); try { if("clean-database.sql".equals(argv[0])) { try { IndexBrowse browse = new IndexBrowse(); browse.setDelete(true); browse.setExecute(true); browse.clearDatabase(); } catch (BrowseException e) { log.error(e.getMessage(),e); throw new IllegalStateException(e.getMessage(),e); } DatabaseManager.loadSql(getScript(argv[0])); } else { DatabaseManager.loadSql(getScript(argv[0])); try { IndexBrowse browse = new IndexBrowse(); browse.setRebuild(true); browse.setExecute(true); browse.initBrowse(); } catch (BrowseException e) { log.error(e.getMessage(),e); throw new IllegalStateException(e.getMessage(),e); } } System.exit(0); } catch (Exception e) { log.fatal("Caught exception:", e); System.exit(1); } } /** * Attempt to get the named script, with the following rules: * etc/<db.name>/<name> * etc/<name> * <name> */ private static FileReader getScript(String name) throws FileNotFoundException, IOException { String dbName = ConfigurationManager.getProperty("db.name"); File myFile = null; if (dbName != null) { myFile = new File("etc/" + dbName + "/" + name); if (myFile.exists()) { return new FileReader(myFile.getCanonicalPath()); } } myFile = new File("etc/" + name); if (myFile.exists()) { return new FileReader(myFile.getCanonicalPath()); } return new FileReader(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.dspace.storage.rdbms; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Represents a database row. * * @author Peter Breton * @version $Revision: 5844 $ */ public class TableRow { /** Marker object to indicate NULLs. */ private static final Object NULL_OBJECT = new Object(); /** The name of the database table containing this row */ private String table; /** * A map of column names to column values. The key of the map is a String, * the column name; the value is an Object, either an Integer, Boolean, * Date, or String. If the value is NULL_OBJECT, then the column was NULL. */ private Map<String, Object> data = new HashMap<String, Object>(); private Map<String, Boolean> changed = new HashMap<String, Boolean>(); /** * Constructor * * @param table * The name of the database table containing this row. * @param columns * A list of column names. Each member of the List is a String. * After construction, the list of columns is fixed; attempting * to access a column not in the list will cause an * IllegalArgumentException to be thrown. */ public TableRow(String table, List<String> columns) { this.table = table; for (String column : columns) { String canonicalized = ColumnInfo.canonicalize(column); data.put(canonicalized, NULL_OBJECT); changed.put(canonicalized, Boolean.TRUE); } } /** * Return the name of the table containing this row, or null if this row is * not associated with a database table. * * @return The name of the table containing this row */ public String getTable() { return table; } /** * Return true if this row contains a column with this name. * * @param column * The column name (case-insensitive) * @return True if this row contains a column with this name. */ public boolean hasColumn(String column) { try { return canonicalizeAndCheck(column) != null; } catch (IllegalArgumentException e) { return false; } } /** * Return true if this row contains this column and the value has been updated. * * @param column * The column name (case-insensitive) * @return True if this row contains a column with this name. */ public boolean hasColumnChanged(String column) { return hasColumnChangedCanonicalized(ColumnInfo.canonicalize(column)); } boolean hasColumnChangedCanonicalized(String column) { return changed.get(column) == Boolean.TRUE; } /** * Return true if the column is an SQL NULL. * * @param column * The column name (case-insensitive) * @return True if the column is an SQL NULL */ public boolean isColumnNull(String column) { return isColumnNullCanonicalized(canonicalizeAndCheck(column)); } boolean isColumnNullCanonicalized(String column) { return data.get(column) == NULL_OBJECT; } /** * Return the integer value of column. * * If the column's type is not an integer, or the column does not exist, an * IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @return The integer value of the column, or -1 if the column is an SQL * null. */ public int getIntColumn(String column) { String canonicalized = canonicalizeAndCheck(column); if (isColumnNullCanonicalized(canonicalized)) { return -1; } Object value = data.get(canonicalized); if (value == null) { throw new IllegalArgumentException("Column " + column + " not present"); } if (!(value instanceof Integer)) { throw new IllegalArgumentException("Value for " + column + " is not an integer"); } return ((Integer) value).intValue(); } /** * Return the long value of column. * * If the column's type is not an long, or the column does not exist, an * IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @return The long value of the column, or -1 if the column is an SQL null. */ public long getLongColumn(String column) { String canonicalized = canonicalizeAndCheck(column); if (isColumnNullCanonicalized(canonicalized)) { return -1; } Object value = data.get(canonicalized); if (value == null) { throw new IllegalArgumentException("Column " + column + " not present"); } // If the value is an integer, it can be represented without error as a long // So, allow the return of a long. (This is needed for Oracle support). if ((value instanceof Integer)) { return ((Integer) value).longValue(); } if (!(value instanceof Long)) { throw new IllegalArgumentException("Value for " + column + " is not a long"); } return ((Long) value).longValue(); } /** * Return the double value of column. * * If the column's type is not an float, or the column does not exist, an * IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @return The double value of the column, or -1 if the column is an SQL null. */ public double getDoubleColumn(String column) { String canonicalized = canonicalizeAndCheck(column); if (isColumnNullCanonicalized(canonicalized)) { return -1; } Object value = data.get(canonicalized); if (value == null) { throw new IllegalArgumentException("Column " + column + " not present"); } if (!(value instanceof Double)) { throw new IllegalArgumentException("Value for " + column + " is not a double"); } return ((Double) value).doubleValue(); } /** * Return the String value of column. * * If the column's type is not a String, or the column does not exist, an * IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @return The String value of the column, or null if the column is an SQL * null. */ public String getStringColumn(String column) { String canonicalized = canonicalizeAndCheck(column); if (isColumnNullCanonicalized(canonicalized)) { return null; } Object value = data.get(canonicalized); if (value == null) { throw new IllegalArgumentException("Column " + column + " not present"); } if (!(value instanceof String)) { throw new IllegalArgumentException("Value is not an string"); } return (String) value; } /** * Return the boolean value of column. * * If the column's type is not a boolean, or the column does not exist, an * IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @return The boolean value of the column, or false if the column is an SQL * null. */ public boolean getBooleanColumn(String column) { String canonicalized = canonicalizeAndCheck(column); if (isColumnNullCanonicalized(canonicalized)) { return false; } Object value = data.get(canonicalized); // make sure that we tolerate integers or booleans if (value == null) { throw new IllegalArgumentException("Column " + column + " not present"); } if ((value instanceof Boolean)) { return ((Boolean) value).booleanValue(); } else if ((value instanceof Integer)) { int i = ((Integer) value).intValue(); if (i == 0) { return false; // 0 is false } return true; // nonzero is true } else { throw new IllegalArgumentException("Value is not a boolean or an integer"); } } /** * Return the date value of column. * * If the column's type is not a date, or the column does not exist, an * IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @return - The date value of the column, or null if the column is an SQL * null. */ public java.util.Date getDateColumn(String column) { String canonicalized = canonicalizeAndCheck(column); if (isColumnNullCanonicalized(canonicalized)) { return null; } Object value = data.get(canonicalized); if (value == null) { throw new IllegalArgumentException("Column " + column + " not present"); } if (!(value instanceof java.util.Date)) { throw new IllegalArgumentException("Value is not a Date"); } return (java.util.Date) value; } /** * Set column to an SQL NULL. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) */ public void setColumnNull(String column) { String canonicalized = canonicalizeAndCheck(column); if (data.get(canonicalized) != NULL_OBJECT) { data.put(canonicalized, NULL_OBJECT); changed.put(canonicalized, Boolean.TRUE); } } /** * Set column to the boolean b. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @param b * The boolean value */ public void setColumn(String column, boolean b) { String canonicalized = canonicalizeAndCheck(column); if (DatabaseManager.isOracle()) { // if oracle, use 1 or 0 for true/false Integer value = b ? Integer.valueOf(1) : Integer.valueOf(0); if (!value.equals(data.get(canonicalized))) { data.put(canonicalized, value); changed.put(canonicalized, Boolean.TRUE); } } else { // default to postgres true/false Boolean value = b ? Boolean.TRUE : Boolean.FALSE; if (!value.equals(data.get(canonicalized))) { data.put(canonicalized, value); changed.put(canonicalized, Boolean.TRUE); } } } /** * Set column to the String s. If s is null, the column is set to null. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @param s * The String value */ public void setColumn(String column, String s) { String canonicalized = canonicalizeAndCheck(column); Object value = (s == null) ? NULL_OBJECT : s; if (!value.equals(data.get(canonicalized))) { data.put(canonicalized, value); changed.put(canonicalized, Boolean.TRUE); } } /** * Set column to the integer i. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @param i * The integer value */ public void setColumn(String column, int i) { String canonicalized = canonicalizeAndCheck(column); Integer value = Integer.valueOf(i); if (!value.equals(data.get(canonicalized))) { data.put(canonicalized, value); changed.put(canonicalized, Boolean.TRUE); } } /** * Set column to the long l. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @param l * The long value */ public void setColumn(String column, long l) { String canonicalized = canonicalizeAndCheck(column); Long value = Long.valueOf(l); if (!value.equals(data.get(canonicalized))) { data.put(canonicalized, value); changed.put(canonicalized, Boolean.TRUE); } } /** * Set column to the double d. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @param d * The double value */ public void setColumn(String column, double d) { String canonicalized = canonicalizeAndCheck(column); Double value = new Double(d); if (!value.equals(data.get(canonicalized))) { data.put(canonicalized, value); changed.put(canonicalized, Boolean.TRUE); } } /** * Set column to the date d. If the date is null, the column is set to NULL * as well. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column * The column name (case-insensitive) * @param d * The date value */ public void setColumn(String column, java.util.Date d) { String canonicalized = canonicalizeAndCheck(column); Object value = (d == null) ? NULL_OBJECT : d; if (!value.equals(data.get(canonicalized))) { data.put(canonicalized, value); changed.put(canonicalized, Boolean.TRUE); } } //////////////////////////////////////// // Utility methods //////////////////////////////////////// /** * Return a String representation of this object. * * @return String representation */ public String toString() { final String NEWLINE = System.getProperty("line.separator"); StringBuffer result; if (table==null) { result = new StringBuffer("no_table"); } else { result = new StringBuffer(table); } result.append(NEWLINE); for (Iterator iterator = data.keySet().iterator(); iterator.hasNext();) { String column = (String) iterator.next(); result.append("\t").append(column).append(" = ").append( isColumnNull(column) ? "NULL" : data.get(column)).append( NEWLINE); } return result.toString(); } /** * Return a hash code for this object. * * @return int hash of object */ public int hashCode() { return toString().hashCode(); } /** * Return true if this object equals obj, false otherwise. * * @param obj * @return true if TableRow objects are equal */ public boolean equals(Object obj) { if (!(obj instanceof TableRow)) { return false; } return data.equals(((TableRow) obj).data); } private String canonicalizeAndCheck(String column) { if (data.containsKey(column)) { return column; } String canonicalized = ColumnInfo.canonicalize(column); if (data.containsKey(canonicalized)) { return canonicalized; } throw new IllegalArgumentException("No such column " + canonicalized); } /** * package private method to reset the flags of which columns have been updated * This is used by the database manager after it has finished processing the contents * of a resultset, so that it can update only columns that have been updated. * Note that this method does not reset the values themselves, only the flags, * and should not be considered safe to call from anywhere other than the DatabaseManager. */ void resetChanged() { for (String column : changed.keySet()) { changed.put(column, Boolean.FALSE); } } }
Java