This is a merge back to trunk of Graham Triggs work to port Configurable Browse to Manakin from the sandbox.

grahamtriggs | 2007-08-01 11:55:51 -0400
  Added IBM ICU dependency
  First attempt at integrating the configurable browse patch
  First attempt at integrating the UI changes for Configurable Browse
  Configurable browse patch - web.xml
  Java code modifications from Configurable Browse patch
  JSP changes from the Configurable Browse patch
  Removed browse changes that should have been committed to the browse branch
  Documentation, config and scripts for configurable browse
  Re-adding Configurable Browse changes following merge
  Messages for the configurable browse
  Fixed use of DCDate for i18n patch
  First attempt to make xmlui compatible with the new BrowseIndex, although not fully use the configuration
  First attempt to make xmlui compatible with new Browse API. Browse basically works, but it's more costly than needs be (unnecessary Item.find()), and only works if you use the default Browse configuration.  
  Fixed problem with second level browse (items for author / subject)
  Updates xmlui components to handle BrowseItem DSOs, ArtifactBrowser now passes these directly. r407@libaxis1:  grahamtriggs | 2007-08-06 09:14:05 -0400
  Minor fixes to make class easier to use
  Fix to only display sort by options on a second level browse
  Updates the ArtifactBrowser, to replace all browse functionality with entirely customisable browse code
  Update the browse index creation on fresh_install
  Fixed problem with indexing non-archived items
  Added caching support (key generation / validity)
  Moved internal class to bottom of file
  Browse code changes
 


git-svn-id: http://scm.dspace.org/svn/repo/trunk@2116 9c30dcfa-912a-0410-8fc2-9e0234be79fd
This commit is contained in:
Mark Diggory
2007-08-06 14:39:38 +00:00
parent abd590081f
commit 97d189b828
108 changed files with 18681 additions and 7666 deletions

View File

@@ -187,5 +187,6 @@
<artifactId>activation</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,121 @@
/*
* AbstractTextFilterBOD.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import org.apache.log4j.Logger;
import org.dspace.text.filter.TextFilter;
/**
* Helper class for creating order delegates.
*
* To configure the filters create a subclass and, in an object initializer,
* create an array of classes that implement TextFilter:
*
* class MyLocaleDelegate extends AbstractTextFilterBOD {
* {
* filters = new TextFilter[] { new LocaleOrderingFilter(); }
* }
* }
*
* The order they are in the array, is the order that they are executed.
* (this may be important for some filters - read their documentation!)
*
* Example configurations that could be used:
* { new DecomposeDiactritics(), new StripDiacritics(), new LowerCaseAndTrim() }
* - Decompose and then strip the diacritics, lowercase and trim the string.
*
* { new MARC21InitialArticleWord(), new DecomposeDiactritics(), new LowerCaseTrim() }
* - Parse the initial article words based on the Library of Congress list of
* definite/indefinite article words, decompose diacritics, and lowercase/trim.
*
* { new LowerCaseTrim(), new LocaleOrderingFilter() }
* - Lowercase the string, then make a locale dependent sort text
* (note that the sort text is not human readable)
*
* @author Graham Triggs
*/
public abstract class AbstractTextFilterBOD implements BrowseOrderDelegate
{
private final static Logger log = Logger.getLogger(AbstractTextFilterBOD.class);
// Initialised in subclass in an object initializer
protected TextFilter[] filters;
/**
* Prepare the appropriate sort string for the given value in the
* given language. Languate should be supplied with the ISO-6390-1
* or ISO-639-2 standards. For example "en" or "eng".
*
* @param value the string value
* @param language the language to interpret in
*/
public String makeSortString(String value, String language)
{
if (filters == null)
{
// Log an error if the class is not configured correctly
log.error("No filters defined for " + this.getClass().getName());
}
else
{
// Normalize language into a two or three character code
if (language != null)
{
if (language.length() > 2 && language.charAt(2) == '_')
language = language.substring(0,2);
if (language.length() > 3)
language = language.substring(0,3);
}
// Iterate through filters, applying each in turn
for (int idx = 0; idx < filters.length; idx++)
{
if (language != null)
value = filters[idx].filter(value, language);
else
value = filters[idx].filter(value);
}
}
return value;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -42,11 +42,11 @@ package org.dspace.browse;
import org.apache.log4j.Logger;
import java.sql.SQLException;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import org.dspace.browse.Browse;
import org.dspace.content.Item;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Context;
@@ -129,7 +129,19 @@ public class BrowseConsumer implements Consumer
for (Iterator ai = toAdd.iterator(); ai.hasNext();)
{
Item i = (Item)ai.next();
Browse.itemAdded(ctx, i);
// FIXME: there is an exception handling problem here
try
{
// Update browse indices
IndexBrowse ib = new IndexBrowse(ctx);
ib.indexItem(i);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new SQLException(e.getMessage());
}
toUpdate.remove(i);
if (log.isDebugEnabled())
log.debug("Added browse indices for Item id="+String.valueOf(i.getID())+", hdl="+i.getHandle());
@@ -139,7 +151,19 @@ public class BrowseConsumer implements Consumer
for (Iterator ui = toUpdate.iterator(); ui.hasNext();)
{
Item i = (Item)ui.next();
Browse.itemChanged(ctx, i);
// FIXME: there is an exception handling problem here
try
{
// Update browse indices
IndexBrowse ib = new IndexBrowse(ctx);
ib.indexItem(i);
}
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.getID())+", hdl="+i.getHandle());
}

View File

@@ -0,0 +1,347 @@
/*
* BrowseCreateDAO.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.util.List;
import java.util.Map;
/**
* 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;
/**
* Insert an index record into the given table for the given item id. The value
* is the human readable value for the field, the sortValue is the normalised version
* (normalised in whatever way the caller sees fit), and 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, "Human Readable", "human readable", map);
* </code>
*
* @param table the browse table to insert the index in
* @param itemID the database id of the item being indexed
* @param value the human readable value of the index
* @param sortValue the sortable value of the index
* @param sortCols an Integer-String map of sort column numbers and values
* @throws BrowseException
*/
public void insertIndex(String table, int itemID, String value, String sortValue, Map 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 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 sortValue) throws BrowseException;
/**
* Create 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 distinctID the id of the distinct record
* @throws BrowseException
*/
public void createDistinctMapping(String table, int itemID, int distinctID) 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 testTableExistance(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 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 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 execute whether to action the create or not
* @return the instructions (SQL) that effect the indices
* @throws BrowseException
*/
public String[] createDatabaseIndices(String table, 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;
/**
* 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 indicies 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 map the name of the associated distinct mapping table
* @throws BrowseException
*/
public void pruneExcess(String table, String map) 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) throws BrowseException;
}

View File

@@ -0,0 +1,690 @@
/*
* BrowseCreateDAOOracle.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dspace.core.Context;
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 Community2Item.community_id, " + table + ".* " +
"FROM " + table + ", Community2Item " +
"WHERE " + table + ".item_id = Community2Item.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, boolean execute) throws BrowseException
{
try
{
String sortIndexName = table + "_value_idx";
String itemIndexName = table + "_item_id_idx";
String createSortIndex = "CREATE INDEX " + sortIndexName + " ON "
+ table + "(sort_value)";
String createItemIndex = "CREATE INDEX " + itemIndexName + " ON "
+ table + "(item_id)";
if (execute)
{
DatabaseManager.updateQuery(context, createSortIndex);
DatabaseManager.updateQuery(context, createItemIndex);
}
String[] array = { createSortIndex + ";", createItemIndex + ";" };
return array;
}
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#createDistinctMapping(java.lang.String, int, int)
*/
public void createDistinctMapping(String table, int itemID, int distinctID) throws BrowseException
{
try
{
TableRow tr = DatabaseManager.create(context, table);
tr.setColumn("item_id", itemID);
tr.setColumn("distinct_id", distinctID);
DatabaseManager.update(context, tr);
}
catch (SQLException e)
{
log.error("caught exception: ", e);
String msg = "problem creating distinct mapping: table=" + table + ",item-id=" + itemID + ",distinct_id=" + distinctID;
throw new BrowseException(msg, e);
}
}
/* (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, " +
"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 sortCols, boolean execute) throws BrowseException
{
try
{
StringBuffer sb = new StringBuffer();
sb.append("sort_value ");
sb.append(getSortColumnDefinition());
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 NUMBER REFERENCES item(item_id)," +
"value " + getValueColumnDefinition() + ", " +
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 = { new Integer(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#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 sortValue) throws BrowseException
{
TableRowIterator tri = null;
if (log.isDebugEnabled())
{
log.debug("getDistinctID: table=" + table + ",value=" + value + ",sortValue=" + sortValue);
}
try
{
Object[] params = { value };
String select = "SELECT id FROM " + table;
if (isValueColumnClob())
select = select + " WHERE TO_CHAR(value)=?";
else
select = select + " WHERE value=?";
tri = DatabaseManager.query(context, select, params);
int distinctID = -1;
if (!tri.hasNext())
{
distinctID = insertDistinctRecord(table, value, 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
{
tri.close();
}
}
/* (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 sortValue) throws BrowseException
{
if (log.isDebugEnabled())
{
log.debug("insertDistinctRecord: table=" + table + ",value=" + value+ ",sortValue=" + sortValue);
}
try
{
TableRow dr = DatabaseManager.create(context, table);
dr.setColumn("value", utils.truncateValue(value));
dr.setColumn("sort_value", utils.truncateSortValue(sortValue));
DatabaseManager.update(context, dr);
int distinctID = dr.getIntColumn("id");
if (log.isDebugEnabled())
{
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, String value, String sortValue, Map sortCols)
throws BrowseException
{
try
{
// create us a row in the index
TableRow row = DatabaseManager.create(context, table);
// set the primary information for the index
row.setColumn("item_id", itemID);
row.setColumn("value", utils.truncateValue(value));
row.setColumn("sort_value", utils.truncateSortValue(sortValue));
// now set the columns for the other sort values
Iterator itra = sortCols.keySet().iterator();
while (itra.hasNext())
{
Integer key = (Integer) itra.next();
String nValue = (String) sortCols.get(key);
row.setColumn("sort_" + key.toString(), utils.truncateSortValue(nValue));
}
DatabaseManager.update(context, row);
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new BrowseException(e);
}
}
/* (non-Javadoc)
* @see org.dspace.browse.BrowseCreateDAO#pruneDistinct(java.lang.String, java.lang.String)
*/
public void pruneDistinct(String table, String map) throws BrowseException
{
try
{
String query = "DELETE FROM " + table +
" WHERE id NOT IN " +
"(SELECT distinct_id FROM " + map + ")";
DatabaseManager.updateQuery(context, query);
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new BrowseException(e);
}
}
/* (non-Javadoc)
* @see org.dspace.browse.BrowseCreateDAO#pruneExcess(java.lang.String, java.lang.String)
*/
public void pruneExcess(String table, String map) throws BrowseException
{
TableRowIterator tri = null;
try
{
String query = "SELECT item_id FROM " + table + " WHERE item_id NOT IN ( SELECT item_id FROM item WHERE in_archive = true AND withrdawn = false)";
tri = DatabaseManager.query(context, query);
while (tri.hasNext())
{
TableRow row = tri.next();
String delete = "DELETE FROM " + table + " WHERE item_id = " + Integer.toString(row.getIntColumn("item_id"));
String deleteDistinct = "DELETE FROM " + map + " WHERE item_id = " + Integer.toString(row.getIntColumn("item_id"));
DatabaseManager.updateQuery(context, delete);
DatabaseManager.updateQuery(context, deleteDistinct);
}
}
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#testTableExistance(java.lang.String)
*/
public boolean testTableExistance(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;
}
}

View File

@@ -0,0 +1,636 @@
/*
* BrowseCreateDAOPostgres.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dspace.core.Context;
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 Community2Item.community_id, " + table + ".* " +
"FROM " + table + ", Community2Item " +
"WHERE " + table + ".item_id = Community2Item.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, boolean execute)
throws BrowseException
{
try
{
String sortIndexName = table + "_value_index";
String itemIndexName = table + "_item_id_idx";
String createSortIndex = "CREATE INDEX " + sortIndexName + " on "
+ table + "(sort_value);";
String createItemIndex = "CREATE INDEX " + itemIndexName + " ON "
+ table + "(item_id);";
if (execute)
{
DatabaseManager.updateQuery(context, createSortIndex);
DatabaseManager.updateQuery(context, createItemIndex);
}
String[] array = { createSortIndex, createItemIndex };
return array;
}
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#createDistinctMapping(java.lang.String, int, int)
*/
public void createDistinctMapping(String table, int itemID, int distinctID)
throws BrowseException
{
try
{
TableRow tr = DatabaseManager.create(context, table);
tr.setColumn("item_id", itemID);
tr.setColumn("distinct_id", distinctID);
DatabaseManager.update(context, tr);
}
catch (SQLException e)
{
log.error("caught exception: ", e);
String msg = "problem creating distinct mapping: table=" + table + ",item-id=" + itemID + ",distinct_id=" + distinctID;
throw new BrowseException(msg, e);
}
}
/* (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, " +
"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 sortCols, boolean execute)
throws BrowseException
{
try
{
StringBuffer sb = new StringBuffer();
sb.append("sort_value ");
sb.append(getSortColumnDefinition());
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)," +
"value " + getValueColumnDefinition() + ", " +
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 = { new Integer(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#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 sortValue)
throws BrowseException
{
TableRowIterator tri = null;
if (log.isDebugEnabled())
{
log.debug("getDistinctID: table=" + table + ",value=" + value + ",sortValue=" + sortValue);
}
try
{
Object[] params = { value };
String select = "SELECT id FROM " + table + " WHERE value = ?";
tri = DatabaseManager.query(context, select, params);
int distinctID = -1;
if (!tri.hasNext())
{
distinctID = insertDistinctRecord(table, value, 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#insertDistinctRecord(java.lang.String, java.lang.String, java.lang.String)
*/
public int insertDistinctRecord(String table, String value, String sortValue)
throws BrowseException
{
log.debug("insertDistinctRecord: table=" + table + ",value=" + value+ ",sortValue=" + sortValue);
try
{
TableRow dr = DatabaseManager.create(context, table);
dr.setColumn("value", utils.truncateValue(value));
dr.setColumn("sort_value", utils.truncateSortValue(sortValue));
DatabaseManager.update(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, String value, String sortValue, Map sortCols)
throws BrowseException
{
try
{
// create us a row in the index
TableRow row = DatabaseManager.create(context, table);
// set the primary information for the index
row.setColumn("item_id", itemID);
row.setColumn("value", utils.truncateValue(value));
row.setColumn("sort_value", utils.truncateSortValue(sortValue));
// now set the columns for the other sort values
Iterator itra = sortCols.keySet().iterator();
while (itra.hasNext())
{
Integer key = (Integer) itra.next();
String nValue = (String) sortCols.get(key);
row.setColumn("sort_" + key.toString(), utils.truncateSortValue(nValue));
}
DatabaseManager.update(context, row);
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new BrowseException(e);
}
}
/* (non-Javadoc)
* @see org.dspace.browse.BrowseCreateDAO#pruneDistinct(java.lang.String, java.lang.String)
*/
public void pruneDistinct(String table, String map)
throws BrowseException
{
try
{
String query = "DELETE FROM " + table +
" WHERE id NOT IN " +
"(SELECT distinct_id FROM " + map + ")";
DatabaseManager.updateQuery(context, query);
}
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new BrowseException(e);
}
}
/* (non-Javadoc)
* @see org.dspace.browse.BrowseCreateDAO#pruneExcess(java.lang.String, java.lang.String)
*/
public void pruneExcess(String table, String map)
throws BrowseException
{
TableRowIterator tri = null;
try
{
String query = "SELECT item_id FROM " + table + " WHERE item_id NOT IN ( SELECT item_id FROM item WHERE in_archive = true AND withdrawn = false)";
tri = DatabaseManager.query(context, query);
while (tri.hasNext())
{
TableRow row = tri.next();
String delete = "DELETE FROM " + table + " WHERE item_id = " + Integer.toString(row.getIntColumn("item_id"));
String deleteDistinct = "DELETE FROM " + map + " WHERE item_id = " + Integer.toString(row.getIntColumn("item_id"));
DatabaseManager.updateQuery(context, delete);
DatabaseManager.updateQuery(context, deleteDistinct);
}
}
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#testTableExistance(java.lang.String)
*/
public boolean testTableExistance(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 + ") ";
}
}

View File

@@ -0,0 +1,395 @@
/*
* BrowseDAO.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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 doValueQuery() throws BrowseException;
/**
* This executes a query which returns a List object containing BrowseItem objects
* represening the results of a full item browse.
*
* @return List of BrowseItem objects
* @throws BrowseException
*/
public List 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;
/**
* 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 getFocusField();
/**
* 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 setFocusField(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 getFocusValue();
/**
* 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 setFocusValue(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 values that we will be selected distinct on (only selecting
* one of each value).
*
* @return an array of values to select distinct on
*/
public String[] getDistinctValues();
/**
* Set an array of columns that will be selected distinct on (only selecting
* one of each value)
*
* @param fields an array of values to select distinct on
*/
public void selectDistinctOn(String[] fields);
/**
* 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);
/**
* Get the value which we are constraining all our browse results to contain.
*
* @return the value to which to constrain results
*/
public String getValue();
/**
* 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 setValue(String value);
/**
* Get the name of the field in which the value to constrain results is
* contained
*
* @return the name of the field
*/
public String getValueField();
/**
* Set he name of the field in which the value to constrain results is
* contained
*
* @param valueField the name of the field
*/
public void setValueField(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();
}

View File

@@ -0,0 +1,130 @@
/*
* BrowseDAOFactory.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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 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");
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,124 @@
/*
* BrowseDAOUtils.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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);
}

View File

@@ -0,0 +1,209 @@
/*
* BrowseDAOUtilsDefault.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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);
}
}

View File

@@ -0,0 +1,107 @@
/*
* BrowseDAOUtilsOracle.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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 = "...";
}
}
}

View File

@@ -0,0 +1,79 @@
/*
* BrowseDAOUtilsPostgres.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,70 @@
/*
* BrowseException.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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);
}
}

View File

@@ -0,0 +1,699 @@
/*
* BrowseIndex.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.dspace.core.ConfigurationManager;
/**
* 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 class BrowseIndex
{
/** the configuration number, as specified in the config */
private int number;
/** the name of the browse index, as specified in the config */
private String name;
/** the value of the metadata, as specified in the config */
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;
/** the message key to use to generate the UI component */
private String messageKey;
/** a three part array of the metadata bits (e.g. dc.contributor.author) */
private String[] mdBits;
/** the sort options available for this index */
private Map sortOptions = new HashMap();
/**
* 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
*/
public BrowseIndex(String definition, int number)
throws BrowseException
{
this.number = number;
String rx = "(\\w+):([\\w\\.\\*]+):(\\w+):(\\w+)";
Pattern pattern = Pattern.compile(rx);
Matcher matcher = pattern.matcher(definition);
if (!matcher.matches())
{
throw new BrowseException("Browse Index configuration is not valid: webui.browse.index." +
number + " = " + definition);
}
messageKey = name = matcher.group(1);
metadata = matcher.group(2);
datatype = matcher.group(3);
displayType = matcher.group(4);
// now load the sort options
loadSortOptions();
}
/**
* @return Returns the datatype.
*/
public String getDataType()
{
return datatype;
}
/**
* @param datatype The datatype to set.
*/
public void setDataType(String datatype)
{
this.datatype = datatype;
}
/**
* @return Returns the displayType.
*/
public String getDisplayType()
{
return displayType;
}
/**
* @param displayType The displayType to set.
*/
public void setDisplayType(String displayType)
{
this.displayType = displayType;
}
/**
* @return Returns the mdBits.
*/
public String[] getMdBits()
{
return mdBits;
}
/**
* @param mdBits The mdBits to set.
*/
public void setMdBits(String[] mdBits)
{
this.mdBits = mdBits;
}
/**
* @return Returns the messageKey.
*/
public String getMessageKey()
{
return messageKey;
}
/**
* @param messageKey The messageKey to set.
*/
public void setMessageKey(String messageKey)
{
this.messageKey = messageKey;
}
/**
* @return Returns the metadata.
*/
public String getMetadata()
{
return metadata;
}
/**
* @param metadata The metadata to set.
*/
public void setMetadata(String metadata)
{
this.metadata = metadata;
}
/**
* @return Returns the name.
*/
public String getName()
{
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return Returns the number.
*/
public int getNumber()
{
return number;
}
/**
* @param number The number to set.
*/
public void setNumber(int number)
{
this.number = number;
}
/**
* @param sortOptions The sortOptions to set.
*/
public void setSortOptions(Map sortOptions)
{
this.sortOptions = sortOptions;
}
/**
* Populate the internal array containing the bits of metadata, for
* ease of use later
*/
public void generateMdBits()
{
try
{
mdBits = interpretField(metadata, 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 circumnstances
*
* @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)
{
return BrowseIndex.getSequenceName(this.number, 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)
{
String baseName = "bi_" + number;
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
*
* @param number the index configuration number
* @param isCommunity whether this is a community constrained index (view)
* @param isCollection whether this is a collection constrainted 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
*/
public static String getTableName(int number, boolean isCommunity, boolean isCollection, boolean isDistinct, boolean isMap)
{
String baseName = "bi_" + number;
// 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 constrainted 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
*/
public String getTableName(boolean isCommunity, boolean isCollection, boolean isDistinct, boolean isMap)
{
return BrowseIndex.getTableName(number, 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 constrainted index (view)
* @return the name of the table
*/
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
*/
public String getTableName(boolean isDistinct, boolean isCommunity, boolean isCollection)
{
return getTableName(isCommunity, isCollection, isDistinct, false);
}
/**
* Get the name of the distinct map table for the given set of circumstances. This
* is the same as calling
*
* <code>
* getTableName(isCommunity, isCollection, false, true);
* </code>
*
* @param isCommunity
* @param isCollection
* @return the map table name
*/
public String getMapName(boolean isCommunity, boolean isCollection)
{
return getTableName(isCommunity, isCollection, false, true);
}
/**
* 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 getMapName()
{
return getTableName(false, false, false, true);
}
/**
* Get the name of the colum 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(datatype);
}
/**
* Is the browse index type for a date?
*
* @return true if date type, false if not
*/
public boolean isDate()
{
return "date".equals(datatype);
}
/**
* 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(datatype);
}
/**
* Is the browse index of display type single?
*
* @return true if singe, false if not
*/
public boolean isSingle()
{
return "single".equals(displayType);
}
/**
* Is the browse index of display type full?
*
* @return true if full, false if not
*/
public boolean isFull()
{
return "full".equals(displayType);
}
/**
* @return the SortOptions object for this index
*/
public Map getSortOptions()
{
return sortOptions;
}
/**
* For the specific browse index, load the sort options from
* configuration
*
* @throws BrowseException
*/
public void loadSortOptions()
throws BrowseException
{
Enumeration en = ConfigurationManager.propertyNames();
ArrayList browseIndices = new ArrayList();
String rx = "webui\\.browse\\.sort-option\\.(\\d+)";
Pattern pattern = Pattern.compile(rx);
while (en.hasMoreElements())
{
String property = (String) en.nextElement();
Matcher matcher = pattern.matcher(property);
if (matcher.matches())
{
int number = Integer.parseInt(matcher.group(1));
String option = ConfigurationManager.getProperty(property);
SortOption so = new SortOption(number, option);
sortOptions.put(new Integer(number), so);
}
}
}
/**
* @deprecated
* @return
* @throws BrowseException
*/
public static String[] tables()
throws BrowseException
{
BrowseIndex[] bis = getBrowseIndices();
ArrayList tables = new ArrayList();
for (int i = 0; i < bis.length; i++)
{
String tableName = bis[i].getTableName();
tables.add(tableName);
}
// FIXME: this complies with the old BrowseTables method, but I'm
// not really sure why it's here
tables.add("Communities2Item");
String[] returnTables = new String[tables.size()];
returnTables = (String[]) tables.toArray((String[]) returnTables);
return returnTables;
}
/**
* @deprecated
* @return
* @throws BrowseException
*/
public static Map getBrowseIndicesMap()
throws BrowseException
{
Map map = new HashMap();
BrowseIndex[] bis = getBrowseIndices();
for (int i = 0 ; i < bis.length; i++)
{
map.put(new Integer(bis[i].getNumber()), bis[i]);
}
return map;
}
/**
* 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
{
Enumeration en = ConfigurationManager.propertyNames();
ArrayList browseIndices = new ArrayList();
String rx = "webui\\.browse\\.index\\.(\\d+)";
Pattern pattern = Pattern.compile(rx);
while (en.hasMoreElements())
{
String property = (String) en.nextElement();
Matcher matcher = pattern.matcher(property);
if (matcher.matches())
{
int number = Integer.parseInt(matcher.group(1));
String definition = ConfigurationManager.getProperty(property);
BrowseIndex bi = new BrowseIndex(definition, number);
browseIndices.add(bi);
}
}
BrowseIndex[] bis = new BrowseIndex[browseIndices.size()];
bis = (BrowseIndex[]) browseIndices.toArray((BrowseIndex[]) 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
{
Enumeration en = ConfigurationManager.propertyNames();
ArrayList browseIndices = new ArrayList();
String rx = "webui\\.browse\\.index\\.(\\d+)";
Pattern pattern = Pattern.compile(rx);
while (en.hasMoreElements())
{
String property = (String) en.nextElement();
Matcher matcher = pattern.matcher(property);
if (matcher.matches())
{
int number = Integer.parseInt(matcher.group(1));
String definition = ConfigurationManager.getProperty(property);
BrowseIndex bi = new BrowseIndex(definition, number);
if (bi.getName().equals(name))
{
return bi;
}
}
}
return null;
}
/**
* 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;
}
}

View File

@@ -39,36 +39,25 @@
*/
package org.dspace.browse;
import java.sql.SQLException;
import java.util.ArrayList;
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;
/**
* The results of a Browse method call.
* The results of a Browse, including all the contextual information about
* the query, as well as the results and associated information to create
* pagable navigation.
*
* <p>
* Results are a List of objects returned from the browse; each returned object
* is either a String (for getAuthors()) or an {@link org.dspace.content.Item}
* (for all the getItems.... methods). The list is readonly, and is guaranteed
* to be non-null.
* </p>
*
* <p>
* overallPosition is the position of the first element of results within the
* Browse index. Positions begin with 0.
* </p>
*
* <p>
* total is the number of objects in the index. Note that this is a snapshot,
* which is only guaranteed to be correct at the time the browse method was
* called.
* </p>
*
* <p>
* offset is the position of the requested object within the results. This
* position is also 0-based.
* </p>
* @author Richard Jones
*/
public class BrowseInfo
{
@@ -99,6 +88,54 @@ public class BrowseInfo
*/
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;
/** 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;
/** database id of the item at the top of the next page */
private int nextItem = -1;
/** string value of the value at the top of the next page */
private String nextValue;
/** database id of the item at the top of the previous page */
private int prevItem = -1;
/** string value of the value at the top of the previous page */
private String prevValue;
/** the value upon which we are focussing */
private String focus;
/** number of resutls to display per page */
private int resultsPerPage = -1;
/** database id of the item upon which we are focussing */
private int focusItem = -1;
/** number of metadata elements to display before truncating using "et al" */
private int etAl = -1;
/**
* Constructor
*
@@ -124,6 +161,350 @@ public class BrowseInfo
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;
}
/**
* 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 id the database id of the item at the top of the next page
*/
public void setNextItem(int id)
{
this.nextItem = id;
}
/**
* @return the database id of the item at the top of the next page
*/
public int getNextItem()
{
return this.nextItem;
}
/**
* @param value the string value of the value at the top of the next page
*/
public void setNextValue(String value)
{
this.nextValue = value;
}
/**
* @return the string value of the value at the top of the next page
*/
public String getNextValue()
{
return this.nextValue;
}
/**
* @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 getPrevItem()
{
return prevItem;
}
/**
* @param prevItem The prevItem to set.
*/
public void setPrevItem(int prevItem)
{
this.prevItem = prevItem;
}
/**
* @return Returns the prevValue.
*/
public String getPrevValue()
{
return prevValue;
}
/**
* @param prevValue The prevValue to set.
*/
public void setPrevValue(String prevValue)
{
this.prevValue = prevValue;
}
/**
* @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;
}
/**
* 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
* (for the authors browse) or an {@link org.dspace.content.Item}(for the
@@ -146,16 +527,49 @@ public class BrowseInfo
return (String[]) results.toArray(new String[results.size()]);
}
/**
* @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()
public Item[] getItemResults(Context context)
throws BrowseException
{
return (Item[]) results.toArray(new Item[results.size()]);
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.
*
@@ -232,4 +646,352 @@ public class BrowseInfo
{
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 (!"".equals(nextValue) && (nextValue != null))
{
return true;
}
if (nextItem != -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 (!"".equals(prevValue) && (prevValue != null))
{
return true;
}
if (prevItem != -1)
{
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 poisition 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.isFull())
{
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: " + value);
}
if (isStartsWith())
{
sb.append(" sort column starting with: " + focus);
}
else if (hasFocus())
{
sb.append(" sort column focus: " + focus);
}
}
else if (browseIndex.isSingle())
{
sb.append("Listing single column: " + browseIndex.getMetadata());
if (isStartsWith())
{
sb.append(" sort column starting with: " + focus);
}
else if (hasFocus())
{
sb.append(" sort column focus: " + 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.isSingle() && !isSecondLevel())
{
sb.append(valueListingString());
}
else if (browseIndex.isFull() || 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())
{
if (browseIndex.isSingle() && !isSecondLevel())
{
sb.append(this.nextValue);
}
else if (browseIndex.isFull() || isSecondLevel())
{
sb.append("Item ID: " + Integer.toString(this.nextItem));
}
}
else
{
sb.append("n/a");
}
sb.append(";");
sb.append("Top of previous page: ");
if (hasPrevPage())
{
if (browseIndex.isSingle() && !isSecondLevel())
{
sb.append(this.prevValue);
}
else if (browseIndex.isFull() || isSecondLevel())
{
sb.append("Item ID: " + Integer.toString(this.prevItem));
}
}
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();
}
}

View File

@@ -0,0 +1,509 @@
/*
* BrowseItem.java
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
import org.dspace.storage.rdbms.TableRowIterator;
/**
* 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 metadata = new ArrayList();
/** database id of the item */
private int id = -1;
/** item handle */
private String handle = null;
/** query to obtain all the items from the database */
private String findAll = "SELECT * FROM item WHERE in_archive = true AND withdrawn = false";
/** query to check the existance of an item id */
private String getByID = "SELECT id FROM item WHERE item_id = ?";
/** query to get the text value of a metadata element only (qualifier is NULL) */
private String getByMetadataElement = "SELECT 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 = ?";
/** query to get the text value of a metadata element and qualifier */
private String getByMetadata = "SELECT 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 = ?";
/** query to get the text value of a metadata element with the wildcard qualifier (*) */
private String getByMetadataAnyQualifier = "SELECT 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 = ?";
/** inner item, if we really absolutely have to instantiate it */
private Item item;
/**
* 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
*/
public BrowseItem(Context context, int id)
{
this.context = context;
this.id = id;
}
/**
* Get an integer array of all the item ids in the database
*
* @return integer array of item ids
* @throws SQLException
*/
public Integer[] findAll()
throws SQLException
{
TableRowIterator tri = DatabaseManager.query(context, findAll);
ArrayList ids = new ArrayList();
while (tri.hasNext())
{
TableRow row = tri.next();
ids.add(new Integer(row.getIntColumn("item_id")));
}
Integer[] ints = new Integer[ids.size()];
return (Integer[]) ids.toArray((Integer[]) ints);
}
/**
* 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
{
// if the qualifier is a wildcard, we have to get it out of the
// database
if (Item.ANY.equals(qualifier))
{
return queryMetadata(schema, element, qualifier, lang);
}
if (!metadata.isEmpty())
{
List values = new ArrayList();
Iterator i = metadata.iterator();
while (i.hasNext())
{
DCValue dcv = (DCValue) i.next();
if (match(schema, element, qualifier, lang, dcv))
{
values.add(dcv);
}
}
if (values.isEmpty())
{
return queryMetadata(schema, element, qualifier, lang);
}
// else, Create an array of matching values
DCValue[] valueArray = new DCValue[values.size()];
valueArray = (DCValue[]) values.toArray(valueArray);
return valueArray;
}
else
{
return queryMetadata(schema, element, qualifier, lang);
}
}
/**
* Get the type of object. This object masquerates 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 elemenent, 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;
}
/**
* 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 schema
* @param element
* @param qualifier
* @param lang
* @return
* @throws SQLException
*/
public DCValue[] queryMetadata(String schema, String element, String qualifier, String lang)
throws SQLException
{
ArrayList values = new ArrayList();
TableRowIterator tri;
if (qualifier == null)
{
Object[] params = { new Integer(id), element, schema };
tri = DatabaseManager.query(context, getByMetadataElement, params);
}
else if (Item.ANY.equals(qualifier))
{
Object[] params = { new Integer(id), element, schema };
tri = DatabaseManager.query(context, getByMetadataAnyQualifier, params);
}
else
{
Object[] params = { new Integer(id), element, qualifier, schema };
tri = DatabaseManager.query(context, getByMetadata, params);
}
if (!tri.hasNext())
{
return null;
}
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");
metadata.add(dcv);
values.add(dcv);
}
DCValue[] dcvs = new DCValue[values.size()];
return (DCValue[]) values.toArray(dcvs);
}
/* (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.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)))
{
Thumbnail thumbnail = new Thumbnail(thumbnailBitstream, originalBitstream);
return thumbnail;
}
}
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;
}
}
}

View File

@@ -0,0 +1,142 @@
/*
* BrowseOrder.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dspace.core.PluginManager;
/**
* Class implementing static helpers for anywhere that interacts with the sort columns
* (ie. ItemsByAuthor.sort_author, ItemsByTitle.sort_title)
*
* This class maps index 'types' to delegates that implement the sort string creation
*
* Types can be defined or configured using the plugin manager:
*
* plugin.named.org.dspace.browse.BrowseOrderDelegate=
* org.dspace.browse.BrowseOrderTitleMarc21=title
* org.dspace.browse.BrowseOrderAuthor=author
*
* The following standard types have been defined by default, but can be reconfigured
* via the plugin manager:
*
* author = org.dspace.browse.BrowseOrderAuthor
* title = org.dspace.browse.BrowseOrderTitle
* text = org.dspace.browse.BrowseOrderText
*
* IMPORTANT - If you change any of the orderings, you need to rebuild the browse sort columns
* (ie. run 'index-all', or 'dsrun org.dspace.browse.InitializeBrowse')
*
* @author Graham Triggs
* @version $Revision: 1.0 $
*/
public class BrowseOrder
{
private final static Logger log = LogManager.getLogger(BrowseOrder.class);
public final static String AUTHOR = "author";
public final static String TITLE = "title";
public final static String TEXT = "text";
// Array of all available order delegates - avoids excessive calls to plugin manager
private final static String[] delegates = PluginManager.getAllPluginNames(BrowseOrderDelegate.class);
private final static BrowseOrderDelegate authorDelegate = new BrowseOrderAuthor();
private final static BrowseOrderDelegate titleDelegate = new BrowseOrderTitle();
private final static BrowseOrderDelegate textDelegate = new BrowseOrderText();
/**
* Generate a sort string for the given DC metadata
*/
public static String makeSortString(String value, String language, String type)
{
BrowseOrderDelegate delegate = null;
// If a named index has been supplied
if (type != null && type.length() > 0)
{
// Use a delegate if one is configured
if ((delegate = BrowseOrder.getDelegate(type)) != null)
{
return delegate.makeSortString(value, language);
}
}
// No delegates found, so apply defaults
if (type.equalsIgnoreCase(BrowseOrder.AUTHOR) && authorDelegate != null)
{
return authorDelegate.makeSortString(value, language);
}
if (type.equalsIgnoreCase(BrowseOrder.TITLE) && titleDelegate != null)
{
return titleDelegate.makeSortString(value, language);
}
if (type.equalsIgnoreCase(BrowseOrder.TEXT) && textDelegate != null)
{
return textDelegate.makeSortString(value, language);
}
return value;
}
/**
* Retrieve the named delegate
*/
private static BrowseOrderDelegate getDelegate(String name)
{
if (name != null && name.length() > 0)
{
// Check the cached array of names to see if the delegate has been configured
for (int idx = 0; idx < delegates.length; idx++)
{
if (delegates[idx].equals(name))
{
return (BrowseOrderDelegate)PluginManager.getNamedPlugin(BrowseOrderDelegate.class, name);
}
}
}
return null;
}
}

View File

@@ -0,0 +1,58 @@
/*
* BrowseOrderAuthor.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import org.dspace.text.filter.DecomposeDiactritics;
import org.dspace.text.filter.LowerCaseAndTrim;
import org.dspace.text.filter.TextFilter;
/**
* Standard author ordering delegate implementation
*
* @author Graham Triggs
*/
public class BrowseOrderAuthor extends AbstractTextFilterBOD
{
{
filters = new TextFilter[] { new DecomposeDiactritics(),
new LowerCaseAndTrim() };
}
}

View File

@@ -0,0 +1,59 @@
/*
* BrowseOrderDelegate.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
/**
* Interface for browse order delegates
*
* @author Graham Triggs
*/
public interface BrowseOrderDelegate
{
/**
* Prepare the appropriate sort string for the given value in the
* given language. Languate should be supplied with the ISO-6390-1
* or ISO-639-2 standards. For example "en" or "eng".
*
* @param value the string value
* @param language the language to interpret in
*/
public String makeSortString(String value, String language);
}

View File

@@ -0,0 +1,58 @@
/*
* BrowseOrderText.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import org.dspace.text.filter.DecomposeDiactritics;
import org.dspace.text.filter.LowerCaseAndTrim;
import org.dspace.text.filter.TextFilter;
/**
* Standard text ordering delegate implementation
*
* @author Graham Triggs
*/
public class BrowseOrderText extends AbstractTextFilterBOD
{
{
filters = new TextFilter[] { new DecomposeDiactritics(),
new LowerCaseAndTrim() };
}
}

View File

@@ -1,9 +1,9 @@
/*
* InitializeBrowse.java
* BrowseOrderTitle.java
*
* Version: $Revision$
* Version: $Revision: 1.0 $
*
* Date: $Date$
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
@@ -37,60 +37,24 @@
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.sql.SQLException;
import org.dspace.core.Context;
import org.dspace.text.filter.DecomposeDiactritics;
import org.dspace.text.filter.LowerCaseAndTrim;
import org.dspace.text.filter.StandardInitialArticleWord;
import org.dspace.text.filter.TextFilter;
/**
* Command-line tool to create Browse indexes.
* Standard title ordering delegate implementation
*
* @author Peter Breton
* @version $Revision$
* @author Graham Triggs
*/
public class InitializeBrowse
public class BrowseOrderTitle extends AbstractTextFilterBOD
{
/** Private Constructor */
private InitializeBrowse()
{
}
/**
* Creates Browse indexes, destroying the old ones.
*
* @param argv
* Command-line arguments
*/
public static void main(String[] argv)
{
Context context = null;
int status = 0;
try
{
System.out.print("Indexing all Items in DSpace....");
context = new Context();
Browse.indexAll(context);
context.complete();
System.out.println(" ... Done");
}
catch (SQLException sqle)
{
status = 1;
if (context != null)
{
context.abort();
}
System.err.println("Error: Browse index NOT created");
sqle.printStackTrace();
}
finally
{
System.exit(status);
}
}
{
filters = new TextFilter[] { new StandardInitialArticleWord(),
new DecomposeDiactritics(),
new LowerCaseAndTrim() };
}
}

View File

@@ -0,0 +1,60 @@
/*
* BrowseOrderTitleMarc21.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import org.dspace.text.filter.DecomposeDiactritics;
import org.dspace.text.filter.LowerCaseAndTrim;
import org.dspace.text.filter.MARC21InitialArticleWord;
import org.dspace.text.filter.TextFilter;
/**
* MARC 21 title ordering delegate implementation
*
* @author Graham Triggs
*/
public class BrowseOrderTitleMarc21 extends AbstractTextFilterBOD
{
{
filters = new TextFilter[] { new MARC21InitialArticleWord(),
new DecomposeDiactritics(),
new LowerCaseAndTrim() };
}
}

View File

@@ -0,0 +1,217 @@
/*
* BrowseOutput.java
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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);
}
}
}
}

View File

@@ -1,513 +0,0 @@
/*
* BrowseScope.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.core.Context;
/**
* Object which describes the desired parameters for a browse. A scope object
* contains the following:
*
* <dl>
* <dt>scope</dt>
* <dd>A {@link org.dspace.content.Community}, a
* {@link org.dspace.content.Collection}, or null. If the scope is a community
* or collection, browses return only objects within the community or
* collection.</dd>
*
* <dt>focus</dt>
* <dd>The point at which a Browse begins. This can be a String, an
* {@link org.dspace.content.Item}(given by either the Item object or its id),
* or null. <br>
* If a String, Browses begin with values lexicographically greater than or
* equal to the String. <br>
* If an Item, Browses begin with the value of the Item in the corresponding
* browse index. If the item has multiple values in the index, the behavior is
* undefined. <br>
* If null, Browses begin at the start of the index.</dd>
*
* <dt>total</dt>
* <dd>The total number of results returned from a Browse. A total of -1 means
* to return all results.</dd>
*
* <dt>numberBefore</dt>
* <dd>The maximum number of results returned previous to the focus.</dd>
* </dl>
*
* @author Peter Breton
* @version $Revision$
*/
public class BrowseScope implements Cloneable
{
/** The DSpace context */
private Context context;
/** The scope */
private Object scope;
/** The String or Item at which to start the browse. */
private Object focus;
/** Total results to return. -1 indicates all results. */
private int total;
/** Maximum number of results previous to the focus */
private int numberBefore;
// Internal variables used by Browse
/** The type of browse */
private int browseType;
/** Whether results should be ascending or descending */
private boolean ascending;
/** Whether results should be sorted */
private Boolean sort;
/**
* Create a browse scope with the given context. The default scope settings
* are:
* <ul>
* <li>Include results from all of DSpace
* <li>Start from the beginning of the given index
* <li>Return 21 total results
* <li>Return 3 values previous to focus
* </ul>
*
* @param context
* The DSpace context.
*/
public BrowseScope(Context context)
{
this.context = context;
scope = null;
focus = null;
total = 21;
numberBefore = 3;
}
/**
* Clone this object
*/
public Object clone()
{
BrowseScope clone = new BrowseScope(context);
clone.scope = scope;
clone.focus = focus;
clone.total = total;
clone.numberBefore = numberBefore;
clone.browseType = browseType;
clone.ascending = ascending;
clone.sort = sort;
return clone;
}
/**
* Set the browse scope to all of DSpace.
*/
public void setScopeAll()
{
scope = null;
}
/**
* Limit the browse to a community.
*
* @param community
* The community to browse.
*/
public void setScope(Community community)
{
scope = community;
}
/**
* Limit the browse to a collection.
*
* @param collection
* The collection to browse.
*/
public void setScope(Collection collection)
{
scope = collection;
}
/**
* Browse starts at item i. Note that if the item has more than one value
* for the given browse, the results are undefined.
*
* This setting is ignored for itemsByAuthor, byAuthor, and lastSubmitted
* browses.
*
* @param item
* The item to begin the browse at.
*/
public void setFocus(Item item)
{
focus = item;
}
/**
* Browse starts at value. If value is null, Browses begin from the start of
* the index.
*
* This setting is ignored for itemsByAuthor and lastSubmitted browses.
*
* @param value
* The value to begin the browse at.
*/
public void setFocus(String value)
{
focus = value.toLowerCase();
}
/**
* Browse starts at the item with the given id. Note that if the item has
* more than one value for the given browse index, the results are
* undefined.
*
* This setting is ignored for itemsByAuthor, byAuthor, and lastSubmitted
* browses.
*
* @param item_id
* The item to begin the browse at.
*/
public void setFocus(int item_id)
{
focus = new Integer(item_id);
}
/**
* Browse starts at beginning (default).
*/
public void noFocus()
{
focus = null;
}
/**
* Set the total returned to n. If n is -1, all results are returned.
*
* @param n
* The total number of results to return
*/
public void setTotal(int n)
{
total = n;
}
/**
* Return all results from browse.
*/
public void setTotalAll()
{
setTotal(-1);
}
/**
* Set the maximum number of results to return previous to the focus.
*
* @param n
* The maximum number of results to return previous to the focus.
*/
public void setNumberBefore(int n)
{
this.numberBefore = n;
}
////////////////////////////////////////
// Accessor methods
////////////////////////////////////////
/**
* Return the context for the browse.
*
* @return The context for the browse.
*/
public Context getContext()
{
return context;
}
/**
* Return the browse scope.
*
* @return The browse scope.
*/
public Object getScope()
{
return scope;
}
/**
* Return the browse focus. This is either an
* {@link org.dspace.content.Item}, an Integer (the Item id) or a String.
*
* @return The focus of the browse.
*/
public Object getFocus()
{
return focus;
}
/**
* Return the maximum number of results to return. A total of -1 indicates
* that all matching results should be returned.
*
* @return The maximum number of results.
*/
public int getTotal()
{
return total;
}
/**
* Return the maximum number of results to return previous to the focus.
*
* @return The maximum number of results previous to the focus.
*/
public int getNumberBefore()
{
return numberBefore;
}
/**
* Return true if there is no limit on the number of matches returned, false
* otherwise.
*/
public boolean hasNoLimit()
{
return total == -1;
}
/**
* Return true if there is a focus for the browse, false otherwise.
*/
public boolean hasFocus()
{
return focus != null;
}
////////////////////////////////////////
// Convenience methods at package scope
////////////////////////////////////////
/**
* Return true if the focus is an Item.
*/
boolean focusIsItem()
{
return (focus instanceof Item) || (focus instanceof Integer);
}
/**
* Return true if the focus is a String.
*/
boolean focusIsString()
{
return (focus instanceof String);
}
/**
* Return the focus item id.
*/
int getFocusItemId()
{
if (!focusIsItem())
{
throw new IllegalArgumentException("Focus is not an Item");
}
if (focus instanceof Integer)
{
return ((Integer) focus).intValue();
}
return ((Item) focus).getID();
}
/**
* Return the focus string value.
*/
String getFocusValue()
{
return (String) focus;
}
/**
* True if the scope is that of a collection.
*/
boolean isCollectionScope()
{
if (scope == null)
{
return false;
}
return scope instanceof Collection;
}
/**
* True if the scope is that of a community.
*/
boolean isCommunityScope()
{
if (scope == null)
{
return false;
}
return scope instanceof Community;
}
/**
* True if the scope is all of DSpace.
*/
boolean isAllDSpaceScope()
{
return scope == null;
}
////////////////////////////////////////
// Internal browse fields
////////////////////////////////////////
/**
* Return the type of browse (one of the constants in Browse).
*/
int getBrowseType()
{
return browseType;
}
void setBrowseType(int type)
{
browseType = type;
}
/**
* If true, sort the results by title. If false, sort the results by date.
* If null, do no sorting at all.
*/
Boolean getSortByTitle()
{
return sort;
}
void setSortByTitle(Boolean s)
{
this.sort = s;
}
/**
* If true, results are in ascending order. Otherwise, results are in
* descending order.
*/
boolean getAscending()
{
return ascending;
}
void setAscending(boolean a)
{
this.ascending = a;
}
/**
* Return true if this BrowseScope is equal to another object, false
* otherwise.
*
* @param obj
* The object to compare to
* @return True if this BrowseScope is equal to the other object, false
* otherwise.
*/
public boolean equals(Object obj)
{
if (!(obj instanceof BrowseScope))
{
return false;
}
BrowseScope other = (BrowseScope) obj;
return _equals(scope, other.scope) && _equals(focus, other.focus)
&& _equals(sort, other.sort) && (total == other.total)
&& (browseType == other.browseType)
&& (ascending == other.ascending)
&& (numberBefore == other.numberBefore);
}
private boolean _equals(Object first, Object second)
{
if ((first == null) && (second == null))
{
return true;
}
if ((first != null) && (second == null))
{
return false;
}
if ((first == null) && (second != null))
{
return false;
}
return first.equals(second);
}
/*
* Return a hashCode for this object.
*/
public int hashCode()
{
return new StringBuffer().append(scope).append(focus).append(total)
.append(numberBefore).append(browseType).append(ascending)
.append(sort).toString().hashCode();
}
}

View File

@@ -0,0 +1,517 @@
/*
* BrowserScope.java
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.util.Map;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Context;
/**
* 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 = "ASC";
/** the field upon which to sort */
private int sortBy;
/** the value to restrict the browse to */
private String value;
/** the language of the value to restrict the browse to */
private String valueLang;
/** the item id focus of the browse */
private int focus;
/** 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 vFocus;
/** the language of the value upon which to focus */
private String vFocusLang;
/** the browse level */
private int level = 0;
/**
* 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)
{
this.browseIndex = browseIndex;
}
/**
* @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 getFocus()
{
return focus;
}
/**
* @param focus The focus to set.
*/
public void setFocus(int focus)
{
this.focus = focus;
}
/**
* @return the value to focus on
*/
public String getValueFocus()
{
return vFocus;
}
/**
* @param value the value to focus on
*/
public void setValueFocus(String value)
{
this.vFocus = value;
}
/**
* @return the language of the value to focus on
*/
public String getValueFocusLang()
{
return vFocusLang;
}
/**
* @param valueLang the language of the value to focus on
*/
public void setValueFocusLang(String valueLang)
{
this.vFocusLang = valueLang;
}
/**
* @return Returns the order.
*/
public String getOrder()
{
return order;
}
/**
* @param order The order to set.
*/
public void setOrder(String order)
{
if (order != null && !"".equals(order))
this.order = order;
}
/**
* @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)
{
this.sortBy = sortBy;
}
/**
* Obtain the sort option
*
* @return the sort option
* @throws BrowseException
*/
public SortOption getSortOption()
throws BrowseException
{
if (sortOption == null)
{
if (browseIndex != null)
{
if (sortBy <= 0)
{
String dataType = browseIndex.getDataType();
String type = ("date".equals(dataType) ? "date" : "text");
sortOption = new SortOption(0, browseIndex.getName(), browseIndex.getMetadata(), type);
}
else
{
Map map = browseIndex.getSortOptions();
SortOption so = (SortOption) map.get(new Integer(sortBy));
sortOption = so;
}
}
}
return sortOption;
}
/**
* @return Returns the startsWith.
*/
public String getStartsWith()
{
return startsWith;
}
/**
* @param startsWith The startsWith to set.
*/
public void setStartsWith(String 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 language.
*/
public String getValueLang()
{
return valueLang;
}
/**
* @param valueLang The language to set.
*/
public void setValueLang(String valueLang)
{
this.valueLang = valueLang;
}
/**
* @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
*/
public boolean isAscending()
{
if ("ASC".equals(order))
{
return true;
}
return false;
}
/**
* @return true if has value, false if not
*/
public boolean hasValue()
{
if (value == null || "".equals(value))
{
return false;
}
return true;
}
/**
* @return true if has item focus, false if not
*/
public boolean hasFocus()
{
if (focus == -1)
{
return false;
}
return true;
}
/**
* @return true if has value focus, false if not
*/
public boolean hasValueFocus()
{
if (this.vFocus != 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;
}
}

View File

@@ -0,0 +1,108 @@
/*
* CrossLinks.java
*
* Version: $Revision: 1.9 $
*
* Date: $Date: 2005/04/20 14:23:12 $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.util.HashMap;
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 HashMap links = new HashMap();
/**
* 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 (String) links.get(metadata);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,167 @@
/*
* ItemListConfig.java
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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 metadata = new HashMap();
/** a map of column number to data type */
private Map types = new HashMap();
/** 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 = new Integer(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, new Integer(ItemListConfig.DATE));
}
else
{
types.put(key, new Integer(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 (String[]) metadata.get(new Integer(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 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;
}
}

View File

@@ -0,0 +1,168 @@
/*
* LocaleOrderingFilter.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.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 throught the elements of the collator
CollationElementIterator iter = collator.getCollationElementIterator(str);
while ((element = iter.next()) != CollationElementIterator.NULLORDER)
{
// Generate a hexadecimal string representaion 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;
}
}

View File

@@ -0,0 +1,265 @@
/*
* SortOption.java
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class to mediate with the sort configuration
*
* @author Richard Jones
*
*/
public class SortOption
{
/** the sort configuration number */
private int number;
/** the name of the sort */
private String name;
/** the metadata field to sort on */
private String metadata;
/** the type of data we are sorting by */
private String type;
/** the metadata broken down into bits for convenience */
private String[] mdBits;
/**
* Construct a new SortOption object with the given parameters
*
* @param number
* @param name
* @param md
* @param type
* @throws BrowseException
*/
public SortOption(int number, String name, String md, String type)
throws BrowseException
{
this.name = name;
this.type = type;
this.metadata = md;
this.number = number;
generateMdBits();
}
/**
* Construct a new SortOption object using the definition from the configuration
*
* @param number
* @param definition
* @throws BrowseException
*/
public SortOption(int number, String definition)
throws BrowseException
{
this.number = number;
String rx = "(\\w+):([\\w\\.\\*]+):(\\w+)";
Pattern pattern = Pattern.compile(rx);
Matcher matcher = pattern.matcher(definition);
if (!matcher.matches())
{
throw new BrowseException("Sort Order configuration is not valid: webui.browse.sort-order." +
number + " = " + definition);
}
name = matcher.group(1);
metadata = matcher.group(2);
type = matcher.group(3);
generateMdBits();
}
/**
* @return Returns the metadata.
*/
public String getMetadata()
{
return metadata;
}
/**
* @param metadata The metadata to set.
*/
public void setMetadata(String metadata)
{
this.metadata = metadata;
}
/**
* @return Returns the name.
*/
public String getName()
{
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return Returns the type.
*/
public String getType()
{
return type;
}
/**
* @param type The type to set.
*/
public void setType(String type)
{
this.type = type;
}
/**
* @return Returns the number.
*/
public int getNumber()
{
return number;
}
/**
* @param number The number to set.
*/
public void setNumber(int number)
{
this.number = number;
}
/**
* @return a 3 element array of the metadata bits
*/
public String[] getMdBits()
{
return mdBits;
}
/**
* Tell the class to generate the metadata bits
*
* @throws BrowseException
*/
public void generateMdBits()
throws BrowseException
{
try
{
mdBits = interpretField(metadata, null);
}
catch(IOException e)
{
throw new BrowseException(e);
}
}
/**
* 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;
}
/**
* Is this a date field
*
* @return
*/
public boolean isDate()
{
if (type != null)
{
if ("date".equals(type))
{
return true;
}
}
return false;
}
/**
* Is the default sort option
*
* @return
*/
public boolean isDefault()
{
if (number == 0)
{
return true;
}
return false;
}
}

View File

@@ -0,0 +1,100 @@
/*
* Thumbnail.java
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.browse;
import org.dspace.content.Bitstream;
/**
* Wrapper class for bitstreams with Thumbnails associated with them for
* convenience in the browse system
*
* @author Richard Jones
*
*/
public class Thumbnail
{
/** the bitstream that is actually the thumbnail */
private Bitstream thumb;
/** the original bitstream for which this is the thumbnail */
private Bitstream original;
/**
* Construct a new thumbnail using the two bitstreams
*
* @param thumb the thumbnail bitstream
* @param original the original bitstream
*/
public Thumbnail(Bitstream thumb, Bitstream original)
{
this.thumb = thumb;
this.original = original;
}
/**
* @return Returns the original.
*/
public Bitstream getOriginal()
{
return original;
}
/**
* @param original The original to set.
*/
public void setOriginal(Bitstream original)
{
this.original = original;
}
/**
* @return Returns the thumb.
*/
public Bitstream getThumb()
{
return thumb;
}
/**
* @param thumb The thumb to set.
*/
public void setThumb(Bitstream thumb)
{
this.thumb = thumb;
}
}

View File

@@ -3,19 +3,26 @@
<head>
<!--
Author: Peter Breton
Author: Richard Jones
Version: $Revision$
Date: $Date$
-->
</head>
<body bgcolor="white">
<p>
Provides classes and methods for browsing Items in DSpace by title, author,
date, or subject. The main class is <a href="Browse.html">Browse</a>.
Callers of the API use <a href="BrowseScope.html">BrowseScope</a>
objects to describe the desired browse; the results are returned as
<a href="BrowseInfo.html">BrowseInfo</a> objects.
Provides classes and mehtods for browsing Items in DSpace by whatever
is specified in the configuration. The standard method by which you
would perform a browse is as follows:
</p>
<ul>
<li>Create a <a href="BrowserScope.html">BrowserScope</a> object. This object holds all of the parameters
of your browse request</li>
<li>Pass the <a href="BrowserScope.html">BrowserScope</a> object into the <a href="BrowseEngine.html">BrowseEngine</a> object.
This object should be invoked through either the browse() method or the browseMini() method</li>
<li>The <a href="BrowseEngine.html">BrowseEngine</a> will pass back a <a href="BrowseInfo.html">BrowseInfo</a> object which contains all the relevant details of your request</li>
</ul>
<p>
Browses only return archived Items; other Items (eg, those
in the workflow system) are ignored.
@@ -27,21 +34,27 @@ in the workflow system) are ignored.
An example use of the Browse API is shown below:
<pre>
// Create or obtain a context object
Context context;
Context context = new Context();
// Create a BrowseScope object within the context
BrowseScope scope = new BrowseScope(context);
BrowserScope scope = new BrowserScope(context);
// The browse is limited to the test collection
Collection test;
scope.setScope(test);
Collection test = Collection.find(context, someID);
scope.setBrowseContainer(test);
// Set the focus
scope.setFocus("Test Title");
// A maximum of 30 items will be returned
scope.setTotal(30);
// Up to 5 Items with titles before Test Title
scope.setNumberBefore(5);
scope.setResultsPerPage(30);
// set ordering to DESC
scope.setOrder("DESC");
BrowseInfo results = Browse.getItemsByTitle(scope);
// now execute the browse
BrowseEngine be = new BrowseEngine();
BrowseInfo results = be.browse(scope);
</pre>
</p>
@@ -65,65 +78,29 @@ Thesis and Antithesis
<h2>Browse Indexes</h2>
<p>
The Browse API uses database tables to index Items by title, author,
date of issue,date of accession, or subject keywords. When an Item is added to DSpace,
modified, or removed from DSpace via the
The Browse API uses database tables to index Items based on the supplied
configuration. When an Item is added to DSpace, modified or removed via the
<a href="../content/package-summary.html">Content Management API</a>, the
indexes are automatically updated.
</p>
<p>
The mapping between the indexes and Dublin Core values is:
To rebuild the database tables for the browse (on configuration change), or
to re-index just the contents of the existing tables, use the following
commands from <a href="IndexBrowse.html">IndexBrowse</a>:
</p>
<table>
<p>A complete rebuild of the database and the indices:</p>
<tr>
<th align="left">Index</th>
<th align="left">Element</th>
<th align="left">Qualifier</th>
</tr>
<pre>
[dspace]/dsrun org.dspace.browse.IndexBrowse -f -r
</pre>
<tr>
<td>Title</td>
<td>title</td>
<td>none</td>
</tr>
<p>A complete re-index of the archive contents:</p>
<tr>
<td>Author</td>
<td>contributor</td>
<td>(any)</td>
</tr>
<tr>
<td>Date</td>
<td>date</td>
<td>issued</td>
</tr>
</table>
</p>
<p>
You should not attempt to manipulate the tables which contain the
items, metadata values, or indexes via direct database manipulation
(eg, with SQL statements), because doing so incorrectly may corrupt
the indexes. If the indexes somehow become corrupted, however, running
the InitializeBrowse command-line tool will rebuild them:
</p>
<code>java org.dspace.browse.InitializeBrowse</code>
<p>
<!--
FIXME Should reference either the documentation for index-all
or for command-line tools
-->
Note that the <em>index-all</em> command-line tool rebuilds both the
Browse and Search indexes.
</p>
<pre>
[dspace]/dsrun org.dspace.browse.IndexBrowse -i
</pre>
</body>
</html>

View File

@@ -52,7 +52,8 @@ import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseException;
import org.dspace.browse.IndexBrowse;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
@@ -987,31 +988,41 @@ public class Collection extends DSpaceObject
// Remove items
ItemIterator items = getAllItems();
while (items.hasNext())
try
{
Item item = items.next();
if (item.isOwningCollection(this))
{
int itemId = item.getID();
// the collection to be deletd is the owning collection, thus remove
// the item from all collections it belongs to
Collection[] collections = item.getCollections();
for (int i=0; i< collections.length; i++)
{
//notify Browse of removing item.
Browse.itemRemoved(ourContext, itemId);
collections[i].removeItem(item);
}
}
// the item was only mapped to this collection, so just remove it
else
{
//notify Browse of removing item mapping.
Browse.itemChanged(ourContext, item);
removeItem(item);
}
while (items.hasNext())
{
Item item = items.next();
IndexBrowse ib = new IndexBrowse(ourContext);
if (item.isOwningCollection(this))
{
// the collection to be deletd is the owning collection, thus remove
// the item from all collections it belongs to
Collection[] collections = item.getCollections();
for (int i=0; i< collections.length; i++)
{
//notify Browse of removing item.
ib.itemRemoved(item);
// Browse.itemRemoved(ourContext, itemId);
collections[i].removeItem(item);
}
}
// the item was only mapped to this collection, so just remove it
else
{
//notify Browse of removing item mapping.
ib.indexItem(item);
// Browse.itemChanged(ourContext, item);
removeItem(item);
}
}
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
// Delete bitstream logo

View File

@@ -55,7 +55,8 @@ import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseException;
import org.dspace.browse.IndexBrowse;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
@@ -1699,8 +1700,19 @@ public class Item extends DSpaceObject
**/
if (isArchived())
{
// Remove from Browse indices
Browse.itemRemoved(ourContext, getID());
// FIXME: there is an exception handling problem here
try
{
// Remove from indicies
IndexBrowse ib = new IndexBrowse(ourContext);
ib.itemRemoved(this);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new SQLException(e.getMessage());
}
}
// Delete the Dublin Core

View File

@@ -45,7 +45,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseOrder;
/**
* Compare two Items by their DCValues.
@@ -256,6 +256,6 @@ public class ItemComparator implements Comparator
return value.value;
}
return Browse.getNormalizedTitle(value.value, value.language);
return BrowseOrder.makeSortString(value.value, value.language, BrowseOrder.TITLE);
}
}

View File

@@ -0,0 +1,75 @@
/*
* CollectionHomeProcessor.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.plugin;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.core.Context;
/**
* Interface that must be implemented by any plugin wanting to be called at
* the inception of the Community home page (in HandleServlet). Classes that implement the process method
* and appear in the configuration will be run before the at the start of preparing the community home page has any
* chance to continue its execution
*
* @author Richard Jones
*
*/
public interface CollectionHomeProcessor
{
/**
* execute the process
*
* @param context the DSpace context
* @param request the HTTP request
* @param response the HTTP response
* @param community The community object whose home page we are on
*
* @throws PluginException any particular problem with the plugin execution
* @throws AuthorizeException Authorisation errors during plugin execution
*/
void process(Context context, HttpServletRequest request,
HttpServletResponse response, Collection collection)
throws PluginException, AuthorizeException;
}

View File

@@ -0,0 +1,75 @@
/*
* CommunityHomeProcessor.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.plugin;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Community;
import org.dspace.core.Context;
/**
* Interface that must be implemented by any plugin wanting to be called at
* the inception of the Community home page (in HandleServlet). Classes that implement the process method
* and appear in the configuration will be run before the at the start of preparing the community home page has any
* chance to continue its execution
*
* @author Richard Jones
*
*/
public interface CommunityHomeProcessor
{
/**
* execute the process
*
* @param context the DSpace context
* @param request the HTTP request
* @param response the HTTP response
* @param community The community object whose home page we are on
*
* @throws PluginException any particular problem with the plugin execution
* @throws AuthorizeException Authorisation errors during plugin execution
*/
void process(Context context, HttpServletRequest request,
HttpServletResponse response, Community community)
throws PluginException, AuthorizeException;
}

View File

@@ -0,0 +1,92 @@
/*
* PluginException.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.plugin;
import java.lang.Exception;
/**
* General exception class for all code that runs as a plugin in DSpace
*
* @author Richard Jones
*
*/
public class PluginException extends Exception
{
/**
* basic constructor
*
*/
public PluginException()
{
super();
}
/**
* Construct an exception with the passed message
*
* @param message a message for the exception
*/
public PluginException(String message)
{
super(message);
}
/**
* Construct an exception with the passed message to encapsulate
* the passed Throwable
*
* @param message a message for the exception
* @param e throwable which triggered this exception
*/
public PluginException(String message, Throwable e)
{
super(message, e);
}
/**
* Construct an exception to encapsulate the passed Throwable
*
* @param e the throwable which triggered this exception
*/
public PluginException(Throwable e)
{
super(e);
}
}

View File

@@ -0,0 +1,61 @@
/*
* DecomposeDiacritics.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
import com.ibm.icu.text.Normalizer;
/**
* Decompose diacritic characters to character + diacritic
*
* @author Graham Triggs
*/
public class DecomposeDiactritics implements TextFilter
{
public String filter(String str)
{
return Normalizer.normalize(str, Normalizer.NFD);
}
public String filter(String str, String lang)
{
return Normalizer.normalize(str, Normalizer.NFD);
}
}

View File

@@ -0,0 +1,214 @@
/*
* InitialArticleWord.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
/**
* Abstract class for implementing initial article word filters
* Allows you to create new classes with their own rules for mapping
* languages to article word lists.
*
* @author Graham Triggs
*/
public abstract class InitialArticleWord implements TextFilter
{
/**
* When no language is passed, just return the string
*/
public String filter(String str)
{
return str;
}
/**
* Do an initial definite/indefinite article filter on the passed string.
* On matching an initial word, can strip or move to the end, depending on the
* configuration of the implementing class.
*
* @param str The string to parse
* @param lang The language of the passed string
* @return String The filtered string
*/
public String filter(String str, String lang)
{
// Get the list of article words for this language
String[] articleWordArr = getArticleWords(lang);
// If we have an article word array, process the string
if (articleWordArr != null && articleWordArr.length > 0)
{
String initialArticleWord = null;
int curPos = 0;
int initialStart = -1;
int initialEnd = -1;
// Iterate through the characters until we find something significant, or hit the end
while (initialEnd < 0 && curPos < str.length())
{
// Have we found a significant character
if (Character.isLetterOrDigit(str.charAt(curPos)) || str.charAt(curPos) == '\'')
{
// Mark this as the cut point for the initial word
initialStart = curPos;
// Loop through the article words looking for a match
for (int idx = 0; initialEnd < 0 && idx < articleWordArr.length; idx++)
{
// Extract a fragment from the string to test
// Must be same length as the article word
if (idx > 1 && initialArticleWord != null)
{
// Only need to do so if we haven't already got one
// of the right length
if (initialArticleWord.length() != articleWordArr[idx].length())
initialArticleWord = extractText(str, curPos, articleWordArr[idx].length());
}
else
{
initialArticleWord = extractText(str, curPos, articleWordArr[idx].length());
}
// Does the fragment match an article word?
if (initialArticleWord!= null && initialArticleWord.equalsIgnoreCase(articleWordArr[idx]))
{
// Check to see if the next character in the source
// is a whitespace
boolean isNextWhitespace = Character.isWhitespace(
str.charAt(curPos + articleWordArr[idx].length())
);
// Check to see if the last character of the article word is a letter or digit
boolean endsLetterOrDigit = Character.isLetterOrDigit(initialArticleWord.charAt(initialArticleWord.length() - 1));
// If the last character of the article word is a letter or digit,
// then it must be followed by whitespace, if not, it can be anything
// Setting endPos signifies that we have found an article word
if (endsLetterOrDigit && isNextWhitespace)
initialEnd = curPos + initialArticleWord.length();
else if (!endsLetterOrDigit)
initialEnd = curPos + initialArticleWord.length();
}
}
// Quit the loop, as we have a significant character
break;
}
// Keep going
curPos++;
}
// If endPos is positive, then we've found an article word
if (initialEnd > 0)
{
// Find a cut point in the source string, removing any whitespace after the article word
int cutPos = initialEnd;
while (cutPos < str.length() && Character.isWhitespace(str.charAt(cutPos)))
cutPos++;
// Are we stripping the article word?
if (stripInitialArticle)
{
// Yes, simply return everything after the cut
return str.substring(cutPos);
}
else
{
// No - move the initial article word to the end
return new StringBuffer(str.substring(cutPos))
.append(wordSeperator)
.append(str.substring(initialStart, initialEnd))
.toString();
}
}
}
// Didn't do any processing, or didn't find an initial article word
// Return the original string
return str;
}
protected InitialArticleWord(boolean stripWord)
{
stripInitialArticle = stripWord;
}
protected InitialArticleWord()
{
stripInitialArticle = false;
}
/**
* Abstract method to get the list of words to use in the initial word filter
*
* @param lang The language to retrieve article words for
* @return An array of definite/indefinite article words
*/
protected abstract String[] getArticleWords(String lang);
// Seperator to use when appending article to end
private String wordSeperator = ", ";
// Flag to signify initial article word should be removed
// If false, then the initial article word is appended to the end
private boolean stripInitialArticle = false;
/**
* Helper method to extract text from a string.
* Ensures that there is significant data (ie. non-whitespace)
* after the segment requested.
*
* @param str
* @param pos
* @param len
* @return
*/
private String extractText(String str, int pos, int len)
{
int testPos = pos + len;
while (testPos < str.length() && Character.isWhitespace(str.charAt(testPos)))
testPos++;
if (testPos < str.length())
return str.substring(pos, pos + len);
return null;
}
}

View File

@@ -0,0 +1,185 @@
/*
* LanguageCodes.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
import java.util.HashMap;
import java.util.Map;
/**
* Define languages - both as IANA and ISO639-2 codes
*
* @author Graham Triggs
*/
public class Language
{
public final String IANA;
public final String ISO639_1;
public final String ISO639_2;
public static Language AFRIKAANS = Language.create("af", "af", "afr");
public static Language ALBANIAN = Language.create("sq", "sq", "alb");
public static Language ARABIC = Language.create("ar", "ar", "ara");
public static Language BALUCHI = Language.create("bal", "", "bal");
public static Language BASQUE = Language.create("eu", "", "baq");
public static Language BRAHUI = Language.create("", "", "");
public static Language CATALAN = Language.create("ca", "ca", "cat");
public static Language CLASSICAL_GREEK = Language.create("grc", "", "grc");
public static Language DANISH = Language.create("da", "da", "dan");
public static Language DUTCH = Language.create("nl", "ni", "dut");
public static Language ENGLISH = Language.create("en", "en", "eng");
public static Language ESPERANTO = Language.create("eo", "eo", "epo");
public static Language FRENCH = Language.create("fr", "fr", "fre");
public static Language FRISIAN = Language.create("fy", "fy", "fri");
public static Language GALICIAN = Language.create("gl", "gl", "glg");
public static Language GERMAN = Language.create("de", "de", "ger");
public static Language GREEK = Language.create("el", "el", "gre");
public static Language HAWAIIAN = Language.create("haw", "", "haw");
public static Language HEBREW = Language.create("he", "he", "heb");
public static Language HUNGARIAN = Language.create("hu", "hu", "hun");
public static Language ICELANDIC = Language.create("is", "is", "ice");
public static Language IRISH = Language.create("ga", "ga", "gle");
public static Language ITALIAN = Language.create("it", "it", "ita");
public static Language MALAGASY = Language.create("mg", "mg", "mlg");
public static Language MALTESE = Language.create("mt", "mt", "mlt");
public static Language NEAPOLITAN_ITALIAN = Language.create("nap", "", "nap");
public static Language NORWEGIAN = Language.create("no", "no", "nor");
public static Language PORTUGUESE = Language.create("pt", "pt", "por");
public static Language PANJABI = Language.create("pa", "pa", "pan");
public static Language PERSIAN = Language.create("fa", "fa", "per");
public static Language PROVENCAL = Language.create("pro", "", "pro");
public static Language PROVENCAL_OCCITAN = Language.create("oc", "oc", "oci");
public static Language ROMANIAN = Language.create("ro", "ro", "rum");
public static Language SCOTS = Language.create("sco", "", "sco");
public static Language SCOTTISH_GAELIC = Language.create("gd", "gd", "gae");
public static Language SHETLAND_ENGLISH = Language.create("", "", "");
public static Language SPANISH = Language.create("es", "es", "spa");
public static Language SWEDISH = Language.create("sv", "sv", "swe");
public static Language TAGALOG = Language.create("tl", "tl", "tgl");
public static Language TURKISH = Language.create("tr", "tr", "tur");
public static Language URDU = Language.create("ur", "ur", "urd");
public static Language WALLOON = Language.create("wa", "wa", "wln");
public static Language WELSH = Language.create("cy", "cy", "wel");
public static Language YIDDISH = Language.create("yi", "yi", "yid");
public static Language getLanguage(String lang)
{
return LanguageMaps.getLanguage(lang);
}
public static Language getLanguageForIANA(String iana)
{
return LanguageMaps.getLanguageForIANA(iana);
}
public static Language getLanguageForISO639_2(String iso)
{
return LanguageMaps.getLanguageForISO639_2(iso);
}
private static synchronized Language create(String iana, String iso639_1, String iso639_2)
{
Language lang = null;
lang = (lang != null ? lang : LanguageMaps.getLanguageForIANA(iana));
lang = (lang != null ? lang : LanguageMaps.getLanguageForISO639_1(iso639_1));
lang = (lang != null ? lang : LanguageMaps.getLanguageForISO639_2(iso639_2));
return (lang != null ? lang : new Language(iana, iso639_1, iso639_2));
}
private static class LanguageMaps
{
private static final Map langMapIANA = new HashMap();
private static final Map langMapISO639_1 = new HashMap();
private static final Map langMapISO639_2 = new HashMap();
static void add(Language l)
{
if (l.IANA != null && l.IANA.length() > 0 && !langMapIANA.containsKey(l.IANA))
langMapIANA.put(l.IANA, l);
if (l.ISO639_1 != null && l.ISO639_1.length() > 0 && !langMapISO639_1.containsKey(l.ISO639_1))
langMapISO639_1.put(l.ISO639_1, l);
if (l.ISO639_2 != null && l.ISO639_2.length() > 0 && !langMapISO639_2.containsKey(l.ISO639_2))
langMapISO639_2.put(l.ISO639_2, l);
}
public static Language getLanguage(String lang)
{
if (langMapIANA.containsKey(lang))
return (Language)langMapIANA.get(lang);
return (Language)langMapISO639_2.get(lang);
}
public static Language getLanguageForIANA(String iana)
{
return (Language)langMapIANA.get(iana);
}
public static Language getLanguageForISO639_1(String iso)
{
return (Language)langMapISO639_1.get(iso);
}
public static Language getLanguageForISO639_2(String iso)
{
return (Language)langMapISO639_2.get(iso);
}
}
private Language(String iana, String iso639_1, String iso639_2)
{
IANA = iana;
ISO639_1 = iso639_1;
ISO639_2 = iso639_2;
LanguageMaps.add(this);
}
private Language()
{
IANA = null;
ISO639_1 = null;
ISO639_2 = null;
}
}

View File

@@ -0,0 +1,61 @@
/*
* LowerCaseAndTrim.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
/**
* Lowercase and trim leading / trailing whitespace
*
* @author Graham Triggs
*/
public class LowerCaseAndTrim implements TextFilter
{
public String filter(String str)
{
return str.toLowerCase().trim();
}
public String filter(String str, String lang)
{
return str.toLowerCase().trim();
}
}

View File

@@ -0,0 +1,327 @@
/*
* MARC21InitialArticleWord.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Implements MARC 21 standards to disregard initial
* definite or indefinite article in sorting.
*
* Note: This only works for languages defined with IANA code entries.
*
* @author Graham Triggs
*/
public class MARC21InitialArticleWord extends InitialArticleWord
{
public MARC21InitialArticleWord()
{
// Default behaviour is to strip the initial word completely
super(true);
}
public MARC21InitialArticleWord(boolean stripWord)
{
super(stripWord);
}
/**
* Return the list of definite and indefinite article codes
* for this language.
*/
protected String[] getArticleWords(String lang)
{
// No language - no words
if (lang == null)
return null;
Language l = Language.getLanguage(lang);
// Is the lanugage in our map?
if (l != null && ianaArticleMap.containsKey(l.IANA))
{
// Get the list of words for this language
ArticlesForLang articles = (ArticlesForLang)ianaArticleMap.get(l.IANA);
if (articles != null)
return articles.words;
}
return null;
}
// Mapping of IANA codes to article word lists
private static Map ianaArticleMap = new HashMap();
// Static initialisation - convert word -> languages map
// into language -> words map
static
{
/* Define a mapping for article words to the languages that have them.
* Take from: http://www.loc.gov/marc/bibliographic/bdapp-e.html
*/
Object[][] articleWordArray = {
{ "a", Language.ENGLISH, Language.GALICIAN, Language.HUNGARIAN, Language.PORTUGUESE, Language.ROMANIAN, Language.SCOTS, Language.YIDDISH },
{ "a'", Language.SCOTTISH_GAELIC },
{ "al", Language.ROMANIAN },
{ "al-", Language.ARABIC, Language.BALUCHI, Language.BRAHUI, Language.PANJABI, Language.PERSIAN, Language.TURKISH, Language.URDU },
{ "am", Language.SCOTTISH_GAELIC },
{ "an", Language.ENGLISH, Language.IRISH, Language.SCOTS, Language.SCOTTISH_GAELIC, Language.YIDDISH },
{ "an t-", Language.IRISH, Language.SCOTTISH_GAELIC },
{ "ane", Language.SCOTS },
{ "ang", Language.TAGALOG },
{ "ang mga", Language.TAGALOG },
{ "as", Language.GALICIAN, Language.PORTUGUESE },
{ "az", Language.HUNGARIAN },
{ "bat", Language.BASQUE },
{ "bir", Language.TURKISH },
{ "d'", Language.ENGLISH },
{ "da", Language.SHETLAND_ENGLISH },
{ "das", Language.GERMAN },
{ "de", Language.DANISH, Language.DUTCH, Language.ENGLISH, Language.FRISIAN, Language.NORWEGIAN, Language.SWEDISH },
{ "dei", Language.NORWEGIAN },
{ "dem", Language.GERMAN },
{ "den", Language.DANISH, Language.GERMAN, Language.NORWEGIAN, Language.SWEDISH },
{ "der", Language.GERMAN, Language.YIDDISH },
{ "des", Language.GERMAN, Language.WALLOON },
{ "det", Language.DANISH, Language.NORWEGIAN, Language.SWEDISH },
{ "di", Language.YIDDISH },
{ "die", Language.AFRIKAANS, Language.GERMAN, Language.YIDDISH },
{ "dos", Language.YIDDISH },
{ "e", Language.NORWEGIAN },
{ "'e", Language.FRISIAN },
{ "een", Language.DUTCH },
{ "eene", Language.DUTCH },
{ "egy", Language.HUNGARIAN },
{ "ei", Language.NORWEGIAN },
{ "ein", Language.GERMAN, Language.NORWEGIAN, Language.WALLOON },
{ "eine", Language.GERMAN },
{ "einem", Language.GERMAN },
{ "einen", Language.GERMAN },
{ "einer", Language.GERMAN },
{ "eines", Language.GERMAN },
{ "eit", Language.NORWEGIAN },
{ "el", Language.CATALAN, Language.SPANISH },
{ "el-", Language.ARABIC },
{ "els", Language.CATALAN },
{ "en", Language.CATALAN, Language.DANISH, Language.NORWEGIAN, Language.SWEDISH },
{ "enne", Language.WALLOON },
{ "et", Language.DANISH, Language.NORWEGIAN },
{ "ett", Language.SWEDISH },
{ "eyn", Language.YIDDISH },
{ "eyne", Language.YIDDISH },
{ "gl'", Language.ITALIAN },
{ "gli", Language.PROVENCAL },
{ "ha-", Language.HEBREW },
{ "hai", Language.CLASSICAL_GREEK, Language.GREEK },
{ "he", Language.HAWAIIAN },
{ "h\u0113", Language.CLASSICAL_GREEK, Language.GREEK }, // e macron
{ "he-", Language.HEBREW },
{ "heis", Language.GREEK },
{ "hen", Language.GREEK },
{ "hena", Language.GREEK },
{ "henas", Language.GREEK },
{ "het", Language.DUTCH },
{ "hin", Language.ICELANDIC },
{ "hina", Language.ICELANDIC },
{ "hinar", Language.ICELANDIC },
{ "hinir", Language.ICELANDIC },
{ "hinn", Language.ICELANDIC },
{ "hinna", Language.ICELANDIC },
{ "hinnar", Language.ICELANDIC },
{ "hinni", Language.ICELANDIC },
{ "hins", Language.ICELANDIC },
{ "hinu", Language.ICELANDIC },
{ "hinum", Language.ICELANDIC },
{ "hi\u01d2", Language.ICELANDIC },
{ "ho", Language.CLASSICAL_GREEK, Language.GREEK },
{ "hoi", Language.CLASSICAL_GREEK, Language.GREEK },
{ "i", Language.ITALIAN },
{ "ih'", Language.PROVENCAL },
{ "il", Language.ITALIAN, Language.PROVENCAL_OCCITAN },
{ "il-", Language.MALTESE },
{ "in", Language.FRISIAN },
{ "it", Language.FRISIAN },
{ "ka", Language.HAWAIIAN },
{ "ke", Language.HAWAIIAN },
{ "l'", Language.CATALAN, Language.FRENCH, Language.ITALIAN, Language.PROVENCAL_OCCITAN, Language.WALLOON },
{ "l-", Language.MALTESE },
{ "la", Language.CATALAN, Language.ESPERANTO, Language.FRENCH, Language.ITALIAN, Language.PROVENCAL_OCCITAN, Language.SPANISH },
{ "las", Language.PROVENCAL_OCCITAN, Language.SPANISH },
{ "le", Language.FRENCH, Language.ITALIAN, Language.PROVENCAL_OCCITAN },
{ "les", Language.CATALAN, Language.FRENCH, Language.PROVENCAL_OCCITAN, Language.WALLOON },
{ "lh", Language.PROVENCAL_OCCITAN },
{ "lhi", Language.PROVENCAL_OCCITAN },
{ "li", Language.PROVENCAL_OCCITAN },
{ "lis", Language.PROVENCAL_OCCITAN },
{ "lo", Language.ITALIAN, Language.PROVENCAL_OCCITAN, Language.SPANISH },
{ "los", Language.PROVENCAL_OCCITAN, Language.SPANISH },
{ "lou", Language.PROVENCAL_OCCITAN },
{ "lu", Language.PROVENCAL_OCCITAN },
{ "mga", Language.TAGALOG },
{ "m\u0303ga", Language.TAGALOG },
{ "mia", Language.GREEK },
{ "'n", Language.AFRIKAANS, Language.DUTCH, Language.FRISIAN },
{ "na", Language.HAWAIIAN, Language.IRISH, Language.SCOTTISH_GAELIC },
{ "na h-", Language.IRISH, Language.SCOTTISH_GAELIC },
{ "nje", Language.ALBANIAN },
{ "ny", Language.MALAGASY },
{ "'o", Language.NEAPOLITAN_ITALIAN },
{ "o", Language.GALICIAN, Language.HAWAIIAN, Language.PORTUGUESE, Language.ROMANIAN },
{ "os", Language.PORTUGUESE },
{ "'r", Language.ICELANDIC },
{ "'s", Language.GERMAN },
{ "sa", Language.TAGALOG },
{ "sa mga", Language.TAGALOG },
{ "si", Language.TAGALOG },
{ "sin\u00e1", Language.TAGALOG },
{ "'t", Language.DUTCH, Language.FRISIAN },
{ "ta", Language.CLASSICAL_GREEK, Language.GREEK },
{ "tais", Language.CLASSICAL_GREEK },
{ "tas", Language.CLASSICAL_GREEK },
{ "t\u0113", Language.CLASSICAL_GREEK }, // e macron
{ "t\u0113n", Language.CLASSICAL_GREEK, Language.GREEK }, // e macron
{ "t\u0113s", Language.CLASSICAL_GREEK, Language.GREEK }, // e macron
{ "the", Language.ENGLISH },
{ "t\u014d", Language.CLASSICAL_GREEK, Language.GREEK }, // o macron
{ "tois", Language.CLASSICAL_GREEK },
{ "t\u014dn", Language.CLASSICAL_GREEK, Language.GREEK }, // o macron
{ "tou", Language.CLASSICAL_GREEK, Language.GREEK },
{ "um", Language.PORTUGUESE },
{ "uma", Language.PORTUGUESE },
{ "un", Language.CATALAN, Language.FRENCH, Language.ITALIAN, Language.PROVENCAL_OCCITAN, Language.ROMANIAN, Language.SPANISH },
{ "un'", Language.ITALIAN },
{ "una", Language.CATALAN, Language.ITALIAN, Language.PROVENCAL_OCCITAN, Language.SPANISH },
{ "une", Language.FRENCH },
{ "unei", Language.ROMANIAN },
{ "unha", Language.GALICIAN },
{ "uno", Language.ITALIAN, Language.PROVENCAL_OCCITAN },
{ "uns", Language.PROVENCAL_OCCITAN },
{ "unui", Language.ROMANIAN },
{ "us", Language.PROVENCAL_OCCITAN },
{ "y", Language.WELSH },
{ "ye", Language.ENGLISH },
{ "yr", Language.WELSH }
};
// Initialize the lang -> article map
ianaArticleMap = new HashMap();
int wordIdx = 0;
int langIdx = 0;
// Iterate through word/language array
// Generate temporary language map
Map langWordMap = new HashMap();
for (wordIdx = 0; wordIdx < articleWordArray.length; wordIdx++)
{
for (langIdx = 1; langIdx < articleWordArray[wordIdx].length; langIdx++)
{
Language lang = (Language)articleWordArray[wordIdx][langIdx];
if (lang != null && lang.IANA.length() > 0)
{
List words = (List)langWordMap.get(lang);
if (words == null)
{
words = new ArrayList();
langWordMap.put(lang, words);
}
// Add language to list if we haven't done so already
if (!words.contains(articleWordArray[wordIdx][0]))
words.add(articleWordArray[wordIdx][0]);
}
}
}
// Iterate through languages
Iterator langIter = langWordMap.keySet().iterator();
while (langIter.hasNext())
{
Language lang = (Language)langIter.next();
List wordList = (List)langWordMap.get(lang);
// Convert the list into an array of strings
String[] words = new String[wordList.size()];
for (int idx = 0; idx < wordList.size(); idx++)
words[idx] = (String)wordList.get(idx);
// Sort the array into length order - longest to shortest
// This ensures maximal matching on the article words
Arrays.sort(words, new MARC21InitialArticleWord.InverseLengthComparator() );
// Add language/article entry to map
ianaArticleMap.put(lang.IANA, new MARC21InitialArticleWord.ArticlesForLang(lang, words));
}
}
// Wrapper class for inserting word arrays into a map
private static class ArticlesForLang
{
final Language lang;
final String[] words;
ArticlesForLang(Language lang, String[] words)
{
this.lang = lang;
this.words = words;
}
}
// Compare strings according to their length - longest to shortest
private static class InverseLengthComparator implements Comparator
{
public int compare(Object arg0, Object arg1)
{
return ((String)arg1).length() - ((String)arg0).length();
};
};
}

View File

@@ -0,0 +1,62 @@
/*
* Standard1InitialArticleWord.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
/**
* Implements existing DSpace initial article word behaviour
*
* Note: This only works for languages defined with ISO code entries.
*
* @author Graham Triggs
*/
public class StandardInitialArticleWord extends InitialArticleWord
{
private static final String[] articleWords = { "the", "an", "a" };
protected String[] getArticleWords(String lang)
{
if (lang.startsWith("en"))
return articleWords;
return null;
}
}

View File

@@ -0,0 +1,61 @@
/*
* StripDiacritics.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
/**
* Strips decomposed diacritic characters from the supplied string
*
* @author Graham Triggs
*
*/
public class StripDiacritics implements TextFilter
{
public String filter(String str)
{
return str.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
public String filter(String str, String lang)
{
return str.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
}

View File

@@ -0,0 +1,52 @@
/*
* TextFilter.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/03/02 11:22:13 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.text.filter;
/**
* Define an interface for all browse ordering filters.
* @author Graham Triggs
*/
public interface TextFilter
{
public String filter(String str);
public String filter(String str, String lang);
}

View File

@@ -1,3 +1,53 @@
browse.page-title = Browsing DSpace
browse.et-al = et al
browse.type.author = Author
browse.type.subject = Subject
browse.type.title = Title
browse.type.dateissued = Issue Date
browse.type.dateaccessioned = Submit Date
browse.nav.jump = Jump to:
browse.nav.enter = or enter first few letters:
browse.nav.go = Go!
browse.nav.date.jump = Jump to a point in the index:
browse.nav.month = (Choose month)
browse.nav.year = (Choose year)
browse.nav.type-year = Or type in a year:
browse.full.header = Browsing {0} by
browse.full.sort-by = Sort by:
browse.full.order = In order:
browse.full.rpp = Results/Page
browse.full.range = Showing results {0} to {1} of {2}
browse.full.prev = &lt;&nbsp;previous
browse.full.next = next&nbsp;&gt;
browse.full.etal = Authors/Record:
browse.full.etal.unlimited = All
browse.single.header = Browsing {0} by
browse.single.order = Order:
browse.single.rpp = Results/Page
browse.single.range = Showing results {0} to {1} of {2}
browse.single.prev = &lt;&nbsp;previous
browse.single.next = next&nbsp;&gt;
browse.no-results.col = There are no entries in the index for Collection "{0}".
browse.no-results.com = There are no entries in the index for Community "{0}".
browse.no-results.genericScope = There are no entries in the index for "All of DSpace".
browse.no-results.title = No Entries in Index
browse.menu.author = Author
browse.menu.subject = Subject
browse.menu.title = Title
browse.menu.dateissued = Issue Date
browse.menu.dateaccessioned = Submit Date
browse.sort-by.title = title
browse.sort-by.date = date
browse.order.asc = Ascending
browse.order.desc = Descending
help.collection-admin = /help/collection-admin.html
help.index = /help/index.html

View File

@@ -0,0 +1,92 @@
/*
* RecentCollectionSubmissions.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.core.Context;
import org.dspace.plugin.CollectionHomeProcessor;
import org.dspace.plugin.PluginException;
import org.dspace.app.webui.components.RecentSubmissionsManager;
/**
* This class obtains recent submissions to the given collection by
* implementing the CollectionHomeProcessor.
*
* @author Richard Jones
*
*/
public class RecentCollectionSubmissions implements CollectionHomeProcessor
{
/**
* blank constructor - does nothing.
*
*/
public RecentCollectionSubmissions()
{
}
/* (non-Javadoc)
* @see org.dspace.plugin.CommunityHomeProcessor#process(org.dspace.core.Context, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.dspace.content.Community)
*/
public void process(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection)
throws PluginException, AuthorizeException
{
try
{
RecentSubmissionsManager rsm = new RecentSubmissionsManager(context);
RecentSubmissions recent = rsm.getRecentSubmissions(collection);
request.setAttribute("recently.submitted", recent);
}
catch (RecentSubmissionsException e)
{
throw new PluginException(e);
}
}
}

View File

@@ -0,0 +1,91 @@
/*
* RecentCommunitySubmissions.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Community;
import org.dspace.core.Context;
import org.dspace.plugin.CommunityHomeProcessor;
import org.dspace.plugin.PluginException;
import org.dspace.app.webui.components.RecentSubmissionsManager;
/**
* This class obtains recent submissions to the given community by
* implementing the CommunityHomeProcessor.
*
* @author Richard Jones
*
*/
public class RecentCommunitySubmissions implements CommunityHomeProcessor
{
/**
* blank constructor - does nothing
*
*/
public RecentCommunitySubmissions()
{
}
/* (non-Javadoc)
* @see org.dspace.plugin.CommunityHomeProcessor#process(org.dspace.core.Context, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.dspace.content.Community)
*/
public void process(Context context, HttpServletRequest request, HttpServletResponse response, Community community)
throws PluginException, AuthorizeException
{
try
{
RecentSubmissionsManager rsm = new RecentSubmissionsManager(context);
RecentSubmissions recent = rsm.getRecentSubmissions(community);
request.setAttribute("recently.submitted", recent);
}
catch (RecentSubmissionsException e)
{
throw new PluginException(e);
}
}
}

View File

@@ -0,0 +1,107 @@
/*
* RecentSubmissions.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.components;
import org.dspace.content.Item;
/**
* Basic class for representing the set of items which are recent submissions
* to the archive
*
* @author Richard Jones
*
*/
public class RecentSubmissions
{
/** The set of items being represented */
private Item[] items;
/**
* Construct a new RecentSubmissions object to represent the passed
* array of items
*
* @param items
*/
public RecentSubmissions(Item[] items)
{
this.items = items;
}
/**
* obtain the number of recent submissions available
*
* @return the number of items
*/
public int count()
{
return items.length;
}
/**
* Obtain the array of items
*
* @return an array of items
*/
public Item[] getRecentSubmissions()
{
return items;
}
/**
* Get the item which is in the i'th position. Therefore i = 1 gets the
* most recently submitted item, while i = 3 gets the 3rd most recently
* submitted item
*
* @param i the position of the item to retrieve
* @return the Item
*/
public Item getRecentSubmission(int i)
{
if (i < items.length)
{
return items[i];
}
else
{
return null;
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* RecentSubmissionsException.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.components;
/**
* General exception to be thrown by code working with recent submissions
*
* @author Richard Jones
*
*/
public class RecentSubmissionsException extends Exception
{
public RecentSubmissionsException()
{
super();
// TODO Auto-generated constructor stub
}
public RecentSubmissionsException(String message)
{
super(message);
// TODO Auto-generated constructor stub
}
public RecentSubmissionsException(String message, Throwable cause)
{
super(message, cause);
// TODO Auto-generated constructor stub
}
public RecentSubmissionsException(Throwable cause)
{
super(cause);
// TODO Auto-generated constructor stub
}
}

View File

@@ -0,0 +1,125 @@
/*
* RecentSubmissionsManager.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.components;
import org.dspace.core.Context;
import org.dspace.content.DSpaceObject;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowserScope;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseException;
import org.dspace.core.ConfigurationManager;
import org.dspace.content.Item;
import org.apache.log4j.Logger;
/**
* Class that obtains recent submissions to DSpace containers.
* @author rdjones
*
*/
public class RecentSubmissionsManager
{
/** logger */
private static Logger log = Logger.getLogger(RecentSubmissionsManager.class);
/** DSpace context */
private Context context;
/**
* Construct a new RecentSubmissionsManager with the given DSpace context
*
* @param context
*/
public RecentSubmissionsManager(Context context)
{
this.context = context;
}
/**
* Obtain the recent submissions from the given container object. This
* method uses the configuration to determine which field and how many
* items to retrieve from the DSpace Object.
*
* If the object you pass in is not a Community or Collection (e.g. an Item
* is a DSpaceObject which cannot be used here), an exception will be thrown
*
* @param dso DSpaceObject: Community or Collection
* @return The recently submitted items
* @throws RecentSubmissionsException
*/
public RecentSubmissions getRecentSubmissions(DSpaceObject dso)
throws RecentSubmissionsException
{
try
{
// get our configuration
String source = ConfigurationManager.getProperty("recent.submissions.index");
String count = ConfigurationManager.getProperty("recent.submissions.count");
// prep our engine and scope
BrowseEngine be = new BrowseEngine(context);
BrowserScope bs = new BrowserScope(context);
BrowseIndex bi = BrowseIndex.getBrowseIndex(source);
// fill in the scope with the relevant gubbins
bs.setBrowseIndex(bi);
bs.setOrder("DESC"); // FIXME: eek - plain text flag! Should be BrowserScope.ASC or something
bs.setResultsPerPage(Integer.parseInt(count));
bs.setBrowseContainer(dso);
bs.setSortBy(0);
BrowseInfo results = be.browseMini(bs);
Item[] items = results.getItemResults(context);
RecentSubmissions rs = new RecentSubmissions(items);
return rs;
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new RecentSubmissionsException(e);
}
}
}

View File

@@ -0,0 +1,689 @@
/*
* BrowseListTag.java
*
* Version: $Revision: 1.30 $
*
* Date: $Date: 2006/04/05 02:15:45 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.jsptag;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.Authenticate;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.storage.bitstore.BitstreamStorageManager;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.dspace.browse.BrowseItem;
import org.dspace.browse.Thumbnail;
import org.dspace.browse.CrossLinks;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseInfo;
/**
* Tag for display a list of items
*
* @author Robert Tansley
* @version $Revision: 1.30 $
*/
public class BrowseListTag extends TagSupport
{
/** log4j category */
private static Logger log = Logger.getLogger(BrowseListTag.class);
/** Items to display */
private BrowseItem[] items;
/** Row to highlight, -1 for no row */
private int highlightRow = -1;
/** Column to emphasise, identified by metadata field */
private String emphColumn;
/** Config value of thumbnail view toggle */
private boolean showThumbs;
/** Config browse/search width and height */
private int thumbItemListMaxWidth;
private int thumbItemListMaxHeight;
/** Config browse/search thumbnail link behaviour */
private boolean linkToBitstream = false;
/** The default fields to be displayed when listing items */
private static String listFields = "dc.date.issued(date), dc.title, dc.contributor.*";
/** The default field which is bound to the browse by date */
private static String dateField = "dc.date.issued";
/** The default field which is bound to the browse by title */
private static String titleField = "dc.title";
private static String authorField = "dc.contributor.*";
private static int authorLimit = -1;
private BrowseInfo browseInfo;
public BrowseListTag()
{
super();
getThumbSettings();
}
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();
/* just leave this out now
boolean emphasiseDate = false;
boolean emphasiseTitle = false;
if (emphColumn != null)
{
emphasiseDate = emphColumn.equalsIgnoreCase("date");
emphasiseTitle = emphColumn.equalsIgnoreCase("title");
}
*/
// get the elements to display
String configLine = ConfigurationManager.getProperty("webui.itemlist.columns");
if (configLine != null)
{
listFields = configLine;
}
// get the date and title fields
String dateLine = ConfigurationManager.getProperty("webui.browse.index.date");
if (dateLine != null)
{
dateField = dateLine;
}
String titleLine = ConfigurationManager.getProperty("webui.browse.index.title");
if (titleLine != null)
{
titleField = titleLine;
}
// get the author truncation config
String authorLine = ConfigurationManager.getProperty("webui.browse.author-field");
if (authorLine != null)
{
authorField = authorLine;
}
StringTokenizer st = new StringTokenizer(listFields, ",");
// make an array to hold all the frags that we will use
int columns = st.countTokens();
String[] frags = new String[columns * items.length];
try
{
// get the interlinking configuration too
CrossLinks cl = new CrossLinks();
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<tr>");
// Write the column headings
int colCount = 1;
boolean isDate = false;
boolean emph = false;
boolean isAuthor = false;
while (st.hasMoreTokens())
{
String field = st.nextToken().toLowerCase().trim();
String cOddOrEven = ((colCount % 2) == 0 ? "Odd" : "Even");
// find out if the field is a date
if (field.indexOf("(date)") > 0)
{
field = field.replaceAll("\\(date\\)", "");
isDate = true;
}
// find out if this is the author column
if (field.equals(authorField))
{
isAuthor = true;
}
// find out if this field needs to link out to other browse views
String browseType = "";
boolean viewFull = false;
if (cl.hasLink(field))
{
browseType = cl.getLinkType(field);
viewFull = BrowseIndex.getBrowseIndex(browseType).isFull();
}
// get the schema and the element qualifier pair
// (Note, the schema is not used for anything yet)
// (second note, I hate this bit of code. There must be
// a much more elegant way of doing this. Tomcat has
// some weird problems with variations on this code that
// I tried, which is why it has ended up the way it is)
StringTokenizer eq = new StringTokenizer(field, ".");
String[] tokens = { "", "", "" };
int k = 0;
while(eq.hasMoreTokens())
{
tokens[k] = eq.nextToken().toLowerCase().trim();
k++;
}
String schema = tokens[0];
String element = tokens[1];
String qualifier = tokens[2];
// find out if we are emphasising this field
/*
if ((field.equals(dateField) && emphasiseDate) ||
(field.equals(titleField) && emphasiseTitle))
{
emph = true;
}
*/
if (field.equals(emphColumn))
{
emph = true;
}
// prepare the strings for the header
String id = "t" + Integer.toString(colCount);
String css = "oddRow" + cOddOrEven + "Col";
String message = "itemlist." + field;
// output the header
out.print("<th id=\"" + id + "\" class=\"" + css + "\">"
+ (emph ? "<strong>" : "")
+ LocaleSupport.getLocalizedMessage(pageContext, message)
+ (emph ? "</strong>" : "") + "</th>");
// now prepare the frags for each of the table elements
for (int i = 0; i < items.length; i++)
{
// first get hold of the relevant metadata for this column
DCValue[] metadataArray;
if (qualifier.equals("*"))
{
metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY);
}
else if (qualifier.equals(""))
{
metadataArray = items[i].getMetadata(schema, element, null, Item.ANY);
}
else
{
metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY);
}
// save on a null check which would make the code untidy
if (metadataArray == null)
{
metadataArray = new DCValue[0];
}
// now prepare the content of the table division
String metadata = "-";
if (metadataArray.length > 0)
{
// format the date field correctly
if (isDate)
{
// FIXME: why on _earth_ is this here. Thumbnail config should
// be part of the display columns configuration
String thumbs = "";
if (showThumbs)
{
thumbs = getThumbMarkup(hrq, items[i]);
}
DCDate dd = new DCDate(metadataArray[0].value);
metadata = UIUtil.displayDate(dd, false, false, hrq) + thumbs;
}
// format the title field correctly
else if (field.equals(titleField))
{
metadata = "<a href=\"" + hrq.getContextPath() + "/handle/"
+ items[i].getHandle() + "\">"
+ Utils.addEntities(metadataArray[0].value)
+ "</a>";
}
// format all other fields
else
{
// limit the number of records if this is the author field (if
// -1, then the limit is the full list)
boolean truncated = false;
int loopLimit = metadataArray.length;
if (isAuthor)
{
int fieldMax = (authorLimit == -1 ? metadataArray.length : authorLimit);
loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax);
truncated = (fieldMax < metadataArray.length);
log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit) + " from an original " + Integer.toString(metadataArray.length));
}
StringBuffer sb = new StringBuffer();
for (int j = 0; j < loopLimit; j++)
{
String startLink = "";
String endLink = "";
if (!"".equals(browseType))
{
String argument = "value";
if (viewFull)
{
argument = "vfocus";
}
startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type=" + browseType + "&amp;" +
argument + "=" + Utils.addEntities(metadataArray[j].value);
if (metadataArray[j].language != null)
{
startLink = startLink + "&amp;" +
argument + "_lang=" + Utils.addEntities(metadataArray[j].language) +
"\">";
}
else
{
startLink = startLink + "\">";
}
endLink = "</a>";
}
sb.append(startLink);
sb.append(Utils.addEntities(metadataArray[j].value));
sb.append(endLink);
if (j < (loopLimit - 1))
{
sb.append("; ");
}
}
if (truncated)
{
String etal = LocaleSupport.getLocalizedMessage(pageContext, "browse.et-al");
sb.append(", " + etal);
}
metadata = "<em>" + sb.toString() + "</em>";
}
}
// now prepare the XHTML frag for this division
String rOddOrEven;
if (i == highlightRow)
{
rOddOrEven = "highlight";
}
else
{
rOddOrEven = ((i % 2) == 1 ? "odd" : "even");
}
// prepare extra special layout requirements for dates
String extras = "";
if (isDate)
{
extras = "nowrap=\"nowrap\" align=\"right\"";
}
int idx = ((i + 1) * columns) - columns + colCount - 1;
frags[idx] = "<td headers=\"" + id + "\" class=\""
+ rOddOrEven + "Row" + cOddOrEven + "Col\" " + extras + ">"
+ (emph ? "<strong>" : "") + metadata + (emph ? "</strong>" : "")
+ "</td>";
}
colCount++;
isDate = false;
emph = false;
}
out.println("</tr>");
// now output all the frags in the right order for the page
for (int i = 0; i < frags.length; i++)
{
if ((i + 1) % columns == 1)
{
out.println("<tr>");
}
out.println(frags[i]);
if ((i + 1) % columns == 0)
{
out.println("</tr>");
}
}
// close the table
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
catch (SQLException e)
{
throw new JspException(e);
}
catch (BrowseException e)
{
throw new JspException(e);
}
return SKIP_BODY;
}
public BrowseInfo getBrowseInfo()
{
return browseInfo;
}
public void setBrowseInfo(BrowseInfo browseInfo)
{
this.browseInfo = browseInfo;
setItems(browseInfo.getBrowseItemResults());
authorLimit = browseInfo.getEtAl();
}
/**
* Get the items to list
*
* @return the items
*/
public BrowseItem[] getItems()
{
return items;
}
/**
* Set the items to list
*
* @param itemsIn
* the items
*/
public void setItems(BrowseItem[] itemsIn)
{
items = itemsIn;
}
/**
* Get the row to highlight - null or -1 for no row
*
* @return the row to highlight
*/
public String getHighlightrow()
{
return String.valueOf(highlightRow);
}
/**
* Set the row to highlight
*
* @param highlightRowIn
* the row to highlight or -1 for no highlight
*/
public void setHighlightrow(String highlightRowIn)
{
if ((highlightRowIn == null) || highlightRowIn.equals(""))
{
highlightRow = -1;
}
else
{
try
{
highlightRow = Integer.parseInt(highlightRowIn);
}
catch (NumberFormatException nfe)
{
highlightRow = -1;
}
}
}
/**
* Get the column to emphasise - "title", "date" or null
*
* @return the column to emphasise
*/
public String getEmphcolumn()
{
return emphColumn;
}
/**
* Set the column to emphasise - "title", "date" or null
*
* @param emphColumnIn
* column to emphasise
*/
public void setEmphcolumn(String emphColumnIn)
{
emphColumn = emphColumnIn;
}
public void release()
{
highlightRow = -1;
emphColumn = null;
items = null;
}
/* get the required thumbnail config items */
private void getThumbSettings()
{
showThumbs = ConfigurationManager
.getBooleanProperty("webui.browse.thumbnail.show");
if (showThumbs)
{
thumbItemListMaxHeight = ConfigurationManager
.getIntProperty("webui.browse.thumbnail.maxheight");
if (thumbItemListMaxHeight == 0)
{
thumbItemListMaxHeight = ConfigurationManager
.getIntProperty("thumbnail.maxheight");
}
thumbItemListMaxWidth = ConfigurationManager
.getIntProperty("webui.browse.thumbnail.maxwidth");
if (thumbItemListMaxWidth == 0)
{
thumbItemListMaxWidth = ConfigurationManager
.getIntProperty("thumbnail.maxwidth");
}
}
String linkBehaviour = ConfigurationManager
.getProperty("webui.browse.thumbnail.linkbehaviour");
if (linkBehaviour != null)
{
if (linkBehaviour.equals("bitstream"))
{
linkToBitstream = true;
}
}
}
/*
* Get the (X)HTML width and height attributes. As the browser is being used
* for scaling, we only scale down otherwise we'll get hideously chunky
* images. This means the media filter should be run with the maxheight and
* maxwidth set greater than or equal to the size of the images required in
* the search/browse
*/
private String getScalingAttr(HttpServletRequest hrq, Bitstream bitstream)
throws JspException
{
BufferedImage buf;
try
{
Context c = UIUtil.obtainContext(hrq);
InputStream is = BitstreamStorageManager.retrieve(c, bitstream
.getID());
//AuthorizeManager.authorizeAction(bContext, this, Constants.READ);
// read in bitstream's image
buf = ImageIO.read(is);
is.close();
}
catch (SQLException sqle)
{
throw new JspException(sqle.getMessage());
}
catch (IOException ioe)
{
throw new JspException(ioe.getMessage());
}
// now get the image dimensions
float xsize = (float) buf.getWidth(null);
float ysize = (float) buf.getHeight(null);
// scale by x first if needed
if (xsize > (float) thumbItemListMaxWidth)
{
// calculate scaling factor so that xsize * scale = new size (max)
float scale_factor = (float) thumbItemListMaxWidth / xsize;
// now reduce x size and y size
xsize = xsize * scale_factor;
ysize = ysize * scale_factor;
}
// scale by y if needed
if (ysize > (float) thumbItemListMaxHeight)
{
float scale_factor = (float) thumbItemListMaxHeight / ysize;
// now reduce x size
// and y size
xsize = xsize * scale_factor;
ysize = ysize * scale_factor;
}
StringBuffer sb = new StringBuffer("width=\"").append(xsize).append(
"\" height=\"").append(ysize).append("\"");
return sb.toString();
}
/* generate the (X)HTML required to show the thumbnail */
private String getThumbMarkup(HttpServletRequest hrq, BrowseItem item)
throws JspException
{
try
{
Thumbnail thumbnail = item.getThumbnail();
if (thumbnail == null)
{
return "";
}
StringBuffer thumbFrag = new StringBuffer();
if (linkToBitstream)
{
Bitstream original = thumbnail.getOriginal();
String link = hrq.getContextPath() + "/bitstream/" + item.getHandle() + "/" + original.getSequenceID() + "/" +
UIUtil.encodeBitstreamName(original.getName(), Constants.DEFAULT_ENCODING);
thumbFrag.append("<a target=\"_blank\" href=\"" + link + "\" />");
}
else
{
String link = hrq.getContextPath() + "/handle/" + item.getHandle();
thumbFrag.append("<a href=\"" + link + "\" />");
}
Bitstream thumb = thumbnail.getThumb();
String img = hrq.getContextPath() + "/retrieve/" + thumb.getID() + "/" +
UIUtil.encodeBitstreamName(thumb.getName(), Constants.DEFAULT_ENCODING);
String alt = thumb.getName();
thumbFrag.append("<img src=\"" + img + "\" alt=\"" + alt + "\" /></a>");
return thumbFrag.toString();
}
catch (SQLException sqle)
{
throw new JspException(sqle.getMessage());
}
catch (UnsupportedEncodingException e)
{
throw new JspException("Server does not support DSpace's default encoding. ", e);
}
}
}

View File

@@ -368,15 +368,31 @@ public class ItemTag extends TagSupport
}
else if (isAuthor)
{
out.print("<a href=\"" + request.getContextPath() + "/items-by-author?author="
+ URLEncoder.encode(values[j].value, "UTF-8") + "\">" + values[j].value
+ "</a>");
String bType = ConfigurationManager.getProperty("webui.authorlinks.browse");
if (bType != null)
{
out.print("<a href=\"" + request.getContextPath() + "/browse?type=" + bType + "&value="
+ URLEncoder.encode(values[j].value, "UTF-8") + "\">" + Utils.addEntities(values[j].value)
+ "</a>");
}
else
{
out.print(Utils.addEntities(values[j].value));
}
}
else if (isSubject)
{
out.print("<a href=\"" + request.getContextPath() + "/items-by-subject?subject="
+ URLEncoder.encode(values[j].value, "UTF-8") + "\">" + values[j].value
+ "</a>");
String sType = ConfigurationManager.getProperty("webui.authorlinks.browse");
if (sType != null)
{
out.print("<a href=\"" + request.getContextPath() + "/browse?type=" + sType + "&value="
+ URLEncoder.encode(values[j].value, "UTF-8") + "\">" + Utils.addEntities(values[j].value)
+ "</a>");
}
else
{
out.print(Utils.addEntities(values[j].value));
}
}
else
{

View File

@@ -1,501 +0,0 @@
/*
* BrowseServlet.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseScope;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
/**
* Servlet for browsing through indices. This can be used to browse authors,
* items by date, or items by title. In the deployment description, the initial
* parameter "browse" should be set to one of these values:
* <p>
* <ul>
* <lI><code>titles</code>- for browsing items by title (the default)</li>
* <lI><code>authors</code>- for browsing authors</li>
* <lI><code>dates</code>- for browsing items by date</li>
* </ul>
* <p>
* Hence there should be three instances of this servlet, one for each type of
* browse.
*
* @author Robert Tansley
* @version $Revision$
*/
public class BrowseServlet extends DSpaceServlet
{
/** log4j category */
private static Logger log = Logger.getLogger(BrowseServlet.class);
/** Is this servlet for browsing authors? */
private boolean browseAuthors;
/** Is this servlet for browsing items by title? */
private boolean browseTitles;
/** Is this servlet for browsing items by date? */
private boolean browseDates;
/** Is this servlet for browsing items by subject? */
private boolean browseSubjects;
public void init()
{
// Sort out what we're browsing - default is titles
String browseWhat = getInitParameter("browse");
browseAuthors = ((browseWhat != null) && browseWhat
.equalsIgnoreCase("authors"));
browseDates = ((browseWhat != null) && browseWhat
.equalsIgnoreCase("dates"));
browseSubjects = ((browseWhat != null) && browseWhat
.equalsIgnoreCase("subjects"));
browseTitles = ((!browseAuthors && !browseDates)&& !browseSubjects );
}
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
// We will resolve the HTTP request parameters into a scope
BrowseScope scope = new BrowseScope(context);
// Will need to know whether to highlight the "focus" point
boolean highlight = false;
// Build up log information
String logInfo = "";
// For browse by date, we'll need to work out the URL query string to
// use when the user swaps the ordering, so that they stay at the same
// point in the index
String flipOrderingQuery = "";
// Grab HTTP request parameters
String focus = request.getParameter("focus");
String startsWith = request.getParameter("starts_with");
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
// The following three are specific to browsing items by date
String month = request.getParameter("month");
String year = request.getParameter("year");
String order = request.getParameter("order");
// For browse by date: oldest item first?
boolean oldestFirst = false;
if ((order != null) && order.equalsIgnoreCase("oldestfirst"))
{
oldestFirst = true;
}
if (browseDates && (year != null) && !year.equals("")
&& ((startsWith == null) || startsWith.equals("")))
{
// We're browsing items by date, the user hasn't typed anything
// into the "year" text box, and they've selected a year from
// the drop-down list. From this we work out where to start
// the browse.
startsWith = year;
if ((month != null) & !month.equals("-1"))
{
// They've selected a month as well
if (month.length() == 1)
{
// Ensure double-digit month number
month = "0" + month;
}
startsWith = year + "-" + month;
}
}
// Set the scope according to the parameters passed in
if (focus != null)
{
// ----------------------------------------------
// Browse should start at a specified focus point
// ----------------------------------------------
if (browseAuthors||browseSubjects)
{
// For browsing authors, focus is just a text value
scope.setFocus(focus);
}
else
{
// For browsing items by title or date, focus is a Handle
Item item = (Item) HandleManager
.resolveToObject(context, focus);
if (item == null)
{
// Handle is invalid one. Show an error.
JSPManager.showInvalidIDError(request, response, focus,
Constants.ITEM);
return;
}
scope.setFocus(item);
}
// Will need to highlight the focus
highlight = true;
logInfo = "focus=" + focus + ",";
if (browseDates)
{
// if the date order is flipped, we'll keep the same focus
flipOrderingQuery = "focus="
+ URLEncoder.encode(focus, Constants.DEFAULT_ENCODING)
+ "&amp;";
}
}
else if (startsWith != null)
{
// ----------------------------------------------
// Start the browse using user-specified text
// ----------------------------------------------
if (browseDates)
{
// if the date order is flipped, we'll keep the same focus
flipOrderingQuery = "starts_with="
+ URLEncoder.encode(startsWith,
Constants.DEFAULT_ENCODING) + "&amp;";
/*
* When the user is browsing with the most recent items first,
* the browse code algorithm doesn't quite do what some people
* might expect. For example, if in the index there are entries:
*
* Mar-2000 15-Feb-2000 6-Feb-2000 15-Jan-2000
*
* and the user has selected "Feb 2000" as the start point for
* the browse, the browse algorithm will start at the first
* point in that index *after* "Feb 2000". "Feb 2000" would
* appear in the index above between 6-Feb-2000 and 15-Jan-2000.
* So, the browse code in this case will start the browse at
* "15-Jan-2000". This isn't really what users are likely to
* want: They're more likely to want the browse to start at the
* first Feb 2000 date, i.e. 15-Feb-2000. A similar scenario
* occurs when the user enters just a year. Our quick hack to
* produce this behaviour is to add "-32" to the startsWith
* variable, when sorting with most recent items first. This
* means the browse code starts at the topmost item in the index
* that matches the user's input, rather than the point in the
* index where the user's input would appear.
*/
if (!oldestFirst)
{
startsWith = startsWith + "-32";
}
}
scope.setFocus(startsWith);
highlight = true;
logInfo = "starts_with=" + startsWith + ",";
}
else if ((top != null) || (bottom != null))
{
// ----------------------------------------------
// Paginating: put specified entry at top or bottom
// ----------------------------------------------
// Use a single value and a boolean to simplify the code below
String val = bottom;
boolean isTop = false;
if (top != null)
{
val = top;
isTop = true;
}
if (browseAuthors || browseSubjects)
{
// Value will be a text value for author browse
scope.setFocus(val);
}
else
{
// Value is Handle if we're browsing items by title or date
Item item = (Item) HandleManager.resolveToObject(context, val);
if (item == null)
{
// Handle is invalid one. Show an error.
JSPManager.showInvalidIDError(request, response, focus,
Constants.ITEM);
return;
}
scope.setFocus(item);
}
// This entry appears at the top or bottom, and so needs to have
// 0 or 20 entries shown before it
scope.setNumberBefore(isTop ? 0 : 20);
logInfo = (isTop ? "top" : "bottom") + "=" + val + ",";
if (browseDates)
{
// If the date order is flipped, we'll flip the table upside
// down - i.e. the top will become the bottom and the bottom
// the top.
if (top != null)
{
flipOrderingQuery = "bottom="
+ URLEncoder
.encode(top, Constants.DEFAULT_ENCODING)
+ "&amp;";
}
else
{
flipOrderingQuery = "top="
+ URLEncoder.encode(bottom,
Constants.DEFAULT_ENCODING) + "&amp;";
}
}
}
// ----------------------------------------------
// If none of the above apply, no positioning parameters
// set - use start of index
// ----------------------------------------------
// Are we in a community or collection?
Community community = UIUtil.getCommunityLocation(request);
Collection collection = UIUtil.getCollectionLocation(request);
if (collection != null)
{
logInfo = logInfo + ",collection_id=" + collection.getID() + ",";
scope.setScope(collection);
}
else if (community != null)
{
logInfo = logInfo + ",community_id=" + community.getID() + ",";
scope.setScope(community);
}
BrowseInfo browseInfo;
try
{
// Query the browse index
if (browseAuthors)
{
browseInfo = Browse.getAuthors(scope);
}
else if (browseDates)
{
browseInfo = Browse.getItemsByDate(scope, oldestFirst);
}
else if (browseSubjects)
{
browseInfo = Browse.getSubjects(scope);
}
else
{
browseInfo = Browse.getItemsByTitle(scope);
}
}
catch (SQLException sqle)
{
// An invalid scope was given
JSPManager.showIntegrityError(request, response);
return;
}
// Write log entry
String what = "title";
if (browseAuthors)
{
what = "author";
}
else if (browseSubjects)
{
what = "subject";
}
else if (browseDates)
{
what = "date";
}
log.info(LogManager.getHeader(context, "browse_" + what, logInfo
+ "results=" + browseInfo.getResultCount()));
if (browseInfo.getResultCount() == 0)
{
// No results!
request.setAttribute("community", community);
request.setAttribute("collection", collection);
JSPManager.showJSP(request, response, "/browse/no-results.jsp");
}
else
{
// Work out what the query strings will be for the previous
// and next pages
if (!browseInfo.isFirst())
{
// Not the first page, so we'll need a "previous page" button
// The top entry of the current page becomes the bottom
// entry of the "previous page"
String s;
if (browseAuthors || browseSubjects) //aneesh
{
s = (browseInfo.getStringResults())[0];
}
else
{
Item firstItem = (browseInfo.getItemResults())[0];
s = firstItem.getHandle();
}
if (browseDates && oldestFirst)
{
// For browsing by date, oldest first, we need
// to add the ordering parameter
request.setAttribute("previous.query",
"order=oldestfirst&amp;bottom="
+ URLEncoder.encode(s,
Constants.DEFAULT_ENCODING));
}
else
{
request.setAttribute("previous.query", "bottom="
+ URLEncoder.encode(s, Constants.DEFAULT_ENCODING));
}
}
if (!browseInfo.isLast())
{
// Not the last page, so we'll need a "next page" button
// The bottom entry of the current page will be the top
// entry in the next page
String s;
if (browseAuthors)
{
String[] authors = browseInfo.getStringResults();
s = authors[authors.length - 1];
}
else if (browseSubjects)
{
String[] subjects = browseInfo.getStringResults();
s = subjects[subjects.length - 1];
}
else
{
Item[] items = browseInfo.getItemResults();
Item lastItem = items[items.length - 1];
s = lastItem.getHandle();
}
if (browseDates && oldestFirst)
{
// For browsing by date, oldest first, we need
// to add the ordering parameter
request.setAttribute("next.query", "order=oldestfirst&amp;top="
+ URLEncoder.encode(s, Constants.DEFAULT_ENCODING));
}
else
{
request.setAttribute("next.query", "top="
+ URLEncoder.encode(s, Constants.DEFAULT_ENCODING));
}
}
// Set appropriate attributes and forward to results page
request.setAttribute("community", community);
request.setAttribute("collection", collection);
request.setAttribute("browse.info", browseInfo);
request.setAttribute("highlight", new Boolean(highlight));
if (browseAuthors)
{
JSPManager.showJSP(request, response, "/browse/authors.jsp");
}
else if (browseSubjects)
{
JSPManager.showJSP(request, response, "/browse/subjects.jsp");
}
else if (browseDates)
{
request.setAttribute("oldest.first", new Boolean(oldestFirst));
request.setAttribute("flip.ordering.query", flipOrderingQuery);
JSPManager.showJSP(request, response,
"/browse/items-by-date.jsp");
}
else
{
JSPManager.showJSP(request, response,
"/browse/items-by-title.jsp");
}
}
}
}

View File

@@ -0,0 +1,373 @@
/*
* BrowserServlet.java
*
* Version: $Revision: $
*
* Date: $Date: $
*
* Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowserScope;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* Servlet for browsing through indices, as they are defined in
* the configuration. This class can take a wide variety of inputs from
* the user interface:
*
* - type: the type of browse (index name) being performed
* - order: (ASC | DESC) the direction for result sorting
* - value: A specific value to find items around. For example the author name or subject
* - month: integer specification of the month of a date browse
* - year: integer specification of the year of a date browse
* - starts_with: string value at which to start browsing
* - vfocus: start browsing with a value of this string
* - focus: integer id of the item at which to start browsing
* - rpp: integer number of results per page to display
* - sort_by: integer specification of the field to search on
* - etal: integer number to limit multiple value items specified in config to
*
* @author Richard Jones
* @version $Revision: $
*/
public class BrowserServlet extends DSpaceServlet
{
/** log4j category */
private static Logger log = Logger.getLogger(BrowserServlet.class);
/**
* Do the usual DSpace GET method. You will notice that browse does not currently
* respond to POST requests.
*/
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
try
{
// all browse requests currently come to GET.
// first, lift all the stuff out of the request that we might need
String type = request.getParameter("type");
String order = request.getParameter("order");
String value = request.getParameter("value");
String valueLang = request.getParameter("value_lang");
String month = request.getParameter("month");
String year = request.getParameter("year");
String startsWith = request.getParameter("starts_with");
String valueFocus = request.getParameter("vfocus");
String valueFocusLang = request.getParameter("vfocus_lang");
int focus = UIUtil.getIntParameter(request, "focus");
int resultsperpage = UIUtil.getIntParameter(request, "rpp");
int sortBy = UIUtil.getIntParameter(request, "sort_by");
int etAl = UIUtil.getIntParameter(request, "etal");
// get the community or collection location for the browse request
// Note that we are only interested in getting the "smallest" container,
// so if we find a collection, we don't bother looking up the community
Collection collection = null;
Community community = null;
collection = UIUtil.getCollectionLocation(request);
if (collection == null)
{
community = UIUtil.getCommunityLocation(request);
}
// process the input, performing some inline validation
if (type == null || "".equals(type))
{
showError(context, request, response);
}
BrowseIndex bi = BrowseIndex.getBrowseIndex(type);
if (bi == null)
{
throw new BrowseException("There is no browse index of the type: " + type);
}
// if no resultsperpage set, default to 20
if (resultsperpage == -1)
{
resultsperpage = 20;
}
// if no order parameter, default to ascending
if (order == null || "".equals(order))
{
order = "ASC";
}
// if year and perhaps month have been selected, we translate these into "startsWith"
// if startsWith has already been defined then it is overwritten
if (year != null && !"".equals(year) && !"-1".equals(year))
{
startsWith = year;
if ((month != null) && !"-1".equals(month) && !"".equals(month))
{
// subtract 1 from the month, so the match works appropriately
if ("ASC".equals(order))
{
month = Integer.toString((Integer.parseInt(month) - 1));
}
// They've selected a month as well
if (month.length() == 1)
{
// Ensure double-digit month number
month = "0" + month;
}
startsWith = year + "-" + month;
}
}
// determine which level of the browse we are at: 0 for top, 1 for second
int level = 0;
if (value != null)
{
level = 1;
}
// if a value has been specified but a sort_by parameter has not been, we
// need to set it as a default
if (value != null && sortBy == -1)
{
Map map = bi.getSortOptions();
if (map == null)
{
throw new BrowseException("Value browse cannot complete without a sortable column");
}
if (map.size() == 0)
{
throw new BrowseException("Value browse cannot complete without a sortable column");
}
sortBy = ((Integer) map.keySet().iterator().next()).intValue();
}
// if sortBy is still not set, set it to 0, which is default to use the primary index value
if (sortBy == -1)
{
sortBy = 0;
}
// figure out the setting for author list truncation
if (etAl == -1) // there is no limit, or the UI says to use the default
{
int limitLine = ConfigurationManager.getIntProperty("webui.browse.author-limit");
if (limitLine != 0)
{
etAl = limitLine;
}
}
else // if the user has set a limit
{
if (etAl == 0) // 0 is the user setting for unlimited
{
etAl = -1; // but -1 is the application setting for unlimited
}
}
// log the request
String comHandle = "n/a";
if (community != null)
{
comHandle = community.getHandle();
}
String colHandle = "n/a";
if (collection != null)
{
colHandle = collection.getHandle();
}
String arguments = "type=" + type + ",order=" + order + ",value=" + value +
",month=" + month + ",year=" + year + ",starts_with=" + startsWith +
",vfocus=" + valueFocus + ",focus=" + focus + ",rpp=" + resultsperpage +
",sort_by=" + sortBy + ",community=" + comHandle + ",collection=" + colHandle +
",level=" + level + ",etal=" + etAl;
log.info(LogManager.getHeader(context, "browse", arguments));
// set up a BrowseScope and start loading the values into it
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bi);
scope.setOrder(order);
scope.setValue(value);
scope.setValueLang(valueLang);
scope.setFocus(focus);
scope.setValueFocus(valueFocus);
scope.setValueFocusLang(valueFocusLang);
scope.setStartsWith(startsWith);
scope.setResultsPerPage(resultsperpage);
scope.setSortBy(sortBy);
scope.setBrowseLevel(level);
// assign the scope of either Community or Collection if necessary
if (community != null)
{
scope.setBrowseContainer(community);
}
else if (collection != null)
{
scope.setBrowseContainer(collection);
}
// now start up a browse engine and get it to do the work for us
BrowseEngine be = new BrowseEngine(context);
BrowseInfo binfo = be.browse(scope);
// add the etAl limit to the BrowseInfo object
binfo.setEtAl(etAl);
request.setAttribute("browse.info", binfo);
if (binfo.hasResults())
{
if (bi.isSingle() && !scope.isSecondLevel())
{
showSinglePage(context, request, response);
}
else
{
showFullPage(context, request, response);
}
}
else
{
showNoResultsPage(context, request, response);
}
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
}
/**
* Display the error page
*
* @param context
* @param request
* @param response
* @throws ServletException
* @throws IOException
* @throws SQLException
* @throws AuthorizeException
*/
protected void showError(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
JSPManager.showJSP(request, response, "/browse/error.jsp");
}
/**
* Display the No Results page
*
* @param context
* @param request
* @param response
* @throws ServletException
* @throws IOException
* @throws SQLException
* @throws AuthorizeException
*/
protected void showNoResultsPage(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
JSPManager.showJSP(request, response, "/browse/no-results.jsp");
}
/**
* Display the single page. This is the page which lists just the single values of a
* metadata browse, not individual items. Single values are links through to all the items
* that match that metadata value
*
* @param context
* @param request
* @param response
* @throws ServletException
* @throws IOException
* @throws SQLException
* @throws AuthorizeException
*/
protected void showSinglePage(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
JSPManager.showJSP(request, response, "/browse/single.jsp");
}
/**
* Display a full item listing.
*
* @param context
* @param request
* @param response
* @throws ServletException
* @throws IOException
* @throws SQLException
* @throws AuthorizeException
*/
protected void showFullPage(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
JSPManager.showJSP(request, response, "/browse/full.jsp");
}
}

View File

@@ -44,13 +44,13 @@ import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
@@ -59,31 +59,33 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowserScope;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.search.Harvest;
import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Description;
import com.sun.syndication.feed.rss.Image;
import com.sun.syndication.feed.rss.TextInput;
import com.sun.syndication.io.WireFeedOutput;
import com.sun.syndication.io.FeedException;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.content.Bitstream;
import org.dspace.content.DCValue;
import org.dspace.content.DCDate;
import org.dspace.core.LogManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseScope;
import org.dspace.handle.HandleManager;
import org.dspace.search.Harvest;
import com.sun.syndication.io.WireFeedOutput;
/**
* Servlet for handling requests for a syndication feed. The Handle of the collection
@@ -296,107 +298,137 @@ public class FeedServlet extends DSpaceServlet
private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
BrowseScope scope = new BrowseScope(context);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
try
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
scope.setScope(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
scope.setScope(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.index");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.index");
}
BrowseIndex bix = BrowseIndex.getBrowseIndex(idx);
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
return channel;
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setTotal(itemCount);
List results = Browse.getLastSubmitted(scope);
List items = new ArrayList();
for ( int i = 0; i < results.size(); i++ )
catch (BrowseException e)
{
items.add( itemFromDSpaceItem(context, (Item)results.get(i)) );
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
channel.setItems(items);
return channel;
}
/**

View File

@@ -54,8 +54,6 @@ import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseScope;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCValue;
@@ -65,10 +63,13 @@ import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.core.PluginManager;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.Subscribe;
import org.dspace.handle.HandleManager;
import org.dspace.plugin.CollectionHomeProcessor;
import org.dspace.plugin.CommunityHomeProcessor;
/**
* Servlet for handling requests within a community or collection. The Handle is
@@ -365,16 +366,8 @@ public class HandleServlet extends DSpaceServlet
// get any subcommunities of the community
Community[] subcommunities = community.getSubcommunities();
// Find the 5 last submitted items
BrowseScope scope = new BrowseScope(context);
scope.setScope(community);
scope.setTotal(5);
List items = Browse.getLastSubmitted(scope);
// Get titles and URLs to item pages
String[] itemTitles = getItemTitles(items);
String[] itemLinks = getItemURLs(context, items);
// perform any necessary pre-processing
preProcessCommunityHome(context, request, response, community);
// is the user a COMMUNITY_EDITOR?
if (community.canEditBoolean())
@@ -400,8 +393,6 @@ public class HandleServlet extends DSpaceServlet
}
// Forward to community home page
request.setAttribute("last.submitted.titles", itemTitles);
request.setAttribute("last.submitted.urls", itemLinks);
request.setAttribute("community", community);
request.setAttribute("collections", collections);
request.setAttribute("subcommunities", subcommunities);
@@ -409,6 +400,26 @@ public class HandleServlet extends DSpaceServlet
}
}
private void preProcessCommunityHome(Context context, HttpServletRequest request,
HttpServletResponse response, Community community)
throws ServletException, IOException, SQLException
{
try
{
CommunityHomeProcessor[] chp = (CommunityHomeProcessor[]) PluginManager.getPluginSequence(CommunityHomeProcessor.class);
for (int i = 0; i < chp.length; i++)
{
chp[i].process(context, request, response, community);
}
}
catch (Exception e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
}
/**
* Show a collection home page, or deal with button press on home page
*
@@ -462,17 +473,9 @@ public class HandleServlet extends DSpaceServlet
log.info(LogManager.getHeader(context, "view_collection",
"collection_id=" + collection.getID()));
// Find the 5 last submitted items
BrowseScope scope = new BrowseScope(context);
scope.setScope(collection);
scope.setTotal(5);
List items = Browse.getLastSubmitted(scope);
// Get titles and URLs to item pages
String[] itemTitles = getItemTitles(items);
String[] itemLinks = getItemURLs(context, items);
// perform any necessary pre-processing
preProcessCollectionHome(context, request, response, collection);
// Is the user logged in/subscribed?
EPerson e = context.getCurrentUser();
boolean subscribed = false;
@@ -521,8 +524,6 @@ public class HandleServlet extends DSpaceServlet
}
// Forward to collection home page
request.setAttribute("last.submitted.titles", itemTitles);
request.setAttribute("last.submitted.urls", itemLinks);
request.setAttribute("collection", collection);
request.setAttribute("community", community);
request.setAttribute("logged.in", new Boolean(e != null));
@@ -536,6 +537,25 @@ public class HandleServlet extends DSpaceServlet
}
}
private void preProcessCollectionHome(Context context, HttpServletRequest request,
HttpServletResponse response, Collection collection)
throws ServletException, IOException, SQLException
{
try
{
CollectionHomeProcessor[] chp = (CollectionHomeProcessor[]) PluginManager.getPluginSequence(CollectionHomeProcessor.class);
for (int i = 0; i < chp.length; i++)
{
chp[i].process(context, request, response, collection);
}
}
catch (Exception e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
}
/**
* Check to see if a browse or search button has been pressed on a community
* or collection home page. If so, redirect to the appropriate URL.
@@ -573,27 +593,7 @@ public class HandleServlet extends DSpaceServlet
prefix = "/handle/" + location + "/";
}
if (button.equals("submit_titles"))
{
// Redirect to browse by title
url = request.getContextPath() + prefix + "browse-title";
}
else if (button.equals("submit_authors"))
{
// Redirect to browse authors
url = request.getContextPath() + prefix + "browse-author";
}
else if (button.equals("submit_subjects"))
{
// Redirect to browse by date
url = request.getContextPath() + prefix + "browse-subject";
}
else if (button.equals("submit_dates"))
{
// Redirect to browse by date
url = request.getContextPath() + prefix + "browse-date";
}
else if (button.equals("submit_search")
if (button.equals("submit_search")
|| (request.getParameter("query") != null))
{
/*

View File

@@ -1,138 +0,0 @@
/*
* ItemsByAuthorServlet.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseScope;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* Displays the items with a particular author.
*
* @author Robert Tansley
* @version $Revision$
*/
public class ItemsByAuthorServlet extends DSpaceServlet
{
/** log4j logger */
private static Logger log = Logger.getLogger(ItemsByAuthorServlet.class);
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
// We will resolve the HTTP request parameters into a scope
BrowseScope scope = new BrowseScope(context);
// Get log information
String logInfo = "";
// Get the HTTP parameters
String author = request.getParameter("author");
String order = request.getParameter("order");
// How should we order the items?
boolean orderByTitle;
if ((order != null) && order.equalsIgnoreCase("title"))
{
orderByTitle = true;
logInfo = "order=title";
}
else
{
orderByTitle = false;
logInfo = "order=date";
}
// Get the community or collection scope
Community community = UIUtil.getCommunityLocation(request);
Collection collection = UIUtil.getCollectionLocation(request);
if (collection != null)
{
logInfo = logInfo + ",collection_id=" + collection.getID();
scope.setScope(collection);
}
else if (community != null)
{
logInfo = logInfo + ",community_id=" + community.getID();
scope.setScope(community);
}
// Ensure author is non-null
if (author == null)
{
author = "";
}
// Do the browse
scope.setFocus(author);
BrowseInfo browseInfo = Browse.getItemsByAuthor(scope, orderByTitle);
log.info(LogManager.getHeader(context, "items_by_author", logInfo
+ ",result_count=" + browseInfo.getResultCount()));
// Display the JSP
request.setAttribute("community", community);
request.setAttribute("collection", collection);
request.setAttribute("author", author);
request.setAttribute("order.by.title", new Boolean(orderByTitle));
request.setAttribute("browse.info", browseInfo);
JSPManager.showJSP(request, response, "/browse/items-by-author.jsp");
}
}

View File

@@ -1,137 +0,0 @@
/*
* ItemsBySubjectServlet.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseScope;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
/**
* Displays the items with a particular subject.
*
* @version $Revision$
*/
public class ItemsBySubjectServlet extends DSpaceServlet
{
/** log4j logger */
private static Logger log = Logger.getLogger(ItemsBySubjectServlet.class);
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
// We will resolve the HTTP request parameters into a scope
BrowseScope scope = new BrowseScope(context);
// Get log information
String logInfo = "";
// Get the HTTP parameters
String subject = request.getParameter("subject");
String order = request.getParameter("order");
// How should we order the items?
boolean orderByTitle;
if ((order != null) && order.equalsIgnoreCase("title"))
{
orderByTitle = true;
logInfo = "order=title";
}
else
{
orderByTitle = false;
logInfo = "order=date";
}
// Get the community or collection scope
Community community = UIUtil.getCommunityLocation(request);
Collection collection = UIUtil.getCollectionLocation(request);
if (collection != null)
{
logInfo = logInfo + ",collection_id=" + collection.getID();
scope.setScope(collection);
}
else if (community != null)
{
logInfo = logInfo + ",community_id=" + community.getID();
scope.setScope(community);
}
// Ensure subject is non-null
if (subject == null)
{
subject = "";
}
// Do the browse
scope.setFocus(subject);
BrowseInfo browseInfo = Browse.getItemsBySubject(scope, orderByTitle);
log.info(LogManager.getHeader(context, "items_by_subject", logInfo
+ ",result_count=" + browseInfo.getResultCount()));
// Display the JSP
request.setAttribute("community", community);
request.setAttribute("collection", collection);
request.setAttribute("subject", subject);
request.setAttribute("order.by.title", new Boolean(orderByTitle));
request.setAttribute("browse.info", browseInfo);
JSPManager.showJSP(request, response, "/browse/items-by-subject.jsp");
}
}

View File

@@ -39,26 +39,33 @@
*/
package org.dspace.app.webui.servlet.admin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedList;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.servlet.DSpaceServlet;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowserScope;
import org.dspace.browse.IndexBrowse;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
import org.dspace.storage.rdbms.TableRowIterator;
/**
* Servlet for editing and deleting (expunging) items
@@ -67,6 +74,9 @@ import org.dspace.storage.rdbms.TableRowIterator;
*/
public class ItemMapServlet extends DSpaceServlet
{
/** Logger */
private static Logger log = Logger.getLogger(ItemMapServlet.class);
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws java.sql.SQLException,
javax.servlet.ServletException, java.io.IOException,
@@ -80,329 +90,372 @@ public class ItemMapServlet extends DSpaceServlet
javax.servlet.ServletException, java.io.IOException,
AuthorizeException
{
String jspPage = null;
// get with a collection ID means put up browse window
int myID = UIUtil.getIntParameter(request, "cid");
// get collection
Collection myCollection = Collection.find(context, myID);
// authorize check
AuthorizeManager.authorizeAction(context, myCollection,
Constants.COLLECTION_ADMIN);
String action = request.getParameter("action");
if (action == null)
{
action = "";
}
// Defined non-empty value shows that 'Cancel' has been pressed
String cancel = request.getParameter("cancel");
if (cancel == null)
{
cancel = "";
}
if (action.equals("") || !cancel.equals(""))
{
// get with no action parameter set means to put up the main page
// which is statistics and some command buttons to add/remove items
//
// also holds for interruption by pressing 'Cancel'
int count_native = 0; // # of items owned by this collection
int count_import = 0; // # of virtual items
Map myItems = new HashMap(); // # for the browser
Map myCollections = new HashMap(); // collections for list
Map myCounts = new HashMap(); // counts for each collection
// get all items from that collection, add them to a hash
ItemIterator i = myCollection.getItems();
// iterate through the items in this collection, and count how many
// are native, and how many are imports, and which collections they
// came from
while (i.hasNext())
{
Item myItem = i.next();
// get key for hash
Integer myKey = new Integer(myItem.getID());
if (myItem.isOwningCollection(myCollection))
{
count_native++;
}
else
{
count_import++;
}
// is the collection in the hash?
Collection owningCollection = myItem.getOwningCollection();
Integer cKey = new Integer(owningCollection.getID());
if (myCollections.containsKey(cKey))
{
Integer x = (Integer) myCounts.get(cKey);
int myCount = x.intValue() + 1;
// increment count for that collection
myCounts.put(cKey, new Integer(myCount));
}
else
{
// store and initialize count
myCollections.put(cKey, owningCollection);
myCounts.put(cKey, new Integer(1));
}
// store the item
myItems.put(myKey, myItem);
}
// remove this collection's entry because we already have a native
// count
myCollections.remove(new Integer(myCollection.getID()));
// sort items - later
// show page
request.setAttribute("collection", myCollection);
request.setAttribute("count_native", new Integer(count_native));
request.setAttribute("count_import", new Integer(count_import));
request.setAttribute("items", myItems);
request.setAttribute("collections", myCollections);
request.setAttribute("collection_counts", myCounts);
request
.setAttribute("all_collections", Collection
.findAll(context));
// show this page when we're done
jspPage = "itemmap-main.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
/*
* else if( action.equals("add") ) { int itemID =
* UIUtil.getIntParameter(request, "item_id"); String handle =
* (String)request.getParameter("handle"); boolean error = true; Item
* itemToAdd = null;
*
* if( itemID > 0 ) { itemToAdd = Item.find(context, itemID);
*
* if( itemToAdd != null ) error = false; } else if(handle != null &&
* !handle.equals("")) { DSpaceObject
* dso=HandleManager.resolveToObject(context, handle);
*
* if(dso != null && dso.getType() == Constants.ITEM) { itemToAdd =
* (Item)dso; error = false; } }
*
* //FIXME: error handling! if( !error ) { String myTitle =
* itemToAdd.getDC("title",null,Item.ANY)[0].value; String ownerName =
* itemToAdd.getOwningCollection().getMetadata("name");
* // hook up item, but first, does it belong already? TableRowIterator
* tri = DatabaseManager.query(context, "collection2item", "SELECT
* collection2item.* FROM collection2item WHERE " + "collection_id=" +
* myCollection.getID() + " AND item_id=" + itemToAdd.getID());
*
* if(tri.hasNext()) { request.setAttribute("message", "Item is already
* part of that collection!"); } else { // Create mapping
* myCollection.addItem( itemToAdd );
* // set up a nice 'done' message request.setAttribute("message",
* "Item added successfully: <br> " + myTitle + " <br> From Collection:
* <br> " + ownerName);
* }
*
* request.setAttribute("collection", myCollection);
* // show this page when we're done jspPage = "itemmap-info.jsp";
* // show the page JSPManager.showJSP(request, response, jspPage); }
* else { // Display an error } } else if( action.equals("Add Entire
* Collection") ) { int targetID = UIUtil.getIntParameter(request,
* "collection2import");
*
* Collection targetCollection = Collection.find(context, targetID);
* // get all items from that collection and add them if not // already
* added
* // get all items to be added ItemIterator i =
* targetCollection.getItems(); Map toAdd = new HashMap(); String
* message = "";
*
* while( i.hasNext() ) { Item myItem = i.next();
*
* toAdd.put(new Integer(myItem.getID()), myItem); }
* // now see what we already have, removing dups from the 'toAdd' list
* i = myCollection.getItems();
*
* while( i.hasNext() ) { Item myItem = i.next(); Integer myKey = new
* Integer(myItem.getID());
* // remove works even if key isn't present toAdd.remove(myKey); }
* // what's left in toAdd should be added Iterator addKeys =
* toAdd.keySet().iterator();
*
* while( addKeys.hasNext() ) { Item myItem =
* (Item)toAdd.get(addKeys.next()); myCollection.addItem(myItem);
* message += " <br> Added item ID: " + myItem.getID(); }
*
* request.setAttribute("message", message);
* request.setAttribute("collection", myCollection);
* // show this page when we're done jspPage = "itemmap-info.jsp";
* // show the page JSPManager.showJSP(request, response, jspPage); }
*/
else if (action.equals("Remove"))
{
// get item IDs to remove
String[] itemIDs = request.getParameterValues("item_ids");
String message = "remove";
LinkedList removedItems = new LinkedList();
for (int j = 0; j < itemIDs.length; j++)
{
int i = Integer.parseInt(itemIDs[j]);
removedItems.add(itemIDs[j]);
Item myItem = Item.find(context, i);
// make sure item doesn't belong to this collection
if (!myItem.isOwningCollection(myCollection))
{
myCollection.removeItem(myItem);
}
}
request.setAttribute("message", message);
request.setAttribute("collection", myCollection);
request.setAttribute("processedItems", removedItems);
// show this page when we're done
jspPage = "itemmap-info.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
else if (action.equals("Add"))
{
// get item IDs to add
String[] itemIDs = request.getParameterValues("item_ids");
String message = "added";
LinkedList addedItems = new LinkedList();
if (itemIDs == null)
{
message = "none-selected";
}
else
{
for (int j = 0; j < itemIDs.length; j++)
{
int i = Integer.parseInt(itemIDs[j]);
Item myItem = Item.find(context, i);
if (AuthorizeManager.authorizeActionBoolean(context,
myItem, Constants.READ))
{
// make sure item doesn't belong to this collection
if (!myItem.isOwningCollection(myCollection))
{
myCollection.addItem(myItem);
addedItems.add(itemIDs[j]);
}
}
}
}
request.setAttribute("message", message);
request.setAttribute("collection", myCollection);
request.setAttribute("processedItems", addedItems);
// show this page when we're done
jspPage = "itemmap-info.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
else if (action.equals("Search Authors"))
{
// find all items with a matching author string and not currently in
// this collection
// sorting by date would be ideal...
String myQuery = (String) request.getParameter("namepart");
TableRowIterator tri = DatabaseManager.query(context,
"SELECT * from ItemsByAuthor WHERE sort_author like ? AND " +
"item_id NOT IN (SELECT item_id FROM collection2item " +
"WHERE collection_id= ? )",
'%'+myQuery.toLowerCase()+'%',myCollection.getID());
Map items = new HashMap();
while (tri.hasNext())
{
TableRow tr = tri.next();
// now instantiate and pass items to 'Add' page
int itemID = tr.getIntColumn("item_id");
Item myItem = Item.find(context, itemID);
// only put on list if you can read item
if (AuthorizeManager.authorizeActionBoolean(context, myItem,
Constants.READ))
{
items.put(new Integer(itemID), myItem);
}
}
tri.close();
request.setAttribute("collection", myCollection);
request.setAttribute("browsetext", myQuery);
request.setAttribute("items", items);
request.setAttribute("browsetype", new String("Add"));
jspPage = "itemmap-browse.jsp";
JSPManager.showJSP(request, response, jspPage);
}
else if (action.equals("browse"))
{
// target collection to browse
int t = UIUtil.getIntParameter(request, "t");
Collection targetCollection = Collection.find(context, t);
// now find all imported items from that collection
// seemingly inefficient, but database should have this query cached
ItemIterator i = myCollection.getItems();
Map items = new HashMap();
while (i.hasNext())
{
Item myItem = i.next();
if (myItem.isOwningCollection(targetCollection))
{
Integer myKey = new Integer(myItem.getID());
items.put(myKey, myItem);
}
}
request.setAttribute("collection", myCollection);
request.setAttribute("browsetext", targetCollection
.getMetadata("name"));
request.setAttribute("items", items);
request.setAttribute("browsetype", new String("Remove"));
// show this page when we're done
jspPage = "itemmap-browse.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
context.complete();
String jspPage = null;
// get with a collection ID means put up browse window
int myID = UIUtil.getIntParameter(request, "cid");
// get collection
Collection myCollection = Collection.find(context, myID);
// authorize check
AuthorizeManager.authorizeAction(context, myCollection,
Constants.COLLECTION_ADMIN);
String action = request.getParameter("action");
if (action == null)
{
action = "";
}
// Defined non-empty value shows that 'Cancel' has been pressed
String cancel = request.getParameter("cancel");
if (cancel == null)
{
cancel = "";
}
if (action.equals("") || !cancel.equals(""))
{
// get with no action parameter set means to put up the main page
// which is statistics and some command buttons to add/remove items
//
// also holds for interruption by pressing 'Cancel'
int count_native = 0; // # of items owned by this collection
int count_import = 0; // # of virtual items
Map myItems = new HashMap(); // # for the browser
Map myCollections = new HashMap(); // collections for list
Map myCounts = new HashMap(); // counts for each collection
// get all items from that collection, add them to a hash
ItemIterator i = myCollection.getItems();
// iterate through the items in this collection, and count how many
// are native, and how many are imports, and which collections they
// came from
while (i.hasNext())
{
Item myItem = i.next();
// get key for hash
Integer myKey = new Integer(myItem.getID());
if (myItem.isOwningCollection(myCollection))
{
count_native++;
}
else
{
count_import++;
}
// is the collection in the hash?
Collection owningCollection = myItem.getOwningCollection();
Integer cKey = new Integer(owningCollection.getID());
if (myCollections.containsKey(cKey))
{
Integer x = (Integer) myCounts.get(cKey);
int myCount = x.intValue() + 1;
// increment count for that collection
myCounts.put(cKey, new Integer(myCount));
}
else
{
// store and initialize count
myCollections.put(cKey, owningCollection);
myCounts.put(cKey, new Integer(1));
}
// store the item
myItems.put(myKey, myItem);
}
// remove this collection's entry because we already have a native
// count
myCollections.remove(new Integer(myCollection.getID()));
// sort items - later
// show page
request.setAttribute("collection", myCollection);
request.setAttribute("count_native", new Integer(count_native));
request.setAttribute("count_import", new Integer(count_import));
request.setAttribute("items", myItems);
request.setAttribute("collections", myCollections);
request.setAttribute("collection_counts", myCounts);
request
.setAttribute("all_collections", Collection
.findAll(context));
// show this page when we're done
jspPage = "itemmap-main.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
/*
* else if( action.equals("add") ) { int itemID =
* UIUtil.getIntParameter(request, "item_id"); String handle =
* (String)request.getParameter("handle"); boolean error = true; Item
* itemToAdd = null;
*
* if( itemID > 0 ) { itemToAdd = Item.find(context, itemID);
*
* if( itemToAdd != null ) error = false; } else if(handle != null &&
* !handle.equals("")) { DSpaceObject
* dso=HandleManager.resolveToObject(context, handle);
*
* if(dso != null && dso.getType() == Constants.ITEM) { itemToAdd =
* (Item)dso; error = false; } }
*
* //FIXME: error handling! if( !error ) { String myTitle =
* itemToAdd.getDC("title",null,Item.ANY)[0].value; String ownerName =
* itemToAdd.getOwningCollection().getMetadata("name");
* // hook up item, but first, does it belong already? TableRowIterator
* tri = DatabaseManager.query(context, "collection2item", "SELECT
* collection2item.* FROM collection2item WHERE " + "collection_id=" +
* myCollection.getID() + " AND item_id=" + itemToAdd.getID());
*
* if(tri.hasNext()) { request.setAttribute("message", "Item is already
* part of that collection!"); } else { // Create mapping
* myCollection.addItem( itemToAdd );
* // set up a nice 'done' message request.setAttribute("message",
* "Item added successfully: <br> " + myTitle + " <br> From Collection:
* <br> " + ownerName);
* }
*
* request.setAttribute("collection", myCollection);
* // show this page when we're done jspPage = "itemmap-info.jsp";
* // show the page JSPManager.showJSP(request, response, jspPage); }
* else { // Display an error } } else if( action.equals("Add Entire
* Collection") ) { int targetID = UIUtil.getIntParameter(request,
* "collection2import");
*
* Collection targetCollection = Collection.find(context, targetID);
* // get all items from that collection and add them if not // already
* added
* // get all items to be added ItemIterator i =
* targetCollection.getItems(); Map toAdd = new HashMap(); String
* message = "";
*
* while( i.hasNext() ) { Item myItem = i.next();
*
* toAdd.put(new Integer(myItem.getID()), myItem); }
* // now see what we already have, removing dups from the 'toAdd' list
* i = myCollection.getItems();
*
* while( i.hasNext() ) { Item myItem = i.next(); Integer myKey = new
* Integer(myItem.getID());
* // remove works even if key isn't present toAdd.remove(myKey); }
* // what's left in toAdd should be added Iterator addKeys =
* toAdd.keySet().iterator();
*
* while( addKeys.hasNext() ) { Item myItem =
* (Item)toAdd.get(addKeys.next()); myCollection.addItem(myItem);
* message += " <br> Added item ID: " + myItem.getID(); }
*
* request.setAttribute("message", message);
* request.setAttribute("collection", myCollection);
* // show this page when we're done jspPage = "itemmap-info.jsp";
* // show the page JSPManager.showJSP(request, response, jspPage); }
*/
else if (action.equals("Remove"))
{
// get item IDs to remove
String[] itemIDs = request.getParameterValues("item_ids");
String message = "remove";
LinkedList removedItems = new LinkedList();
for (int j = 0; j < itemIDs.length; j++)
{
int i = Integer.parseInt(itemIDs[j]);
removedItems.add(itemIDs[j]);
Item myItem = Item.find(context, i);
// make sure item doesn't belong to this collection
if (!myItem.isOwningCollection(myCollection))
{
myCollection.removeItem(myItem);
try
{
IndexBrowse ib = new IndexBrowse(context);
ib.itemChanged(myItem);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
}
}
request.setAttribute("message", message);
request.setAttribute("collection", myCollection);
request.setAttribute("processedItems", removedItems);
// show this page when we're done
jspPage = "itemmap-info.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
else if (action.equals("Add"))
{
// get item IDs to add
String[] itemIDs = request.getParameterValues("item_ids");
String message = "added";
LinkedList addedItems = new LinkedList();
if (itemIDs == null)
{
message = "none-selected";
}
else
{
for (int j = 0; j < itemIDs.length; j++)
{
int i = Integer.parseInt(itemIDs[j]);
Item myItem = Item.find(context, i);
if (AuthorizeManager.authorizeActionBoolean(context,
myItem, Constants.READ))
{
// make sure item doesn't belong to this collection
if (!myItem.isOwningCollection(myCollection))
{
myCollection.addItem(myItem);
try
{
IndexBrowse ib = new IndexBrowse(context);
ib.itemChanged(myItem);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
addedItems.add(itemIDs[j]);
}
}
}
}
request.setAttribute("message", message);
request.setAttribute("collection", myCollection);
request.setAttribute("processedItems", addedItems);
// show this page when we're done
jspPage = "itemmap-info.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
else if (action.equals("Search Authors"))
{
String name = (String) request.getParameter("namepart");
String bidx = ConfigurationManager.getProperty("itemmap.author.index");
if (bidx == null)
{
throw new ServletException("There is no configuration for itemmap.author.index");
}
Map items = new HashMap();
try
{
BrowserScope bs = new BrowserScope(context);
BrowseIndex bi = BrowseIndex.getBrowseIndex(bidx);
// set up the browse scope
bs.setBrowseIndex(bi);
bs.setOrder("ASC");
bs.setValue(name);
bs.setValueFocus(null);
bs.setResultsPerPage(10000); // an arbitrary number (large) for the time being
bs.setSortBy(0);
bs.setBrowseLevel(1);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo results = be.browse(bs);
Item[] browseItems = results.getItemResults(context);
// FIXME: oh god this is so annoying - what an API /Richard
// we need to deduplicate against existing items in this collection
ItemIterator itr = myCollection.getItems();
ArrayList idslist = new ArrayList();
while (itr.hasNext())
{
idslist.add(new Integer(itr.nextID()));
}
for (int i = 0; i < browseItems.length; i++)
{
// only if it isn't already in this collection
if (!idslist.contains(new Integer(browseItems[i].getID())))
{
// only put on list if you can read item
if (AuthorizeManager.authorizeActionBoolean(context, browseItems[i], Constants.READ))
{
items.put(new Integer(browseItems[i].getID()), browseItems[i]);
}
}
}
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
request.setAttribute("collection", myCollection);
request.setAttribute("browsetext", name);
request.setAttribute("items", items);
request.setAttribute("browsetype", new String("Add"));
jspPage = "itemmap-browse.jsp";
JSPManager.showJSP(request, response, jspPage);
}
else if (action.equals("browse"))
{
// target collection to browse
int t = UIUtil.getIntParameter(request, "t");
Collection targetCollection = Collection.find(context, t);
// now find all imported items from that collection
// seemingly inefficient, but database should have this query cached
ItemIterator i = myCollection.getItems();
Map items = new HashMap();
while (i.hasNext())
{
Item myItem = i.next();
if (myItem.isOwningCollection(targetCollection))
{
Integer myKey = new Integer(myItem.getID());
items.put(myKey, myItem);
}
}
request.setAttribute("collection", myCollection);
request.setAttribute("browsetext", targetCollection
.getMetadata("name"));
request.setAttribute("items", items);
request.setAttribute("browsetype", new String("Remove"));
// show this page when we're done
jspPage = "itemmap-browse.jsp";
// show the page
JSPManager.showJSP(request, response, jspPage);
}
context.complete();
}
}

View File

@@ -251,6 +251,37 @@
</attribute>
</tag>
<tag>
<name>browselist</name>
<tagclass>org.dspace.app.webui.jsptag.BrowseListTag</tagclass>
<info>
Tag for displaying a list of items. Specify highlightrow (starting
from zero) if a row should be highlit. Specify an emphcolumn of
"date" or "title" to emphasise the contents of a column.
</info>
<attribute>
<name>items</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>browseInfo</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>highlightrow</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>emphcolumn</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>communitylist</name>
<tagclass>org.dspace.app.webui.jsptag.CommunityListTag</tagclass>

View File

@@ -189,7 +189,7 @@
<attribute>
<name>key</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>bundle</name>
@@ -219,7 +219,7 @@
<attribute>
<name>value</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>

View File

@@ -154,41 +154,10 @@
<servlet-class>org.dspace.app.webui.servlet.BitstreamServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>browse-author</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.BrowseServlet</servlet-class>
<init-param>
<param-name>browse</param-name>
<param-value>authors</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>browse-date</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.BrowseServlet</servlet-class>
<init-param>
<param-name>browse</param-name>
<param-value>dates</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>browse-subject</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.BrowseServlet</servlet-class>
<init-param>
<param-name>browse</param-name>
<param-value>subjects</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>browse-title</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.BrowseServlet</servlet-class>
<init-param>
<param-name>browse</param-name>
<param-value>titles</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>browse</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.BrowserServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>collection-wizard</servlet-name>
@@ -288,16 +257,6 @@
<servlet-class>org.dspace.app.webui.servlet.InternalErrorServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>items-by-author</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.ItemsByAuthorServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>items-by-subject</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.ItemsBySubjectServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>logout</servlet-name>
<servlet-class>org.dspace.app.webui.servlet.LogoutServlet</servlet-class>
@@ -434,25 +393,10 @@
<url-pattern>/bitstream/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>browse-author</servlet-name>
<url-pattern>/browse-author</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>browse-date</servlet-name>
<url-pattern>/browse-date</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>browse-subject</servlet-name>
<url-pattern>/browse-subject</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>browse-title</servlet-name>
<url-pattern>/browse-title</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>browse</servlet-name>
<url-pattern>/browse</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>community-list</servlet-name>
@@ -554,16 +498,6 @@
<url-pattern>/internal-error</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>items-by-author</servlet-name>
<url-pattern>/items-by-author</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>items-by-subject</servlet-name>
<url-pattern>/items-by-subject</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>logout</servlet-name>
<url-pattern>/logout</url-pattern>

View File

@@ -1,218 +0,0 @@
<%--
- authors.jsp
-
- Version: $Revision$
-
- Date: $Date$
-
- Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
- Display the results of browsing the author index
-
- Attributes to pass in:
- community - pass in if the scope of the browse is a community, or
- a collection within this community
- collection - pass in if the scope of the browse is a collection
- browse.info - the BrowseInfo containing the authors to display
- highlight - Boolean. If true, the focus point of the browse
- is highlighted
- previous.query - The query string to pass to the servlet to get the
- previous page of authors
- next.query - The query string to pass to the servlet to get the next
- page of aitjprs
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.util.List" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.DCDate" %>
<%@ page import="org.dspace.content.DCValue" %>
<%@ page import="org.dspace.content.Item" %>
<%@ page import="org.dspace.core.Utils" %>
<%@ page import="javax.servlet.jsp.jstl.fmt.*" %>
<%@ page import="org.apache.taglibs.standard.tag.common.fmt.BundleSupport" %>
<%@ page import="java.util.Locale" %>
<%
// Get attributes
Collection collection = (Collection) request.getAttribute("collection");
Community community = (Community) request.getAttribute("community");
BrowseInfo browseInfo = (BrowseInfo) request.getAttribute("browse.info");
boolean highlight = ((Boolean) request.getAttribute("highlight")).booleanValue();
String prevQuery = (String) request.getAttribute("previous.query");
String nextQuery = (String) request.getAttribute("next.query");
%>
<dspace:layout titlekey="jsp.browse.authors.title">
<h2><fmt:message key="jsp.browse.authors.title"/></h2>
<form action="browse-author" method="get">
<%-- Browse controls --%>
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2"> <%--allow for greek alphabet also--%>
<tr>
<td class="browseBar">
<%--<span class="browseBarLabel">Jump&nbsp;to:&nbsp;</span>--%>
<span class="browseBarLabel"><fmt:message key="jsp.browse.authors.jump"/></span>
<a href="browse-author?starts_with=0">0-9</a>
<%
for (char c = 'A'; c <= 'Z'; c++)
{
%>
<a href="browse-author?starts_with=<%= c %>"><%= c %></a>
<%
}
%>
</td>
</tr>
<tr>
<td class="browseBar" align="center" id="tstarts_with">
<span class="browseBarLabel"><label for="tstarts_with"><fmt:message key="jsp.browse.authors.enter"/>&nbsp;</label></span>
<%--<span class="browseBarLabel">or enter first few letters:&nbsp;</span>--%>
<%--<input type="text" name="starts_with">&nbsp;<input type="submit" value="Go!">--%>
<input type="text" name="starts_with"/>&nbsp;<input type="submit" value="<fmt:message key="jsp.browse.general.go"/>" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<br />
<%--<p align="center">Showing authors <%= browseInfo.getOverallPosition() + 1 %>-<%= browseInfo.getOverallPosition() + browseInfo.getResultCount() %> of <%= browseInfo.getTotal() %>.</p>--%>
<p align="center"><fmt:message key="jsp.browse.authors.show">
<fmt:param><%= browseInfo.getOverallPosition() + 1 %></fmt:param>
<fmt:param><%= browseInfo.getOverallPosition() + browseInfo.getResultCount() %></fmt:param>
<fmt:param><%= browseInfo.getTotal() %></fmt:param>
</fmt:message></p>
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<%-- <a="browse-author?<%= prevQuery %>">Previous page</a> --%>
<a href="browse-author?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-author?<%= nextQuery %>">Next page</a> --%>
<a href="browse-author?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
<%-- The authors --%>
<table align="center" class="miscTable" summary="This table displays a list of authors">
<%
// Row: toggles between Odd and Even
String row = "odd";
String[] results = browseInfo.getStringResults();
for (int i = 0; i < results.length; i++)
{
%>
<tr>
<td class="<%= highlight && i==browseInfo.getOffset() ? "highlight" : row %>RowOddCol">
<a href="items-by-author?author=<%= URLEncoder.encode(results[i], "UTF-8") %>"><%= Utils.addEntities(results[i]) %></a>
</td>
</tr>
<%
row = ( row.equals( "odd" ) ? "even" : "odd" );
}
%>
</table>
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<a href="browse-author?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-author?<%= nextQuery %>">Next page</a> --%>
<a href="browse-author?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
</form>
</dspace:layout>

View File

@@ -0,0 +1,524 @@
<%--
- full.jsp
-
- Version: $Revision: 1.0 $
-
- Date: $Date: 2006/04/27 00:00:00 $
-
- Copyright (c) 2006, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
- Display the results of browsing a full hit list
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.browse.BrowseIndex" %>
<%@ page import="org.dspace.browse.SortOption" %>
<%@ page import="org.dspace.core.ConfigurationManager" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="org.dspace.content.DCDate" %>
<%@ page import="org.dspace.app.webui.util.UIUtil" %>
<%
// First, get the browse info object
BrowseInfo bi = (BrowseInfo) request.getAttribute("browse.info");
BrowseIndex bix = bi.getBrowseIndex();
SortOption so = bi.getSortOption();
Map sos = bix.getSortOptions();
// values used by the header
String scope = "";
String type = "";
String value = "";
Community community = null;
Collection collection = null;
if (bi.inCommunity())
{
community = (Community) bi.getBrowseContainer();
}
if (bi.inCollection())
{
collection = (Collection) bi.getBrowseContainer();
}
if (community != null)
{
scope = "\"" + community.getMetadata("name") + "\"";
}
if (collection != null)
{
scope = "\"" + collection.getMetadata("name") + "\"";
}
type = bix.getName();
if (bi.hasValue())
{
value = "\"" + bi.getValue() + "\"";
}
// next and previous links are of the form:
// [handle/<prefix>/<suffix>/]browse?type=<type>&sort_by=<sort_by>&order=<order>[&value=<value>][&rpp=<rpp>][&[focus=<focus>|vfocus=<vfocus>]
// prepare the next and previous links
String linkBase = request.getContextPath() + "/";
if (collection != null)
{
linkBase = linkBase + "handle/" + collection.getHandle() + "/";
}
if (community != null)
{
linkBase = linkBase + "handle/" + community.getHandle() + "/";
}
String direction = (bi.isAscending() ? "ASC" : "DESC");
String valueString = "";
if (bi.hasValue())
{
valueString = "&amp;value=" + URLEncoder.encode(bi.getValue());
}
String sharedLink = linkBase + "browse?type=" + URLEncoder.encode(bix.getName()) +
"&amp;sort_by=" + URLEncoder.encode(Integer.toString(so.getNumber())) +
"&amp;order=" + URLEncoder.encode(direction) +
"&amp;rpp=" + URLEncoder.encode(Integer.toString(bi.getResultsPerPage())) +
"&amp;etal=" + URLEncoder.encode(Integer.toString(bi.getEtAl())) +
valueString;
String next = sharedLink;
String prev = sharedLink;
if (bi.hasNextPage())
{
next = next + "&amp;";
if (bi.getNextItem() == -1)
{
next = next + "vfocus=" + URLEncoder.encode(bi.getNextValue());
}
else
{
next = next + "focus=" + URLEncoder.encode(Integer.toString(bi.getNextItem()));
}
}
if (bi.hasPrevPage())
{
prev = prev + "&amp;";
if (bi.getPrevItem() == -1)
{
prev = prev + "vfocus=" + URLEncoder.encode(bi.getPrevValue());
}
else
{
prev = prev + "focus=" + URLEncoder.encode(Integer.toString(bi.getPrevItem()));
}
}
// prepare a url for use by form actions
String formaction = request.getContextPath() + "/";
if (collection != null)
{
formaction = formaction + "handle/" + collection.getHandle() + "/";
}
if (community != null)
{
formaction = formaction + "handle/" + community.getHandle() + "/";
}
formaction = formaction + "browse";
// prepare the known information about sorting, ordering and results per page
String sortedBy = so.getName();
String ascSelected = (bi.isAscending() ? "selected=\"selected\"" : "");
String descSelected = (bi.isAscending() ? "" : "selected=\"selected\"");
int rpp = bi.getResultsPerPage();
// the message key for the type
String typeKey = "browse.type." + bix.getName();
%>
<%-- OK, so here we start to develop the various components we will use in the UI --%>
<dspace:layout titlekey="browse.page-title">
<%-- Build the header (careful use of spacing) --%>
<h2>
<fmt:message key="browse.full.header"><fmt:param value="<%= scope %>"/></fmt:message> <fmt:message key="<%= typeKey %>"/> <%= value %>
</h2>
<%-- Include the main navigation for all the browse pages --%>
<%-- This first part is where we render the standard bits required by both possibly navigations --%>
<div align="center" id="browse_navigation">
<form method="get" action="<%= formaction %>">
<input type="hidden" name="type" value="<%= bix.getName() %>"/>
<input type="hidden" name="sort_by" value="<%= so.getNumber() %>"/>
<input type="hidden" name="order" value="<%= direction %>"/>
<input type="hidden" name="rpp" value="<%= rpp %>"/>
<input type="hidden" name="etal" value="<%= bi.getEtAl() %>" />
<%
if (bi.hasValue())
{
%><input type="hidden" name="value" value="<%= bi.getValue() %>"/><%
}
%>
<%-- If we are browsing by a date, or sorting by a date, render the date selection header --%>
<%
if (so.isDate() || (bix.isDate() && so.isDefault()))
{
%>
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0" summary="Browsing by date">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2">
<tr>
<td class="browseBar">
<span class="browseBarLabel"><fmt:message key="browse.nav.date.jump"/> </span>
<select name="year">
<option selected="selected" value="-1"><fmt:message key="browse.nav.year"/></option>
<%
int thisYear = DCDate.getCurrent().getYear();
for (int i = thisYear; i >= 1990; i--)
{
%>
<option><%= i %></option>
<%
}
%>
<option>1985</option>
<option>1980</option>
<option>1975</option>
<option>1970</option>
<option>1960</option>
<option>1950</option>
</select>
<select name="month">
<option selected="selected" value="-1"><fmt:message key="browse.nav.month"/></option>
<%
for (int i = 1; i <= 12; i++)
{
%>
<option value="<%= i %>"><%= DCDate.getMonthName(i, UIUtil.getSessionLocale(request)) %></option>
<%
}
%>
</select>
</td>
<td class="browseBar" rowspan="2">
<input type="submit" value="<fmt:message key="browse.nav.go"/>" />
</td>
</tr>
<tr>
<%-- HACK: Shouldn't use align here --%>
<td class="browseBar" align="center">
<span class="browseBarLabel"><fmt:message key="browse.nav.type-year"/></span>
<input type="text" name="starts_with" size="4" maxlength="4"/>
</td>
</tr>
</table>
</td>
</tr>
</table>
<%
}
// If we are not browsing by a date, render the string selection header //
else
{
%>
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0" summary="Browse the respository">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2">
<tr>
<td class="browseBar">
<span class="browseBarLabel"><fmt:message key="browse.nav.jump"/></span>
<a href="<%= sharedLink %>&amp;starts_with=0">0-9</a>
<%
for (char c = 'A'; c <= 'Z'; c++)
{
%>
<a href="<%= sharedLink %>&amp;starts_with=<%= c %>"><%= c %></a>
<%
}
%>
</td>
</tr>
<tr>
<td class="browseBar" align="center">
<span class="browseBarLabel"><fmt:message key="browse.nav.enter"/>&nbsp;</span>
<input type="text" name="starts_with"/>&nbsp;<input type="submit" value="<fmt:message key="browse.nav.go"/>" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<%
}
%>
</form>
</div>
<%-- End of Navigation Headers --%>
<%-- Include a component for modifying sort by, order, results per page, and et-al limit --%>
<div align="center" id="browse_controls">
<form method="get" action="<%= formaction %>">
<input type="hidden" name="type" value="<%= bix.getName() %>"/>
<%
if (bi.hasValue())
{
%><input type="hidden" name="value" value="<%= bi.getValue() %>"/><%
}
%>
<%-- The following code can be used to force the browse around the current focus. Without
it the browse will revert to page 1 of the results each time a change is made --%>
<%--
if (!bi.hasItemFocus() && bi.hasFocus())
{
%><input type="hidden" name="vfocus" value="<%= bi.getFocus() %>"/><%
}
--%>
<%--
if (bi.hasItemFocus())
{
%><input type="hidden" name="focus" value="<%= bi.getFocusItem() %>"/><%
}
--%>
<%
if (sos.size() > 1 && bi.getBrowseLevel() > 0)
{
%>
<fmt:message key="browse.full.sort-by"/>
<select name="sort_by">
<%
Iterator itr = sos.keySet().iterator();
while (itr.hasNext())
{
SortOption sortBy = (SortOption) sos.get((Integer) itr.next());
String selected = (sortBy.getName().equals(sortedBy) ? "selected=\"selected\"" : "");
String mKey = "browse.sort-by." + sortBy.getName();
%> <option value="<%= sortBy.getNumber() %>" <%= selected %>><fmt:message key="<%= mKey %>"/></option><%
}
%>
</select>
<%
}
%>
<fmt:message key="browse.full.order"/>
<select name="order">
<option value="ASC" <%= ascSelected %>><fmt:message key="browse.order.asc" /></option>
<option value="DESC" <%= descSelected %>><fmt:message key="browse.order.desc" /></option>
</select>
<fmt:message key="browse.full.rpp"/>
<select name="rpp">
<%
for (int i = 5; i <= 100 ; i += 5)
{
String selected = (i == rpp ? "selected=\"selected\"" : "");
%>
<option value="<%= i %>" <%= selected %>><%= i %></option>
<%
}
%>
</select>
<fmt:message key="browse.full.etal" />
<select name="etal">
<%
String unlimitedSelect = "";
if (bi.getEtAl() == -1)
{
unlimitedSelect = "selected=\"selected\"";
}
%>
<option value="0" <%= unlimitedSelect %>><fmt:message key="browse.full.etal.unlimited"/></option>
<%
int cfgd = ConfigurationManager.getIntProperty("webui.browse.author-limit");
boolean insertedCurrent = false;
boolean insertedDefault = false;
for (int i = 0; i <= 50 ; i += 5)
{
// for the first one, we want 1 author, not 0
if (i == 0)
{
String sel = (i + 1 == bi.getEtAl() ? "selected=\"selected\"" : "");
%><option value="1" <%= sel %>>1</option><%
}
// if the current i is greated than that configured by the user,
// insert the one specified in the right place in the list
if (i > bi.getEtAl() && !insertedCurrent && bi.getEtAl() != -1 && bi.getEtAl() != 0 && bi.getEtAl() != 1)
{
%><option value="<%= bi.getEtAl() %>" selected="selected"><%= bi.getEtAl() %></option><%
insertedCurrent = true;
}
// if the current i is greated than that configured by the administrator (dspace.cfg)
// insert the one specified in the right place in the list
if (i > cfgd && !insertedDefault && cfgd != -1 && cfgd != 0 && cfgd != 1 && bi.getEtAl() != cfgd)
{
%><option value="<%= cfgd %>"><%= cfgd %></option><%
insertedDefault = true;
}
// determine if the current not-special case is selected
String selected = (i == bi.getEtAl() ? "selected=\"selected\"" : "");
// do this for all other cases than the first and the current
if (i != 0 && i != bi.getEtAl())
{
%>
<option value="<%= i %>" <%= selected %>><%= i %></option>
<%
}
}
%>
</select>
<input type="submit" name="submit_browse" value="Update"/>
</form>
</div>
<%-- give us the top report on what we are looking at --%>
<div align="center" class="browse_range">
<fmt:message key="browse.full.range">
<fmt:param value="<%= Integer.toString(bi.getStart()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getFinish()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getTotal()) %>"/>
</fmt:message>
</div>
<%-- do the top previous and next page links --%>
<div align="center">
<%
if (bi.hasPrevPage())
{
%>
<a href="<%= prev %>"><fmt:message key="browse.full.prev"/></a>&nbsp;
<%
}
%>
<%
if (bi.hasNextPage())
{
%>
&nbsp;<a href="<%= next %>"><fmt:message key="browse.full.next"/></a>
<%
}
%>
</div>
<%-- output the results using the browselist tag --%>
<dspace:browselist browseInfo="<%= bi %>" emphcolumn="<%= bix.getMetadata() %>" />
<%-- give us the bottom report on what we are looking at --%>
<div align="center" class="browse_range">
<fmt:message key="browse.full.range">
<fmt:param value="<%= Integer.toString(bi.getStart()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getFinish()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getTotal()) %>"/>
</fmt:message>
</div>
<%-- do the bottom previous and next page links --%>
<div align="center">
<%
if (bi.hasPrevPage())
{
%>
<a href="<%= prev %>"><fmt:message key="browse.full.prev"/></a>&nbsp;
<%
}
%>
<%
if (bi.hasNextPage())
{
%>
&nbsp;<a href="<%= next %>"><fmt:message key="browse.full.next"/></a>
<%
}
%>
</div>
<%-- dump the results for debug (uncomment to enable) --%>
<%--
<!-- <%= bi.toString() %> -->
--%>
</dspace:layout>

View File

@@ -1,133 +0,0 @@
<%--
- items_by_author.jsp
-
- Version: $Revision$
-
- Date: $Date$
-
- Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
- Display items by a particular author
-
- Attributes to pass in:
-
- community - pass in if the scope of the browse is a community, or
- a collection within this community
- collection - pass in if the scope of the browse is a collection
- browse.info - the BrowseInfo containing the items to display
- author - The name of the author
- sort.by.date - Boolean. if true, we're sorting by date, otherwise by
- title.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.Item" %>
<%@ page import="org.dspace.core.Utils" %>
<%
Collection collection = (Collection) request.getAttribute("collection");
Community community = (Community) request.getAttribute("community");
BrowseInfo browseInfo = (BrowseInfo) request.getAttribute("browse.info" );
String author = (String) request.getAttribute("author");
boolean orderByTitle = ((Boolean) request.getAttribute("order.by.title")).booleanValue();
%>
<dspace:layout titlekey="jsp.browse.items-by-author.title">
<h2><fmt:message key="jsp.browse.items-by-author.heading1"/> "<%= Utils.addEntities(author) %>"</h2>
<%-- Sorting controls --%>
<table border="0" cellpadding="10" align="center" summary="Browse the repository by author">
<tr>
<td colspan="2" align="center" class="standard">
<%-- <a href="browse-author?starts_with=<%= URLEncoder.encode(author) %>">Return to Browse by Author</a> --%>
<a href="browse-author?starts_with=<%= URLEncoder.encode(author) %>"><fmt:message key="jsp.browse.items-by-author.return"/></a>
</td>
</tr>
<tr>
<td class="standard">
<%
if (orderByTitle)
{
%>
<%-- <strong>Sorting by Title</strong> --%>
<strong><fmt:message key="jsp.browse.items-by-author.sort1"/></strong>
</td>
<td class="standard">
<%-- <a href="items-by-author?author=<%= URLEncoder.encode(author) %>&order=date">Sort by Date</a> --%>
<a href="items-by-author?author=<%= URLEncoder.encode(author) %>&amp;order=date"><fmt:message key="jsp.browse.items-by-author.sort2"/></a>
<%
}
else
{
%>
<%-- <a href="items-by-author?author=<%= URLEncoder.encode(author) %>&order=title">Sort by Title</a> --%>
<a href="items-by-author?author=<%= URLEncoder.encode(author) %>&amp;order=title"><fmt:message key="jsp.browse.items-by-author.sort3"/></a>
</td>
<td class="standard">
<%-- <strong>Sorting by Date</strong> --%>
<strong><fmt:message key="jsp.browse.items-by-author.sort4"/></strong>
<%
}
%>
</td>
</tr>
</table>
<%-- <p align="center">Showing <%= browseInfo.getResultCount() %> items.</p> --%>
<p align="center"><fmt:message key="jsp.browse.items-by-author.show">
<fmt:param><%= browseInfo.getResultCount() %></fmt:param>
</fmt:message></p>
<%-- The items --%>
<%
String emphColumn = (orderByTitle ? "title" : "date");
%>
<dspace:itemlist items="<%= browseInfo.getItemResults() %>" emphcolumn="<%= emphColumn %>" />
</dspace:layout>

View File

@@ -1,289 +0,0 @@
<%--
- items-by-date.jsp
-
- Version: $Revision$
-
- Date: $Date$
-
- Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
- Display the results of browsing a title or date index
-
- Attributes to pass in:
- community - pass in if the scope of the browse is a community, or
- a collection within this community
- collection - pass in if the scope of the browse is a collection
- browse.info - the BrowseInfo containing the items to display
- highlight - Boolean. If true, the focus point of the browse
- is highlighted
- previous.query - The query string to pass to the servlet to get the
- previous page of items
- next.query - The query string to pass to the servlet to get the next
- page of items
- oldest.first - Boolean - if browsing dates, indicates whether oldest
- items are first
- flip.ordering.query - the query string for flipping the order of the
- index between oldest first and most recent first
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="org.dspace.core.I18nUtil" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.DCDate" %>
<%@ page import="org.dspace.content.DCValue" %>
<%@ page import="org.dspace.content.Item" %>
<%
// Get attributes
Collection collection = (Collection) request.getAttribute("collection");
Community community = (Community) request.getAttribute("community");
BrowseInfo browseInfo = (BrowseInfo) request.getAttribute("browse.info");
boolean highlight = ((Boolean) request.getAttribute("highlight")).booleanValue();
String prevQuery = (String) request.getAttribute("previous.query");
String nextQuery = (String) request.getAttribute("next.query");
// Browse by date only stuff
boolean oldestFirst = ((Boolean) request.getAttribute("oldest.first")).booleanValue();
String flipOrderingQuery = (String) request.getAttribute("flip.ordering.query");
%>
<dspace:layout titlekey="jsp.browse.items-by-date.title">
<h2><fmt:message key="jsp.browse.items-by-date.title"/></h2>
<%-- Date browse controls table --%>
<form action="browse-date" method="get">
<%
if (oldestFirst)
{
// Remember ordering when using browse controls
%>
<input type="hidden" name="order" value="oldestfirst"/>
<%
}
%>
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0" summary="Browse the respository by date">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2">
<tr>
<td class="browseBar">
<%-- <span class="browseBarLabel">Jump to a point in the index: </span> --%>
<span class="browseBarLabel"><fmt:message key="jsp.browse.items-by-date.jump"/> </span>
<select name="month">
<%-- <option selected value="-1">(Choose month)</option> --%>
<option selected="selected" value="-1"><fmt:message key="jsp.browse.items-by-date.month"/></option>
<%
for (int i = 1; i <= 12; i++)
{
%>
<option value="<%= i %>"><%= DCDate.getMonthName(i, I18nUtil.getSupportedLocale(request.getLocale())) %></option>
<%
}
%>
</select>
<select name="year">
<%-- <option selected value="-1">(Choose year)</option> --%>
<option selected="selected" value="-1"><fmt:message key="jsp.browse.items-by-date.year"/></option>
<%
int thisYear = DCDate.getCurrent().getYear();
for (int i = thisYear; i >= 1990; i--)
{
%>
<option><%= i %></option>
<%
}
%>
<option>1985</option>
<option>1980</option>
<option>1975</option>
<option>1970</option>
<option>1960</option>
<option>1950</option>
</select>
</td>
<td class="browseBar" rowspan="2">
<%-- <input type="submit" value="Go"> --%>
<input type="submit" value="<fmt:message key="jsp.browse.general.go"/>" />
</td>
</tr>
<tr>
<%-- HACK: Shouldn't use align here --%>
<td class="browseBar" align="center">
<%-- <span class="browseBarLabel">Or type in a year:</span> --%>
<span class="browseBarLabel"><fmt:message key="jsp.browse.items-by-date.type"/></span>
<input type="text" name="starts_with" size="4" maxlength="4"/>
</td>
</tr>
</table>
</td>
</tr>
</table>
<%-- Flip the ordering controls --%>
<table border="0" width="70%" align="center">
<tr>
<td align="left" class="standard">
<%
if (oldestFirst)
{
%>
<%-- <a href="browse-date?<%= flipOrderingQuery %>">Show Most Recent First</a> --%>
<a href="browse-date?<%= flipOrderingQuery %>"><fmt:message key="jsp.browse.items-by-date.recent"/></a>
<%
}
else
{
%>
<%-- <strong>Ordering With Most Recent First</strong> --%>
<strong><fmt:message key="jsp.browse.items-by-date.order1"/></strong>
<%
}
%>
</td>
<td align="right" class="standard">
<%
if( oldestFirst )
{
%>
<%-- <strong>Ordering With Oldest First</strong> --%>
<strong><fmt:message key="jsp.browse.items-by-date.order2"/></strong>
<%
}
else
{
%>
<%-- <a href="browse-date?<%= flipOrderingQuery %>order=oldestfirst">Show Oldest First</a> --%>
<a href="browse-date?<%= flipOrderingQuery %>order=oldestfirst"><fmt:message key="jsp.browse.items-by-date.old"/></a>
<%
}
%>
</td>
</tr>
</table>
</form>
<br/>
<%-- <p align="center">Showing items <%= browseInfo.getOverallPosition()+1 %>-<%= browseInfo.getOverallPosition()+browseInfo.getResultCount() %> of <%= browseInfo.getTotal() %>.</p> --%>
<p align="center"><fmt:message key="jsp.browse.items-by-date.show">
<fmt:param><%= browseInfo.getOverallPosition()+1 %></fmt:param>
<fmt:param><%= browseInfo.getOverallPosition()+browseInfo.getResultCount() %></fmt:param>
<fmt:param><%= browseInfo.getTotal() %></fmt:param>
</fmt:message></p>
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<%-- <a href="browse-date?<%= prevQuery %>">Previous page</a> --%>
<a href="browse-date?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-date?<%= nextQuery %>">Next page</a> --%>
<a href="browse-date?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
<%
String highlightAttribute = "-1";
if (highlight)
{
highlightAttribute = String.valueOf(browseInfo.getOffset());
}
%>
<dspace:itemlist items="<%= browseInfo.getItemResults() %>" emphcolumn="date" highlightrow="<%= highlightAttribute %>" />
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<%-- <a href="browse-date?<%= prevQuery %>">Previous page</a> --%>
<a href="browse-date?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-date?<%= nextQuery %>">Next page</a> --%>
<a href="browse-date?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
</dspace:layout>

View File

@@ -1,126 +0,0 @@
<%--
- items_by_subject.jsp
-
- Version: $Revision$
-
- Date: $Date$
-
- Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
- Display items by a particular subject
-
- Attributes to pass in:
-
- community - pass in if the scope of the browse is a community, or
- a collection within this community
- collection - pass in if the scope of the browse is a collection
- browse.info - the BrowseInfo containing the items to display
- subject - The name of the subject
- sort.by.date - Boolean. if true, we're sorting by date, otherwise by
- title.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.Item" %>
<%@ page import="org.dspace.core.Utils" %>
<%
Collection collection = (Collection) request.getAttribute("collection");
Community community = (Community) request.getAttribute("community");
BrowseInfo browseInfo = (BrowseInfo) request.getAttribute("browse.info" );
String subject = (String) request.getAttribute("subject");
boolean orderByTitle = ((Boolean) request.getAttribute("order.by.title")).booleanValue();
%>
<dspace:layout titlekey="jsp.browse.items-by-subject.title">
<h2><fmt:message key="jsp.browse.items-by-subject.heading1"/> "<%= Utils.addEntities(subject) %>"</h2>
<%-- Sorting controls --%>
<table border="0" cellpadding="10" align="center" summary="Browse the repository by subject">
<tr>
<td colspan="2" align="center" class="standard">
<a href="browse-subject?starts_with=<%= URLEncoder.encode(subject) %>"><fmt:message key="jsp.browse.items-by-subject.return"/></a>
</td>
</tr>
<tr>
<td class="standard">
<%
if (orderByTitle)
{
%>
<strong><fmt:message key="jsp.browse.items-by-subject.sort1"/></strong>
</td>
<td class="standard">
<a href="items-by-subject?subject=<%= URLEncoder.encode(subject) %>&amp;order=date"><fmt:message key="jsp.browse.items-by-subject.sort2"/></a>
<%
}
else
{
%>
<a href="items-by-subject?subject=<%= URLEncoder.encode(subject) %>&amp;order=title"><fmt:message key="jsp.browse.items-by-subject.sort3"/></a>
</td>
<td class="standard">
<strong><fmt:message key="jsp.browse.items-by-subject.sort4"/></strong>
<%
}
%>
</td>
</tr>
</table>
<p align="center"><fmt:message key="jsp.browse.items-by-subject.show">
<fmt:param><%= browseInfo.getResultCount() %></fmt:param>
</fmt:message></p>
<%-- The items --%>
<%
String emphColumn = (orderByTitle ? "title" : "date");
%>
<dspace:itemlist items="<%= browseInfo.getItemResults() %>" emphcolumn="<%= emphColumn %>" />
</dspace:layout>

View File

@@ -1,205 +0,0 @@
<%--
- items-by-title.jsp
-
- Version: $Revision$
-
- Date: $Date$
-
- Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
- Display the results of browsing title index
-
- Attributes to pass in:
- community - pass in if the scope of the browse is a community, or
- a collection within this community
- collection - pass in if the scope of the browse is a collection
- browse.info - the BrowseInfo containing the items to display
- highlight - Boolean. If true, the focus point of the browse
- is highlighted
- previous.query - The query string to pass to the servlet to get the
- previous page of items
- next.query - The query string to pass to the servlet to get the next
- page of items
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"
prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.DCDate" %>
<%@ page import="org.dspace.content.DCValue" %>
<%@ page import="org.dspace.content.Item" %>
<%
// Get attributes
Collection collection = (Collection) request.getAttribute("collection");
Community community = (Community) request.getAttribute("community");
BrowseInfo browseInfo = (BrowseInfo) request.getAttribute("browse.info");
boolean highlight = ((Boolean) request.getAttribute("highlight")).booleanValue();
String prevQuery = (String) request.getAttribute("previous.query");
String nextQuery = (String) request.getAttribute("next.query");
%>
<dspace:layout titlekey="jsp.browse.items-by-title.title">
<h2><fmt:message key="jsp.browse.items-by-title.title"/></h2>
<%-- Title browse controls table --%>
<form action="browse-title" method="get">
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0" summary="Browse the respository by title">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2"> <%--allow for greek alphabet also--%>
<tr>
<td class="browseBar">
<%-- <span class="browseBarLabel">Jump&nbsp;to:&nbsp;</span> --%>
<span class="browseBarLabel"><fmt:message key="jsp.browse.items-by-title.jump"/></span>
<a href="browse-title?starts_with=0">0-9</a>
<%
for (char c = 'A'; c <= 'Z'; c++)
{
%>
<a href="browse-title?starts_with=<%= c %>"><%= c %></a>
<%
}
%>
</td>
</tr>
<tr>
<td class="browseBar" align="center">
<%-- <span class="browseBarLabel">or enter first few letters:&nbsp;</span> --%>
<span class="browseBarLabel"><fmt:message key="jsp.browse.items-by-title.enter"/>&nbsp;</span>
<%-- <input type="text" name="starts_with"/>&nbsp;<input type="submit" value="Go!"> --%>
<input type="text" name="starts_with"/>&nbsp;<input type="submit" value="<fmt:message key="jsp.browse.general.go"/>" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<br/>
<p align="center">
<%-- Showing items <%= browseInfo.getOverallPosition()+1 %>-<%= browseInfo.getOverallPosition()+browseInfo.getResultCount() %>
of <%= browseInfo.getTotal() %>. --%>
<fmt:message key="jsp.browse.items-by-title.show">
<fmt:param><%= browseInfo.getOverallPosition()+1 %></fmt:param>
<fmt:param><%= browseInfo.getOverallPosition()+browseInfo.getResultCount() %></fmt:param>
<fmt:param><%= browseInfo.getTotal() %></fmt:param>
</fmt:message>
</p>
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<%-- <a href="browse-title?<%= prevQuery %>">Previous page</a> --%>
<a href="browse-title?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-title?<%= nextQuery %>">Next page</a> --%>
<a href="browse-title?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
<%
String highlightAttribute = "-1";
if (highlight)
{
highlightAttribute = String.valueOf(browseInfo.getOffset());
}
%>
<dspace:itemlist items="<%= browseInfo.getItemResults() %>" emphcolumn="title" highlightrow="<%= highlightAttribute %>" />
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<%-- <a href="browse-title?<%= prevQuery %>">Previous page</a> --%>
<a href="browse-title?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-title?<%= nextQuery %>">Next page</a> --%>
<a href="browse-title?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
</dspace:layout>

View File

@@ -52,43 +52,57 @@
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="javax.servlet.jsp.jstl.fmt.LocaleSupport" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%
// Retrieve attributes
Community community = (Community) request.getAttribute("community");
Collection collection = (Collection) request.getAttribute("collection");
// get the BrowseInfo object
BrowseInfo bi = (BrowseInfo) request.getAttribute("browse.info");
// Retrieve community and collection if necessary
Community community = null;
Collection collection = null;
if (bi.inCommunity())
{
community = (Community) bi.getBrowseContainer();
}
if (bi.inCollection())
{
collection = (Collection) bi.getBrowseContainer();
}
// FIXME: this is not using the i18n
// Description of what the user is actually browsing, and where link back
String linkText = LocaleSupport.getLocalizedMessage(pageContext, "jsp.general.home");
String linkBack = "/";
if(collection != null)
if (collection != null)
{
linkText = collection.getMetadata("name");
linkBack = "/handle/" + collection.getHandle();
}
else if(community != null)
else if (community != null)
{
linkText = community.getMetadata("name");
linkBack = "/handle/" + community.getHandle();
}
%>
<dspace:layout titlekey="jsp.browse.no-results.title">
<h1><fmt:message key="jsp.browse.no-results.title"/></h1>
<dspace:layout titlekey="browse.no-results.title">
<h1><fmt:message key="browse.no-results.title"/></h1>
<p>
<%
if (collection != null)
{
%>
<fmt:message key="jsp.browse.no-results.col">
<fmt:message key="browse.no-results.col">
<fmt:param><%= collection.getMetadata("name")%></fmt:param>
</fmt:message>
<%
@@ -96,7 +110,7 @@
else if (community != null)
{
%>
<fmt:message key="jsp.browse.no-results.com">
<fmt:message key="browse.no-results.com">
<fmt:param><%= community.getMetadata("name")%></fmt:param>
</fmt:message>
<%
@@ -104,7 +118,7 @@
else
{
%>
<fmt:message key="jsp.browse.no-results.genericScope"/>
<fmt:message key="browse.no-results.genericScope"/>
<%
}
%>
@@ -112,4 +126,9 @@
<p><a href="<%= request.getContextPath() %><%= linkBack %>"><%= linkText %></a></p>
<%-- dump the results for debug (uncomment to enable) --%>
<%--
<!-- <%= bi.toString() %> -->
--%>
</dspace:layout>

View File

@@ -0,0 +1,391 @@
<%--
- single.jsp
-
- Version: $Revision: 1.9 $
-
- Date: $Date: 2005/08/25 17:20:26 $
-
- Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
-
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.browse.BrowseIndex" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.DCDate" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="org.dspace.core.Utils" %>
<%@ page import="org.dspace.app.webui.util.UIUtil" %>
<%
//First, get the browse info object
BrowseInfo bi = (BrowseInfo) request.getAttribute("browse.info");
BrowseIndex bix = bi.getBrowseIndex();
//values used by the header
String scope = "";
String type = "";
Community community = null;
Collection collection = null;
if (bi.inCommunity())
{
community = (Community) bi.getBrowseContainer();
}
if (bi.inCollection())
{
collection = (Collection) bi.getBrowseContainer();
}
if (community != null)
{
scope = "\"" + community.getMetadata("name") + "\"";
}
if (collection != null)
{
scope = "\"" + collection.getMetadata("name") + "\"";
}
type = bix.getName();
//FIXME: so this can probably be placed into the Messages.properties file at some point
// String header = "Browsing " + scope + " by " + type;
// get the values together for reporting on the browse values
// String range = "Showing results " + bi.getStart() + " to " + bi.getFinish() + " of " + bi.getTotal();
// prepare the next and previous links
String linkBase = request.getContextPath() + "/";
if (collection != null)
{
linkBase = linkBase + "handle/" + collection.getHandle() + "/";
}
if (community != null)
{
linkBase = linkBase + "handle/" + community.getHandle() + "/";
}
String direction = (bi.isAscending() ? "ASC" : "DESC");
String sharedLink = linkBase + "browse?type=" + URLEncoder.encode(bix.getName()) +
"&amp;order=" + URLEncoder.encode(direction) +
"&amp;rpp=" + URLEncoder.encode(Integer.toString(bi.getResultsPerPage()));
// prepare the next and previous links
String next = sharedLink;
String prev = sharedLink;
if (bi.hasNextPage())
{
next = next + "&amp;";
if (bi.getNextItem() == -1)
{
next = next + "vfocus=" + URLEncoder.encode(bi.getNextValue());
}
}
if (bi.hasPrevPage())
{
prev = prev + "&amp;";
if (bi.getPrevItem() == -1)
{
prev = prev + "vfocus=" + URLEncoder.encode(bi.getPrevValue());
}
}
// prepare a url for use by form actions
String formaction = request.getContextPath() + "/";
if (collection != null)
{
formaction = formaction + "handle/" + collection.getHandle() + "/";
}
if (community != null)
{
formaction = formaction + "handle/" + community.getHandle() + "/";
}
formaction = formaction + "browse";
String ascSelected = (bi.isAscending() ? "selected=\"selected\"" : "");
String descSelected = (bi.isAscending() ? "" : "selected=\"selected\"");
int rpp = bi.getResultsPerPage();
// the message key for the type
String typeKey = "browse.type." + bix.getName();
%>
<dspace:layout titlekey="browse.page-title">
<%-- Build the header (careful use of spacing) --%>
<h2>
<fmt:message key="browse.single.header"><fmt:param value="<%= scope %>"/></fmt:message> <fmt:message key="<%= typeKey %>"/>
</h2>
<%-- Include the main navigation for all the browse pages --%>
<%-- This first part is where we render the standard bits required by both possibly navigations --%>
<div align="center" id="browse_navigation">
<form method="get" action="<%= formaction %>">
<input type="hidden" name="type" value="<%= bix.getName() %>"/>
<input type="hidden" name="order" value="<%= direction %>"/>
<input type="hidden" name="rpp" value="<%= rpp %>"/>
<%-- If we are browsing by a date, or sorting by a date, render the date selection header --%>
<%
if (bix.isDate())
{
%>
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0" summary="Browsing by date">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2">
<tr>
<td class="browseBar">
<span class="browseBarLabel"><fmt:message key="browse.nav.date.jump"/> </span>
<select name="year">
<option selected="selected" value="-1"><fmt:message key="browse.nav.year"/></option>
<%
int thisYear = DCDate.getCurrent().getYear();
for (int i = thisYear; i >= 1990; i--)
{
%>
<option><%= i %></option>
<%
}
%>
<option>1985</option>
<option>1980</option>
<option>1975</option>
<option>1970</option>
<option>1960</option>
<option>1950</option>
</select>
<select name="month">
<option selected="selected" value="-1"><fmt:message key="browse.nav.month"/></option>
<%
for (int i = 1; i <= 12; i++)
{
%>
<option value="<%= i %>"><%= DCDate.getMonthName(i, UIUtil.getSessionLocale(request)) %></option>
<%
}
%>
</select>
</td>
<td class="browseBar" rowspan="2">
<input type="submit" value="<fmt:message key="browse.nav.go"/>" />
</td>
</tr>
<tr>
<%-- HACK: Shouldn't use align here --%>
<td class="browseBar" align="center">
<span class="browseBarLabel"><fmt:message key="browse.nav.type-year"/></span>
<input type="text" name="starts_with" size="4" maxlength="4"/>
</td>
</tr>
</table>
</td>
</tr>
</table>
<%
}
// If we are not browsing by a date, render the string selection header //
else
{
%>
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0" summary="Browse the respository">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2">
<tr>
<td class="browseBar">
<span class="browseBarLabel"><fmt:message key="browse.nav.jump"/></span>
<a href="<%= sharedLink %>&amp;starts_with=0">0-9</a>
<%
for (char c = 'A'; c <= 'Z'; c++)
{
%>
<a href="<%= sharedLink %>&amp;starts_with=<%= c %>"><%= c %></a>
<%
}
%>
</td>
</tr>
<tr>
<td class="browseBar" align="center">
<span class="browseBarLabel"><fmt:message key="browse.nav.enter"/>&nbsp;</span>
<input type="text" name="starts_with"/>&nbsp;<input type="submit" value="<fmt:message key="browse.nav.go"/>" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<%
}
%>
</form>
</div>
<%-- End of Navigation Headers --%>
<%-- Include a component for modifying sort by, order and results per page --%>
<div align="center" id="browse_controls">
<form method="get" action="<%= formaction %>">
<input type="hidden" name="type" value="<%= bix.getName() %>"/>
<%-- The following code can be used to force the browse around the current focus. Without
it the browse will revert to page 1 of the results each time a change is made --%>
<%--
if (!bi.hasItemFocus() && bi.hasFocus())
{
%><input type="hidden" name="vfocus" value="<%= bi.getFocus() %>"/><%
}
--%>
<fmt:message key="browse.single.order"/>
<select name="order">
<option value="ASC" <%= ascSelected %>>Ascending</option>
<option value="DESC" <%= descSelected %>>Descending</option>
</select>
<fmt:message key="browse.single.rpp"/>
<select name="rpp">
<%
for (int i = 5; i <= 100 ; i += 5)
{
String selected = (i == rpp ? "selected=\"selected\"" : "");
%>
<option value="<%= i %>" <%= selected %>><%= i %></option>
<%
}
%>
</select>
<input type="submit" name="submit_browse" value="Update"/>
</form>
</div>
<%-- give us the top report on what we are looking at --%>
<div align="center" class="browse_range">
<fmt:message key="browse.single.range">
<fmt:param value="<%= Integer.toString(bi.getStart()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getFinish()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getTotal()) %>"/>
</fmt:message>
</div>
<%-- do the top previous and next page links --%>
<div align="center">
<%
if (bi.hasPrevPage())
{
%>
<a href="<%= prev %>"><fmt:message key="browse.single.prev"/></a>&nbsp;
<%
}
%>
<%
if (bi.hasNextPage())
{
%>
&nbsp;<a href="<%= next %>"><fmt:message key="browse.single.next"/></a>
<%
}
%>
</div>
<%-- THE RESULTS --%>
<table align="center" class="miscTable" summary="This table displays a list of results">
<%
// Row: toggles between Odd and Even
String row = "odd";
String[] results = bi.getStringResults();
for (int i = 0; i < results.length; i++)
{
%>
<tr>
<td class="<%= row %>RowOddCol">
<a href="<%= sharedLink %>&amp;value=<%= URLEncoder.encode(results[i], "UTF-8") %>"><%= Utils.addEntities(results[i]) %></a>
</td>
</tr>
<%
row = ( row.equals( "odd" ) ? "even" : "odd" );
}
%>
</table>
<%-- give us the bottom report on what we are looking at --%>
<div align="center" class="browse_range">
<fmt:message key="browse.single.range">
<fmt:param value="<%= Integer.toString(bi.getStart()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getFinish()) %>"/>
<fmt:param value="<%= Integer.toString(bi.getTotal()) %>"/>
</fmt:message>
</div>
<%-- do the bottom previous and next page links --%>
<div align="center">
<%
if (bi.hasPrevPage())
{
%>
<a href="<%= prev %>"><fmt:message key="browse.single.prev"/></a>&nbsp;
<%
}
%>
<%
if (bi.hasNextPage())
{
%>
&nbsp;<a href="<%= next %>"><fmt:message key="browse.single.next"/></a>
<%
}
%>
</div>
<%-- dump the results for debug (uncomment to enable) --%>
<%--
<!-- <%= bi.toString() %> -->
--%>
</dspace:layout>

View File

@@ -1,218 +0,0 @@
<%--
- subjects.jsp
-
- Version: $Revision$
-
- Date: $Date$
-
- Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
- Institute of Technology. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
-
- - Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- - Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- - Neither the name of the Hewlett-Packard Company nor the name of the
- Massachusetts Institute of Technology nor the names of their
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- DAMAGE.
--%>
<%--
- Display the results of browsing the subject index
-
- Attributes to pass in:
- community - pass in if the scope of the browse is a community, or
- a collection within this community
- collection - pass in if the scope of the browse is a collection
- browse.info - the BrowseInfo containing the subjects to display
- highlight - Boolean. If true, the focus point of the browse
- is highlighted
- previous.query - The query string to pass to the servlet to get the
- previous page of authors
- next.query - The query string to pass to the servlet to get the next
- page of aitjprs
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.dspace.org/dspace-tags.tld" prefix="dspace" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.util.List" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.DCDate" %>
<%@ page import="org.dspace.content.DCValue" %>
<%@ page import="org.dspace.content.Item" %>
<%@ page import="org.dspace.core.Utils" %>
<%@ page import="javax.servlet.jsp.jstl.fmt.*" %>
<%@ page import="org.apache.taglibs.standard.tag.common.fmt.BundleSupport" %>
<%@ page import="java.util.Locale" %>
<%
// Get attributes
Collection collection = (Collection) request.getAttribute("collection");
Community community = (Community) request.getAttribute("community");
BrowseInfo browseInfo = (BrowseInfo) request.getAttribute("browse.info");
boolean highlight = ((Boolean) request.getAttribute("highlight")).booleanValue();
String prevQuery = (String) request.getAttribute("previous.query");
String nextQuery = (String) request.getAttribute("next.query");
%>
<dspace:layout titlekey="jsp.browse.subject.title">
<h2><fmt:message key="jsp.browse.subject.title"/></h2>
<form action="browse-subject" method="get">
<%-- Browse controls --%>
<table align="center" border="0" bgcolor="#CCCCCC" cellpadding="0">
<tr>
<td>
<table border="0" bgcolor="#EEEEEE" cellpadding="2"> <%--allow for greek alphabet also--%>
<tr>
<td class="browseBar">
<%--<span class="browseBarLabel">Jump&nbsp;to:&nbsp;</span>--%>
<span class="browseBarLabel"><fmt:message key="jsp.browse.subject.jump"/></span>
<a href="browse-subject?starts_with=0">0-9</a>
<%
for (char c = 'A'; c <= 'Z'; c++)
{
%>
<a href="browse-subject?starts_with=<%= c %>"><%= c %></a>
<%
}
%>
</td>
</tr>
<tr>
<td class="browseBar" align="center" id="tstarts_with">
<span class="browseBarLabel"><label for="tstarts_with"><fmt:message key="jsp.browse.subject.enter"/>&nbsp;</label></span>
<%--<span class="browseBarLabel">or enter first few letters:&nbsp;</span>--%>
<%--<input type="text" name="starts_with">&nbsp;<input type="submit" value="Go!">--%>
<input type="text" name="starts_with"/>&nbsp;<input type="submit" value="<fmt:message key="jsp.browse.general.go"/>" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<br />
<%--<p align="center">Showing subjects <%= browseInfo.getOverallPosition() + 1 %>-<%= browseInfo.getOverallPosition() + browseInfo.getResultCount() %> of <%= browseInfo.getTotal() %>.</p>--%>
<p align="center"><fmt:message key="jsp.browse.subject.show">
<fmt:param><%= browseInfo.getOverallPosition() + 1 %></fmt:param>
<fmt:param><%= browseInfo.getOverallPosition() + browseInfo.getResultCount() %></fmt:param>
<fmt:param><%= browseInfo.getTotal() %></fmt:param>
</fmt:message></p>
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<%-- <a="browse-subject?<%= prevQuery %>">Previous page</a> --%>
<a href="browse-subject?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-subject?<%= nextQuery %>">Next page</a> --%>
<a href="browse-subject?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
<%-- The subjects --%>
<table align="center" class="miscTable" summary="This table displays a list of subjects">
<%
// Row: toggles between Odd and Even
String row = "odd";
String[] results = browseInfo.getStringResults();
for (int i = 0; i < results.length; i++)
{
%>
<tr>
<td class="<%= highlight && i==browseInfo.getOffset() ? "highlight" : row %>RowOddCol">
<a href="items-by-subject?subject=<%= URLEncoder.encode(results[i], "UTF-8") %>"><%= Utils.addEntities(results[i]) %></a>
</td>
</tr>
<%
row = ( row.equals( "odd" ) ? "even" : "odd" );
}
%>
</table>
<%-- Previous page/Next page --%>
<table align="center" border="0" width="70%">
<tr>
<td class="standard" align="left">
<%
if (prevQuery != null)
{
%>
<a href="browse-subject?<%= prevQuery %>"><fmt:message key="jsp.browse.general.previous"/></a>
<%
}
%>
</td>
<td class="standard" align="right">
<%
if (nextQuery != null)
{
%>
<%-- <a href="browse-subject?<%= nextQuery %>">Next page</a> --%>
<a href="browse-subject?<%= nextQuery %>"><fmt:message key="jsp.browse.general.next"/></a>
<%
}
%>
</td>
</tr>
</table>
</form>
</dspace:layout>

View File

@@ -66,6 +66,11 @@
<%@ page import="org.dspace.core.Utils"%>
<%@ page import="org.dspace.core.ConfigurationManager"%>
<%@ page import="org.dspace.eperson.Group" %>
<%@ page import="org.dspace.browse.BrowseIndex" %>
<%@ page import="org.dspace.app.webui.components.RecentSubmissions" %>
<%@ page import="org.dspace.content.Item" %>
<%@ page import="org.dspace.content.DCValue" %>
@@ -75,11 +80,8 @@
Community community = (Community) request.getAttribute("community");
Group submitters = (Group) request.getAttribute("submitters");
String[] lastSubmittedTitles = (String[])
request.getAttribute("last.submitted.titles");
String[] lastSubmittedURLs = (String[])
request.getAttribute("last.submitted.urls");
RecentSubmissions rs = (RecentSubmissions) request.getAttribute("recently.submitted");
boolean loggedIn =
((Boolean) request.getAttribute("logged.in")).booleanValue();
boolean subscribed =
@@ -93,6 +95,8 @@
Boolean submit_b = (Boolean)request.getAttribute("can_submit_button");
boolean submit_button = (submit_b == null ? false : submit_b.booleanValue());
// get the browse indices
BrowseIndex[] bis = BrowseIndex.getBrowseIndices();
// Put the metadata values into guaranteed non-null variables
String name = collection.getMetadata("name");
@@ -150,10 +154,10 @@
</table>
<%-- Search/Browse --%>
<form method="get" action="">
<table class="miscTable" align="center" summary="This table allows you to search through all collections in the repository">
<tr>
<td class="evenRowEvenCol" colspan="2">
<form method="get" action="">
<table>
<tr>
<td class="standard" align="center">
@@ -171,17 +175,32 @@
<input type="submit" name="submit_search" value="<fmt:message key="jsp.general.go"/>" />
</td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td align="center" class="standard">
<td align="center" class="standard" valign="middle">
<small><fmt:message key="jsp.general.orbrowse"/>&nbsp;</small>
<input type="submit" name="submit_titles" value="<fmt:message key="jsp.general.titles.button"/>" />&nbsp;<input type="submit" name="submit_authors" value="<fmt:message key="jsp.general.authors.button"/>" />&nbsp;<input type="submit" name="submit_subjects" value="<fmt:message key="jsp.general.subjects.button"/>" />&nbsp;<input type="submit" name="submit_dates" value="<fmt:message key="jsp.general.date.button"/>" />
<%-- Insert the dynamic list of browse options --%>
<%
for (int i = 0; i < bis.length; i++)
{
String key = "browse.menu." + bis[i].getMessageKey();
%>
<div class="browse_buttons">
<form method="get" action="<%= request.getContextPath() %>/handle/<%= collection.getHandle() %>/browse">
<input type="hidden" name="type" value="<%= bis[i].getName() %>"/>
<%-- <input type="hidden" name="collection" value="<%= collection.getHandle() %>" /> --%>
<input type="submit" name="submit_browse" value="<fmt:message key="<%= key %>"/>"/>
</form>
</div>
<%
}
%>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<table width="100%" align="center" cellspacing="10">
<tr>
@@ -289,16 +308,23 @@
<h3><fmt:message key="jsp.collection-home.recentsub"/></h3>
<%
for (int i = 0; i < lastSubmittedTitles.length; i++)
{
String displayTitle = (lastSubmittedTitles[i] == null
? LocaleSupport.getLocalizedMessage(pageContext, "jsp.general.untitled")
: Utils.addEntities(lastSubmittedTitles[i]));
%>
<p class="recentItem"><a href="<%= request.getContextPath() %><%= lastSubmittedURLs[i] %>"><%= displayTitle %></a></p>
<%
}
if (rs != null)
{
Item[] items = rs.getRecentSubmissions();
for (int i = 0; i < items.length; i++)
{
DCValue[] dcv = items[i].getMetadata("dc", "title", null, Item.ANY);
String displayTitle = "Untitled";
if (dcv != null)
{
if (dcv.length > 0)
{
displayTitle = dcv[0].value;
}
}
%><p class="recentItem"><a href="<%= request.getContextPath() %>/handle/<%= items[i].getHandle() %>"><%= displayTitle %></a></p><%
}
}
%>
<p>&nbsp;</p>
<%

View File

@@ -63,6 +63,12 @@
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.core.Utils" %>
<%@ page import="org.dspace.core.ConfigurationManager" %>
<%@ page import="org.dspace.browse.BrowseIndex" %>
<%@ page import="org.dspace.app.webui.components.RecentSubmissions" %>
<%@ page import="org.dspace.content.Item" %>
<%@ page import="org.dspace.content.DCValue" %>
<%
@@ -72,11 +78,9 @@
(Collection[]) request.getAttribute("collections");
Community[] subcommunities =
(Community[]) request.getAttribute("subcommunities");
String[] lastSubmittedTitles = (String[])
request.getAttribute("last.submitted.titles");
String[] lastSubmittedURLs = (String[])
request.getAttribute("last.submitted.urls");
RecentSubmissions rs = (RecentSubmissions) request.getAttribute("recently.submitted");
Boolean editor_b = (Boolean)request.getAttribute("editor_button");
boolean editor_button = (editor_b == null ? false : editor_b.booleanValue());
Boolean add_b = (Boolean)request.getAttribute("add_button");
@@ -84,6 +88,8 @@
Boolean remove_b = (Boolean)request.getAttribute("remove_button");
boolean remove_button = (remove_b == null ? false : remove_b.booleanValue());
// get the browse indices
BrowseIndex[] bis = BrowseIndex.getBrowseIndices();
// Put the metadata values into guaranteed non-null variables
String name = community.getMetadata("name");
@@ -128,16 +134,15 @@
<%-- Search/Browse --%>
<form method="get" action="">
<table class="miscTable" align="center" summary="This table allows you to search through all communities held in the repository">
<tr>
<td class="evenRowEvenCol" colspan="2">
<form method="get" action="">
<table>
<tr>
<td class="standard" align="center">
<%--<small><strong>In:</strong></small>&nbsp;<select name="location">--%>
<small><label for="tlocation"><strong><fmt:message key="jsp.general.location"/></strong></label></small>&nbsp;<select name="location" id="tlocation">
<%--<option value="/">All of DSpace</option>--%>
<option value="/"><fmt:message key="jsp.general.genericScope"/></option>
<option selected="selected" value="<%= community.getHandle() %>"><%= name %></option>
<%
@@ -164,16 +169,32 @@
<small><label for="tquery"><strong><fmt:message key="jsp.general.searchfor"/>&nbsp;</strong></label></small><input type="text" name="query" id="tquery" />&nbsp;<input type="submit" name="submit_search" value="<fmt:message key="jsp.general.go"/>" />
</td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td align="center" class="standard">
<small><fmt:message key="jsp.general.orbrowse"/>&nbsp;</small><input type="submit" name="submit_titles" value="<fmt:message key="jsp.general.titles.button"/>" />&nbsp;<input type="submit" name="submit_authors" value="<fmt:message key="jsp.general.authors.button"/>" />&nbsp;<input type="submit" name="submit_subjects" value="<fmt:message key="jsp.general.subjects.button"/>" />&nbsp;<input type="submit" name="submit_dates" value="<fmt:message key="jsp.general.date.button"/>" />
<td align="center" class="standard" valign="middle">
<small><fmt:message key="jsp.general.orbrowse"/>&nbsp;</small>
<%-- Insert the dynamic list of browse options --%>
<%
for (int i = 0; i < bis.length; i++)
{
String key = "browse.menu." + bis[i].getMessageKey();
%>
<div class="browse_buttons">
<form method="get" action="<%= request.getContextPath() %>/handle/<%= community.getHandle() %>/browse">
<input type="hidden" name="type" value="<%= bis[i].getName() %>"/>
<%-- <input type="hidden" name="community" value="<%= community.getHandle() %>" /> --%>
<input type="submit" name="submit_browse" value="<fmt:message key="<%= key %>"/>"/>
</form>
</div>
<%
}
%>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<%= intro %>
@@ -327,18 +348,27 @@
</tr>
</table>
<% } %>
<%-- Recently Submitted items --%>
<h3><fmt:message key="jsp.community-home.recentsub"/></h3>
<%
for (int i = 0; i < lastSubmittedTitles.length; i++)
{
String displayTitle = (lastSubmittedTitles[i] == null
? LocaleSupport.getLocalizedMessage(pageContext, "jsp.general.untitled")
: Utils.addEntities(lastSubmittedTitles[i]));
%>
<p class="recentItem"><a href="<%= request.getContextPath() %><%= lastSubmittedURLs[i] %>"><%= displayTitle %></a></p>
<%
}
if (rs != null)
{
Item[] items = rs.getRecentSubmissions();
for (int i = 0; i < items.length; i++)
{
DCValue[] dcv = items[i].getMetadata("dc", "title", null, Item.ANY);
String displayTitle = "Untitled";
if (dcv != null)
{
if (dcv.length > 0)
{
displayTitle = dcv[0].value;
}
}
%><p class="recentItem"><a href="<%= request.getContextPath() %>/handle/<%= items[i].getHandle() %>"><%= displayTitle %></a></p><%
}
}
%>
<p>&nbsp;</p>
<%

View File

@@ -56,7 +56,9 @@
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.eperson.EPerson" %>
<%@ page import="org.dspace.core.ConfigurationManager" %>
<%@ page import="org.dspace.browse.BrowseIndex" %>
<%@ page import="org.dspace.browse.BrowseInfo" %>
<%@ page import="java.util.Map" %>
<%
// Is anyone logged in?
EPerson user = (EPerson) request.getAttribute("dspace.current.user");
@@ -84,6 +86,15 @@
navbarEmail = navbarEmail.substring(0, 17) + "...";
}
}
// get the browse indices
Map bis = BrowseIndex.getBrowseIndicesMap();
BrowseInfo binfo = (BrowseInfo) request.getAttribute("browse.info");
String browseCurrent = "";
if (binfo != null)
{
browseCurrent = binfo.getBrowseIndex().getName();
}
%>
<%-- Search Box --%>
@@ -157,41 +168,28 @@
</td>
</tr>
<tr class="navigationBarItem">
<td>
<img alt="" src="<%= request.getContextPath() %>/image/<%= ( currentPage.endsWith( "/browse-title" ) ? "arrow-highlight" : "arrow" ) %>.gif" width="16" height="16" />
</td>
<td nowrap="nowrap" class="navigationBarItem">
<a href="<%= request.getContextPath() %>/browse-title"><fmt:message key="jsp.layout.navbar-default.titles"/></a>
</td>
</tr>
<tr class="navigationBarItem">
<td>
<img alt="" src="<%= request.getContextPath() %>/image/<%= ( currentPage.endsWith( "/browse-author" ) ? "arrow-highlight" : "arrow" ) %>.gif" width="16" height="16"/>
</td>
<td nowrap="nowrap" class="navigationBarItem">
<a href="<%= request.getContextPath() %>/browse-author"><fmt:message key="jsp.layout.navbar-default.authors"/></a>
</td>
</tr>
<%-- Insert the dynamic browse indices here --%>
<tr class="navigationBarItem">
<td>
<img alt="" src="<%= request.getContextPath() %>/image/<%= ( currentPage.endsWith( "/browse-subject" ) ? "arrow-highlight" : "arrow" ) %>.gif" width="16" height="16" />
</td>
<td nowrap="nowrap" class="navigationBarItem">
<a href="<%= request.getContextPath() %>/browse-subject"><fmt:message key="jsp.layout.navbar-default.subjects"/></a>
</td>
</tr>
<%
for (int i = 0; i < bis.size(); i++)
{
BrowseIndex bix = (BrowseIndex) bis.get(new Integer(i + 1));
String key = "browse.menu." + bix.getMessageKey();
%>
<tr class="navigationBarItem">
<td>
<img alt="" src="<%= request.getContextPath() %>/image/<%= ( browseCurrent.equals(bix.getName()) ? "arrow-highlight" : "arrow" ) %>.gif" width="16" height="16"/>
</td>
<td nowrap="nowrap" class="navigationBarItem">
<a href="<%= request.getContextPath() %>/browse?type=<%= bix.getName() %>"><fmt:message key="<%= key %>"/></a>
</td>
</tr>
<%
}
%>
<tr class="navigationBarItem">
<td>
<img alt="" src="<%= request.getContextPath() %>/image/<%= ( currentPage.endsWith( "/browse-date" ) ? "arrow-highlight" : "arrow" ) %>.gif" width="16" height="16"/>
</td>
<td nowrap="nowrap" class="navigationBarItem">
<a href="<%= request.getContextPath() %>/browse-date"><fmt:message key="jsp.layout.navbar-default.date"/></a>
</td>
</tr>
<%-- End of dynamic browse indices --%>
<tr>
<td colspan="2">&nbsp;</td>

View File

@@ -1,8 +1,5 @@
User-agent: *
Disallow: /browse-author
Disallow: /items-by-author
Disallow: /browse-date
Disallow: /browse-subject
Disallow: /browse
# Uncomment the following line only if sitemaps.org or HTML sitemaps are used
#Disallow: /browse-title

View File

@@ -641,3 +641,26 @@ img.controlledvocabulary {
.controlledVocabularyLink {
font-family: "verdana", "Arial", "Helvetica", sans-serif;
font-size: 8pt; }
.browse_buttons
{
float: right;
padding: 1px;
margin: 1px;
}
#browse_navigation
{
margin-bottom: 10px;
}
#browse_controls
{
margin-bottom: 10px;
}
.browse_range
{
margin-top: 5px;
margin-bottom: 5px;
}

View File

@@ -339,6 +339,11 @@
<artifactId>axis-saaj</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>3.4.4</version>
</dependency>
</dependencies>
</dependencyManagement>

View File

@@ -45,7 +45,8 @@ import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseException;
import org.dspace.browse.IndexBrowse;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.core.Constants;
@@ -88,7 +89,16 @@ public class FlowMapperUtils
if (!item.isOwningCollection(toCollection))
{
toCollection.addItem(item);
Browse.itemChanged(context,item);
// FIXME Exception handling
try
{
IndexBrowse ib = new IndexBrowse(context);
ib.indexItem(item);
}
catch (BrowseException bex)
{
throw new UIException("Unable to process browse", bex);
}
}
}
}
@@ -127,7 +137,16 @@ public class FlowMapperUtils
if (!item.isOwningCollection(toCollection))
{
toCollection.removeItem(item);
Browse.itemChanged(context,item);
// FIXME Exception handling
try
{
IndexBrowse ib = new IndexBrowse(context);
ib.indexItem(item);
}
catch (BrowseException bex)
{
throw new UIException("Unable to process browse", bex);
}
}
}
}

View File

@@ -1,374 +0,0 @@
/*
* AbstractBrowse.java
*
* Version: $Revision: 1.2 $
*
* Date: $Date: 2006/04/25 15:24:23 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseScope;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
/**
* This is an abstract search page that may be specialized to the various forms:
* by titles, dates, or authors.
*
* FIXME: Needs Support browse by subject.
*
* @author Scott Phillips
* @author Paulo Jobim
*/
public class AbstractBrowse extends AbstractDSpaceTransformer
{
/** How many results should appear on one page? */
protected static final int RESULTS_PER_PAGE = 11;
/** The possible browsing modes */
protected static final int MODE_BY_TITLE = 1;
protected static final int MODE_BY_DATE = 2;
protected static final int MODE_BY_AUTHOR = 3;
protected static final int MODE_BY_AUTHOR_ITEM = 4;
protected static final int MODE_BY_SUBJECT = 5;
protected static final int MODE_BY_SUBJECT_ITEM = 6;
/**
* Browsing related parameters, the preformBrowse() method will
* determine these cached results.
*/
protected BrowseInfo browseInfo;
protected BrowseScope browseScope;
protected boolean browseItem;
/**
* Preform the browse for the given mode.
*
* @param mode
* The browsing mode.
*/
public void performBrowse(int mode) throws SQLException, UIException
{
// Check to see if we have the browse results cached.
if (this.browseInfo != null && this.browseScope != null)
return;
// We will resolve the HTTP request parameters into a scope
Context context = ContextUtil.obtainContext(objectModel);
Request request = ObjectModelHelper.getRequest(objectModel);
// HTTP Parameters
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
String startsWith = request.getParameter("startsWith");
String month = request.getParameter("month");
String year = request.getParameter("year");
String author = request.getParameter("author");
String subject = request.getParameter("subject");
try {
if (top != null)
top = URLDecoder.decode(top,Constants.DEFAULT_ENCODING);
if (bottom != null)
bottom = URLDecoder.decode(bottom,Constants.DEFAULT_ENCODING);
if (author != null)
author = URLDecoder.decode(author,Constants.DEFAULT_ENCODING);
if (subject != null)
subject = URLDecoder.decode(subject,Constants.DEFAULT_ENCODING);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException("Unable to decode url parameters: top, bottom, subject or author.",uee);
}
// Buld the browse scope
BrowseScope scope = new BrowseScope(context);
scope.setTotal(RESULTS_PER_PAGE);
if (top != null && !"".equals(top))
{
if (mode == MODE_BY_AUTHOR || mode == MODE_BY_SUBJECT)
{
scope.setFocus(top);
scope.setNumberBefore(0);
}
else
{
Item item = (Item) HandleManager.resolveToObject(context, top);
scope.setFocus(item);
scope.setNumberBefore(0);
}
}
else if (bottom != null && !"".equals(bottom))
{
if (mode == MODE_BY_AUTHOR || mode == MODE_BY_SUBJECT)
{
scope.setFocus(bottom);
scope.setNumberBefore(RESULTS_PER_PAGE - 1);
}
else
{
Item item = (Item) HandleManager.resolveToObject(context, bottom);
scope.setFocus(item);
scope.setNumberBefore(RESULTS_PER_PAGE - 1);
}
}
else if (startsWith != null && !"".equals(startsWith))
{
scope.setFocus(startsWith);
scope.setNumberBefore(0);
}
else if (mode == MODE_BY_DATE && year != null
&& !"".equals(year))
{
if (month != null & !"-1".equals(month))
{
if (month.length() == 1)
month = "0" + month;
scope.setFocus(year + "-" + month);
scope.setNumberBefore(0);
}
else
{
scope.setFocus(year + "-01");
scope.setNumberBefore(0);
}
}
else if (mode == MODE_BY_AUTHOR_ITEM)
{
scope.setFocus(author);
}
else if (mode == MODE_BY_SUBJECT_ITEM)
{
scope.setFocus(subject);
}
// Are we in a community or collection?
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso instanceof Community)
scope.setScope((Community) dso);
if (dso instanceof Collection)
scope.setScope((Collection) dso);
// Query the browse index
BrowseInfo browseInfo;
if (mode == MODE_BY_TITLE)
{
browseInfo = Browse.getItemsByTitle(scope);
}
else if (mode == MODE_BY_DATE)
{
browseInfo = Browse.getItemsByDate(scope, false);
}
else if (mode == MODE_BY_AUTHOR)
{
browseInfo = Browse.getAuthors(scope);
}
else if (mode == MODE_BY_AUTHOR_ITEM)
{
browseInfo = Browse.getItemsByAuthor(scope, true);
}
else if (mode == MODE_BY_SUBJECT)
{
browseInfo = Browse.getSubjects(scope);
}
else if (mode == MODE_BY_SUBJECT_ITEM)
{
browseInfo = Browse.getItemsBySubject(scope, true);
}
else
{
throw new UIException("Unknown mode selected.");
}
// Save the search results for later access.
this.browseInfo = browseInfo;
this.browseScope = scope;
if (mode == MODE_BY_AUTHOR || mode == MODE_BY_SUBJECT)
this.browseItem = false;
else
this.browseItem = true;
}
/**
* The URL query string of of the previous page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as approprate by the calle.
*
* @param objectModel
* Cocoon' object model.
* @return The query string if available, otherwise null.
*/
public String previousPageURL(String baseURL)
throws UIException
{
try
{
// A search must be preformed first.
if (browseInfo == null)
return null;
if (browseInfo.isFirst())
return null;
Map<String,String> parameters = new HashMap<String,String>();
if (browseItem)
{
Item[] items = browseInfo.getItemResults();
if (items == null || items.length <= 0)
return null;
String bottom = URLEncoder.encode(items[0].getHandle(),
Constants.DEFAULT_ENCODING);
parameters.put("bottom",bottom);
}
else
{
String[] strings = browseInfo.getStringResults();
if (strings == null || strings.length <= 0)
return null;
String bottom = URLEncoder.encode(strings[0],
Constants.DEFAULT_ENCODING);
parameters.put("bottom",bottom);
}
return super.generateURL(baseURL,parameters);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException(uee);
}
}
/**
* The URL query string of of the next page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as approprate by the calle.
*
* @param objectModel
* Cocoon' object model.
* @return The query string if available, otherwise null.
*/
public String nextPageURL(String baseURL) throws UIException
{
try
{
// A search must be preformed first.
if (browseInfo == null)
return null;
if (browseInfo.isLast())
return null;
Map<String,String> parameters = new HashMap<String,String>();
if (browseItem)
{
Item[] items = browseInfo.getItemResults();
if (items == null || items.length <= 0)
return null;
String top = URLEncoder.encode(items[items.length - 1].getHandle(),
Constants.DEFAULT_ENCODING);
parameters.put("top",top);
}
else
{
String[] strings = browseInfo.getStringResults();
if (strings == null || strings.length <= 0)
return null;
String top = URLEncoder.encode(strings[strings.length - 1],
Constants.DEFAULT_ENCODING);
parameters.put("top",top);
}
return super.generateURL(baseURL,parameters);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException(uee);
}
}
/**
* Recyle
*/
public void recycle() {
this.browseInfo = null;
this.browseScope = null;
super.recycle();
}
}

View File

@@ -1,272 +0,0 @@
/*
* BrowseAuthorItems.java
*
* Version: $Revision: 1.15 $
*
* Date: $Date: 2006/06/02 21:36:56 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Xref;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
/**
* Display the results of browsing items belonging to a particular author index.
* This component may either apply to all communities and collection or be
* scoped to just one community / collection depending upon the url.
*
* FIXME: Currently the Browse.getItemsByAuthor turns off pagination, this
* causes problems when a single author has published many items in DSpace. To
* limit the problem we implement simple pagination untop of the browse results
* using "authorTop" & "authorBottom" parameters similar to how they are used by
* the other browsers. This should be changed when the browse code is updated,
* so that the un-used items are not instanceated.
*
* @author Scott Phillips
*/
public class BrowseAuthorItems extends AbstractBrowse implements CacheableProcessingComponent
{
/** Language strings: */
private static final Message T_title =
message("xmlui.ArtifactBrowser.BrowseAuthorItems.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.BrowseAuthorItems.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.BrowseAuthorItems.head");
private static final Message T_back =
message("xmlui.ArtifactBrowser.BrowseAuthorItems.back");
/** How many items should appear on one page */
private static final int ITEMS_PER_PAGE = 20;
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String key = "";
key += "-" + request.getParameter("top");
key += "-" + request.getParameter("bottom");
key += "-" + request.getParameter("startsWith");
key += "-" + request.getParameter("month");
key += "-" + request.getParameter("year");
key += "-" + request.getParameter("author");
key += "-" + request.getParameter("authorTop");
key += "-" + request.getParameter("authorBottom");
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include all items on this browse page, along
* with all bundles and bitstreams refrenced by them. The one change that
* will not be refelected in this cache is a change is community/collection
* hierarchy.
*/
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
validity.add(dso);
performBrowse(MODE_BY_AUTHOR_ITEM);
for (Item item : browseInfo.getItemResults())
{
validity.add(item);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath, T_dspace_home);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta,contextPath);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add the browse-author-item division.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Preform the actual search
performBrowse(MODE_BY_AUTHOR_ITEM);
Request request = ObjectModelHelper.getRequest(objectModel);
Item[] items = browseInfo.getItemResults();
String top = request.getParameter("authorTop");
String bottom = request.getParameter("authorBottom");
String author = request.getParameter("author");
// Determine Pagination variables
int itemsTotal = items.length;
int firstItemIndex = 0;
int lastItemIndex = firstItemIndex + ITEMS_PER_PAGE;
// Should we shift the pagination view because of a top or bottom
// directive?
if (top != null)
{
// Move the indexs to match pagination
firstItemIndex = Integer.valueOf(top);
lastItemIndex = firstItemIndex + ITEMS_PER_PAGE;
}
else if (bottom != null)
{
lastItemIndex = Integer.valueOf(bottom);
firstItemIndex = lastItemIndex - ITEMS_PER_PAGE;
}
// Check four out of bounds indices.
if (firstItemIndex < 0)
firstItemIndex = 0;
if (lastItemIndex > items.length - 1)
lastItemIndex = items.length - 1;
// Determine the next & previous link;
String baseURL = "browse-author-items?author=" + URLEncode(author);
String previousPage = null;
String nextPage = null;
if (firstItemIndex > 0)
previousPage = baseURL + "&authorBottom=" + (firstItemIndex);
if (lastItemIndex < items.length - 1)
nextPage = baseURL + "&authorTop=" + (lastItemIndex);
// Build the DRI Body
Division div = body.addDivision("browse-by-author-item","primary");
div.setHead(T_head.parameterize(author));
// Navigatioal aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation",
"browse-author-items", Division.METHOD_POST,"secondary navigation");
Xref link = jump.addPara().addXref("browse-author?startsWith=" + URLEncode(author));
link.addContent(T_back);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-author-item-results","primary");
results.setSimplePagination(itemsTotal, firstItemIndex + 1, lastItemIndex + 1,
previousPage, nextPage);
// Refrence all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-author-item",
ReferenceSet.TYPE_SUMMARY_LIST, "author", null);
for (int i = firstItemIndex; i <= lastItemIndex; i++)
{
referenceSet.addReference(items[i]);
}
}
/**
* Recycle
*/
public void recycle() {
this.validity = null;
super.recycle();
}
}

View File

@@ -1,244 +0,0 @@
/*
* BrowseAuthors.java
*
* Version: $Revision: 1.16 $
*
* Date: $Date: 2006/07/27 18:24:34 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.xml.sax.SAXException;
/**
* Display the results of browsing authors index. This component may either apply
* to all communities and collection or be scoped to just one community /
* collection depending upon the url.
*
* @author Scott Phillips
*/
public class BrowseAuthors extends AbstractBrowse implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.BrowseAuthors.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.BrowseAuthors.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.BrowseAuthors.head");
private static final Message T_starts_with =
message("xmlui.ArtifactBrowser.BrowseAuthors.starts_with");
private static final Message T_go =
message("xmlui.general.go");
private static final Message T_column_heading =
message("xmlui.ArtifactBrowser.BrowseAuthors.column_heading");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String key = "";
key += "-" + request.getParameter("top");
key += "-" + request.getParameter("bottom");
key += "-" + request.getParameter("startsWith");
key += "-" + request.getParameter("month");
key += "-" + request.getParameter("year");
key += "-" + request.getParameter("author");
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include all items on this browse page, along
* with all bundles and bitstreams refrenced by them. The one change that
* will not be refelected in this cache is a change is community/collection
* hierarchy.
*/
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
validity.add(dso);
performBrowse(MODE_BY_AUTHOR);
for (String author : browseInfo.getStringResults())
{
validity.add(author);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta,contextPath);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add the browse-author division.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
performBrowse(MODE_BY_AUTHOR);
// Pagination variables
int itemsTotal = browseInfo.getTotal();
int firstItemIndex = browseInfo.getOverallPosition() + 1;
int lastItemIndex = browseInfo.getOverallPosition()
+ browseInfo.getResultCount();
String previousPage = previousPageURL("browse-author");
String nextPage = nextPageURL("browse-author");
// Build the DRI Body
Division div = body.addDivision("browse-by-author","primary");
div.setHead(T_head);
// Navigatioal aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation",
"browse-author", Division.METHOD_POST,"secondary navigation");
List jumpList = jump.addList("jump-list", List.TYPE_SIMPLE, "alphabet");
for (char c = 'A'; c <= 'Z'; c++)
jumpList.addItemXref("browse-author?startsWith=" + c, String
.valueOf(c));
Para jumpForm = jump.addPara();
jumpForm.addContent(T_starts_with);
jumpForm.addText("startsWith");
jumpForm.addButton("submit").setValue(T_go);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-author-results","primary");
results.setSimplePagination(itemsTotal, firstItemIndex, lastItemIndex,
previousPage, nextPage);
Table authorTable = results.addTable("browse-by-author-results",
browseInfo.getResultCount() + 1, 1);
authorTable.addRow(Row.ROLE_HEADER).addCell().addContent(T_column_heading);
for (String author : browseInfo.getStringResults())
{
Cell cell = authorTable.addRow().addCell();
cell.addXref("browse-author-items?author=" + URLEncode(author),
author);
}
}
/**
* Recycle
*/
public void recycle() {
this.validity = null;
super.recycle();
}
}

View File

@@ -1,291 +0,0 @@
/*
* BrowseDates.java
*
* Version: $Revision: 1.18 $
*
* Date: $Date: 2006/07/27 18:24:34 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Locale;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DCDate;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
/**
* Display the results of browsing by dates index. This component may either
* apply to all communities and collection or be scoped to just one community /
* collection depending upon the url.
*
* @author Scott Phillips
*/
public class BrowseDates extends AbstractBrowse implements CacheableProcessingComponent
{
/** Languag strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.BrowseDates.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.BrowseDates.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.BrowseDates.head");
private static final Message T_jump_select =
message("xmlui.ArtifactBrowser.BrowseDates.jump_select");
private static final Message T_choose_month =
message("xmlui.ArtifactBrowser.BrowseDates.choose_month");
private static final Message T_choose_year =
message("xmlui.ArtifactBrowser.BrowseDates.choose_year");
private static final Message T_jump_year =
message("xmlui.ArtifactBrowser.BrowseDates.jump_year");
private static final Message T_jump_year_help =
message("xmlui.ArtifactBrowser.BrowseDates.jump_year_help");
private static final Message T_go =
message("xmlui.general.go");
/**
* These varables dictate when the drop down list of years is to break from
* 1 year increments, to 5 year increments, to 10 year increments, and
* finialy to stop.
*/
private static final int ONE_YEAR_LIMIT = 10;
private static final int FIVE_YEAR_LIMIT = 30;
private static final int TEN_YEAR_LIMIT = 100;
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String key = "";
key += "-" + request.getParameter("top");
key += "-" + request.getParameter("bottom");
key += "-" + request.getParameter("startsWith");
key += "-" + request.getParameter("month");
key += "-" + request.getParameter("year");
key += "-" + request.getParameter("author");
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include all items on this browse page, along
* with all bundles and bitstreams refrenced by them. The one change that
* will not be refelected in this cache is a change is community/collection
* hierarchy.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
validity.add(dso);
performBrowse(MODE_BY_DATE);
for (Item item : browseInfo.getItemResults())
{
validity.add(item);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta,contextPath);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add the browse-date division.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
this.performBrowse(MODE_BY_DATE);
// Pagination variables
int itemsTotal = browseInfo.getTotal();
int firstItemIndex = browseInfo.getOverallPosition() + 1;
int lastItemIndex = browseInfo.getOverallPosition()
+ browseInfo.getResultCount();
String previousPage = previousPageURL("browse-date");
String nextPage = nextPageURL("browse-date");
// Build the DRI Body
Division div = body.addDivision("browse-by-date","primary");
div.setHead(T_head);
// Navigatioal aid
Division jump = div.addInteractiveDivision("browse-navigation",
"browse-date", Division.METHOD_POST,"secondary navigation");
Para jumpForm = jump.addPara();
jumpForm.addContent(T_jump_select);
Select month = jumpForm.addSelect("month");
month.addOption(false, "-1", T_choose_month);
for (int i = 1; i <= 12; i++)
{
month.addOption(false, String.valueOf(i), DCDate.getMonthName(i, Locale.getDefault()));
}
Select year = jumpForm.addSelect("year");
year.addOption(false, "-1", T_choose_year);
int currentYear = DCDate.getCurrent().getYear();
int i = currentYear;
int oneYearBreak = ((currentYear - ONE_YEAR_LIMIT) / 5) * 5;
int fiveYearBreak = ((currentYear - FIVE_YEAR_LIMIT) / 10) * 10;
int tenYearBreak = (currentYear - TEN_YEAR_LIMIT);
do
{
year.addOption(false, String.valueOf(i), String.valueOf(i));
if (i <= fiveYearBreak)
i -= 10;
else if (i <= oneYearBreak)
i -= 5;
else
i--;
}
while (i > tenYearBreak);
jumpForm = jump.addPara();
jumpForm.addContent(T_jump_year);
jumpForm.addText("startsWith").setHelp(T_jump_year_help);
jumpForm.addButton("submit").setValue(T_go);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-date-results","primary");
results.setSimplePagination(itemsTotal, firstItemIndex, lastItemIndex,
previousPage, nextPage);
// Refrence all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-date",
ReferenceSet.TYPE_SUMMARY_LIST, "date", null);
for (Item item : browseInfo.getItemResults())
{
referenceSet.addReference(item);
}
}
/**
* Recycle
*/
public void recycle() {
this.validity = null;
super.recycle();
}
}

View File

@@ -1,266 +0,0 @@
/*
* BrowseAuthorItems.java
*
* Version: $Revision: 1.15 $
*
* Date: $Date: 2006/06/02 21:36:56 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Xref;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
/**
* Display the results of browsing items belonging to a particular subject index.
* This component may either apply to all communities and collection or be
* scoped to just one community / collection depending upon the url.
*
* @author Paulo Jobim
* @author Alexey Maslov
*/
public class BrowseSubjectItems extends AbstractBrowse implements CacheableProcessingComponent
{
/** Language strings: */
private static final Message T_title =
message("xmlui.ArtifactBrowser.BrowseSubjectItems.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.BrowseSubjectItems.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.BrowseSubjectItems.head");
private static final Message T_back =
message("xmlui.ArtifactBrowser.BrowseSubjectItems.back");
/** How many items should appear on one page */
private static final int ITEMS_PER_PAGE = 20;
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String key = "";
key += "-" + request.getParameter("top");
key += "-" + request.getParameter("bottom");
key += "-" + request.getParameter("startsWith");
key += "-" + request.getParameter("month");
key += "-" + request.getParameter("year");
key += "-" + request.getParameter("subject");
key += "-" + request.getParameter("subjectTop");
key += "-" + request.getParameter("subjectBottom");
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include all items on this browse page, along
* with all bundles and bitstreams refrenced by them. The one change that
* will not be refelected in this cache is a change is community/collection
* hierarchy.
*/
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
validity.add(dso);
performBrowse(MODE_BY_SUBJECT_ITEM);
for (Item item : browseInfo.getItemResults())
{
validity.add(item);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath, T_dspace_home);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta,contextPath);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add the browse-subject-item division.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Preform the actual search
performBrowse(MODE_BY_SUBJECT_ITEM);
Request request = ObjectModelHelper.getRequest(objectModel);
Item[] items = browseInfo.getItemResults();
String top = request.getParameter("subjectTop");
String bottom = request.getParameter("subjectBottom");
String subject = request.getParameter("subject");
// Determine Pagination variables
int itemsTotal = items.length;
int firstItemIndex = 0;
int lastItemIndex = firstItemIndex + ITEMS_PER_PAGE;
// Should we shift the pagination view because of a top or bottom
// directive?
if (top != null)
{
// Move the indexs to match pagination
firstItemIndex = Integer.valueOf(top);
lastItemIndex = firstItemIndex + ITEMS_PER_PAGE;
}
else if (bottom != null)
{
lastItemIndex = Integer.valueOf(bottom);
firstItemIndex = lastItemIndex - ITEMS_PER_PAGE;
}
// Check four out of bounds indices.
if (firstItemIndex < 0)
firstItemIndex = 0;
if (lastItemIndex > items.length - 1)
lastItemIndex = items.length - 1;
// Determine the next & previous link;
String baseURL = "browse-subject-items?subject=" + URLEncode(subject);
String previousPage = null;
String nextPage = null;
if (firstItemIndex > 0)
previousPage = baseURL + "&subjectBottom=" + (firstItemIndex);
if (lastItemIndex < items.length - 1)
nextPage = baseURL + "&subjectTop=" + (lastItemIndex);
// Build the DRI Body
Division div = body.addDivision("browse-by-subject-item","primary");
div.setHead(T_head.parameterize(subject));
// Navigatioal aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation",
"browse-subject-items", Division.METHOD_POST,"secondary navigation");
Xref link = jump.addPara().addXref("browse-subject?startsWith=" + URLEncode(subject));
link.addContent(T_back);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-subject-item-results","primary");
results.setSimplePagination(itemsTotal, firstItemIndex + 1, lastItemIndex + 1,
previousPage, nextPage);
// Refrence all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-subject-item",
ReferenceSet.TYPE_SUMMARY_LIST, "subject", null);
for (int i = firstItemIndex; i <= lastItemIndex; i++)
{
referenceSet.addReference(items[i]);
}
}
/**
* Recycle
*/
public void recycle() {
this.validity = null;
super.recycle();
}
}

View File

@@ -1,245 +0,0 @@
/*
* BrowseAuthors.java
*
* Version: $Revision: 1.16 $
*
* Date: $Date: 2006/07/27 18:24:34 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.xml.sax.SAXException;
/**
* Display the results of browsing subject index. This component may either apply
* to all communities and collection or be scoped to just one community /
* collection depending upon the url.
*
* @author Paulo Jobim
* @author Alexey Maslov
*/
public class BrowseSubjects extends AbstractBrowse implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.BrowseSubjects.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.BrowseSubjects.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.BrowseSubjects.head");
private static final Message T_starts_with =
message("xmlui.ArtifactBrowser.BrowseSubjects.starts_with");
private static final Message T_go =
message("xmlui.general.go");
private static final Message T_column_heading =
message("xmlui.ArtifactBrowser.BrowseSubjects.column_heading");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String key = "";
key += "-" + request.getParameter("top");
key += "-" + request.getParameter("bottom");
key += "-" + request.getParameter("startsWith");
key += "-" + request.getParameter("month");
key += "-" + request.getParameter("year");
key += "-" + request.getParameter("subject");
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include all items on this browse page, along
* with all bundles and bitstreams refrenced by them. The one change that
* will not be refelected in this cache is a change is community/collection
* hierarchy.
*/
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
validity.add(dso);
performBrowse(MODE_BY_SUBJECT);
for (String subject : browseInfo.getStringResults())
{
validity.add(subject);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta,contextPath);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add the browse-subject division.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
performBrowse(MODE_BY_SUBJECT);
// Pagination variables
int itemsTotal = browseInfo.getTotal();
int firstItemIndex = browseInfo.getOverallPosition() + 1;
int lastItemIndex = browseInfo.getOverallPosition()
+ browseInfo.getResultCount();
String previousPage = previousPageURL("browse-subject");
String nextPage = nextPageURL("browse-subject");
// Build the DRI Body
Division div = body.addDivision("browse-by-subject","primary");
div.setHead(T_head);
// Navigatioal aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation",
"browse-subject", Division.METHOD_POST,"secondary navigation");
List jumpList = jump.addList("jump-list", List.TYPE_SIMPLE, "alphabet");
for (char c = 'A'; c <= 'Z'; c++)
jumpList.addItemXref("browse-subject?startsWith=" + c, String
.valueOf(c));
Para jumpForm = jump.addPara();
jumpForm.addContent(T_starts_with);
jumpForm.addText("startsWith");
jumpForm.addButton("submit").setValue(T_go);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-subject-results","primary");
results.setSimplePagination(itemsTotal, firstItemIndex, lastItemIndex,
previousPage, nextPage);
Table subjectTable = results.addTable("browse-by-subject-results",
browseInfo.getResultCount() + 1, 1);
subjectTable.addRow(Row.ROLE_HEADER).addCell().addContent(T_column_heading);
for (String subject : browseInfo.getStringResults())
{
Cell cell = subjectTable.addRow().addCell();
cell.addXref("browse-subject-items?subject=" + URLEncode(subject),
subject);
}
}
/**
* Recycle
*/
public void recycle() {
this.validity = null;
super.recycle();
}
}

View File

@@ -1,245 +0,0 @@
/*
* BrowseTitles.java
*
* Version: $Revision: 1.15 $
*
* Date: $Date: 2006/07/27 18:24:34 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.xml.sax.SAXException;
/**
* Display the results of browsing title index. This component may either apply
* to all communities and collection or be scoped to just one community /
* collection depending upon the url.
*
* @author Scott Phillips
*/
public class BrowseTitles extends AbstractBrowse implements CacheableProcessingComponent
{
/** Language strings */
private final static Message T_title =
message("xmlui.ArtifactBrowser.BrowseTitles.title");
private final static Message T_dspace_home =
message("xmlui.general.dspace_home");
private final static Message T_trail =
message("xmlui.ArtifactBrowser.BrowseTitles.trail");
private final static Message T_head =
message("xmlui.ArtifactBrowser.BrowseTitles.head");
private final static Message T_starts_with =
message("xmlui.ArtifactBrowser.BrowseTitles.starts_with");
private final static Message T_starts_with_help =
message("xmlui.ArtifactBrowser.BrowseTitles.starts_with_help");
private final static Message T_go =
message("xmlui.general.go");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
Request request = ObjectModelHelper.getRequest(objectModel);
String key = "";
key += "-" + request.getParameter("top");
key += "-" + request.getParameter("bottom");
key += "-" + request.getParameter("startsWith");
key += "-" + request.getParameter("month");
key += "-" + request.getParameter("year");
key += "-" + request.getParameter("author");
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include all items on this browse page, along
* with all bundles and bitstreams refrenced by them. The one change that
* will not be refelected in this cache is a change is community/collection
* hierarchy.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
validity.add(dso);
performBrowse(MODE_BY_TITLE);
for (Item item : browseInfo.getItemResults())
{
validity.add(item);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta,contextPath);
pageMeta.addTrail().addContent(T_trail);
}
/**
* Add the browse-title division.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
performBrowse(MODE_BY_TITLE);
// Pagination variables
int itemsTotal = browseInfo.getTotal();
int firstItemIndex = browseInfo.getOverallPosition() + 1;
int lastItemIndex = browseInfo.getOverallPosition()
+ browseInfo.getResultCount();
String previousPage = previousPageURL("browse-title");
String nextPage = nextPageURL("browse-title");
// Build the DRI Body
Division div = body.addDivision("browse-by-title","primary");
div.setHead(T_head);
// Navigatioal aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation",
"browse-title", Division.METHOD_POST, "secondary navigation");
List jumpList = jump.addList("jump-list", List.TYPE_SIMPLE, "alphabet");
for (char c = 'A'; c <= 'Z'; c++)
jumpList.addItemXref("browse-title?startsWith=" + c, String
.valueOf(c));
Para jumpForm = jump.addPara();
jumpForm.addContent(T_starts_with);
jumpForm.addText("startsWith").setHelp(T_starts_with_help);
jumpForm.addButton("submit").setValue(T_go);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-title-results","primary");
results.setSimplePagination(itemsTotal, firstItemIndex, lastItemIndex,
previousPage, nextPage);
// Refrence all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-title",
ReferenceSet.TYPE_SUMMARY_LIST, "title", null);
for (Item item : browseInfo.getItemResults())
{
referenceSet.addReference(item);
}
}
/**
* Recycle
*/
public void recycle() {
this.validity = null;
super.recycle();
}
}

View File

@@ -46,7 +46,9 @@ import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.cocoon.DSpaceFeedGenerator;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
@@ -59,8 +61,11 @@ import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseScope;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseItem;
import org.dspace.browse.BrowserScope;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
@@ -75,6 +80,8 @@ import org.xml.sax.SAXException;
*/
public class CollectionViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
private static final Logger log = Logger.getLogger(DSpaceFeedGenerator.class);
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
@@ -104,7 +111,7 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache
private static final int RECENT_SUBMISISONS = 5;
/** The cache of recently submitted items */
private java.util.List<Item> recentSubmissionItems;
private java.util.List<BrowseItem> recentSubmissionItems;
/** Cached validity object */
private SourceValidity validity;
@@ -161,7 +168,7 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache
validity.add(collection);
// add reciently submitted items
for(Item item : getRecientlySubmittedIems(collection))
for(BrowseItem item : getRecientlySubmittedIems(collection))
{
validity.add(item);
}
@@ -271,7 +278,7 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache
// Reciently submitted items
{
java.util.List<Item> items = getRecientlySubmittedIems(collection);
java.util.List<BrowseItem> items = getRecientlySubmittedIems(collection);
Division lastSubmittedDiv = home
.addDivision("collection-recent-submission","secondary recent-submission");
@@ -279,7 +286,7 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache
ReferenceSet lastSubmitted = lastSubmittedDiv.addReferenceSet(
"collection-last-submitted", ReferenceSet.TYPE_SUMMARY_LIST,
null, "recent-submissions");
for (Item item : items)
for (BrowseItem item : items)
{
lastSubmitted.addReference(item);
}
@@ -292,18 +299,29 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache
* @param collection The collection.
*/
@SuppressWarnings("unchecked") // The cast from getLastSubmitted is correct, it dose infact return a list of Items.
private java.util.List<Item> getRecientlySubmittedIems(Collection collection)
private java.util.List<BrowseItem> getRecientlySubmittedIems(Collection collection)
throws SQLException
{
if (recentSubmissionItems != null)
return recentSubmissionItems;
BrowserScope scope = new BrowserScope(context);
scope.setCollection(collection);
scope.setResultsPerPage(RECENT_SUBMISISONS);
// FIXME Exception Handling
try
{
scope.setBrowseIndex(BrowseIndex.getBrowseIndex("dateaccessioned"));
BrowseEngine be = new BrowseEngine(context);
this.recentSubmissionItems = be.browse(scope).getResults();
}
catch (BrowseException bex)
{
log.error("Caught BrowseException", bex);
}
BrowseScope scope = new BrowseScope(context);
scope.setScope(collection);
scope.setTotal(RECENT_SUBMISISONS);
this.recentSubmissionItems = Browse.getLastSubmitted(scope);
return this.recentSubmissionItems;
}

View File

@@ -46,7 +46,9 @@ import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.cocoon.DSpaceFeedGenerator;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
@@ -60,8 +62,11 @@ import org.dspace.app.xmlui.wing.element.Reference;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseScope;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseItem;
import org.dspace.browse.BrowserScope;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
@@ -72,11 +77,14 @@ import org.xml.sax.SAXException;
/**
* Display a single community. This includes a full text search, browse by list,
* community display and a list of recent submissions.
*
* private static final Logger log = Logger.getLogger(DSpaceFeedGenerator.class);
* @author Scott Phillips
*/
public class CommunityViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
private static final Logger log = Logger.getLogger(DSpaceFeedGenerator.class);
/** Language Strings */
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
@@ -112,7 +120,7 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
private static final int RECENT_SUBMISISONS = 5;
/** The cache of recently submitted items */
private java.util.List<Item> recentSubmittedItems;
private java.util.List<BrowseItem> recentSubmittedItems;
/** Cached validity object */
private SourceValidity validity;
@@ -176,7 +184,7 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
}
// Recently submitted items
for (Item item : getRecientlySubmittedIems(community))
for (BrowseItem item : getRecientlySubmittedIems(community))
{
validity.add(item);
}
@@ -321,7 +329,7 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
// Reciently submitted items
{
java.util.List<Item> items = getRecientlySubmittedIems(community);
java.util.List<BrowseItem> items = getRecientlySubmittedIems(community);
Division lastSubmittedDiv = home
.addDivision("community-recent-submission","secondary recent-submission");
@@ -329,7 +337,7 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
ReferenceSet lastSubmitted = lastSubmittedDiv.addReferenceSet(
"collection-last-submitted", ReferenceSet.TYPE_SUMMARY_LIST,
null, "recent-submissions");
for (Item item : items)
for (BrowseItem item : items)
{
lastSubmitted.addReference(item);
}
@@ -342,17 +350,29 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
* @param community The community.
*/
@SuppressWarnings("unchecked")
private java.util.List<Item> getRecientlySubmittedIems(Community community)
private java.util.List<BrowseItem> getRecientlySubmittedIems(Community community)
throws SQLException
{
if (recentSubmittedItems != null)
return recentSubmittedItems;
BrowseScope scope = new BrowseScope(context);
scope.setScope(community);
scope.setTotal(RECENT_SUBMISISONS);
BrowserScope scope = new BrowserScope(context);
scope.setCommunity(community);
scope.setResultsPerPage(RECENT_SUBMISISONS);
// FIXME Exception Handling
try
{
scope.setBrowseIndex(BrowseIndex.getBrowseIndex("dateaccessioned"));
this.recentSubmittedItems = Browse.getLastSubmitted(scope);
BrowseEngine be = new BrowseEngine(context);
this.recentSubmittedItems = be.browse(scope).getResults();
}
catch (BrowseException bex)
{
log.error("Caught BrowseException", bex);
}
return this.recentSubmittedItems;
}

View File

@@ -0,0 +1,809 @@
package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.RequestUtils;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseItem;
import org.dspace.browse.BrowserScope;
import org.dspace.browse.SortOption;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.xml.sax.SAXException;
/**
* Implements all the browse functionality (browse by title, subject, authors,
* etc.) The types of browse available are configurable by the implementor. See
* dspace.cfg and documentation for instructions on how to configure.
*
* @author Graham Triggs
*/
public class ConfigurableBrowse extends AbstractDSpaceTransformer implements
CacheableProcessingComponent
{
/**
* Static Messages for common text
*/
private final static Message T_dspace_home = message("xmlui.general.dspace_home");
private final static Message T_go = message("xmlui.general.go");
private final static Message T_update = message("xmlui.general.update");
private final static Message T_choose_month = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_month");
private final static Message T_choose_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_year");
private final static Message T_jump_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year");
private final static Message T_jump_year_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year_help");
private final static Message T_jump_select = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_select");
private final static Message T_starts_with = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with");
private final static Message T_starts_with_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with_help");
private final static Message T_sort_by = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.sort_by");
private final static Message T_order = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.order");
private final static Message T_rpp = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.rpp");
private final static Message T_etal = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.etal");
private final static Message T_etal_all = message("xmlui.ArtifactBrowser.ConfigurableBrowse.etal.all");
private final static Message T_order_asc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.asc");
private final static Message T_order_desc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.desc");
private final static String BROWSE_URL_BASE = "browse";
/**
* These variables dictate when the drop down list of years is to break from
* 1 year increments, to 5 year increments, to 10 year increments, and
* finally to stop.
*/
private static final int ONE_YEAR_LIMIT = 10;
private static final int FIVE_YEAR_LIMIT = 30;
private static final int TEN_YEAR_LIMIT = 100;
/** Cached validity object */
private SourceValidity validity;
/** Cached UI parameters and results */
private BrowseParams userParams;
private BrowseInfo browseInfo;
public Serializable getKey()
{
try
{
BrowseParams params = getUserParams();
String key = params.getKey();
if (key != null)
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
}
return "0";
}
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
validity.add(dso);
BrowseInfo info = getBrowseInfo();
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the browse items to the validity
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
validity.add(item);
}
}
else
{
// Add the metadata to the validity
for (String singleEntry : browseInfo.getStringResults())
{
validity.add(singleEntry);
}
}
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException,
SQLException, IOException, AuthorizeException
{
BrowseParams params = getUserParams();
// Get the name of the index
String type = params.scope.getBrowseIndex().getName();
// For a second level browse (ie. items for author),
// get the value we are focussing on (ie. author).
// (empty string if none).
String value = (params.scope.getValue() != null ? "\"" + params.scope.getValue() + "\"" : "");
// Get the name of any scoping element (collection / community)
String scopeName = "";
if (params.scope.getCollection() != null)
scopeName = params.scope.getCollection().getName();
else if (params.scope.getCommunity() != null)
scopeName = params.scope.getCommunity().getName();
else
scopeName = "";
pageMeta.addMetadata("title").addContent(
message("xmlui.ArtifactBrowser.ConfigurableBrowse." + type + ".title")
.parameterize(scopeName, value));
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta, contextPath);
pageMeta.addTrail().addContent(
message("xmlui.ArtifactBrowser.ConfigurableBrowse." + type + ".trail")
.parameterize(scopeName));
}
/**
* Add the browse-title division.
*/
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException,
IOException, AuthorizeException
{
BrowseParams params = getUserParams();
BrowseInfo info = getBrowseInfo();
String type = info.getBrowseIndex().getName();
// Build the DRI Body
Division div = body.addDivision("browse-by-" + type, "primary");
div.setHead(message("xmlui.ArtifactBrowser.ConfigurableBrowse." + type + ".title")
.parameterize(
(info.getBrowseContainer() != null ? info.getBrowseContainer().getName() : ""),
(info.getValue() != null ? "\"" + info.getValue() + "\"" : "")));
// Build the internal navigation (jump lists)
addBrowseJumpNavigation(div, info, params);
// Build the sort and display controls
addBrowseControls(div, info, params);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-" + type + "-results", "primary");
// Add the pagination
results.setSimplePagination(info.getTotal(), browseInfo.getOverallPosition() + 1,
browseInfo.getOverallPosition() + browseInfo.getResultCount(), getPreviousPageURL(
params, info), getNextPageURL(params, info));
// Reference all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-" + type,
ReferenceSet.TYPE_SUMMARY_LIST, type, null);
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the items to the browse results
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
referenceSet.addReference(item);
}
}
else // browsing a list of unique metadata entries
{
// Create a table for the results
Table singleTable = results.addTable("browse-by-" + type + "-results",
browseInfo.getResultCount() + 1, 1);
// Add the column heading
singleTable.addRow(Row.ROLE_HEADER).addCell().addContent(
message("xmlui.ArtifactBrowser.ConfigurableBrowse." + type + ".column_heading"));
// Iterate each result
for (String singleEntry : browseInfo.getStringResults())
{
// Create a Map of the query parameters for the link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(BrowseParams.TYPE, URLEncode(type));
queryParams.put(BrowseParams.VALUE, URLEncode(singleEntry));
// Create an entry in the table, and a linked entry
Cell cell = singleTable.addRow().addCell();
cell.addXref(super.generateURL(BROWSE_URL_BASE, queryParams), singleEntry);
}
}
}
/**
* Recycle
*/
public void recycle()
{
this.validity = null;
this.userParams = null;
this.browseInfo = null;
super.recycle();
}
/**
* Makes the jump-list navigation for the results
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseJumpNavigation(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Get the name of the index
String type = info.getBrowseIndex().getName();
// Prepare a Map of query parameters required for all links
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.putAll(params.getCommonParameters());
queryParams.putAll(params.getControlParameters());
// Navigation aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation", BROWSE_URL_BASE,
Division.METHOD_POST, "secondary navigation");
// Add all the query parameters as hidden fields on the form
for (String key : queryParams.keySet())
jump.addHidden(key).setValue(queryParams.get(key));
// If this is a date based browse, render the date navigation
if (isSortedByDate(info))
{
Para jumpForm = jump.addPara();
// Create a select list to choose a month
jumpForm.addContent(T_jump_select);
Select month = jumpForm.addSelect(BrowseParams.MONTH);
month.addOption(false, "-1", T_choose_month);
for (int i = 1; i <= 12; i++)
{
month.addOption(false, String.valueOf(i), DCDate.getMonthName(i, Locale
.getDefault()));
}
// Create a select list to choose a year
Select year = jumpForm.addSelect(BrowseParams.YEAR);
year.addOption(false, "-1", T_choose_year);
int currentYear = DCDate.getCurrent().getYear();
int i = currentYear;
// Calculate where to move from 1, 5 to 10 year jumps
int oneYearBreak = ((currentYear - ONE_YEAR_LIMIT) / 5) * 5;
int fiveYearBreak = ((currentYear - FIVE_YEAR_LIMIT) / 10) * 10;
int tenYearBreak = (currentYear - TEN_YEAR_LIMIT);
do
{
year.addOption(false, String.valueOf(i), String.valueOf(i));
if (i <= fiveYearBreak)
i -= 10;
else if (i <= oneYearBreak)
i -= 5;
else
i--;
}
while (i > tenYearBreak);
// Create a free text entry box for the year
jumpForm = jump.addPara();
jumpForm.addContent(T_jump_year);
jumpForm.addText("start_with").setHelp(T_jump_year_help);
jumpForm.addButton("submit").setValue(T_go);
}
else
{
// Create a clickable list of the alphabet
List jumpList = jump.addList("jump-list", List.TYPE_SIMPLE, "alphabet");
for (char c = 'A'; c <= 'Z'; c++)
{
Map<String, String> cQuery = new HashMap<String, String>(queryParams);
cQuery.put(BrowseParams.STARTS_WITH, Character.toString(c));
jumpList.addItemXref(super.generateURL(BROWSE_URL_BASE, cQuery), Character
.toString(c));
}
// Create a free text field for the initial characters
Para jumpForm = jump.addPara();
jumpForm.addContent(T_starts_with);
jumpForm.addText(BrowseParams.STARTS_WITH).setHelp(T_starts_with_help);
jumpForm.addButton("submit").setValue(T_go);
}
}
/**
* Add the controls to changing sorting and display options.
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseControls(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Prepare a Map of query parameters required for all links
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.putAll(params.getCommonParameters());
Division controls = div.addInteractiveDivision("browse-controls", BROWSE_URL_BASE,
Division.METHOD_POST, "browse controls");
// Add all the query parameters as hidden fields on the form
for (String key : queryParams.keySet())
controls.addHidden(key).setValue(queryParams.get(key));
Para controlsForm = controls.addPara();
// If we are browsing a 'second level' list of items
if (isItemBrowse(info) && info.isSecondLevel())
{
// Create a drop down of the different sort columns available
Map<Integer, SortOption> sortOptions = info.getBrowseIndex().getSortOptions();
// Only generate the list if we have multiple columns
if (sortOptions.size() > 1)
{
controlsForm.addContent(T_sort_by);
Select sortSelect = controlsForm.addSelect(BrowseParams.SORT_BY);
for (Integer sortKey : sortOptions.keySet())
{
SortOption sort = sortOptions.get(sortKey);
sortSelect.addOption(sort.equals(info.getSortOption()), sort.getNumber(),
message("xmlui.ArtifactBrowser.ConfigurableBrowse.sort_by." + sort.getName()));
}
}
}
// Create a control to changing ascending / descending order
controlsForm.addContent(T_order);
Select orderSelect = controlsForm.addSelect(BrowseParams.ORDER);
orderSelect.addOption("ASC".equals(params.scope.getOrder()), "ASC", T_order_asc);
orderSelect.addOption("DESC".equals(params.scope.getOrder()), "DESC", T_order_desc);
// Create a control for the number of records to display
controlsForm.addContent(T_rpp);
Select rppSelect = controlsForm.addSelect(BrowseParams.RESULTS_PER_PAGE);
for (int i = 5; i <= 100; i += 5)
{
rppSelect.addOption((i == info.getResultsPerPage()), i, Integer.toString(i));
}
// Create a control for the number of authors per item to display
// FIXME This is currently disabled, as the supporting functionality
// is not currently present in xmlui
//if (isItemBrowse(info))
//{
// controlsForm.addContent(T_etal);
// Select etalSelect = controlsForm.addSelect(BrowseParams.ETAL);
//
// etalSelect.addOption((info.getEtAl() < 0), 0, T_etal_all);
// etalSelect.addOption(1 == info.getEtAl(), 1, Integer.toString(1));
//
// for (int i = 5; i <= 50; i += 5)
// {
// etalSelect.addOption(i == info.getEtAl(), i, Integer.toString(i));
// }
//}
controlsForm.addButton("update").setValue(T_update);
}
/**
* The URL query string of of the previous page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getPreviousPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a previous page link if this is the first page
if (info.isFirst())
return null;
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParameters());
parameters.putAll(params.getControlParameters());
if (info.hasPrevPage())
{
if (info.getPrevItem() < 0)
parameters.put(BrowseParams.FOCUS_VALUE, URLEncode(info.getPrevValue()));
else
parameters.put(BrowseParams.FOCUS, Integer.toString(info.getPrevItem()));
}
return super.generateURL(BROWSE_URL_BASE, parameters);
}
/**
* The URL query string of of the next page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getNextPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a next page link if this is the last page
if (info.isLast())
return null;
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParameters());
parameters.putAll(params.getControlParameters());
if (info.hasNextPage())
{
if (info.getNextItem() < 0)
parameters.put(BrowseParams.FOCUS_VALUE, URLEncode(info.getNextValue()));
else
parameters.put(BrowseParams.FOCUS, Integer.toString(info.getNextItem()));
}
return super.generateURL(BROWSE_URL_BASE, parameters);
}
/**
* Get the query parameters supplied to the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseParams getUserParams() throws SQLException, UIException
{
if (this.userParams != null)
return this.userParams;
Context context = ContextUtil.obtainContext(objectModel);
Request request = ObjectModelHelper.getRequest(objectModel);
BrowseParams params = new BrowseParams();
params.month = request.getParameter(BrowseParams.MONTH);
params.year = request.getParameter(BrowseParams.YEAR);
params.etAl = RequestUtils.getIntParameter(request, BrowseParams.ETAL);
params.scope = new BrowserScope(context);
// Are we in a community or collection?
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso instanceof Community)
params.scope.setCommunity((Community) dso);
if (dso instanceof Collection)
params.scope.setCollection((Collection) dso);
try
{
params.scope.setBrowseIndex(BrowseIndex.getBrowseIndex(request
.getParameter(BrowseParams.TYPE)));
params.scope.setFocus(RequestUtils.getIntParameter(request, BrowseParams.FOCUS));
params.scope.setOrder(request.getParameter(BrowseParams.ORDER));
params.scope.setResultsPerPage(RequestUtils.getIntParameter(request,
BrowseParams.RESULTS_PER_PAGE));
params.scope.setSortBy(RequestUtils.getIntParameter(request, BrowseParams.SORT_BY));
params.scope.setStartsWith(request.getParameter(BrowseParams.STARTS_WITH));
params.scope.setValue(request.getParameter(BrowseParams.VALUE));
params.scope.setValueFocus(request.getParameter(BrowseParams.FOCUS_VALUE));
params.scope.setValueFocusLang(request.getParameter(BrowseParams.FOCUS_VALUE_LANG));
params.scope.setValueLang(request.getParameter(BrowseParams.VALUE_LANG));
if (params.scope.getValue() != null)
params.scope.setBrowseLevel(1);
// if year and perhaps month have been selected, we translate these
// into "startsWith"
// if startsWith has already been defined then it is overwritten
if (params.year != null && !"".equals(params.year) && !"-1".equals(params.year))
{
String startsWith = params.year;
if ((params.month != null) && !"-1".equals(params.month)
&& !"".equals(params.month))
{
// subtract 1 from the month, so the match works
// appropriately
if ("ASC".equals(params.scope.getOrder()))
{
params.month = Integer.toString((Integer.parseInt(params.month) - 1));
}
// They've selected a month as well
if (params.month.length() == 1)
{
// Ensure double-digit month number
params.month = "0" + params.month;
}
startsWith = params.year + "-" + params.month;
}
params.scope.setStartsWith(startsWith);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to create browse parameters", bex);
}
this.userParams = params;
return params;
}
/**
* Get the results of the browse. If the results haven't been generated yet,
* then this will perform the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseInfo getBrowseInfo() throws SQLException, UIException
{
if (this.browseInfo != null)
return this.browseInfo;
Context context = ContextUtil.obtainContext(objectModel);
// Get the parameters we will use for the browse
// (this includes a browse scope)
BrowseParams params = getUserParams();
try
{
// Create a new browse engine, and perform the browse
BrowseEngine be = new BrowseEngine(context);
this.browseInfo = be.browse(params.scope);
// figure out the setting for author list truncation
if (params.etAl < 0)
{
// there is no limit, or the UI says to use the default
int etAl = ConfigurationManager.getIntProperty("webui.browse.author-limit");
if (etAl != 0)
{
this.browseInfo.setEtAl(etAl);
}
}
else if (params.etAl == 0) // 0 is the user setting for unlimited
{
this.browseInfo.setEtAl(-1); // but -1 is the application
// setting for unlimited
}
else
// if the user has set a limit
{
this.browseInfo.setEtAl(params.etAl);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to process browse", bex);
}
return this.browseInfo;
}
/**
* Is this a browse on a list of items, or unique metadata values?
*
* @param info
* @return
*/
private boolean isItemBrowse(BrowseInfo info)
{
return info.getBrowseIndex().isFull() || info.isSecondLevel();
}
/**
* Is this browse sorted by date?
* @param info
* @return
*/
private boolean isSortedByDate(BrowseInfo info)
{
return info.getSortOption().isDate() ||
(info.getBrowseIndex().isDate() && info.getSortOption().isDefault());
}
}
/*
* Helper class to track browse parameters
*/
class BrowseParams
{
String month;
String year;
int etAl;
BrowserScope scope;
final static String MONTH = "month";
final static String YEAR = "year";
final static String ETAL = "etal";
final static String TYPE = "type";
final static String FOCUS = "focus";
final static String FOCUS_VALUE = "vfocus";
final static String FOCUS_VALUE_LANG = "vfocus_lang";
final static String ORDER = "order";
final static String RESULTS_PER_PAGE = "rpp";
final static String SORT_BY = "sort_by";
final static String STARTS_WITH = "starts_with";
final static String VALUE = "value";
final static String VALUE_LANG = "value_lang";
/*
* Creates a map of the browse options common to all pages (type / value /
* value language)
*/
Map<String, String> getCommonParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put(BrowseParams.TYPE, AbstractDSpaceTransformer.URLEncode(this.scope
.getBrowseIndex().getName()));
if (scope.getValue() != null)
paramMap.put(BrowseParams.VALUE, AbstractDSpaceTransformer.URLEncode(scope.getValue()));
if (scope.getValueLang() != null)
paramMap.put(BrowseParams.VALUE_LANG, AbstractDSpaceTransformer.URLEncode(scope
.getValueLang()));
return paramMap;
}
/*
* Creates a Map of the browse control options (sort by / ordering / results
* per page / authors per item)
*/
Map<String, String> getControlParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put(BrowseParams.SORT_BY, Integer.toString(this.scope.getSortBy()));
paramMap
.put(BrowseParams.ORDER, AbstractDSpaceTransformer.URLEncode(this.scope.getOrder()));
paramMap.put(BrowseParams.RESULTS_PER_PAGE, Integer
.toString(this.scope.getResultsPerPage()));
paramMap.put(BrowseParams.ETAL, Integer.toString(this.etAl));
return paramMap;
}
String getKey()
{
try
{
String key = "";
key += "-" + scope.getBrowseIndex().getName();
key += "-" + scope.getBrowseLevel();
key += "-" + scope.getStartsWith();
key += "-" + scope.getResultsPerPage();
key += "-" + scope.getSortBy();
key += "-" + scope.getSortOption().getNumber();
key += "-" + scope.getOrder();
key += "-" + scope.getFocus();
key += "-" + scope.getValue();
key += "-" + scope.getValueLang();
key += "-" + scope.getValueFocus();
key += "-" + scope.getValueFocusLang();
key += "-" + etAl;
return key;
}
catch (Exception e)
{
return null; // ignore exception and return no key
}
}
};

View File

@@ -42,6 +42,8 @@ package org.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
@@ -58,6 +60,8 @@ import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
@@ -162,11 +166,11 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr
List browseContext = browse.addList("context");
browseGlobal.setHead(T_head_all_of_dspace);
browseGlobal.addItemXref(contextPath + "/community-list",T_communities_and_collections);
browseGlobal.addItemXref(contextPath + "/browse-title",T_browse_titles);
browseGlobal.addItemXref(contextPath + "/browse-author",T_browse_authors);
browseGlobal.addItemXref(contextPath + "/browse-subject",T_browse_subjects);
browseGlobal.addItemXref(contextPath + "/browse-date",T_browse_dates);
// Add the configured browse lists for 'top level' browsing
addBrowseOptions(browseGlobal, contextPath + "/browse");
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
@@ -187,11 +191,9 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr
browseContext.setHead(T_head_this_community);
}
// Add the configured browse lists for scoped browsing
String handle = dso.getHandle();
browseContext.addItemXref(contextPath + "/handle/" + handle + "/browse-title",T_browse_titles);
browseContext.addItemXref(contextPath + "/handle/" + handle + "/browse-author",T_browse_authors);
browseContext.addItemXref(contextPath + "/handle/" + handle + "/browse-subject",T_browse_subjects);
browseContext.addItemXref(contextPath + "/handle/" + handle + "/browse-date",T_browse_dates);
addBrowseOptions(browseContext, contextPath + "/handle/" + handle + "/browse");
}
}
@@ -239,4 +241,37 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr
}
}
}
/**
* Add navigation for the configured browse tables to the supplied list.
*
* @param browseList
* @param browseURL
* @throws WingException
*/
private void addBrowseOptions(List browseList, String browseURL) throws WingException
{
// FIXME Exception handling
try
{
// Get a Map of all the browse tables
Map<Integer, BrowseIndex> bis = BrowseIndex.getBrowseIndicesMap();
for (int i = 0; i < bis.size(); i++)
{
// Create a Map of the query parameters for this link
Map<String, String> queryParams = new HashMap<String, String>();
BrowseIndex bix = (BrowseIndex) bis.get(new Integer(i + 1));
queryParams.put("type", bix.getName());
// Add a link to this browse
browseList.addItemXref(super.generateURL(browseURL, queryParams),
message("xmlui.ArtifactBrowser.Navigation.browse_" + bix.getName()));
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to get browse indicies", bex);
}
}
}

View File

@@ -63,10 +63,13 @@ import org.apache.cocoon.generation.AbstractGenerator;
import org.apache.cocoon.util.HashUtil;
import org.apache.cocoon.xml.dom.DOMStreamer;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.browse.Browse;
import org.dspace.browse.BrowseScope;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowserScope;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
@@ -122,6 +125,7 @@ import com.sun.syndication.io.WireFeedOutput;
public class DSpaceFeedGenerator extends AbstractGenerator
implements Configurable, CacheableProcessingComponent, Recyclable
{
private static final Logger log = Logger.getLogger(DSpaceFeedGenerator.class);
/** The feed's requested format */
private String format = null;
@@ -537,14 +541,24 @@ public class DSpaceFeedGenerator extends AbstractGenerator
if (recentSubmissionItems != null)
return recentSubmissionItems;
BrowseScope scope = new BrowseScope(context);
BrowserScope scope = new BrowserScope(context);
if (dso instanceof Collection)
scope.setScope((Collection) dso);
scope.setCollection((Collection) dso);
else if (dso instanceof Community)
scope.setScope((Community) dso);
scope.setTotal(itemCount);
scope.setCommunity((Community) dso);
scope.setResultsPerPage(itemCount);
this.recentSubmissionItems = Browse.getLastSubmitted(scope);
// FIXME Exception handling
try
{
scope.setBrowseIndex(BrowseIndex.getBrowseIndex("dateaccessioned"));
BrowseEngine be = new BrowseEngine(context);
this.recentSubmissionItems = be.browse(scope).getResults();
}
catch (BrowseException bex)
{
log.error("Caught browse exception", bex);
}
return this.recentSubmissionItems;
}

View File

@@ -46,6 +46,7 @@ import java.util.List;
import org.dspace.app.xmlui.wing.ObjectManager;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.browse.BrowseItem;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
@@ -76,7 +77,12 @@ public class DSpaceObjectManager implements ObjectManager
public boolean manageObject(Object object) throws WingException
{
// First check that the object is of a type we can manage.
if (object instanceof Item)
if (object instanceof BrowseItem)
{
dsos.add((BrowseItem) object);
return true;
}
else if (object instanceof Item)
{
dsos.add((Item) object);
return true;

View File

@@ -45,6 +45,7 @@ import java.sql.SQLException;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.browse.BrowseItem;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
@@ -314,6 +315,22 @@ public class DSpaceValidity implements SourceValidity
this.add(bundle);
}
}
else if (dso instanceof BrowseItem)
{
BrowseItem browseItem = (BrowseItem) dso;
validityKey.append("BrowseItem:");
validityKey.append(browseItem.getHandle());
DCValue[] dcvs = browseItem.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (DCValue dcv : dcvs)
{
validityKey.append(dcv.schema + ".");
validityKey.append(dcv.element + ".");
validityKey.append(dcv.qualifier + ".");
validityKey.append(dcv.language + "=");
validityKey.append(dcv.value);
}
}
else if (dso instanceof Bundle)
{
Bundle bundle = (Bundle) dso;

View File

@@ -184,6 +184,31 @@ public class RequestUtils {
return values;
}
/**
* Obtain a parameter from the given request as an int. <code>-1</code> is
* returned if the parameter is garbled or does not exist.
*
* @param request
* the HTTP request
* @param param
* the name of the parameter
*
* @return the integer value of the parameter, or -1
*/
public static int getIntParameter(Request request, String param)
{
String val = request.getParameter(param);
try
{
return Integer.parseInt(val.trim());
}
catch (Exception e)
{
// Problem with parameter
return -1;
}
}
}

Some files were not shown because too many files have changed in this diff Show More