Merge remote-tracking branch 'upstream/master' into DS-1456

This commit is contained in:
Mark H. Wood
2013-10-15 09:27:30 -04:00
395 changed files with 33151 additions and 9317 deletions

1
.gitignore vendored
View File

@@ -11,6 +11,7 @@ target/
*.ipr
*.iws
.idea/
overlays/
## Ignore project files created by NetBeans
nbproject/private/

1
.travis.yml Normal file
View File

@@ -0,0 +1 @@
language: java

View File

@@ -149,3 +149,13 @@ http.proxy.host =
# port number of proxy server
http.proxy.port =
#####################
# LOGLEVEL SETTINGS #
#####################
loglevel.other = INFO
# loglevel.other: Log level for other third-party tools/APIs used by DSpace
# Possible values (from most to least info): DEBUG, INFO, WARN, ERROR, FATAL
loglevel.dspace = INFO
# loglevel.dspace: Log level for all DSpace-specific code (org.dspace.*)
# Possible values (from most to least info): DEBUG, INFO, WARN, ERROR, FATAL

View File

@@ -96,6 +96,18 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.mycila.maven-license-plugin</groupId>
<artifactId>maven-license-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/src/test/resources/**</exclude>
<exclude>**/src/test/data/**</exclude>
<exclude>**/.gitignore</exclude>
<exclude>src/test/data/dspaceFolder/config/spiders/**</exclude>
</excludes>
</configuration>
</plugin>
<!-- This plugin allows us to run a Groovy script in our Maven POM
(see: http://gmaven.codehaus.org/Executing+Groovy+Code )
We are generating a OS-agnostic version (agnostic.build.dir) of
@@ -196,7 +208,7 @@
</configuration>
</plugin>
<plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
@@ -249,8 +261,12 @@
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers</artifactId>
<artifactId>lucene-analyzers-common</artifactId>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
@@ -289,6 +305,10 @@
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
@@ -431,7 +451,7 @@
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>${lucene.version}</version>
<version>${solr.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
@@ -463,12 +483,18 @@
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.18.6</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.90.3</version>
</dependency>
<dependency>
<groupId>com.coverity.security</groupId>
<artifactId>coverity-escapers</artifactId>
<version>1.1.1</version>
</dependency>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>

View File

@@ -37,7 +37,7 @@ import org.dspace.handle.HandleManager;
*/
public class Harvest
{
private static Context context;
private static Context context;
public static void main(String[] argv) throws Exception
{
@@ -251,6 +251,8 @@ public class Harvest
System.out.println(" (run with -h flag for details)");
System.exit(1);
}
pingResponder(oaiSource, oaiSetID, metadataKey);
}
}
@@ -435,49 +437,80 @@ public class Harvest
System.out.println("Harvest complete. ");
}
/**
* Resets harvest_status and harvest_start_time flags for all collections that have a row in the harvested_collections table
*/
private static void resetHarvesting() {
System.out.print("Resetting harvest status flag on all collections... ");
try
try
{
List<Integer> cids = HarvestedCollection.findAll(context);
for (Integer cid : cids)
{
HarvestedCollection hc = HarvestedCollection.find(context, cid);
//hc.setHarvestResult(null,"");
hc.setHarvestStartTime(null);
hc.setHarvestStatus(HarvestedCollection.STATUS_READY);
hc.update();
}
context.commit();
System.out.println("success. ");
List<Integer> cids = HarvestedCollection.findAll(context);
for (Integer cid : cids)
{
HarvestedCollection hc = HarvestedCollection.find(context, cid);
//hc.setHarvestResult(null,"");
hc.setHarvestStartTime(null);
hc.setHarvestStatus(HarvestedCollection.STATUS_READY);
hc.update();
}
context.commit();
System.out.println("success. ");
}
catch (Exception ex) {
System.out.println("failed. ");
ex.printStackTrace();
System.out.println("failed. ");
ex.printStackTrace();
}
}
/**
* Starts up the harvest scheduler. Terminating this process will stop the scheduler.
*/
private static void startHarvester()
{
try
{
System.out.print("Starting harvest loop... ");
OAIHarvester.startNewScheduler();
System.out.println("running. ");
try
{
System.out.print("Starting harvest loop... ");
OAIHarvester.startNewScheduler();
System.out.println("running. ");
}
catch (Exception ex) {
ex.printStackTrace();
ex.printStackTrace();
}
}
/**
* See if the responder is alive and working.
*
* @param server address of the responder's host.
* @param set name of an item set.
* @param metadataFormat local prefix name, or null for "dc".
*/
private static void pingResponder(String server, String set, String metadataFormat)
{
List<String> errors;
System.out.print("Testing basic PMH access: ");
errors = OAIHarvester.verifyOAIharvester(server, set,
(null != metadataFormat) ? metadataFormat : "dc", false);
if (errors.isEmpty())
System.out.println("OK");
else
{
for (String error : errors)
System.err.println(error);
}
System.out.print("Testing ORE support: ");
errors = OAIHarvester.verifyOAIharvester(server, set,
(null != metadataFormat) ? metadataFormat : "dc", true);
if (errors.isEmpty())
System.out.println("OK");
else
{
for (String error : errors)
System.err.println(error);
}
}
}

View File

@@ -21,9 +21,12 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -74,7 +77,7 @@ import org.dspace.handle.HandleManager;
* <P>
* Modified by David Little, UCSD Libraries 12/21/04 to allow the registration
* of files (bitstreams) into DSpace.
*
*
* @author David Little
* @author Jay Paz
*/
@@ -86,12 +89,12 @@ public class ItemExport
* used for export download
*/
public static final String COMPRESSED_EXPORT_MIME_TYPE = "application/zip";
/** log4j logger */
private static Logger log = Logger.getLogger(ItemExport.class);
/*
*
*
*/
public static void main(String[] argv) throws Exception
{
@@ -390,7 +393,7 @@ public class ItemExport
/**
* Discover the different schemas in use and output a separate metadata XML
* file for each schema.
*
*
* @param c
* @param i
* @param destDir
@@ -561,7 +564,7 @@ public class ItemExport
* were originally registered will be marked in the contents file as such.
* However, the export directory will contain actual copies of the content
* files being exported.
*
*
* @param c
* the DSpace context
* @param i
@@ -720,7 +723,7 @@ public class ItemExport
/**
* Convenience methot to create export a single Community, Collection, or
* Item
*
*
* @param dso
* - the dspace object to export
* @param context
@@ -740,7 +743,7 @@ public class ItemExport
/**
* Convenience method to export a List of dspace objects (Community,
* Collection or Item)
*
*
* @param dsObjects
* - List containing dspace objects
* @param context
@@ -758,7 +761,7 @@ public class ItemExport
/**
* Convenience methot to create export a single Community, Collection, or
* Item
*
*
* @param dso
* - the dspace object to export
* @param context
@@ -778,7 +781,7 @@ public class ItemExport
/**
* Convenience method to export a List of dspace objects (Community,
* Collection or Item)
*
*
* @param dsObjects
* - List containing dspace objects
* @param context
@@ -797,7 +800,7 @@ public class ItemExport
* Does the work creating a List with all the Items in the Community or
* Collection It then kicks off a new Thread to export the items, zip the
* export directory and send confirmation email
*
*
* @param dsObjects
* - List of dspace objects to process
* @param context
@@ -821,16 +824,17 @@ public class ItemExport
// items
// it will be checked against the config file entry
double size = 0;
final ArrayList<Integer> items = new ArrayList<Integer>();
final HashMap<String, List<Integer>> itemsMap = new HashMap<String, List<Integer>>();
for (DSpaceObject dso : dsObjects)
{
if (dso.getType() == Constants.COMMUNITY)
{
Community community = (Community) dso;
// get all the collections in the community
Collection[] collections = community.getCollections();
Collection[] collections = community.getAllCollections();
for (Collection collection : collections)
{
ArrayList<Integer> items = new ArrayList<Integer>();
// get all the items in each collection
ItemIterator iitems = collection.getItems();
try
@@ -859,12 +863,18 @@ public class ItemExport
{
iitems.close();
}
if (items.size() > 0)
{
itemsMap.put("collection_"+collection.getID(), items);
}
}
}
}
else if (dso.getType() == Constants.COLLECTION)
{
Collection collection = (Collection) dso;
ArrayList<Integer> items = new ArrayList<Integer>();
// get all the items in the collection
ItemIterator iitems = collection.getItems();
try
@@ -893,6 +903,10 @@ public class ItemExport
{
iitems.close();
}
if (items.size() > 0)
{
itemsMap.put("collection_"+collection.getID(), items);
}
}
}
else if (dso.getType() == Constants.ITEM)
@@ -910,7 +924,9 @@ public class ItemExport
size += bit.getSize();
}
}
ArrayList<Integer> items = new ArrayList<Integer>();
items.add(item.getID());
itemsMap.put("item_"+item.getID(), items);
}
else
{
@@ -942,7 +958,7 @@ public class ItemExport
}
// if we have any items to process then kick off annonymous thread
if (items.size() > 0)
if (itemsMap.size() > 0)
{
Thread go = new Thread()
{
@@ -955,40 +971,52 @@ public class ItemExport
// create a new dspace context
context = new Context();
// ignore auths
context.setIgnoreAuthorization(true);
iitems = new ItemIterator(context, items);
context.turnOffAuthorisationSystem();
String fileName = assembleFileName("item", eperson,
new Date());
String workDir = getExportWorkDirectory()
String workParentDir = getExportWorkDirectory()
+ System.getProperty("file.separator")
+ fileName;
String downloadDir = getExportDownloadDirectory(eperson
.getID());
File wkDir = new File(workDir);
if (!wkDir.exists() && !wkDir.mkdirs())
{
log.error("Unable to create working directory");
}
File dnDir = new File(downloadDir);
if (!dnDir.exists() && !dnDir.mkdirs())
{
log.error("Unable to create download directory");
}
// export the items using normal export method
exportItem(context, iitems, workDir, 1, migrate);
Iterator<String> iter = itemsMap.keySet().iterator();
while(iter.hasNext())
{
String keyName = iter.next();
iitems = new ItemIterator(context, itemsMap.get(keyName));
String workDir = workParentDir
+ System.getProperty("file.separator")
+ keyName;
File wkDir = new File(workDir);
if (!wkDir.exists() && !wkDir.mkdirs())
{
log.error("Unable to create working directory");
}
// export the items using normal export method
exportItem(context, iitems, workDir, 1, migrate);
iitems.close();
}
// now zip up the export directory created above
zip(workDir, downloadDir
zip(workParentDir, downloadDir
+ System.getProperty("file.separator")
+ fileName + ".zip");
// email message letting user know the file is ready for
// download
emailSuccessMessage(context, eperson, fileName + ".zip");
// return to enforcing auths
context.setIgnoreAuthorization(false);
context.restoreAuthSystemState();
}
catch (Exception e1)
{
@@ -1008,7 +1036,7 @@ public class ItemExport
{
iitems.close();
}
// Make sure the database connection gets closed in all conditions.
try {
context.complete();
@@ -1023,11 +1051,16 @@ public class ItemExport
go.isDaemon();
go.start();
}
else
{
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
emailErrorMessage(eperson, I18nUtil.getMessage("org.dspace.app.itemexport.no-result", supportedLocale));
}
}
/**
* Create a file name based on the date and eperson
*
*
* @param eperson
* - eperson who requested export and will be able to download it
* @param date
@@ -1061,7 +1094,7 @@ public class ItemExport
/**
* Use config file entry for org.dspace.app.itemexport.download.dir and id
* of the eperson to create a download directory name
*
*
* @param ePersonID
* - id of the eperson who requested export archive
* @return String representing a directory in the form of
@@ -1085,7 +1118,7 @@ public class ItemExport
/**
* Returns config file entry for org.dspace.app.itemexport.work.dir
*
*
* @return String representing config file entry for
* org.dspace.app.itemexport.work.dir
* @throws Exception
@@ -1104,7 +1137,7 @@ public class ItemExport
/**
* Used to read the export archived. Inteded for download.
*
*
* @param fileName
* the name of the file to download
* @param eperson
@@ -1129,7 +1162,7 @@ public class ItemExport
/**
* Get the file size of the export archive represented by the file name.
*
*
* @param fileName
* name of the file to get the size.
* @throws Exception
@@ -1175,7 +1208,7 @@ public class ItemExport
* The file name of the export archive contains the eperson id of the person
* who created it When requested for download this method can check if the
* person requesting it is the same one that created it
*
*
* @param context
* dspace context
* @param fileName
@@ -1208,7 +1241,7 @@ public class ItemExport
/**
* Reads the download directory for the eperson to see if any export
* archives are available
*
*
* @param eperson
* @return a list of file names representing export archives that have been
* processed
@@ -1245,7 +1278,7 @@ public class ItemExport
* A clean up method that is ran before a new export archive is created. It
* uses the config file entry 'org.dspace.app.itemexport.life.span.hours' to
* determine if the current exports are too old and need pruging
*
*
* @param epersonID
* - the id of the eperson to clean up
* @throws Exception
@@ -1328,7 +1361,7 @@ public class ItemExport
* with calling method about success or failure. We accomplis this
* communication with email instead. Send a success email once the export
* archive is complete and ready for download
*
*
* @param context
* - the current Context
* @param eperson
@@ -1344,7 +1377,7 @@ public class ItemExport
try
{
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success"));
email.addRecipient(eperson.getEmail());
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/exportdownload/" + fileName);
email.addArgument(ConfigurationManager.getProperty("org.dspace.app.itemexport.life.span.hours"));
@@ -1362,7 +1395,7 @@ public class ItemExport
* with calling method about success or failure. We accomplis this
* communication with email instead. Send an error email if the export
* archive fails
*
*
* @param eperson
* - EPerson to send the error message to
* @param error
@@ -1376,7 +1409,7 @@ public class ItemExport
try
{
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error"));
email.addRecipient(eperson.getEmail());
email.addArgument(error);
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/feedback");
@@ -1461,7 +1494,7 @@ public class ItemExport
// byte[] b = new byte[ (int)(cpFile.length()) ];
cpFileInputStream = new FileInputStream(cpFile);
cpFileInputStream = new FileInputStream(cpFile);
ZipEntry cpZipEntry = new ZipEntry(strZipEntryName);
cpZipOutputStream.putNextEntry(cpZipEntry);

View File

@@ -8,7 +8,10 @@
package org.dspace.app.mediafilter;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.image.*;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.Font;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -22,6 +25,8 @@ import org.dspace.core.ConfigurationManager;
* Filter image bitstreams, scaling the image to be within the bounds of
* thumbnail.maxwidth, thumbnail.maxheight, the size we want our thumbnail to be
* no bigger than. Creates only JPEGs.
*
* @author Jason Sherman <jsherman@usao.edu>
*/
public class BrandedPreviewJPEGFilter extends MediaFilter
{
@@ -73,6 +78,10 @@ public class BrandedPreviewJPEGFilter extends MediaFilter
.getIntProperty("webui.preview.maxwidth");
float ymax = (float) ConfigurationManager
.getIntProperty("webui.preview.maxheight");
boolean blurring = (boolean) ConfigurationManager
.getBooleanProperty("webui.preview.blurring");
boolean hqscaling = (boolean) ConfigurationManager
.getBooleanProperty("webui.preview.hqscaling");
int brandHeight = ConfigurationManager.getIntProperty("webui.preview.brand.height");
String brandFont = ConfigurationManager.getProperty("webui.preview.brand.font");
int brandFontPoint = ConfigurationManager.getIntProperty("webui.preview.brand.fontpoint");
@@ -137,6 +146,23 @@ public class BrandedPreviewJPEGFilter extends MediaFilter
BufferedImage branded = new BufferedImage((int) xsize, (int) ysize + brandHeight,
BufferedImage.TYPE_INT_RGB);
// Use blurring if selected in config.
// a little blur before scaling does wonders for keeping moire in check.
if (blurring)
{
// send the buffered image off to get blurred.
buf = getBlurredInstance((BufferedImage) buf);
}
// Use high quality scaling method if selected in config.
// this has a definite performance penalty.
if (hqscaling)
{
// send the buffered image off to get an HQ downscale.
buf = getScaledInstance((BufferedImage) buf, (int) xsize, (int) ysize,
(Object) RenderingHints.VALUE_INTERPOLATION_BICUBIC, (boolean) true);
}
// now render the image into the preview buffer
Graphics2D g2d = branded.createGraphics();
g2d.drawImage(buf, 0, 0, (int) xsize, (int) ysize, null);
@@ -158,4 +184,113 @@ public class BrandedPreviewJPEGFilter extends MediaFilter
return bais; // hope this gets written out before its garbage collected!
}
public BufferedImage getNormalizedInstance(BufferedImage buf)
{
int type = (buf.getTransparency() == Transparency.OPAQUE) ?
BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB_PRE;
int w, h;
w = buf.getWidth();
h = buf.getHeight();
BufferedImage normal = new BufferedImage(w, h, type);
Graphics2D g2d = normal.createGraphics();
g2d.drawImage(buf, 0, 0, w, h, Color.WHITE, null);
g2d.dispose();
return normal;
}
public BufferedImage getBlurredInstance(BufferedImage buf)
{
/**
* Convenience method that returns a blurred instance of the
* provided {@code BufferedImage}.
*
*/
buf = getNormalizedInstance(buf);
// kernel for blur op
float[] matrix = {
0.111f, 0.111f, 0.111f,
0.111f, 0.111f, 0.111f,
0.111f, 0.111f, 0.111f,
};
// perform the blur and return the blurred version.
BufferedImageOp blur = new ConvolveOp( new Kernel(3, 3, matrix) );
BufferedImage blurbuf = blur.filter(buf, null);
return blurbuf;
}
/**
* Convenience method that returns a scaled instance of the
* provided {@code BufferedImage}.
*
* @param buf the original image to be scaled
* @param targetWidth the desired width of the scaled instance,
* in pixels
* @param targetHeight the desired height of the scaled instance,
* in pixels
* @param hint one of the rendering hints that corresponds to
* {@code RenderingHints.KEY_INTERPOLATION} (e.g.
* {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
* {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
* {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
* @param higherQuality if true, this method will use a multi-step
* scaling technique that provides higher quality than the usual
* one-step technique (only useful in downscaling cases, where
* {@code targetWidth} or {@code targetHeight} is
* smaller than the original dimensions, and generally only when
* the {@code BILINEAR} hint is specified)
* @return a scaled version of the original {@code BufferedImage}
*/
public BufferedImage getScaledInstance(BufferedImage buf,
int targetWidth,
int targetHeight,
Object hint,
boolean higherQuality)
{
int type = (buf.getTransparency() == Transparency.OPAQUE) ?
BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scalebuf = (BufferedImage)buf;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = buf.getWidth();
h = buf.getHeight();
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = targetWidth;
h = targetHeight;
}
do {
if (higherQuality && w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}
if (higherQuality && h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}
BufferedImage tmp = new BufferedImage(w, h, type);
Graphics2D g2d = tmp.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2d.drawImage(scalebuf, 0, 0, w, h, Color.WHITE, null);
g2d.dispose();
scalebuf = tmp;
} while (w != targetWidth || h != targetHeight);
return scalebuf;
}
}

View File

@@ -8,7 +8,10 @@
package org.dspace.app.mediafilter;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.image.*;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
@@ -21,6 +24,8 @@ import org.dspace.core.ConfigurationManager;
* Filter image bitstreams, scaling the image to be within the bounds of
* thumbnail.maxwidth, thumbnail.maxheight, the size we want our thumbnail to be
* no bigger than. Creates only JPEGs.
*
* @author Jason Sherman <jsherman@usao.edu>
*/
public class JPEGFilter extends MediaFilter implements SelfRegisterInputFormats
{
@@ -71,6 +76,10 @@ public class JPEGFilter extends MediaFilter implements SelfRegisterInputFormats
.getIntProperty("thumbnail.maxwidth");
float ymax = (float) ConfigurationManager
.getIntProperty("thumbnail.maxheight");
boolean blurring = (boolean) ConfigurationManager
.getBooleanProperty("thumbnail.blurring");
boolean hqscaling = (boolean) ConfigurationManager
.getBooleanProperty("thumbnail.hqscaling");
// now get the image dimensions
float xsize = (float) buf.getWidth(null);
@@ -131,6 +140,23 @@ public class JPEGFilter extends MediaFilter implements SelfRegisterInputFormats
BufferedImage thumbnail = new BufferedImage((int) xsize, (int) ysize,
BufferedImage.TYPE_INT_RGB);
// Use blurring if selected in config.
// a little blur before scaling does wonders for keeping moire in check.
if (blurring)
{
// send the buffered image off to get blurred.
buf = getBlurredInstance((BufferedImage) buf);
}
// Use high quality scaling method if selected in config.
// this has a definite performance penalty.
if (hqscaling)
{
// send the buffered image off to get an HQ downscale.
buf = getScaledInstance((BufferedImage) buf, (int) xsize, (int) ysize,
(Object) RenderingHints.VALUE_INTERPOLATION_BICUBIC, (boolean) true);
}
// now render the image into the thumbnail buffer
Graphics2D g2d = thumbnail.createGraphics();
g2d.drawImage(buf, 0, 0, (int) xsize, (int) ysize, null);
@@ -163,4 +189,113 @@ public class JPEGFilter extends MediaFilter implements SelfRegisterInputFormats
// return ImageIO.getReaderFileSuffixes();
return null;
}
public BufferedImage getNormalizedInstance(BufferedImage buf)
{
int type = (buf.getTransparency() == Transparency.OPAQUE) ?
BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB_PRE;
int w, h;
w = buf.getWidth();
h = buf.getHeight();
BufferedImage normal = new BufferedImage(w, h, type);
Graphics2D g2d = normal.createGraphics();
g2d.drawImage(buf, 0, 0, w, h, Color.WHITE, null);
g2d.dispose();
return normal;
}
public BufferedImage getBlurredInstance(BufferedImage buf)
{
/**
* Convenience method that returns a blurred instance of the
* provided {@code BufferedImage}.
*
*/
buf = getNormalizedInstance(buf);
// kernel for blur op
float[] matrix = {
0.111f, 0.111f, 0.111f,
0.111f, 0.111f, 0.111f,
0.111f, 0.111f, 0.111f,
};
// perform the blur and return the blurred version.
BufferedImageOp blur = new ConvolveOp( new Kernel(3, 3, matrix) );
BufferedImage blurbuf = blur.filter(buf, null);
return blurbuf;
}
/**
* Convenience method that returns a scaled instance of the
* provided {@code BufferedImage}.
*
* @param buf the original image to be scaled
* @param targetWidth the desired width of the scaled instance,
* in pixels
* @param targetHeight the desired height of the scaled instance,
* in pixels
* @param hint one of the rendering hints that corresponds to
* {@code RenderingHints.KEY_INTERPOLATION} (e.g.
* {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
* {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
* {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
* @param higherQuality if true, this method will use a multi-step
* scaling technique that provides higher quality than the usual
* one-step technique (only useful in downscaling cases, where
* {@code targetWidth} or {@code targetHeight} is
* smaller than the original dimensions, and generally only when
* the {@code BILINEAR} hint is specified)
* @return a scaled version of the original {@code BufferedImage}
*/
public BufferedImage getScaledInstance(BufferedImage buf,
int targetWidth,
int targetHeight,
Object hint,
boolean higherQuality)
{
int type = (buf.getTransparency() == Transparency.OPAQUE) ?
BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scalebuf = (BufferedImage)buf;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = buf.getWidth();
h = buf.getHeight();
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = targetWidth;
h = targetHeight;
}
do {
if (higherQuality && w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}
if (higherQuality && h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}
BufferedImage tmp = new BufferedImage(w, h, type);
Graphics2D g2d = tmp.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2d.drawImage(scalebuf, 0, 0, w, h, Color.WHITE, null);
g2d.dispose();
scalebuf = tmp;
} while (w != targetWidth || h != targetHeight);
return scalebuf;
}
}

View File

@@ -0,0 +1,56 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa;
/**
* POJO representation for a SHERPA journal
*
* @author Andrea Bollini
*
*/
public class SHERPAJournal
{
private String title;
private String issn;
private String zetopub;
private String romeopub;
public SHERPAJournal(String title, String issn, String zetopub,
String romeopub)
{
super();
this.title = title;
this.issn = issn;
this.zetopub = zetopub;
this.romeopub = romeopub;
}
public String getTitle()
{
return title;
}
public String getIssn()
{
return issn;
}
public String getZetopub()
{
return zetopub;
}
public String getRomeopub()
{
return romeopub;
}
}

View File

@@ -0,0 +1,183 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa;
import java.util.List;
/**
* POJO representation for a SHERPA Publisher record
*
* @author Andrea Bollini
*
*/
public class SHERPAPublisher
{
private String name;
private String alias;
private String homeurl;
private String prearchiving;
private List<String> prerestriction;
private String postarchiving;
private List<String> postrestriction;
private String pubarchiving;
private List<String> pubrestriction;
private List<String> condition;
private String paidaccessurl;
private String paidaccessname;
private String paidaccessnotes;
private List<String[]> copyright;
private String romeocolour;
private String dateadded;
private String dateupdated;
public SHERPAPublisher(String name, String alias, String homeurl,
String prearchiving, List<String> prerestriction,
String postarchiving, List<String> postrestriction,
String pubarchiving, List<String> pubrestriction,
List<String> condition, String paidaccessurl,
String paidaccessname, String paidaccessnotes,
List<String[]> copyright, String romeocolour, String datedded,
String dateupdated)
{
this.name = name;
this.alias = alias;
this.homeurl = homeurl;
this.prearchiving = prearchiving;
this.prerestriction = prerestriction;
this.postarchiving = postarchiving;
this.postrestriction = postrestriction;
this.pubarchiving = pubarchiving;
this.pubrestriction = pubrestriction;
this.condition = condition;
this.paidaccessurl = paidaccessurl;
this.paidaccessname = paidaccessname;
this.paidaccessnotes = paidaccessnotes;
this.copyright = copyright;
this.romeocolour = romeocolour;
this.dateadded = datedded;
this.dateupdated = dateupdated;
}
public String getName()
{
return name;
}
public String getAlias()
{
return alias;
}
public String getHomeurl()
{
return homeurl;
}
public String getPrearchiving()
{
return prearchiving;
}
public List<String> getPrerestriction()
{
return prerestriction;
}
public String getPostarchiving()
{
return postarchiving;
}
public List<String> getPostrestriction()
{
return postrestriction;
}
public String getPubarchiving()
{
return pubarchiving;
}
public List<String> getPubrestriction()
{
return pubrestriction;
}
public List<String> getCondition()
{
return condition;
}
public String getPaidaccessurl()
{
return paidaccessurl;
}
public String getPaidaccessname()
{
return paidaccessname;
}
public String getPaidaccessnotes()
{
return paidaccessnotes;
}
public List<String[]> getCopyright()
{
return copyright;
}
public String getRomeocolour()
{
return romeocolour;
}
public String getDatedded()
{
return dateadded;
}
public String getDateupdated()
{
return dateupdated;
}
}

View File

@@ -0,0 +1,223 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.lang.StringUtils;
import org.dspace.app.util.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* JAVA representation for a SHERPA API Response
*
* @author Andrea Bollini
*
*/
public class SHERPAResponse
{
private boolean error;
private String message;
private String license;
private String licenseURL;
private String disclaimer;
private List<SHERPAJournal> journals;
private List<SHERPAPublisher> publishers;
public SHERPAResponse(InputStream xmlData)
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document inDoc = db.parse(xmlData);
Element xmlRoot = inDoc.getDocumentElement();
Element dataRoot = XMLUtils.getSingleElement(xmlRoot, "romeoapi");
Element headersElement = XMLUtils.getSingleElement(xmlRoot,
"header");
Element journalsElement = XMLUtils.getSingleElement(xmlRoot,
"journals");
Element publishersElement = XMLUtils.getSingleElement(xmlRoot,
"publishers");
message = XMLUtils.getElementValue(headersElement, "message");
if (StringUtils.isNotBlank(message))
{
error = true;
return;
}
license = XMLUtils.getElementValue(headersElement, "license");
licenseURL = XMLUtils.getElementValue(headersElement, "licenseurl");
disclaimer = XMLUtils.getElementValue(headersElement, "disclaimer");
List<Element> journalsList = XMLUtils.getElementList(
journalsElement, "journal");
List<Element> publishersList = XMLUtils.getElementList(
publishersElement, "publisher");
if (journalsList != null)
{
journals = new LinkedList<SHERPAJournal>();
for (Element journalElement : journalsList)
{
journals.add(new SHERPAJournal(
XMLUtils.getElementValue(journalElement, "jtitle"),
XMLUtils.getElementValue(journalElement, "issn"),
XMLUtils.getElementValue(journalElement, "zetopub"),
XMLUtils.getElementValue(journalElement, "romeopub")));
}
}
if (publishersList != null)
{
publishers = new LinkedList<SHERPAPublisher>();
for (Element publisherElement : publishersList)
{
Element preprintsElement = XMLUtils.getSingleElement(
publisherElement, "preprints");
Element preprintsRestrictionElement = XMLUtils
.getSingleElement(publisherElement,
"prerestrictions");
Element postprintsElement = XMLUtils.getSingleElement(
publisherElement, "postprints");
Element postprintsRestrictionElement = XMLUtils
.getSingleElement(publisherElement,
"postrestrictions");
Element pdfversionElement = XMLUtils.getSingleElement(
publisherElement, "pdfversion");
Element pdfversionRestrictionElement = XMLUtils
.getSingleElement(publisherElement,
"pdfrestrictions");
Element conditionsElement = XMLUtils.getSingleElement(
publisherElement, "conditions");
Element paidaccessElement = XMLUtils.getSingleElement(
publisherElement, "paidaccess");
Element copyrightlinksElement = XMLUtils.getSingleElement(
publisherElement, "copyrightlinks");
publishers
.add(new SHERPAPublisher(XMLUtils.getElementValue(
publisherElement, "name"),
XMLUtils.getElementValue(publisherElement,
"alias"), XMLUtils.getElementValue(
publisherElement, "homeurl"),
XMLUtils.getElementValue(preprintsElement,
"prearchiving"),
XMLUtils.getElementValueList(
preprintsRestrictionElement,
"prerestriction"),
XMLUtils.getElementValue(postprintsElement,
"postarchiving"),
XMLUtils.getElementValueList(
postprintsRestrictionElement,
"postrestriction"),
XMLUtils.getElementValue(pdfversionElement,
"pdfarchiving"),
XMLUtils.getElementValueList(
pdfversionRestrictionElement,
"pdfrestriction"),
XMLUtils
.getElementValueList(
conditionsElement,
"condition"), XMLUtils
.getElementValue(paidaccessElement,
"paidaccessurl"), XMLUtils
.getElementValue(paidaccessElement,
"paidaccessname"), XMLUtils
.getElementValue(paidaccessElement,
"paidaccessnotes"),
XMLUtils.getElementValueArrayList(
copyrightlinksElement,
"copyrightlink",
"copyrightlinktext",
"copyrightlinkurl"), XMLUtils
.getElementValue(publisherElement,
"romeocolour"), XMLUtils
.getElementValue(publisherElement,
"dateadded"), XMLUtils
.getElementValue(publisherElement,
"dateupdated")));
}
}
}
catch (Exception e)
{
error = true;
}
}
public SHERPAResponse(String message)
{
this.message = message;
this.error = true;
}
public boolean isError()
{
return error;
}
public String getMessage()
{
return message;
}
public String getLicense()
{
return license;
}
public String getLicenseURL()
{
return licenseURL;
}
public String getDisclaimer()
{
return disclaimer;
}
public List<SHERPAJournal> getJournals()
{
return journals;
}
public List<SHERPAPublisher> getPublishers()
{
return publishers;
}
}

View File

@@ -0,0 +1,67 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.dspace.core.ConfigurationManager;
public class SHERPAService
{
public SHERPAResponse searchByJournalISSN(String query)
{
String endpoint = ConfigurationManager.getProperty("sherpa.romeo.url");
String apiKey = ConfigurationManager.getProperty("sherpa.romeo.apikey");
GetMethod method = null;
try
{
HttpClient client = new HttpClient();
method = new GetMethod(endpoint);
NameValuePair id = new NameValuePair("issn", query);
NameValuePair versions = new NameValuePair("versions", "all");
NameValuePair[] params = null;
if (StringUtils.isNotBlank(apiKey))
{
NameValuePair ak = new NameValuePair("ak", apiKey);
params = new NameValuePair[] { id, versions, ak };
}
else
{
params = new NameValuePair[] { id, versions };
}
method.setQueryString(params);
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK)
{
return new SHERPAResponse("SHERPA/RoMEO return not OK status: "
+ statusCode);
}
return new SHERPAResponse(method.getResponseBodyAsStream());
}
catch (Exception e)
{
return new SHERPAResponse(
"Error processing the SHERPA/RoMEO answer");
}
finally
{
if (method != null)
{
method.releaseConnection();
}
}
}
}

View File

@@ -0,0 +1,18 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa.submit;
import java.util.List;
import org.dspace.content.Item;
import org.dspace.core.Context;
public interface ISSNItemExtractor
{
public List<String> getISSNs(Context context, Item item);
}

View File

@@ -0,0 +1,40 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa.submit;
import java.util.ArrayList;
import java.util.List;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.Context;
public class MetadataAuthorityISSNExtractor implements ISSNItemExtractor
{
private List<String> metadataList;
public void setMetadataList(List<String> metadataList)
{
this.metadataList = metadataList;
}
@Override
public List<String> getISSNs(Context context, Item item)
{
List<String> values = new ArrayList<String>();
for (String metadata : metadataList)
{
DCValue[] dcvalues = item.getMetadata(metadata);
for (DCValue dcvalue : dcvalues)
{
values.add(dcvalue.authority);
}
}
return values;
}
}

View File

@@ -0,0 +1,40 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa.submit;
import java.util.ArrayList;
import java.util.List;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.Context;
public class MetadataValueISSNExtractor implements ISSNItemExtractor
{
private List<String> metadataList;
public void setMetadataList(List<String> metadataList)
{
this.metadataList = metadataList;
}
@Override
public List<String> getISSNs(Context context, Item item)
{
List<String> values = new ArrayList<String>();
for (String metadata : metadataList)
{
DCValue[] dcvalues = item.getMetadata(metadata);
for (DCValue dcvalue : dcvalues)
{
values.add(dcvalue.value);
}
}
return values;
}
}

View File

@@ -0,0 +1,25 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa.submit;
import java.util.List;
public class SHERPASubmitConfigurationService
{
private List<ISSNItemExtractor> issnItemExtractors;
public void setIssnItemExtractors(List<ISSNItemExtractor> issnItemExtractors)
{
this.issnItemExtractors = issnItemExtractors;
}
public List<ISSNItemExtractor> getIssnItemExtractors()
{
return issnItemExtractors;
}
}

View File

@@ -0,0 +1,90 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.sherpa.submit;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.sherpa.SHERPAResponse;
import org.dspace.app.sherpa.SHERPAService;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
public class SHERPASubmitService
{
private SHERPAService sherpaService;
private SHERPASubmitConfigurationService configuration;
/** log4j logger */
private static Logger log = Logger.getLogger(SHERPASubmitService.class);
public void setConfiguration(SHERPASubmitConfigurationService configuration)
{
this.configuration = configuration;
}
public void setSherpaService(SHERPAService sherpaService)
{
this.sherpaService = sherpaService;
}
public SHERPAResponse searchRelatedJournals(Context context, Item item)
{
Set<String> issns = getISSNs(context, item);
if (issns == null || issns.size() == 0)
{
return null;
}
else
{
return sherpaService.searchByJournalISSN(StringUtils.join(issns, ","));
}
}
private Set<String> getISSNs(Context context, Item item)
{
Set<String> issns = new LinkedHashSet<String>();
if (configuration.getIssnItemExtractors() == null)
{
log.warn(LogManager.getHeader(context, "searchRelatedJournals",
"no issnItemExtractors defined"));
return null;
}
for (ISSNItemExtractor extractor : configuration.getIssnItemExtractors())
{
List<String> eIssns = extractor.getISSNs(context, item);
if (eIssns != null)
{
for (String eIssn : eIssns)
{
issns.add(eIssn.trim());
}
}
}
return issns;
}
public boolean hasISSNs(Context context, Item item)
{
Set<String> issns = getISSNs(context, item);
if (issns == null || issns.size() == 0)
{
return false;
}
else
{
return true;
}
}
}

View File

@@ -0,0 +1,192 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.util;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Simple class to read information from small XML using DOM manipulation
*
* @author Andrea Bollini
*
*/
public class XMLUtils
{
/**
*
* @param rootElement
* the starting node
* @param subElementName
* the name of the subelement to find
* @return the list of all DOM Element with the provided name direct child
* of the starting node
*/
public static List<Element> getElementList(Element dataRoot, String name)
{
NodeList list = dataRoot.getElementsByTagName(name);
List<Element> listElements = new ArrayList<Element>();
for (int i = 0; i < list.getLength(); i++)
{
Element item = (Element) list.item(i);
if (item.getParentNode().equals(dataRoot))
{
listElements.add(item);
}
}
return listElements;
}
/**
*
* @param dataRoot
* the starting node
* @param name
* the name of the sub element
* @param attr
* the attribute to get
* @return the value of the attribute for the sub element with the specified
* name in the starting node
*/
public static String getElementAttribute(Element dataRoot, String name,
String attr)
{
Element element = getSingleElement(dataRoot, name);
String attrValue = null;
if (element != null)
{
attrValue = element.getAttribute(attr);
if (StringUtils.isNotBlank(attrValue))
{
attrValue = attrValue.trim();
}
else
attrValue = null;
}
return attrValue;
}
/**
*
* @param dataRoot
* the starting node
* @param name
* the name of the sub element
* @return the text content of the sub element with the specified name in
* the starting node
*/
public static String getElementValue(Element dataRoot, String name)
{
Element element = getSingleElement(dataRoot, name);
String elementValue = null;
if (element != null)
{
elementValue = element.getTextContent();
if (StringUtils.isNotBlank(elementValue))
{
elementValue = elementValue.trim();
}
else
elementValue = null;
}
return elementValue;
}
/**
* Return the first element child with the specified name
*
* @param dataRoot
* the starting node
* @param name
* the name of sub element to look for
* @return the first child element or null if no present
*/
public static Element getSingleElement(Element dataRoot, String name)
{
List<Element> nodeList = getElementList(dataRoot, name);
Element element = null;
if (nodeList != null && nodeList.size() > 0)
{
element = (Element) nodeList.get(0);
}
return element;
}
/**
*
* @param rootElement
* the starting node
* @param subElementName
* the name of the subelement to find
* @return a list of string including all the text contents of the sub
* element with the specified name. If there are not sub element
* with the supplied name the method will return null
*/
public static List<String> getElementValueList(Element rootElement,
String subElementName)
{
if (rootElement == null)
return null;
List<Element> subElements = getElementList(rootElement, subElementName);
if (subElements == null)
return null;
List<String> result = new LinkedList<String>();
for (Element el : subElements)
{
if (StringUtils.isNotBlank(el.getTextContent()))
{
result.add(el.getTextContent().trim());
}
}
return result;
}
/**
* root/subElement[]/field1, field2, fieldN
*
* @param rootElement
* the starting node
* @param subElementName
* the name of the sub element to work on
* @param fieldsName
* the names of the sub-sub-elements from which get the text
* content
* @return a list of array strings. The length of the array is equals to the
* number of fields required. For any fields the first textual value
* found in the sub element is used, null if no value is present
*/
public static List<String[]> getElementValueArrayList(Element rootElement,
String subElementName, String... fieldsName)
{
if (rootElement == null)
return null;
List<Element> subElements = getElementList(rootElement, subElementName);
if (subElements == null)
return null;
List<String[]> result = new LinkedList<String[]>();
for (Element el : subElements)
{
String[] tmp = new String[fieldsName.length];
for (int idx = 0; idx < fieldsName.length; idx++)
{
tmp[idx] = XMLUtils.getElementValue(el, fieldsName[idx]);
}
result.add(tmp);
}
return result;
}
}

View File

@@ -7,6 +7,8 @@
*/
package org.dspace.authenticate;
import org.apache.log4j.Logger;
import java.net.Inet6Address;
import java.net.UnknownHostException;
@@ -30,9 +32,13 @@ import java.net.UnknownHostException;
*
* @version $Revision$
* @author Robert Tansley
* @author Ben Bosman
* @author Roeland Dillen
*/
public class IPMatcher
{
private static Logger log = Logger.getLogger(IPMatcher.class);
/** Network to match */
private byte[] network;
@@ -139,13 +145,26 @@ public class IPMatcher
netmask[1] = (byte) ((fullMask & 0x00FF0000) >>> 16);
netmask[2] = (byte) ((fullMask & 0x0000FF00) >>> 8);
netmask[3] = (byte) (fullMask & 0x000000FF);
ipToBytes(ipPart, network, mustHave4);
if (log.isDebugEnabled()) {
log.debug("fullMask: "+fullMask);
for (int i = 0; i < network.length; i++) {
log.debug("network[" + i + "]: "+network[i]);
}
for (int i = 0; i < netmask.length; i++) {
log.debug("netmask[" + i + "]: "+netmask[i]);
}
}
}
else
{
// full subnet specified
// full netmask specified
ipToBytes(parts[0],network,true);
ipToBytes(parts[1], netmask, true);
}
break;
case 1:
// Get IP
for (int i = 0; i < netmask.length; i++)
@@ -166,6 +185,14 @@ public class IPMatcher
}
network = ip4ToIp6(network);
netmask = ip4MaskToIp6(netmask);
if (log.isDebugEnabled()) {
for (int i = 0; i < network.length; i++) {
log.debug("network[" + i + "]: "+network[i]);
}
for (int i = 0; i < netmask.length; i++) {
log.debug("netmask[" + i + "]: "+netmask[i]);
}
}
}
}
@@ -236,6 +263,7 @@ public class IPMatcher
*/
public boolean match(String ipIn) throws IPMatcherException
{
log.debug("ipIn: "+ipIn);
byte[] candidate;
if (ipIn.indexOf(':') < 0)
@@ -258,6 +286,13 @@ public class IPMatcher
{
if ((candidate[i] & netmask[i]) != (network[i] & netmask[i]))
{
if (log.isDebugEnabled()) {
log.debug("candidate[i]: "+candidate[i]);
log.debug("netmask[i]: "+netmask[i]);
log.debug("candidate[i] & netmask[i]: "+(candidate[i] & netmask[i]));
log.debug("network[i]: "+network[i]);
log.debug("network[i] & netmask[i]: "+(network[i] & netmask[i]));
}
return false;
}
}

View File

@@ -612,7 +612,7 @@ public class LDAPAuthentication
/*
* Add authenticated users to the group defined in dspace.cfg by
* the ldap.login.groupmap.* key.
* the authentication-ldap.login.groupmap.* key.
*/
private void assignGroupsBasedOnLdapDn(String dn, Context context)
{
@@ -644,7 +644,7 @@ public class LDAPAuthentication
// The group does not exist
log.warn(LogManager.getHeader(context,
"ldap_assignGroupsBasedOnLdapDn",
"Group defined in ldap.login.groupmap." + i + " does not exist :: " + dspaceGroupName));
"Group defined in authentication-ldap.login.groupmap." + i + " does not exist :: " + dspaceGroupName));
}
}
catch (AuthorizeException ae)
@@ -657,7 +657,7 @@ public class LDAPAuthentication
}
}
groupMap = ConfigurationManager.getProperty("ldap.login.groupmap." + ++i);
groupMap = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap." + ++i);
}
}
}

View File

@@ -32,20 +32,8 @@ public class BrowseDAOFactory
String className = ConfigurationManager.getProperty("browseDAO.class");
if (className == null)
{
// For compatibility with previous versions
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");
}
// SOLR implementation is the default since DSpace 4.0
return new SolrBrowseDAO(context);
}
try
{
@@ -73,20 +61,8 @@ public class BrowseDAOFactory
String className = ConfigurationManager.getProperty("browseCreateDAO.class");
if (className == null)
{
// For compatibility with previous versions
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");
}
// SOLR implementation is the default since DSpace 4.0
return new SolrBrowseCreateDAO(context);
}
try
{

View File

@@ -680,12 +680,10 @@ public final class BrowseIndex
while ( ((definition = ConfigurationManager.getProperty("webui.browse.index." + idx))) != null)
{
BrowseIndex bi = new BrowseIndex(definition, idx);
//Load the frequency configuration
String freqDefinition = ConfigurationManager.getProperty("webui.browse.metadata.show-freq." + idx);
if (freqDefinition!=null)
bi.displayFrequencies = Boolean.valueOf(freqDefinition);
bi.displayFrequencies = Boolean.valueOf(ConfigurationManager
.getBooleanProperty("webui.browse.metadata.show-freq."
+ idx, true));
browseIndices.add(bi);
idx++;
}

View File

@@ -372,6 +372,9 @@ public class SolrBrowseCreateDAO implements BrowseCreateDAO,
public void insertIndex(String table, int itemID, Map sortCols)
throws BrowseException
{
// this is required to be sure that communities2item will be cleaned
// after the switch to SOLRBrowseDAOs. See DS-1619
dbCreateDAO.deleteCommunityMappings(itemID);
}
@Override

View File

@@ -12,21 +12,7 @@ import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;

View File

@@ -31,6 +31,7 @@ import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.core.LicenseManager;
import org.dspace.core.LogManager;
import org.dspace.eperson.Group;
import org.dspace.event.Event;
@@ -52,7 +53,7 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
* database after calling <code>update</code>. The default group of
* submitters is slightly different - creating or removing this has instant
* effect.
*
*
* @author Robert Tansley
* @version $Revision$
*/
@@ -96,7 +97,7 @@ public class Collection extends DSpaceObject
/**
* Construct a collection with the given table row
*
*
* @param context
* the context this object exists in
* @param row
@@ -139,7 +140,7 @@ public class Collection extends DSpaceObject
submitters = groupFromColumn("submitter");
admins = groupFromColumn("admin");
// Get our Handle if any
handle = HandleManager.findHandle(context, this);
@@ -153,12 +154,12 @@ public class Collection extends DSpaceObject
/**
* Get a collection from the database. Loads in the metadata
*
*
* @param context
* DSpace context object
* @param id
* ID of the collection
*
*
* @return the collection, or null if the ID is invalid.
* @throws SQLException
*/
@@ -199,10 +200,10 @@ public class Collection extends DSpaceObject
/**
* Create a new collection, with a new ID. This method is not public, and
* does not check authorisation.
*
*
* @param context
* DSpace context object
*
*
* @return the newly created collection
* @throws SQLException
* @throws AuthorizeException
@@ -288,10 +289,10 @@ public class Collection extends DSpaceObject
/**
* Get all collections in the system. These are alphabetically sorted by
* collection name.
*
*
* @param context
* DSpace context object
*
*
* @return the collections in the system
* @throws SQLException
*/
@@ -339,7 +340,7 @@ public class Collection extends DSpaceObject
/**
* Get the in_archive items in this collection. The order is indeterminate.
*
*
* @return an iterator over the items in the collection.
* @throws SQLException
*/
@@ -358,7 +359,7 @@ public class Collection extends DSpaceObject
/**
* Get all the items in this collection. The order is indeterminate.
*
*
* @return an iterator over the items in the collection.
* @throws SQLException
*/
@@ -376,7 +377,7 @@ public class Collection extends DSpaceObject
/**
* Get the internal ID of this collection
*
*
* @return the internal identifier
*/
public int getID()
@@ -402,36 +403,36 @@ public class Collection extends DSpaceObject
/**
* Get the value of a metadata field
*
*
* @param field
* the name of the metadata field to get
*
*
* @return the value of the metadata field
*
*
* @exception IllegalArgumentException
* if the requested metadata field doesn't exist
*/
public String getMetadata(String field)
{
String metadata = collectionRow.getStringColumn(field);
return (metadata == null) ? "" : metadata;
return (metadata == null) ? "" : metadata;
}
/**
* Set a metadata value
*
*
* @param field
* the name of the metadata field to get
* @param value
* value to set the field to
*
*
* @exception IllegalArgumentException
* if the requested metadata field doesn't exist
* @exception MissingResourceException
*/
public void setMetadata(String field, String value) throws MissingResourceException
{
if ((field.trim()).equals("name")
if ((field.trim()).equals("name")
&& (value == null || value.trim().equals("")))
{
try
@@ -443,9 +444,9 @@ public class Collection extends DSpaceObject
value = "Untitled";
}
}
/*
* Set metadata field to null if null
/*
* Set metadata field to null if null
* and trim strings to eliminate excess
* whitespace.
*/
@@ -457,7 +458,7 @@ public class Collection extends DSpaceObject
{
collectionRow.setColumn(field, value.trim());
}
modifiedMetadata = true;
addDetails(field);
}
@@ -470,7 +471,7 @@ public class Collection extends DSpaceObject
/**
* Get the logo for the collection. <code>null</code> is returned if the
* collection does not have a logo.
*
*
* @return the logo of the collection, or <code>null</code>
*/
public Bitstream getLogo()
@@ -546,10 +547,10 @@ public class Collection extends DSpaceObject
* Note that while the new group is created in the database, the association
* between the group and the collection is not written until
* <code>update</code> is called.
*
*
* @param step
* the step (1-3) of the workflow to create or get the group for
*
*
* @return the workflow group associated with this collection
* @throws SQLException
* @throws AuthorizeException
@@ -581,7 +582,7 @@ public class Collection extends DSpaceObject
* Set the workflow group corresponding to a particular workflow step.
* <code>null</code> can be passed in if there should be no associated
* group for that workflow step; any existing group is NOT deleted.
*
*
* @param step
* the workflow step (1-3)
* @param g
@@ -606,10 +607,10 @@ public class Collection extends DSpaceObject
* Get the the workflow group corresponding to a particular workflow step.
* This returns <code>null</code> if there is no group associated with
* this collection for the given step.
*
*
* @param step
* the workflow step (1-3)
*
*
* @return the group of reviewers or <code>null</code>
*/
public Group getWorkflowGroup(int step)
@@ -622,7 +623,7 @@ public class Collection extends DSpaceObject
* either the newly created group or the previously existing one. Note that
* other groups may also be allowed to submit to this collection by the
* authorization system.
*
*
* @return the default group of submitters associated with this collection
* @throws SQLException
* @throws AuthorizeException
@@ -645,7 +646,7 @@ public class Collection extends DSpaceObject
// register this as the submitter group
collectionRow.setColumn("submitter", submitters.getID());
AuthorizeManager.addPolicy(ourContext, this, Constants.ADD, submitters);
modified = true;
@@ -653,9 +654,9 @@ public class Collection extends DSpaceObject
}
/**
* Remove the submitters group, if no group has already been created
* then return without error. This will merely dereference the current
* submitters group from the collection so that it may be deleted
* Remove the submitters group, if no group has already been created
* then return without error. This will merely dereference the current
* submitters group from the collection so that it may be deleted
* without violating database constraints.
*/
public void removeSubmitters() throws SQLException, AuthorizeException
@@ -672,11 +673,11 @@ public class Collection extends DSpaceObject
// Remove the link to the collection table.
collectionRow.setColumnNull("submitter");
submitters = null;
modified = true;
}
/**
* Get the default group of submitters, if there is one. Note that the
* authorization system may allow others to submit to the collection, so
@@ -684,7 +685,7 @@ public class Collection extends DSpaceObject
* <P>
* The default group of submitters for collection 100 is the one called
* <code>collection_100_submit</code>.
*
*
* @return the default group of submitters, or <code>null</code> if there
* is no default group.
*/
@@ -697,7 +698,7 @@ public class Collection extends DSpaceObject
* Create a default administrators group if one does not already exist.
* Returns either the newly created group or the previously existing one.
* Note that other groups may also be administrators.
*
*
* @return the default group of editors associated with this collection
* @throws SQLException
* @throws AuthorizeException
@@ -713,7 +714,7 @@ public class Collection extends DSpaceObject
ourContext.turnOffAuthorisationSystem();
admins = Group.create(ourContext);
ourContext.restoreAuthSystemState();
admins.setName("COLLECTION_" + getID() + "_ADMIN");
admins.update();
}
@@ -723,15 +724,15 @@ public class Collection extends DSpaceObject
// register this as the admin group
collectionRow.setColumn("admin", admins.getID());
modified = true;
return admins;
}
/**
* Remove the administrators group, if no group has already been created
* then return without error. This will merely dereference the current
* administrators group from the collection so that it may be deleted
* Remove the administrators group, if no group has already been created
* then return without error. This will merely dereference the current
* administrators group from the collection so that it may be deleted
* without violating database constraints.
*/
public void removeAdministrators() throws SQLException, AuthorizeException
@@ -748,7 +749,7 @@ public class Collection extends DSpaceObject
// Remove the link to the collection table.
collectionRow.setColumnNull("admin");
admins = null;
modified = true;
}
@@ -759,7 +760,7 @@ public class Collection extends DSpaceObject
* <P>
* The default group of administrators for collection 100 is the one called
* <code>collection_100_admin</code>.
*
*
* @return group of administrators, or <code>null</code> if there is no
* default group.
*/
@@ -772,7 +773,7 @@ public class Collection extends DSpaceObject
* Get the license that users must grant before submitting to this
* collection. If the collection does not have a specific license, the
* site-wide default is returned.
*
*
* @return the license for this collection
*/
public String getLicense()
@@ -782,7 +783,7 @@ public class Collection extends DSpaceObject
if (license == null || license.trim().equals(""))
{
// Fallback to site-wide default
license = ConfigurationManager.getDefaultSubmissionLicense();
license = LicenseManager.getDefaultSubmissionLicense();
}
return license;
@@ -790,8 +791,8 @@ public class Collection extends DSpaceObject
/**
* Get the license that users must grant before submitting to this
* collection.
*
* collection.
*
* @return the license for this collection
*/
public String getLicenseCollection()
@@ -801,7 +802,7 @@ public class Collection extends DSpaceObject
/**
* Find out if the collection has a custom license
*
*
* @return <code>true</code> if the collection has a custom license
*/
public boolean hasCustomLicense()
@@ -814,7 +815,7 @@ public class Collection extends DSpaceObject
/**
* Set the license for this collection. Passing in <code>null</code> means
* that the site-wide default will be used.
*
*
* @param license
* the license, or <code>null</code>
*/
@@ -828,7 +829,7 @@ public class Collection extends DSpaceObject
* returned if the collection does not have a template. Submission
* mechanisms may copy this template to provide a convenient starting point
* for a submission.
*
*
* @return the item template, or <code>null</code>
*/
public Item getTemplateItem() throws SQLException
@@ -841,7 +842,7 @@ public class Collection extends DSpaceObject
* no action is taken. Caution: Make sure you call <code>update</code> on
* the collection after doing this, or the item will have been created but
* the collection record will not refer to it.
*
*
* @throws SQLException
* @throws AuthorizeException
*/
@@ -868,7 +869,7 @@ public class Collection extends DSpaceObject
* record in the database, the collection record will be changed, including
* any other changes made; in other words, this method does an
* <code>update</code>.
*
*
* @throws SQLException
* @throws AuthorizeException
* @throws IOException
@@ -881,7 +882,7 @@ public class Collection extends DSpaceObject
collectionRow.setColumnNull("template_item_id");
DatabaseManager.update(ourContext, collectionRow);
if (template != null)
{
log.info(LogManager.getHeader(ourContext, "remove_template_item",
@@ -894,7 +895,7 @@ public class Collection extends DSpaceObject
ourContext.restoreAuthSystemState();
template = null;
}
ourContext.addEvent(new Event(Event.MODIFY, Constants.COLLECTION, getID(), "remove_template_item"));
}
@@ -903,7 +904,7 @@ public class Collection extends DSpaceObject
* the item and the collection - it does nothing like set an issue date,
* remove a personal workspace item etc. This has instant effect;
* <code>update</code> need not be called.
*
*
* @param item
* item to add
* @throws SQLException
@@ -930,7 +931,7 @@ public class Collection extends DSpaceObject
/**
* Remove an item. If the item is then orphaned, it is deleted.
*
*
* @param item
* item to remove
* @throws SQLException
@@ -956,20 +957,20 @@ public class Collection extends DSpaceObject
}
log.info(LogManager.getHeader(ourContext, "remove_item",
"collection_id=" + getID() + ",item_id=" + item.getID()));
DatabaseManager.updateQuery(ourContext,
"DELETE FROM collection2item WHERE collection_id= ? "+
"AND item_id= ? ",
getID(), item.getID());
DatabaseManager.setConstraintImmediate(ourContext, "coll2item_item_fk");
ourContext.addEvent(new Event(Event.REMOVE, Constants.COLLECTION, getID(), Constants.ITEM, item.getID(), item.getHandle()));
}
/**
* Update the collection metadata (including logo and workflow groups) to
* the database. Inserts if this is a new collection.
*
*
* @throws SQLException
* @throws IOException
* @throws AuthorizeException
@@ -996,7 +997,7 @@ public class Collection extends DSpaceObject
clearDetails();
}
}
public boolean canEditBoolean() throws java.sql.SQLException
{
return canEditBoolean(true);
@@ -1020,7 +1021,7 @@ public class Collection extends DSpaceObject
{
canEdit(true);
}
public void canEdit(boolean useInheritance) throws AuthorizeException, SQLException
{
Community[] parents = getCommunities();
@@ -1047,7 +1048,7 @@ public class Collection extends DSpaceObject
* Delete the collection, including the metadata and logo. Items that are
* then orphans are deleted. Groups associated with this collection
* (workflow participants and submitters) are NOT deleted.
*
*
* @throws SQLException
* @throws AuthorizeException
* @throws IOException
@@ -1064,12 +1065,12 @@ public class Collection extends DSpaceObject
// remove subscriptions - hmm, should this be in Subscription.java?
DatabaseManager.updateQuery(ourContext,
"DELETE FROM subscription WHERE collection_id= ? ",
"DELETE FROM subscription WHERE collection_id= ? ",
getID());
// Remove Template Item
removeTemplateItem();
// Remove items
ItemIterator items = getAllItems();
@@ -1079,7 +1080,7 @@ public class Collection extends DSpaceObject
{
Item item = items.next();
IndexBrowse ib = new IndexBrowse(ourContext);
if (item.isOwningCollection(this))
{
// the collection to be deleted is the owning collection, thus remove
@@ -1092,12 +1093,12 @@ public class Collection extends DSpaceObject
// 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.
//notify Browse of removing item mapping.
ib.indexItem(item);
// Browse.itemChanged(ourContext, item);
removeItem(item);
@@ -1226,7 +1227,7 @@ public class Collection extends DSpaceObject
/**
* Get the communities this collection appears in
*
*
* @return array of <code>Community</code> objects
* @throws SQLException
*/
@@ -1282,10 +1283,10 @@ public class Collection extends DSpaceObject
/**
* Return <code>true</code> if <code>other</code> is the same Collection
* as this object, <code>false</code> otherwise
*
*
* @param other
* object to compare to
*
*
* @return <code>true</code> if object passed in represents the same
* collection as this object
*/
@@ -1321,7 +1322,7 @@ public class Collection extends DSpaceObject
/**
* Utility method for reading in a group from a group ID in a column. If the
* column is null, null is returned.
*
*
* @param col
* the column name to read
* @return the group referred to by that column, or null
@@ -1339,7 +1340,7 @@ public class Collection extends DSpaceObject
/**
* return type found in Constants
*
*
* @return int Constants.COLLECTION
*/
public int getType()
@@ -1351,13 +1352,13 @@ public class Collection extends DSpaceObject
* return an array of collections that user has a given permission on
* (useful for trimming 'select to collection' list) or figuring out which
* collections a person is an editor for.
*
*
* @param context
* @param comm
* (optional) restrict search to a community, else null
* @param actionID
* of the action
*
*
* @return Collection [] of collections with matching permissions
* @throws SQLException
*/
@@ -1437,7 +1438,7 @@ public class Collection extends DSpaceObject
return itemcount;
}
public DSpaceObject getAdminObject(int action) throws SQLException
{
DSpaceObject adminObject = null;
@@ -1473,7 +1474,7 @@ public class Collection extends DSpaceObject
}
return adminObject;
}
@Override
public DSpaceObject getParentObject() throws SQLException
{

View File

@@ -793,6 +793,48 @@ public class Community extends DSpaceObject
return communityArray;
}
/**
* Return an array of collections of this community and its subcommunities
*
* @return an array of colections
*/
public Collection[] getAllCollections() throws SQLException
{
List<Collection> collectionList = new ArrayList<Collection>();
for (Community subcommunity : getSubcommunities())
{
addCollectionList(subcommunity, collectionList);
}
for (Collection collection : getCollections())
{
collectionList.add(collection);
}
// Put them in an array
Collection[] collectionArray = new Collection[collectionList.size()];
collectionArray = (Collection[]) collectionList.toArray(collectionArray);
return collectionArray;
}
/**
* Internal method to process subcommunities recursively
*/
private void addCollectionList(Community community, List<Collection> collectionList) throws SQLException
{
for (Community subcommunity : community.getSubcommunities())
{
addCollectionList(subcommunity, collectionList);
}
for (Collection collection : community.getCollections())
{
collectionList.add(collection);
}
}
/**
* Create a new collection within this community. The collection is created
* without any workflow groups or default submitter group.

View File

@@ -69,7 +69,7 @@ public class InstallItem
identifierService.register(c, item, suppliedHandle);
}
} catch (IdentifierException e) {
throw new RuntimeException("Can't create an Identifier!");
throw new RuntimeException("Can't create an Identifier!", e);
}

View File

@@ -114,7 +114,9 @@ public class METSDisseminationCrosswalk
pparams.put("manifestOnly", "true");
// Create a temporary file to disseminate into
String tempDirectory = ConfigurationManager.getProperty("upload.temp.dir");
String tempDirectory = (ConfigurationManager.getProperty("upload.temp.dir") != null)
? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir");
File tempFile = File.createTempFile("METSDissemination" + dso.hashCode(), null, new File(tempDirectory));
tempFile.deleteOnExit();

View File

@@ -182,7 +182,8 @@ public class RoleCrosswalk
}
// Create a temporary file to disseminate into
String tempDirectory = ConfigurationManager.getProperty("upload.temp.dir");
String tempDirectory = (ConfigurationManager.getProperty("upload.temp.dir") != null)
? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir");
File tempFile = File.createTempFile("RoleCrosswalkDisseminate" + dso.hashCode(), null, new File(tempDirectory));
tempFile.deleteOnExit();
@@ -311,7 +312,8 @@ public class RoleCrosswalk
}
// Create a temporary file to ingest from
String tempDirectory = ConfigurationManager.getProperty("upload.temp.dir");
String tempDirectory = (ConfigurationManager.getProperty("upload.temp.dir") != null)
? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir");
File tempFile = File.createTempFile("RoleCrosswalkIngest" + dso.hashCode(), null, new File(tempDirectory));
tempFile.deleteOnExit();
FileOutputStream fileOutStream = null;
@@ -340,4 +342,4 @@ public class RoleCrosswalk
}
}
}
}

View File

@@ -334,7 +334,8 @@ public class RoleDisseminator implements PackageDisseminator
{
writer.writeEmptyElement(MEMBER);
writer.writeAttribute(ID, String.valueOf(member.getID()));
writer.writeAttribute(NAME, member.getName());
if (null != member.getName())
writer.writeAttribute(NAME, member.getName());
}
writer.writeEndElement();
}
@@ -444,9 +445,12 @@ public class RoleDisseminator implements PackageDisseminator
writer.writeStartElement(EPERSON);
writer.writeAttribute(ID, String.valueOf(eperson.getID()));
writer.writeStartElement(EMAIL);
writer.writeCharacters(eperson.getEmail());
writer.writeEndElement();
if (eperson.getEmail()!=null)
{
writer.writeStartElement(EMAIL);
writer.writeCharacters(eperson.getEmail());
writer.writeEndElement();
}
if(eperson.getNetid()!=null)
{
@@ -479,19 +483,25 @@ public class RoleDisseminator implements PackageDisseminator
if (emitPassword)
{
PasswordHash password = eperson.getPasswordHash();
if (null != password)
{
writer.writeStartElement(PASSWORD_HASH);
writer.writeStartElement(PASSWORD_HASH);
String algorithm = password.getAlgorithm();
if (null != algorithm)
{
writer.writeAttribute(PASSWORD_DIGEST, algorithm);
}
String algorithm = password.getAlgorithm();
if (null != algorithm)
writer.writeAttribute(PASSWORD_DIGEST, algorithm);
String salt = password.getSaltString();
if (null != salt)
{
writer.writeAttribute(PASSWORD_SALT, salt);
}
String salt = password.getSaltString();
if (null != salt)
writer.writeAttribute(PASSWORD_SALT, salt);
writer.writeCharacters(password.getHashString());
writer.writeEndElement();
writer.writeCharacters(password.getHashString());
writer.writeEndElement();
}
}
if (eperson.canLogIn())

View File

@@ -7,16 +7,11 @@
*/
package org.dspace.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
@@ -30,8 +25,7 @@ import org.apache.log4j.helpers.OptionConverter;
/**
* Class for reading the DSpace system configuration. The main configuration is
* read in as properties from a standard properties file. Email templates and
* configuration files for other tools are also be accessed via this class.
* read in as properties from a standard properties file.
* <P>
* The main configuration is by default read from the <em>resource</em>
* <code>/dspace.cfg</code>.
@@ -43,7 +37,7 @@ import org.apache.log4j.helpers.OptionConverter;
* of the DSpace installation directory (specified as the property
* <code>dspace.dir</code> in the main configuration file.)
*
*
*
* @author Robert Tansley
* @author Larry Stone - Interpolated values.
* @author Mark Diggory - General Improvements to detection, logging and loading.
@@ -56,20 +50,17 @@ public class ConfigurationManager
/** The configuration properties */
private static Properties properties = null;
/** module configuration properties */
private static Map<String, Properties> moduleProps = new HashMap<String, Properties>();
/** The default license */
private static String license;
// limit of recursive depth of property variable interpolation in
// configuration; anything greater than this is very likely to be a loop.
private static final int RECURSION_LIMIT = 9;
protected ConfigurationManager()
{
}
/**
@@ -80,7 +71,7 @@ public class ConfigurationManager
{
return properties != null;
}
public static boolean isConfigured(String module)
{
return moduleProps.get(module) != null;
@@ -97,24 +88,24 @@ public class ConfigurationManager
// {
// properties = null;
// }
/**
* REMOVED - Flushing the properties could be dangerous in the current DSpace state
* Need to consider how it will affect in-flight processes
*
* Discard properties for a module - will force a reload from disk
* when any of module's properties are requested
*
*
* @param module the module name
*/
// public static void flush(String module)
// {
// moduleProps.remove(module);
// }
/**
* Returns all properties in main configuration
*
*
* @return properties - all non-modular properties
*/
public static Properties getProperties()
@@ -135,7 +126,7 @@ public class ConfigurationManager
/**
* Returns all properties for a given module
*
*
* @param module
* the name of the module
* @return properties - all module's properties
@@ -163,10 +154,10 @@ public class ConfigurationManager
/**
* Get a configuration property
*
*
* @param property
* the name of the property
*
*
* @return the value of the property, or <code>null</code> if the property
* does not exist.
*/
@@ -176,11 +167,11 @@ public class ConfigurationManager
String value = props == null ? null : props.getProperty(property);
return (value != null) ? value.trim() : null;
}
/**
* Get a module configuration property value.
*
* @param module
*
* @param module
* the name of the module, or <code>null</code> for regular configuration
* property
* @param property
@@ -195,7 +186,7 @@ public class ConfigurationManager
{
return getProperty(property);
}
String value = null;
Properties modProps = getMutableProperties(module);
@@ -215,10 +206,10 @@ public class ConfigurationManager
/**
* Get a configuration property as an integer
*
*
* @param property
* the name of the property
*
*
* @return the value of the property. <code>0</code> is returned if the
* property does not exist. To differentiate between this case and
* when the property actually is zero, use <code>getProperty</code>.
@@ -227,16 +218,16 @@ public class ConfigurationManager
{
return getIntProperty(property, 0);
}
/**
* Get a module configuration property as an integer
*
* @param module
* the name of the module
*
*
* @param property
* the name of the property
*
*
* @return the value of the property. <code>0</code> is returned if the
* property does not exist. To differentiate between this case and
* when the property actually is zero, use <code>getProperty</code>.
@@ -248,10 +239,10 @@ public class ConfigurationManager
/**
* Get a configuration property as an integer, with default
*
*
* @param property
* the name of the property
*
*
* @param defaultValue
* value to return if property is not found or is not an Integer.
*
@@ -264,16 +255,16 @@ public class ConfigurationManager
{
return getIntProperty(null, property, defaultValue);
}
/**
* Get a module configuration property as an integer, with default
*
*
* @param module
* the name of the module
*
*
* @param property
* the name of the property
*
*
* @param defaultValue
* value to return if property is not found or is not an Integer.
*
@@ -316,12 +307,12 @@ public class ConfigurationManager
{
return getLongProperty(property, 0);
}
/**
* Get a module configuration property as a long
*
* @param module
* the name of the module
* the name of the module
* @param property
* the name of the property
*
@@ -333,10 +324,10 @@ public class ConfigurationManager
{
return getLongProperty(module, property, 0);
}
/**
* Get a configuration property as an long, with default
*
*
*
* @param property
* the name of the property
@@ -356,7 +347,7 @@ public class ConfigurationManager
/**
* Get a configuration property as an long, with default
*
*
* @param module the module, or <code>null</code> for regular property
*
* @param property
@@ -390,91 +381,14 @@ public class ConfigurationManager
return longValue;
}
/**
* Get the License
*
* @param
* licenseFile file name
*
* @return
* license text
*
*/
public static String getLicenseText(String licenseFile)
{
// Load in default license
InputStream is = null;
InputStreamReader ir = null;
BufferedReader br = null;
try
{
is = new FileInputStream(licenseFile);
ir = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(ir);
String lineIn;
license = "";
while ((lineIn = br.readLine()) != null)
{
license = license + lineIn + '\n';
}
}
catch (IOException e)
{
fatal("Can't load configuration", e);
// FIXME: Maybe something more graceful here, but with the
// configuration we can't do anything
throw new IllegalStateException("Failed to read default license.", e);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException ioe)
{
}
}
if (ir != null)
{
try
{
ir.close();
}
catch (IOException ioe)
{
}
}
if (is != null)
{
try
{
is.close();
}
catch (IOException ioe)
{
}
}
}
return license;
}
/**
* Get a configuration property as a boolean. True is indicated if the value
* of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.)
*
*
* @param property
* the name of the property
*
*
* @return the value of the property. <code>false</code> is returned if
* the property does not exist. To differentiate between this case
* and when the property actually is false, use
@@ -484,17 +398,17 @@ public class ConfigurationManager
{
return getBooleanProperty(property, false);
}
/**
* Get a module configuration property as a boolean. True is indicated if
* Get a module configuration property as a boolean. True is indicated if
* the value of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.)
*
* @param module the module, or <code>null</code> for regular property
*
*
* @param module the module, or <code>null</code> for regular property
*
* @param property
* the name of the property
*
*
* @return the value of the property. <code>false</code> is returned if
* the property does not exist. To differentiate between this case
* and when the property actually is false, use
@@ -504,7 +418,7 @@ public class ConfigurationManager
{
return getBooleanProperty(module, property, false);
}
/**
* Get a configuration property as a boolean, with default.
* True is indicated if the value
@@ -532,8 +446,8 @@ public class ConfigurationManager
* True is indicated if the value
* of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.)
*
* @param module module, or <code>null</code> for regular property
*
* @param module module, or <code>null</code> for regular property
*
* @param property
* the name of the property
@@ -564,19 +478,19 @@ public class ConfigurationManager
/**
* Returns an enumeration of all the keys in the DSpace configuration
*
*
* @return an enumeration of all the keys in the DSpace configuration
*/
public static Enumeration<?> propertyNames()
{
return propertyNames(null);
}
/**
* Returns an enumeration of all the keys in a module configuration
*
* @param module module, or <code>null</code> for regular property
*
*
* @param module module, or <code>null</code> for regular property
*
* @return an enumeration of all the keys in the module configuration,
* or <code>null</code> if the module does not exist.
*/
@@ -586,237 +500,14 @@ public class ConfigurationManager
return props == null ? null : props.propertyNames();
}
/**
* Get the template for an email message. The message is suitable for
* inserting values using <code>java.text.MessageFormat</code>.
*
* @param emailFile
* full name for the email template, for example "/dspace/config/emails/register".
*
* @return the email object, with the content and subject filled out from
* the template
*
* @throws IOException
* if the template couldn't be found, or there was some other
* error reading the template
*/
public static Email getEmail(String emailFile) throws IOException
{
String charset = null;
String subject = "";
StringBuffer contentBuffer = new StringBuffer();
// Read in template
InputStream is = null;
InputStreamReader ir = null;
BufferedReader br = null;
try
{
is = new FileInputStream(emailFile);
ir = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(ir);
boolean more = true;
while (more)
{
String line = br.readLine();
if (line == null)
{
more = false;
}
else if (line.toLowerCase().startsWith("subject:"))
{
// Extract the first subject line - everything to the right
// of the colon, trimmed of whitespace
subject = line.substring(8).trim();
}
else if (line.toLowerCase().startsWith("charset:"))
{
// Extract the character set from the email
charset = line.substring(8).trim();
}
else if (!line.startsWith("#"))
{
// Add non-comment lines to the content
contentBuffer.append(line);
contentBuffer.append("\n");
}
}
}
finally
{
if (br != null)
{
try {
br.close();
} catch (IOException ioe)
{
}
}
if (ir != null)
{
try {
ir.close();
} catch (IOException ioe)
{
}
}
if (is != null)
{
try {
is.close();
} catch (IOException ioe)
{
}
}
}
// Create an email
Email email = new Email();
email.setSubject(subject);
email.setContent(contentBuffer.toString());
if (charset != null)
{
email.setCharset(charset);
}
return email;
}
/**
* Get the site-wide default license that submitters need to grant
*
* @return the default license
*/
public static String getDefaultSubmissionLicense()
{
if (properties == null)
{
loadConfig(null);
}
return license;
}
/**
* Get the path for the news files.
*
*/
public static String getNewsFilePath()
{
String filePath = ConfigurationManager.getProperty("dspace.dir")
+ File.separator + "config" + File.separator;
return filePath;
}
/**
* Reads news from a text file.
*
* @param newsFile
* name of the news file to read in, relative to the news file path.
*/
public static String readNewsFile(String newsFile)
{
String fileName = getNewsFilePath();
fileName += newsFile;
StringBuilder text = new StringBuilder();
try
{
// retrieve existing news from file
FileInputStream fir = new FileInputStream(fileName);
InputStreamReader ir = new InputStreamReader(fir, "UTF-8");
BufferedReader br = new BufferedReader(ir);
String lineIn;
while ((lineIn = br.readLine()) != null)
{
text.append(lineIn);
}
br.close();
ir.close();
fir.close();
}
catch (IOException e)
{
warn("news_read: " + e.getLocalizedMessage());
}
return text.toString();
}
/**
* Writes news to a text file.
*
* @param newsFile
* name of the news file to read in, relative to the news file path.
* @param news
* the text to be written to the file.
*/
public static String writeNewsFile(String newsFile, String news)
{
String fileName = getNewsFilePath();
fileName += newsFile;
try
{
// write the news out to the appropriate file
FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
PrintWriter out = new PrintWriter(osr);
out.print(news);
out.close();
}
catch (IOException e)
{
warn("news_write: " + e.getLocalizedMessage());
}
return news;
}
/**
* Writes license to a text file.
*
* @param licenseFile
* name for the file int which license will be written,
* relative to the current directory.
*/
public static void writeLicenseFile(String licenseFile, String newLicense)
{
try
{
// write the news out to the appropriate file
FileOutputStream fos = new FileOutputStream(licenseFile);
OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
PrintWriter out = new PrintWriter(osr);
out.print(newLicense);
out.close();
}
catch (IOException e)
{
warn("license_write: " + e.getLocalizedMessage());
}
license = newLicense;
}
/** The configuration that was loaded. */
private static File loadedFile = null;
/**
* Return the file that configuration was actually loaded from. Only returns
* a valid File after configuration has been loaded.
*
* Return the file that configuration was actually loaded from.
*
* @deprecated Please remove all direct usage of the configuration file.
* @return File naming configuration data file, or null if not loaded yet.
* @return File naming configuration data file.
*/
protected static File getConfigurationFile()
{
@@ -857,7 +548,7 @@ public class ConfigurationManager
{
modIR.close();
}
if (modIS != null)
{
modIS.close();
@@ -883,17 +574,16 @@ public class ConfigurationManager
}
catch (IOException ioE)
{
fatal("Can't load configuration: " + (modFile == null ? "<unknown>" : modFile.getAbsolutePath()), ioE);
fatal("Can't load configuration: " +
(modFile == null ? "<unknown>" : modFile.getAbsolutePath()), ioE);
}
return;
}
/**
* Load the DSpace configuration properties. Only does anything if
* properties are not already loaded. Properties are loaded in from the
* specified file, or default locations.
*
*
* @param configFile
* The <code>dspace.cfg</code> configuration file to use, or
* <code>null</code> to try default locations
@@ -906,7 +596,7 @@ public class ConfigurationManager
}
URL url = null;
InputStream is = null;
InputStreamReader reader = null;
try
@@ -922,27 +612,27 @@ public class ConfigurationManager
// This isn't really a fatal error though, so catch and ignore
log.warn("Unable to access system properties, ignoring.", se);
}
// should only occur after a flush()
if (loadedFile != null)
{
info("Reloading current config file: " + loadedFile.getAbsolutePath());
url = loadedFile.toURI().toURL();
}
else if (configFile != null)
{
info("Loading provided config file: " + configFile);
loadedFile = new File(configFile);
url = loadedFile.toURI().toURL();
}
// Has the default configuration location been overridden?
else if (configProperty != null)
{
info("Loading system provided config property (-Ddspace.configuration): " + configProperty);
// Load the overriding configuration
loadedFile = new File(configProperty);
url = loadedFile.toURI().toURL();
@@ -954,11 +644,11 @@ public class ConfigurationManager
if (url != null)
{
info("Loading from classloader: " + url);
loadedFile = new File(url.getPath());
}
}
if (url == null)
{
fatal("Cannot find dspace.cfg");
@@ -988,8 +678,8 @@ public class ConfigurationManager
{
fatal("Can't load configuration: " + url, e);
// FIXME: Maybe something more graceful here, but with the
// configuration we can't do anything
// FIXME: Maybe something more graceful here, but without a
// configuration we can't do anything.
throw new IllegalStateException("Cannot load configuration: " + url, e);
}
finally
@@ -1006,131 +696,61 @@ public class ConfigurationManager
if (is != null)
{
try
{
{
is.close();
}
catch (IOException ioe)
{
}
}
}
// Load in default license
File licenseFile = new File(getProperty("dspace.dir") + File.separator
+ "config" + File.separator + "default.license");
FileInputStream fir = null;
InputStreamReader ir = null;
BufferedReader br = null;
try
{
fir = new FileInputStream(licenseFile);
ir = new InputStreamReader(fir, "UTF-8");
br = new BufferedReader(ir);
String lineIn;
license = "";
while ((lineIn = br.readLine()) != null)
{
license = license + lineIn + '\n';
}
br.close();
}
catch (IOException e)
{
fatal("Can't load license: " + licenseFile.toString() , e);
// FIXME: Maybe something more graceful here, but with the
// configuration we can't do anything
throw new IllegalStateException("Cannot load license: " + licenseFile.toString(),e);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException ioe)
{
}
}
if (ir != null)
{
try
{
ir.close();
}
catch (IOException ioe)
{
}
}
if (fir != null)
{
try
{
fir.close();
}
catch (IOException ioe)
{
}
}
}
try
{
/*
* Initialize Logging once ConfigurationManager is initialized.
*
* This is selection from a property in dspace.cfg, if the property
*
* This is controlled by a property in dspace.cfg. If the property
* is absent then nothing will be configured and the application
* will use the defaults provided by log4j.
*
* will use the defaults provided by log4j.
*
* Property format is:
*
*
* log.init.config = ${dspace.dir}/config/log4j.properties
* or
* log.init.config = ${dspace.dir}/config/log4j.xml
*
*
* See default log4j initialization documentation here:
* http://logging.apache.org/log4j/docs/manual.html
*
*
* If there is a problem with the file referred to in
* "log.configuration" it needs to be sent to System.err
* "log.configuration", it needs to be sent to System.err
* so do not instantiate another Logging configuration.
*
*/
String dsLogConfiguration = ConfigurationManager.getProperty("log.init.config");
if (dsLogConfiguration == null || System.getProperty("dspace.log.init.disable") != null)
if (dsLogConfiguration == null || System.getProperty("dspace.log.init.disable") != null)
{
/*
* Do nothing if log config not set in dspace.cfg or "dspace.log.init.disable"
* system property set. Leave it upto log4j to properly init its logging
/*
* Do nothing if log config not set in dspace.cfg or "dspace.log.init.disable"
* system property set. Leave it upto log4j to properly init its logging
* via classpath or system properties.
*/
info("Using default log4j provided log configuration," +
"if unintended, check your dspace.cfg for (log.init.config)");
info("Using default log4j provided log configuration." +
" If unintended, check your dspace.cfg for (log.init.config)");
}
else
{
info("Using dspace provided log configuration (log.init.config)");
File logConfigFile = new File(dsLogConfiguration);
if(logConfigFile.exists())
{
info("Loading: " + dsLogConfiguration);
OptionConverter.selectAndConfigure(logConfigFile.toURI()
.toURL(), null, org.apache.log4j.LogManager
.getLoggerRepository());
@@ -1147,7 +767,61 @@ public class ConfigurationManager
fatal("Can't load dspace provided log4j configuration", e);
throw new IllegalStateException("Cannot load dspace provided log4j configuration",e);
}
}
/**
* Wrapper for {@link NewsManager#getNewsFilePath()}.
* @deprecated since 4.0
*/
public static String getNewsFilePath()
{
return NewsManager.getNewsFilePath();
}
/**
* Wrapper for {@link NewsManager#readNewsFile(java.lang.String)}.
* @deprecated since 4.0
*/
public static String readNewsFile(String name)
{
return NewsManager.readNewsFile(name);
}
/**
* Wrapper for {@link NewsManager#writeNewsFile(java.lang.String, java.lang.String)}.
* @deprecated since 4.0
*/
public static String writeNewsFile(String file, String news)
{
return NewsManager.writeNewsFile(file, news);
}
/**
* Wrapper for {@link LicenseManager#getLicenseText(java.lang.String)}.
* @deprecated since 4.0
*/
public static String getLicenseText(String licenseFile)
{
return LicenseManager.getLicenseText(licenseFile);
}
/**
* Wrapper for {@link LicenseManager#getDefaultSubmissionLicense()}.
* @deprecated since 4.0
*/
public static String getDefaultSubmissionLicense()
{
return LicenseManager.getDefaultSubmissionLicense();
}
/**
* Wrapper for {@link LicenseManager#writeLicenseFile(java.lang.String, java.lang.String)}.
* @deprecated since 4.0
*/
public static void writeLicenseFile(String licenseFile, String newLicense)
{
LicenseManager.writeLicenseFile(licenseFile, newLicense);
}
/**
@@ -1224,7 +898,7 @@ public class ConfigurationManager
* <code>name</code> from <code>dspace.cfg</code> to the standard
* output. If the property does not exist, nothing is written.</li>
* </ul>
*
*
* @param argv
* command-line arguments
*/
@@ -1246,7 +920,7 @@ public class ConfigurationManager
System.exit(0);
}
else if ((argv.length == 4) && argv[0].equals("-module") &&
argv[2].equals("-property"))
argv[2].equals("-property"))
{
String val = getProperty(argv[1], argv[3]);
@@ -1269,7 +943,7 @@ public class ConfigurationManager
System.exit(1);
}
private static void info(String string)
{
if (!isLog4jConfigured())
@@ -1320,8 +994,8 @@ public class ConfigurationManager
}
/*
* Only current solution available to detect
* if log4j is truly configured.
* Only current solution available to detect
* if log4j is truly configured.
*/
private static boolean isLog4jConfigured()
{

View File

@@ -7,31 +7,34 @@
*/
package org.dspace.core;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;
import org.dspace.services.EmailService;
import org.dspace.utils.DSpace;
/**
* Class representing an e-mail message, also used to send e-mails.
@@ -54,57 +57,47 @@ import javax.mail.internet.MimeMultipart;
* starts with "Subject:" the text on the right of the colon is used for the
* subject line. For example:
* <P>
*
*
* <pre>
*
*
* # This is a comment line which is stripped
* #
* # Parameters: {0} is a person's name
* # {1} is the name of a submission
* #
* Subject: Example e-mail
*
*
* Dear {0},
*
*
* Thank you for sending us your submission &quot;{1}&quot;.
*
*
* </pre>
*
*
* <P>
* If the example code above was used to send this mail, the resulting mail
* would have the subject <code>Example e-mail</code> and the body would be:
* <P>
*
*
* <pre>
*
*
*
*
* Dear John,
*
*
* Thank you for sending us your submission &quot;On the Testing of DSpace&quot;.
*
*
* </pre>
*
*
* <P>
* Note that parameters like <code>{0}</code> cannot be placed in the subject
* of the e-mail; they won't get filled out.
*
*
*
*
* @author Robert Tansley
* @author Jim Downing - added attachment handling code
* @version $Revision$
*/
public class Email
{
/*
* Implementation note: It might be necessary to add a quick utility method
* like "send(to, subject, message)". We'll see how far we get without it -
* having all emails as templates in the config allows customisation and
* internationalisation.
*
* Note that everything is stored and the run in send() so that only send()
* throws a MessagingException.
*/
/** The content of the message */
private String content;
@@ -143,7 +136,7 @@ public class Email
/**
* Add a recipient
*
*
* @param email
* the recipient's email address
*/
@@ -156,7 +149,7 @@ public class Email
* Set the content of the message. Setting this "resets" the message
* formatting -<code>addArgument</code> will start. Comments and any
* "Subject:" line must be stripped.
*
*
* @param cnt
* the content of the message
*/
@@ -168,7 +161,7 @@ public class Email
/**
* Set the subject of the message
*
*
* @param s
* the subject of the message
*/
@@ -179,7 +172,7 @@ public class Email
/**
* Set the reply-to email address
*
*
* @param email
* the reply-to email address
*/
@@ -190,7 +183,7 @@ public class Email
/**
* Fill out the next argument in the template
*
*
* @param arg
* the value for the next argument
*/
@@ -224,72 +217,25 @@ public class Email
/**
* Sends the email.
*
*
* @throws MessagingException
* if there was a problem sending the mail.
*/
public void send() throws MessagingException
{
// Get the mail configuration properties
String server = ConfigurationManager.getProperty("mail.server");
String from = ConfigurationManager.getProperty("mail.from.address");
boolean disabled = ConfigurationManager.getBooleanProperty("mail.server.disabled", false);
if (disabled) {
log.info("message not sent due to mail.server.disabled: " + subject);
return;
}
// Set up properties for mail session
Properties props = System.getProperties();
props.put("mail.smtp.host", server);
// Set the port number for the mail server
String portNo = ConfigurationManager.getProperty("mail.server.port");
if (portNo == null)
{
portNo = "25";
}
props.put("mail.smtp.port", portNo.trim());
// If no character set specified, attempt to retrieve a default
if (charset == null)
{
charset = ConfigurationManager.getProperty("mail.charset");
charset = ConfigurationManager.getProperty("mail.charset");
}
// Get session
Session session;
// Get the SMTP server authentication information
String username = ConfigurationManager.getProperty("mail.server.username");
String password = ConfigurationManager.getProperty("mail.server.password");
if (username != null)
{
props.put("mail.smtp.auth", "true");
SMTPAuthenticator smtpAuthenticator = new SMTPAuthenticator(
username, password);
session = Session.getInstance(props, smtpAuthenticator);
}
else
{
session = Session.getDefaultInstance(props);
}
// Set extra configuration properties
String extras = ConfigurationManager.getProperty("mail.extraproperties");
if ((extras != null) && (!"".equals(extras.trim())))
{
String arguments[] = extras.split(",");
String key, value;
for (String argument : arguments)
{
key = argument.substring(0, argument.indexOf('=')).trim();
value = argument.substring(argument.indexOf('=') + 1).trim();
props.put(key, value);
}
}
Session session = new DSpace().getServiceManager().
getServicesByType(EmailService.class).get(0).getSession();
// Create message
MimeMessage message = new MimeMessage(session);
@@ -321,7 +267,7 @@ public class Email
{
message.setSubject(fullSubject);
}
// Add attachments
if (attachments.isEmpty())
{
@@ -363,9 +309,127 @@ public class Email
message.setReplyTo(replyToAddr);
}
Transport.send(message);
if (disabled)
{
StringBuffer text = new StringBuffer(
"Message not sent due to mail.server.disabled:\n");
Enumeration<String> headers = message.getAllHeaderLines();
while (headers.hasMoreElements())
text.append(headers.nextElement()).append('\n');
if (!attachments.isEmpty())
{
text.append("\nAttachments:\n");
for (FileAttachment f : attachments)
text.append(f.name).append('\n');
text.append('\n');
}
text.append('\n').append(fullMessage);
log.info(text);
}
else
Transport.send(message);
}
/**
* Get the template for an email message. The message is suitable for
* inserting values using <code>java.text.MessageFormat</code>.
*
* @param emailFile
* full name for the email template, for example "/dspace/config/emails/register".
*
* @return the email object, with the content and subject filled out from
* the template
*
* @throws IOException
* if the template couldn't be found, or there was some other
* error reading the template
*/
public static Email getEmail(String emailFile)
throws IOException
{
String charset = null;
String subject = "";
StringBuilder contentBuffer = new StringBuilder();
InputStream is = null;
InputStreamReader ir = null;
BufferedReader reader = null;
try
{
is = new FileInputStream(emailFile);
ir = new InputStreamReader(is, "UTF-8");
reader = new BufferedReader(ir);
boolean more = true;
while (more)
{
String line = reader.readLine();
if (line == null)
{
more = false;
}
else if (line.toLowerCase().startsWith("subject:"))
{
subject = line.substring(8).trim();
}
else if (line.toLowerCase().startsWith("charset:"))
{
charset = line.substring(8).trim();
}
else if (!line.startsWith("#"))
{
contentBuffer.append(line);
contentBuffer.append("\n");
}
}
} finally
{
if (reader != null)
{
try {
reader.close();
} catch (IOException ioe)
{
}
}
if (ir != null)
{
try {
ir.close();
} catch (IOException ioe)
{
}
}
if (is != null)
{
try {
is.close();
} catch (IOException ioe)
{
}
}
}
Email email = new Email();
email.setSubject(subject);
email.setContent(contentBuffer.toString());
if (charset != null)
{
email.setCharset(charset);
}
return email;
}
/*
* Implementation note: It might be necessary to add a quick utility method
* like "send(to, subject, message)". We'll see how far we get without it -
* having all emails as templates in the config allows customisation and
* internationalisation.
*
* Note that everything is stored and the run in send() so that only send()
* throws a MessagingException.
*/
/**
* Test method to send an email to check email server settings
*
@@ -402,9 +466,9 @@ public class Email
/**
* Utility struct class for handling file attachments.
*
*
* @author ojd20
*
*
*/
private static class FileAttachment
{
@@ -418,27 +482,4 @@ public class Email
String name;
}
/**
* Inner Class for SMTP authentication information
*/
private static class SMTPAuthenticator extends Authenticator
{
// User name
private String name;
// Password
private String password;
public SMTPAuthenticator(String n, String p)
{
name = n;
password = p;
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(name, password);
}
}
}

View File

@@ -0,0 +1,211 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Encapsulate the deposit license.
*
* @author mhwood
*/
public class LicenseManager
{
private static final Logger log = LoggerFactory.getLogger(LicenseManager.class);
/** The default license */
private static String license;
/**
* Writes license to a text file.
*
* @param licenseFile
* name for the file into which license will be written,
* relative to the current directory.
*/
public static void writeLicenseFile(String licenseFile,
String newLicense)
{
try
{
FileOutputStream fos = new FileOutputStream(licenseFile);
OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
PrintWriter out = new PrintWriter(osr);
out.print(newLicense);
out.close();
} catch (IOException e)
{
log.warn("license_write: " + e.getLocalizedMessage());
}
license = newLicense;
}
/**
* Get the License
*
* @param
* licenseFile file name
*
* @return
* license text
*
*/
public static String getLicenseText(String licenseFile)
{
InputStream is = null;
InputStreamReader ir = null;
BufferedReader br = null;
try
{
is = new FileInputStream(licenseFile);
ir = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(ir);
String lineIn;
license = "";
while ((lineIn = br.readLine()) != null)
{
license = license + lineIn + '\n';
}
} catch (IOException e)
{
log.error("Can't load configuration", e);
throw new IllegalStateException("Failed to read default license.", e);
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException ioe)
{
}
}
if (ir != null)
{
try
{
ir.close();
}
catch (IOException ioe)
{
}
}
if (is != null)
{
try
{
is.close();
} catch (IOException ioe)
{
}
}
}
return license;
}
/**
* Get the site-wide default license that submitters need to grant
*
* @return the default license
*/
public static String getDefaultSubmissionLicense()
{
if (null == license)
{
init();
}
return license;
}
/**
* Load in the default license.
*/
private static void init()
{
File licenseFile = new File(ConfigurationManager.getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "default.license");
FileInputStream fir = null;
InputStreamReader ir = null;
BufferedReader br = null;
try
{
fir = new FileInputStream(licenseFile);
ir = new InputStreamReader(fir, "UTF-8");
br = new BufferedReader(ir);
String lineIn;
LicenseManager.license = "";
while ((lineIn = br.readLine()) != null)
{
LicenseManager.license = LicenseManager.license + lineIn + '\n';
}
br.close();
}
catch (IOException e)
{
log.error("Can't load license: " + licenseFile.toString() , e);
// FIXME: Maybe something more graceful here, but with the
// configuration we can't do anything
throw new IllegalStateException("Cannot load license: "
+ licenseFile.toString(),e);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException ioe)
{
}
}
if (ir != null)
{
try
{
ir.close();
}
catch (IOException ioe)
{
}
}
if (fir != null)
{
try
{
fir.close();
}
catch (IOException ioe)
{
}
}
}
}
}

View File

@@ -0,0 +1,116 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Encapsulate access to the news texts.
*
* @author mhwood
*/
public class NewsManager
{
private static final Logger log = LoggerFactory.getLogger(NewsManager.class);
/** Not instantiable. */
private NewsManager() {}
/**
* Reads news from a text file.
*
* @param newsFile
* name of the news file to read in, relative to the news file path.
*/
public static String readNewsFile(String newsFile)
{
String fileName = getNewsFilePath();
fileName += newsFile;
StringBuilder text = new StringBuilder();
try
{
// retrieve existing news from file
FileInputStream fir = new FileInputStream(fileName);
InputStreamReader ir = new InputStreamReader(fir, "UTF-8");
BufferedReader br = new BufferedReader(ir);
String lineIn;
while ((lineIn = br.readLine()) != null)
{
text.append(lineIn);
}
br.close();
ir.close();
fir.close();
}
catch (IOException e)
{
log.warn("news_read: " + e.getLocalizedMessage());
}
return text.toString();
}
/**
* Writes news to a text file.
*
* @param newsFile
* name of the news file to read in, relative to the news file path.
* @param news
* the text to be written to the file.
*/
public static String writeNewsFile(String newsFile, String news)
{
String fileName = getNewsFilePath();
fileName += newsFile;
try
{
// write the news out to the appropriate file
FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
PrintWriter out = new PrintWriter(osr);
out.print(news);
out.close();
}
catch (IOException e)
{
log.warn("news_write: " + e.getLocalizedMessage());
}
return news;
}
/**
* Get the path for the news files.
*
*/
public static String getNewsFilePath()
{
String filePath = ConfigurationManager.getProperty("dspace.dir")
+ File.separator + "config" + File.separator;
return filePath;
}
}

View File

@@ -26,7 +26,7 @@ import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import com.coverity.security.Escape;
import org.apache.log4j.Logger;
/**
@@ -280,21 +280,7 @@ public final class Utils
*/
public static String addEntities(String value)
{
if (value==null || value.length() == 0)
{
return value;
}
value = value.replaceAll("&", "&amp;");
value = value.replaceAll("\"", "&quot;");
// actually, &apos; is an XML entity, not in HTML.
// that's why it's commented out.
// value = value.replaceAll("'", "&apos;");
value = value.replaceAll("<", "&lt;");
value = value.replaceAll(">", "&gt;");
return value;
return Escape.html(value);
}
/**

View File

@@ -7,6 +7,33 @@
*/
package org.dspace.discovery;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.Vector;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.Transformer;
@@ -16,10 +43,16 @@ import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.utils.URIBuilder;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
@@ -31,23 +64,38 @@ import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.params.MoreLikeThisParams;
import org.apache.solr.common.util.NamedList;
import org.dspace.content.*;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
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.content.ItemIterator;
import org.dspace.content.authority.ChoiceAuthorityManager;
import org.dspace.content.authority.Choices;
import org.dspace.content.authority.MetadataAuthorityManager;
import org.dspace.core.*;
import org.dspace.discovery.configuration.*;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Email;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogManager;
import org.dspace.discovery.configuration.DiscoveryConfiguration;
import org.dspace.discovery.configuration.DiscoveryConfigurationParameters;
import org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration;
import org.dspace.discovery.configuration.DiscoveryHitHighlightingConfiguration;
import org.dspace.discovery.configuration.DiscoveryMoreLikeThisConfiguration;
import org.dspace.discovery.configuration.DiscoveryRecentSubmissionsConfiguration;
import org.dspace.discovery.configuration.DiscoverySearchFilter;
import org.dspace.discovery.configuration.DiscoverySearchFilterFacet;
import org.dspace.discovery.configuration.DiscoverySortConfiguration;
import org.dspace.discovery.configuration.DiscoverySortFieldConfiguration;
import org.dspace.discovery.configuration.HierarchicalSidebarFacetConfiguration;
import org.dspace.handle.HandleManager;
import org.dspace.utils.DSpace;
import org.springframework.stereotype.Service;
import java.io.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* SolrIndexer contains the methods that index Items and their metadata,
* collections, communities, etc. It is meant to either be invoked from the
@@ -78,32 +126,42 @@ public class SolrServiceImpl implements SearchService, IndexingService {
public static final String FILTER_SEPARATOR = "\n|||\n";
public static final String AUTHORITY_SEPARATOR = "###";
public static final String STORE_SEPARATOR = "\n|||\n";
public static final String VARIANTS_STORE_SEPARATOR = "###";
/**
* Non-Static CommonsHttpSolrServer for processing indexing events.
*/
private CommonsHttpSolrServer solr = null;
private HttpSolrServer solr = null;
protected CommonsHttpSolrServer getSolr() throws java.net.MalformedURLException, org.apache.solr.client.solrj.SolrServerException
protected HttpSolrServer getSolr()
{
if ( solr == null)
{
String solrService = new DSpace().getConfigurationService().getProperty("discovery.search.server") ;
String solrService = new DSpace().getConfigurationService()
.getProperty("discovery.search.server");
UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
if(urlValidator.isValid(solrService))
{
try {
log.debug("Solr URL: " + solrService);
solr = new HttpSolrServer(solrService);
log.debug("Solr URL: " + solrService);
solr = new CommonsHttpSolrServer(solrService);
solr.setBaseURL(solrService);
solr.setBaseURL(solrService);
SolrQuery solrQuery = new SolrQuery()
.setQuery("search.resourcetype:2 AND search.resourceid:1");
SolrQuery solrQuery = new SolrQuery()
.setQuery("search.resourcetype:2 AND search.resourceid:1");
solr.query(solrQuery);
solr.query(solrQuery);
} catch (SolrServerException e) {
log.error("Error while initialinging solr server", e);
}
}else{
log.error("Error while initializing solr, invalid url: " + solrService);
}
}
return solr;
@@ -255,10 +313,12 @@ public class SolrServiceImpl implements SearchService, IndexingService {
throws SQLException, IOException {
try {
getSolr().deleteByQuery("handle:\""+handle+"\"");
if(commit)
{
getSolr().commit();
if(getSolr() != null){
getSolr().deleteByQuery("handle:\"" + handle + "\"");
if(commit)
{
getSolr().commit();
}
}
} catch (SolrServerException e)
{
@@ -326,7 +386,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
try {
ItemIterator items = null;
try {
for (items = Item.findAllUnfiltered(context); items.hasNext();)
for (items = Item.findAllUnfiltered(context); items.hasNext();)
{
Item item = items.next();
indexContent(context, item, force);
@@ -354,7 +414,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
context.removeCached(community, community.getID());
}
getSolr().commit();
if(getSolr() != null)
{
getSolr().commit();
}
} catch (Exception e)
{
@@ -379,6 +442,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
try
{
if(getSolr() == null)
{
return;
}
if (force)
{
getSolr().deleteByQuery("search.resourcetype:[2 TO 4]");
@@ -433,6 +500,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
public void optimize()
{
try {
if(getSolr() == null)
{
return;
}
long start = System.currentTimeMillis();
System.out.println("SOLR Search Optimize -- Process Started:"+start);
getSolr().optimize();
@@ -459,9 +530,9 @@ public class SolrServiceImpl implements SearchService, IndexingService {
String recipient = ConfigurationManager
.getProperty("alert.recipient");
if (recipient != null)
if (StringUtils.isNotBlank(recipient))
{
Email email = ConfigurationManager
Email email = Email
.getEmail(I18nUtil.getEmailFilename(
Locale.getDefault(), "internal_error"));
email.addRecipient(recipient);
@@ -516,6 +587,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
QueryResponse rsp;
try {
if(getSolr() == null)
{
return false;
}
rsp = getSolr().query(query);
} catch (SolrServerException e)
{
@@ -598,7 +673,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
protected void writeDocument(SolrInputDocument doc) throws IOException {
try {
getSolr().add(doc);
if(getSolr() != null)
{
getSolr().add(doc);
}
} catch (SolrServerException e)
{
log.error(e.getMessage(), e);
@@ -754,7 +832,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
SolrInputDocument doc = buildDocument(Constants.ITEM, item.getID(), handle,
locations);
log.debug("Building Item: " + handle);
doc.addField("withdrawn", item.isWithdrawn());
@@ -839,7 +917,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
toProjectionFields.add(projectionFieldsString);
}
}
DCValue[] mydc = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (DCValue meta : mydc)
{
@@ -848,7 +926,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
String value = meta.value;
if (value == null)
if (value == null)
{
continue;
}
@@ -864,7 +942,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
{
continue;
}
String authority = null;
String preferedLabel = null;
List<String> variants = null;
@@ -878,7 +956,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
meta.schema,
meta.element,
meta.qualifier):Choices.CF_ACCEPTED;
if (isAuthorityControlled && meta.authority != null
&& meta.confidence >= minConfidence)
{
@@ -965,7 +1043,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
}
doc.addField(searchFilter.getIndexFieldName(), value);
doc.addField(searchFilter.getIndexFieldName() + "_keyword", value);
if (authority != null && preferedLabel == null)
{
doc.addField(searchFilter.getIndexFieldName()
@@ -1006,7 +1084,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
+ AUTHORITY_SEPARATOR + authority);
}
}
//Add a dynamic fields for auto complete in search
doc.addField(searchFilter.getIndexFieldName() + "_ac",
value.toLowerCase() + separator + value);
@@ -1024,7 +1102,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
+ "_ac", var.toLowerCase() + separator
+ var);
}
}
}
if(searchFilter.getFilterType().equals(DiscoverySearchFilterFacet.FILTER_TYPE_FACET))
{
@@ -1048,13 +1126,38 @@ public class SolrServiceImpl implements SearchService, IndexingService {
if(date != null)
{
String indexField = searchFilter.getIndexFieldName() + ".year";
doc.addField(searchFilter.getIndexFieldName() + "_keyword", DateFormatUtils.formatUTC(date, "yyyy"));
doc.addField(indexField, DateFormatUtils.formatUTC(date, "yyyy"));
String yearUTC = DateFormatUtils.formatUTC(date, "yyyy");
doc.addField(searchFilter.getIndexFieldName() + "_keyword", yearUTC);
// add the year to the autocomplete index
doc.addField(searchFilter.getIndexFieldName() + "_ac", yearUTC);
doc.addField(indexField, yearUTC);
if (yearUTC.startsWith("0"))
{
doc.addField(
searchFilter.getIndexFieldName()
+ "_keyword",
yearUTC.replaceFirst("0*", ""));
// add date without starting zeros for autocomplete e filtering
doc.addField(
searchFilter.getIndexFieldName()
+ "_ac",
yearUTC.replaceFirst("0*", ""));
doc.addField(
searchFilter.getIndexFieldName()
+ "_ac",
value.replaceFirst("0*", ""));
doc.addField(
searchFilter.getIndexFieldName()
+ "_keyword",
value.replaceFirst("0*", ""));
}
//Also save a sort value of this year, this is required for determining the upper & lower bound year of our facet
if(doc.getField(indexField + "_sort") == null)
{
//We can only add one year so take the first one
doc.addField(indexField + "_sort", DateFormatUtils.formatUTC(date, "yyyy"));
doc.addField(indexField + "_sort", yearUTC);
}
}
}else
@@ -1140,7 +1243,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
variantsToStore.append(VARIANTS_STORE_SEPARATOR);
variantsToStore.append(var);
}
}
}
doc.addField(
field + "_stored",
value + STORE_SEPARATOR + preferedLabel
@@ -1152,7 +1255,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
+ STORE_SEPARATOR + authority
+ STORE_SEPARATOR + meta.language);
}
if (meta.language != null && !meta.language.trim().equals(""))
{
String langField = field + "." + meta.language;
@@ -1179,9 +1282,9 @@ public class SolrServiceImpl implements SearchService, IndexingService {
{
handlePrefix = "http://hdl.handle.net/";
}
doc.addField("publication_grp",values[0].value.replaceFirst(handlePrefix,"") );
}
else
{
@@ -1272,7 +1375,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} catch (RuntimeException e)
{
log.error("Error while writing item to discovery index: " + handle + " message:"+ e.getMessage(), e);
}
}
}
/**
@@ -1341,6 +1444,14 @@ public class SolrServiceImpl implements SearchService, IndexingService {
// Choose the likely date formats based on string length
switch (t.length())
{
// case from 1 to 3 go through adding anyone a single 0. Case 4 define
// for all the SimpleDateFormat
case 1:
t = "0" + t;
case 2:
t = "0" + t;
case 3:
t = "0" + t;
case 4:
dfArr = new SimpleDateFormat[]{new SimpleDateFormat("yyyy")};
break;
@@ -1415,7 +1526,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
{
return search(context, dso, query, false);
}
public DiscoverResult search(Context context, DSpaceObject dso, DiscoverQuery discoveryQuery, boolean includeWithdrawn) throws SearchServiceException {
if(dso != null)
{
@@ -1437,6 +1548,9 @@ public class SolrServiceImpl implements SearchService, IndexingService {
public DiscoverResult search(Context context, DiscoverQuery discoveryQuery, boolean includeWithdrawn) throws SearchServiceException {
try {
if(getSolr() == null){
return new DiscoverResult();
}
SolrQuery solrQuery = resolveToSolrQuery(context, discoveryQuery, includeWithdrawn);
@@ -1460,7 +1574,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
}
solrQuery.setQuery(query);
if (!includeWithdrawn)
{
solrQuery.addFilterQuery("NOT(withdrawn:true)");
@@ -1594,6 +1708,11 @@ public class SolrServiceImpl implements SearchService, IndexingService {
public InputStream searchJSON(Context context, DiscoverQuery discoveryQuery, String jsonIdentifier) throws SearchServiceException {
if(getSolr() == null)
{
return null;
}
SolrQuery solrQuery = resolveToSolrQuery(context, discoveryQuery, false);
//We use json as out output type
solrQuery.setParam("json.nl", "map");
@@ -1601,7 +1720,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
solrQuery.setParam(CommonParams.WT, "json");
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(solr.getBaseURL()).append("/select?");
urlBuilder.append(getSolr().getBaseURL()).append("/select?");
urlBuilder.append(solrQuery.toString());
try {
@@ -1615,7 +1734,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
}
return null;
}
protected DiscoverResult retrieveResult(Context context, DiscoverQuery query, QueryResponse solrQueryResponse) throws SQLException {
DiscoverResult result = new DiscoverResult();
@@ -1709,10 +1828,11 @@ public class SolrServiceImpl implements SearchService, IndexingService {
if(solrQueryResponse.getFacetQuery() != null)
{
//TODO: do not sort when not a date, just retrieve the facets in the order they where requested !
//At the moment facet queries are only used for dates so we need to sort our results
TreeMap<String, Integer> sortedFacetQueries = new TreeMap<String, Integer>(solrQueryResponse.getFacetQuery());
for(String facetQuery : sortedFacetQueries.descendingKeySet())
// just retrieve the facets in the order they where requested!
// also for the date we ask it in proper (reverse) order
// At the moment facet queries are only used for dates
LinkedHashMap<String, Integer> sortedFacetQueries = new LinkedHashMap<String, Integer>(solrQueryResponse.getFacetQuery());
for(String facetQuery : sortedFacetQueries.keySet())
{
//TODO: do not assume this, people may want to use it for other ends, use a regex to make sure
//We have a facet query, the values looks something like: dateissued.year:[1990 TO 2000] AND -2000
@@ -1722,7 +1842,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
name = name.substring(0, name.lastIndexOf(']')).replaceAll("TO", "-");
String filter = facetQuery.substring(facetQuery.indexOf('['));
filter = filter.substring(0, filter.lastIndexOf(']') + 1);
Integer count = sortedFacetQueries.get(facetQuery);
//No need to show empty years
@@ -1757,21 +1877,25 @@ public class SolrServiceImpl implements SearchService, IndexingService {
/** Simple means to return the search result as an InputStream */
public java.io.InputStream searchAsInputStream(DiscoverQuery query) throws SearchServiceException, java.io.IOException {
try {
org.apache.commons.httpclient.methods.GetMethod method =
new org.apache.commons.httpclient.methods.GetMethod(getSolr().getHttpClient().getHostConfiguration().getHostURL() + "");
method.setQueryString(query.toString());
getSolr().getHttpClient().executeMethod(method);
return method.getResponseBodyAsStream();
} catch (org.apache.solr.client.solrj.SolrServerException e)
if(getSolr() == null)
{
throw new SearchServiceException(e.getMessage(), e);
return null;
}
HttpHost hostURL = (HttpHost)(getSolr().getHttpClient().getParams().getParameter(ClientPNames.DEFAULT_HOST));
HttpGet method = new HttpGet(hostURL.toHostString() + "");
try
{
URI uri = new URIBuilder(method.getURI()).addParameter("q",query.toString()).build();
}
catch (URISyntaxException e)
{
throw new SearchServiceException(e);
}
HttpResponse response = getSolr().getHttpClient().execute(method);
return response.getEntity().getContent();
}
public List<DSpaceObject> search(Context context, String query, int offset, int max, String... filterquery)
@@ -1783,6 +1907,11 @@ public class SolrServiceImpl implements SearchService, IndexingService {
{
try {
if(getSolr() == null)
{
return Collections.emptyList();
}
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery(query);
solrQuery.setFields("search.resourceid", "search.resourcetype");
@@ -1821,7 +1950,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
return new ArrayList<DSpaceObject>(0);
}
}
public DiscoverFilterQuery toFilterQuery(Context context, String field, String operator, String value) throws SQLException{
DiscoverFilterQuery result = new DiscoverFilterQuery();
@@ -1846,15 +1975,24 @@ public class SolrServiceImpl implements SearchService, IndexingService {
filterQuery.insert(0, "-");
}
filterQuery.append(":");
if("equals".equals(operator))
if("equals".equals(operator) || "notequals".equals(operator))
{
//DO NOT ESCAPE RANGE QUERIES !
if(!value.matches("\\[.*TO.*\\]"))
{
value = ClientUtils.escapeQueryChars(value);
filterQuery.append(value);
}
else
{
if (value.matches("\\[\\d{1,4} TO \\d{1,4}\\]"))
{
int minRange = Integer.parseInt(value.substring(1, value.length()-1).split(" TO ")[0]);
int maxRange = Integer.parseInt(value.substring(1, value.length()-1).split(" TO ")[1]);
value = "["+String.format("%04d", minRange) + " TO "+ String.format("%04d", maxRange) + "]";
}
filterQuery.append(value);
}
filterQuery.append(value);
}
else{
//DO NOT ESCAPE RANGE QUERIES !
@@ -1862,7 +2000,9 @@ public class SolrServiceImpl implements SearchService, IndexingService {
{
value = ClientUtils.escapeQueryChars(value);
filterQuery.append("(").append(value).append(")");
}else{
}
else
{
filterQuery.append(value);
}
}
@@ -1902,6 +2042,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
solrQuery.setParam(MoreLikeThisParams.DOC_COUNT, String.valueOf(mltConfig.getMax()));
solrQuery.setParam(MoreLikeThisParams.MIN_WORD_LEN, String.valueOf(mltConfig.getMinWordLength()));
if(getSolr() == null)
{
return Collections.emptyList();
}
QueryResponse rsp = getSolr().query(solrQuery);
NamedList mltResults = (NamedList) rsp.getResponse().get("moreLikeThis");
if(mltResults != null && mltResults.get(item.getType() + "-" + item.getID()) != null)
@@ -1925,7 +2069,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
}
return results;
}
@Override
public String toSortFieldIndex(String metadataField, String type)
{
@@ -2020,7 +2164,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
}
return value;
}
protected String transformAuthorityValue(Context context, String field, String value) throws SQLException {
if (field.endsWith("_filter") || field.endsWith("_ac")
|| field.endsWith("_acid"))
@@ -2051,7 +2195,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
}
return null;
}
protected String transformSortValue(Context context, String field, String value) throws SQLException {
if(field.equals("location.comm") || field.equals("location.coll"))
{
@@ -2097,7 +2241,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
@Override
public void commit() throws SearchServiceException {
try {
getSolr().commit();
if(getSolr() != null)
{
getSolr().commit();
}
} catch (Exception e) {
throw new SearchServiceException(e.getMessage(), e);
}

View File

@@ -79,7 +79,7 @@ public class SolrServiceResourceRestrictionPlugin implements SolrServiceIndexPlu
try {
if(AuthorizeManager.isAdmin(context)){
//Admins always have read access even if no policies are present !
resourceQuery.append(" OR (!read[* TO *])");
resourceQuery.append(" OR (!read:[* TO *])");
}
} catch (SQLException e) {

View File

@@ -31,9 +31,9 @@ import org.dspace.storage.rdbms.TableRow;
* randomly generated and thus hard to guess. When the user presents the token
* back to the system, the AccountManager can use the token to determine the
* identity of the eperson.
*
*
* *NEW* now ignores expiration dates so that tokens never expire
*
*
* @author Peter Breton
* @version $Revision$
*/
@@ -49,12 +49,12 @@ public class AccountManager
/**
* Email registration info to the given email address.
*
*
* Potential error conditions: Cannot create registration data in database
* (throws SQLException) Error sending email (throws MessagingException)
* Error reading email template (throws IOException) Authorization error
* (throws AuthorizeException)
*
*
* @param context
* DSpace context
* @param email
@@ -69,12 +69,12 @@ public class AccountManager
/**
* Email forgot password info to the given email address.
*
*
* Potential error conditions: No EPerson with that email (returns null)
* Cannot create registration data in database (throws SQLException) Error
* sending email (throws MessagingException) Error reading email template
* (throws IOException) Authorization error (throws AuthorizeException)
*
*
* @param context
* DSpace context
* @param email
@@ -93,11 +93,11 @@ public class AccountManager
* person by either the sendRegistrationInfo or sendForgotPasswordInfo
* methods.
* </p>
*
*
* <p>
* If the token is not found return null.
* </p>
*
*
* @param context
* DSpace context
* @param token
@@ -125,7 +125,7 @@ public class AccountManager
/**
* Return the e-mail address referred to by a token, or null if email
* address can't be found ignores expiration of token
*
*
* @param context
* DSpace context
* @param token
@@ -153,7 +153,7 @@ public class AccountManager
/**
* Delete token.
*
*
* @param context
* DSpace context
* @param token
@@ -171,16 +171,16 @@ public class AccountManager
/*
* THIS IS AN INTERNAL METHOD. THE SEND PARAMETER ALLOWS IT TO BE USED FOR
* TESTING PURPOSES.
*
*
* Send an info to the EPerson with the given email address. If isRegister
* is TRUE, this is registration email; otherwise, it is forgot-password
* email. If send is TRUE, the email is sent; otherwise it is skipped.
*
*
* Potential error conditions: No EPerson with that email (returns null)
* Cannot create registration data in database (throws SQLException) Error
* sending email (throws MessagingException) Error reading email template
* (throws IOException) Authorization error (throws AuthorizeException)
*
*
* @param context DSpace context @param email Email address to send the
* forgot-password email to @param isRegister If true, this is for
* registration; otherwise, it is for forgot-password @param send If true,
@@ -227,10 +227,10 @@ public class AccountManager
/**
* Send a DSpace message to the given email address.
*
*
* If isRegister is <code>true</code>, this is registration email;
* otherwise, it is a forgot-password email.
*
*
* @param email
* The email address to mail to
* @param isRegister
@@ -255,7 +255,7 @@ public class AccountManager
.append("token=").append(rd.getStringColumn("token"))
.toString();
Locale locale = context.getCurrentLocale();
Email bean = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, isRegister ? "register"
Email bean = Email.getEmail(I18nUtil.getEmailFilename(locale, isRegister ? "register"
: "change_password"));
bean.addRecipient(email);
bean.addArgument(specialLink);

View File

@@ -905,7 +905,7 @@ public class EPerson extends DSpaceObject
/**
* Return the EPerson's password hash.
*
* @return hash of the password
* @return hash of the password, or null on failure (such as no password).
*/
public PasswordHash getPasswordHash()
{

View File

@@ -72,7 +72,7 @@ public class EPersonConsumer implements Consumer
try
{
EPerson eperson = EPerson.find(context, id);
Email adminEmail = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "registration_notify"));
Email adminEmail = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "registration_notify"));
adminEmail.addRecipient(notifyRecipient);
adminEmail.addArgument(ConfigurationManager.getProperty("dspace.name"));
@@ -80,7 +80,7 @@ public class EPersonConsumer implements Consumer
adminEmail.addArgument(eperson.getFirstName() + " " + eperson.getLastName()); // Name
adminEmail.addArgument(eperson.getEmail());
adminEmail.addArgument(new Date());
adminEmail.setReplyTo(eperson.getEmail());
adminEmail.send();

View File

@@ -48,7 +48,7 @@ import org.dspace.storage.rdbms.TableRowIterator;
/**
* Class defining methods for sending new item e-mail alerts to users
*
*
* @author Robert Tansley
* @version $Revision$
*/
@@ -60,7 +60,7 @@ public class Subscribe
/**
* Subscribe an e-person to a collection. An e-mail will be sent every day a
* new item appears in the collection.
*
*
* @param context
* DSpace context
* @param eperson
@@ -76,10 +76,10 @@ public class Subscribe
|| ((context.getCurrentUser() != null) && (context
.getCurrentUser().getID() == eperson.getID())))
{
// already subscribed?
// already subscribed?
TableRowIterator r = DatabaseManager.query(context,
"SELECT * FROM subscription WHERE eperson_id= ? " +
" AND collection_id= ? ",
" AND collection_id= ? ",
eperson.getID(),collection.getID());
try
@@ -117,7 +117,7 @@ public class Subscribe
* Unsubscribe an e-person to a collection. Passing in <code>null</code>
* for the collection unsubscribes the e-person from all collections they
* are subscribed to.
*
*
* @param context
* DSpace context
* @param eperson
@@ -141,10 +141,10 @@ public class Subscribe
eperson.getID());
}
else
{
{
DatabaseManager.updateQuery(context,
"DELETE FROM subscription WHERE eperson_id= ? " +
"AND collection_id= ? ",
"AND collection_id= ? ",
eperson.getID(),collection.getID());
log.info(LogManager.getHeader(context, "unsubscribe",
@@ -161,7 +161,7 @@ public class Subscribe
/**
* Find out which collections an e-person is subscribed to
*
*
* @param context
* DSpace context
* @param eperson
@@ -195,7 +195,7 @@ public class Subscribe
tri.close();
}
}
Collection[] collArray = new Collection[collections.size()];
return (Collection[]) collections.toArray(collArray);
@@ -203,7 +203,7 @@ public class Subscribe
/**
* Is that e-person subscribed to that collection?
*
*
* @param context
* DSpace context
* @param eperson
@@ -217,7 +217,7 @@ public class Subscribe
{
TableRowIterator tri = DatabaseManager.query(context,
"SELECT * FROM subscription WHERE eperson_id= ? " +
"AND collection_id= ? ",
"AND collection_id= ? ",
eperson.getID(),collection.getID());
try
@@ -246,10 +246,10 @@ public class Subscribe
* <P>
* For example, if today's date is 2002-10-10 (in UTC) items made available
* during 2002-10-09 (UTC) will be included.
*
*
* @param context
* DSpace context object
* @param test
* @param test
*/
public static void processDaily(Context context, boolean test) throws SQLException,
IOException
@@ -306,7 +306,7 @@ public class Subscribe
tri.close();
}
}
// Process the last person
if (currentEPerson != null)
{
@@ -327,36 +327,36 @@ public class Subscribe
* Sends an email to the given e-person with details of new items in the
* given collections, items that appeared yesterday. No e-mail is sent if
* there aren't any new items in any of the collections.
*
*
* @param context
* DSpace context object
* @param eperson
* eperson to send to
* @param collections
* List of collection IDs (Integers)
* @param test
* @param test
*/
public static void sendEmail(Context context, EPerson eperson,
List<Collection> collections, boolean test) throws IOException, MessagingException,
SQLException
{
// Get a resource bundle according to the eperson language preferences
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
ResourceBundle labels = ResourceBundle.getBundle("Messages", supportedLocale);
// Get the start and end dates for yesterday
// The date should reflect the timezone as well. Otherwise we stand to lose that information
// The date should reflect the timezone as well. Otherwise we stand to lose that information
// in truncation and roll to an earlier date than intended.
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
cal.setTime(new Date());
// What we actually want to pass to Harvest is "Midnight of yesterday in my current timezone"
// Truncation will actually pass in "Midnight of yesterday in UTC", which will be,
// at least in CDT, "7pm, the day before yesterday, in my current timezone".
cal.add(Calendar.HOUR, -24);
Date thisTimeYesterday = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
@@ -374,7 +374,7 @@ public class Subscribe
try {
boolean includeAll = ConfigurationManager.getBooleanProperty("harvest.includerestricted.subscription", true);
// we harvest all the changed item from yesterday until now
List<HarvestedItemInfo> itemInfos = Harvest.harvest(context, c, new DCDate(midnightYesterday).toString(), null, 0, // Limit
// and
@@ -386,7 +386,7 @@ public class Subscribe
false, // But not containers
false, // Or withdrawals
includeAll);
if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false))
{
// get only the items archived yesterday
@@ -394,7 +394,7 @@ public class Subscribe
}
else
{
// strip out the item archived today or
// strip out the item archived today or
// not archived yesterday and modified today
itemInfos = filterOutToday(itemInfos);
}
@@ -411,19 +411,19 @@ public class Subscribe
{
isFirst = false;
}
emailText.append(labels.getString("org.dspace.eperson.Subscribe.new-items")).append(" ").append(
c.getMetadata("name")).append(": ").append(
itemInfos.size()).append("\n\n");
for (int j = 0; j < itemInfos.size(); j++)
{
HarvestedItemInfo hii = (HarvestedItemInfo) itemInfos
.get(j);
DCValue[] titles = hii.item.getDC("title", null, Item.ANY);
emailText.append(" ").append(labels.getString("org.dspace.eperson.Subscribe.title")).append(" ");
if (titles.length > 0)
{
emailText.append(titles[0].value);
@@ -432,22 +432,22 @@ public class Subscribe
{
emailText.append(labels.getString("org.dspace.eperson.Subscribe.untitled"));
}
DCValue[] authors = hii.item.getDC("contributor", Item.ANY,
Item.ANY);
if (authors.length > 0)
{
emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.authors")).append(" ").append(
authors[0].value);
for (int k = 1; k < authors.length; k++)
{
emailText.append("\n ").append(
authors[k].value);
}
}
emailText.append("\n ").append(labels.getString("org.dspace.eperson.Subscribe.id")).append(" ").append(
HandleManager.getCanonicalForm(hii.handle)).append(
"\n\n");
@@ -463,47 +463,47 @@ public class Subscribe
// Send an e-mail if there were any new items
if (emailText.length() > 0)
{
if(test)
{
log.info(LogManager.getHeader(context, "subscription:", "eperson=" + eperson.getEmail() ));
log.info(LogManager.getHeader(context, "subscription:", "text=" + emailText.toString() ));
} else {
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "subscription"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "subscription"));
email.addRecipient(eperson.getEmail());
email.addArgument(emailText.toString());
email.send();
log.info(LogManager.getHeader(context, "sent_subscription", "eperson_id=" + eperson.getID() ));
}
}
}
/**
* Method for invoking subscriptions via the command line
*
*
* @param argv
* command-line arguments, none used yet
*/
public static void main(String[] argv)
public static void main(String[] argv)
{
String usage = "org.dspace.eperson.Subscribe [-t] or nothing to send out subscriptions.";
Options options = new Options();
HelpFormatter formatter = new HelpFormatter();
CommandLine line = null;
{
Option opt = new Option("t", "test", false, "Run test session");
opt.setRequired(false);
options.addOption(opt);
}
{
Option opt = new Option("h", "help", false, "Print this help message");
opt.setRequired(false);
@@ -527,14 +527,14 @@ public class Subscribe
formatter.printHelp(usage, options);
System.exit(1);
}
boolean test = line.hasOption("t");
if(test)
{
log.setLevel(Level.DEBUG);
}
Context context = null;
try
@@ -556,7 +556,7 @@ public class Subscribe
}
}
}
private static List<HarvestedItemInfo> filterOutToday(List<HarvestedItemInfo> completeList)
{
log.debug("Filtering out all today item to leave new items list size="
@@ -614,7 +614,7 @@ public class Subscribe
}
else
{
// the item has been modified yesterday...
// the item has been modified yesterday...
filteredList.add(infoObject);
}
}
@@ -632,11 +632,11 @@ public class Subscribe
Date thisTimeYesterday = new Date(System.currentTimeMillis()
- (24 * 60 * 60 * 1000));
String yesterday = sdf.format(thisTimeYesterday);
for (HarvestedItemInfo infoObject : completeList)
{
DCValue[] dateAccArr = infoObject.item.getMetadata("dc", "date", "accessioned", Item.ANY);
if (dateAccArr != null && dateAccArr.length > 0)
{
for(DCValue date : dateAccArr)
@@ -656,9 +656,9 @@ public class Subscribe
}
}
}
}
else
{

File diff suppressed because it is too large Load Diff

View File

@@ -88,9 +88,19 @@ public class IdentifierServiceImpl implements IdentifierService {
//We need to commit our context because one of the providers might require the handle created above
// Next resolve all other services
boolean registered = false;
for (IdentifierProvider service : providers)
{
service.register(context, object, identifier);
if (service.supports(identifier))
{
service.register(context, object, identifier);
registered = true;
}
}
if (!registered)
{
throw new IdentifierException("Cannot register identifier: Didn't "
+ "find a provider that supports this identifier.");
}
//Update our item
object.update();

View File

@@ -10,10 +10,11 @@ package org.dspace.search;
import java.io.Reader;
import java.util.Set;
import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.PorterStemFilter;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.StopwordAnalyzerBase;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.en.PorterStemFilter;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.analysis.util.StopwordAnalyzerBase;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardFilter;
@@ -50,7 +51,7 @@ public class DSAnalyzer extends StopwordAnalyzerBase
/*
* Stop table
*/
protected final Set stopSet;
protected final CharArraySet stopSet;
/**
* Builds an analyzer
@@ -66,7 +67,7 @@ public class DSAnalyzer extends StopwordAnalyzerBase
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
final Tokenizer source = new DSTokenizer(matchVersion, reader);
TokenStream result = new StandardFilter(matchVersion, source);
result = new LowerCaseFilter(matchVersion, result);
result = new StopFilter(matchVersion, result, stopSet);
result = new PorterStemFilter(result);

View File

@@ -35,16 +35,21 @@ import org.apache.commons.cli.PosixParser;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.miscellaneous.LimitTokenCountAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.Version;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
@@ -74,18 +79,18 @@ import org.dspace.app.util.Util;
* collections, communities, etc. It is meant to either be invoked from the
* command line (see dspace/bin/index-all) or via the indexContent() methods
* within DSpace.
*
*
* As of 1.4.2 this class has new incremental update of index functionality
* and better detection of locked state thanks to Lucene 2.1 moving write.lock.
* It will attempt to attain a lock on the index in the event that an update
* is requested and will wait a maximum of 30 seconds (a worst case scenario)
* to attain the lock before giving up and logging the failure to log4j and
* to the DSpace administrator email account.
*
* to attain the lock before giving up and logging the failure to log4j and
* to the DSpace administrator email account.
*
* The Administrator can choose to run DSIndexer in a cron that
* repeats regularly, a failed attempt to index from the UI will be "caught" up
* on in that cron.
*
*
* @author Mark Diggory
* @author Graham Triggs
*/
@@ -103,7 +108,7 @@ public class DSIndexer
private static int batchFlushAfterDocuments = ConfigurationManager.getIntProperty("search.batch.documents", 20);
private static boolean batchProcessingMode = false;
static final Version luceneVersion = Version.LUCENE_35;
static final Version luceneVersion = Version.LUCENE_44;
// Class to hold the index configuration (one instance per config line)
private static class IndexConfig
@@ -127,11 +132,11 @@ public class DSIndexer
this.type = type;
}
}
private static String indexDirectory = ConfigurationManager.getProperty("search.dir");
private static int maxfieldlength = -1;
// TODO: Support for analyzers per language, or multiple indices
/** The analyzer for this DSpace instance */
private static volatile Analyzer analyzer = null;
@@ -154,13 +159,13 @@ public class DSIndexer
};
static {
// calculate maxfieldlength
if (ConfigurationManager.getProperty("search.maxfieldlength") != null)
{
maxfieldlength = ConfigurationManager.getIntProperty("search.maxfieldlength");
}
// read in indexes from the config
ArrayList<String> indexConfigList = new ArrayList<String>();
@@ -169,24 +174,24 @@ public class DSIndexer
{
indexConfigList.add(ConfigurationManager.getProperty("search.index." + i));
}
if (indexConfigList.size() > 0)
{
indexConfigArr = new IndexConfig[indexConfigList.size()];
for (int i = 0; i < indexConfigList.size(); i++)
{
indexConfigArr[i] = new IndexConfig();
String index = indexConfigList.get(i);
String[] configLine = index.split(":");
indexConfigArr[i].indexName = configLine[0];
// Get the schema, element and qualifier for the index
// TODO: Should check valid schema, element, qualifier?
String[] parts = configLine[1].split("\\.");
switch (parts.length)
{
case 3:
@@ -208,7 +213,7 @@ public class DSIndexer
}
}
}
/*
* Increase the default write lock so that Indexing can be interrupted.
*/
@@ -219,7 +224,7 @@ public class DSIndexer
*/
try
{
if (!IndexReader.indexExists(FSDirectory.open(new File(indexDirectory))))
if (!DirectoryReader.indexExists(FSDirectory.open(new File(indexDirectory))))
{
if (!new File(indexDirectory).mkdirs())
@@ -246,10 +251,10 @@ public class DSIndexer
/**
* If the handle for the "dso" already exists in the index, and
* the "dso" has a lastModified timestamp that is newer than
* the document in the index then it is updated, otherwise a
* the "dso" has a lastModified timestamp that is newer than
* the document in the index then it is updated, otherwise a
* new document is added.
*
*
* @param context Users Context
* @param dso DSpace Object (Item, Collection or Community
* @throws SQLException
@@ -261,10 +266,10 @@ public class DSIndexer
}
/**
* If the handle for the "dso" already exists in the index, and
* the "dso" has a lastModified timestamp that is newer than
* the document in the index then it is updated, otherwise a
* the "dso" has a lastModified timestamp that is newer than
* the document in the index then it is updated, otherwise a
* new document is added.
*
*
* @param context Users Context
* @param dso DSpace Object (Item, Collection or Community
* @param force Force update even if not stale.
@@ -290,7 +295,7 @@ public class DSIndexer
/**
* unIndex removes an Item, Collection, or Community only works if the
* DSpaceObject has a handle (uses the handle for its unique ID)
*
*
* @param context DSpace context
* @param dso DSpace Object, can be Community, Item, or Collection
* @throws SQLException
@@ -311,9 +316,9 @@ public class DSIndexer
/**
* Unindex a Document in the Lucene Index.
*
*
* @param context
* @param handle
* @param handle
* @throws SQLException
* @throws IOException
*/
@@ -336,7 +341,7 @@ public class DSIndexer
// handle!");
}
}
/**
* reIndexContent removes something from the index, then re-indexes it
*
@@ -356,10 +361,10 @@ public class DSIndexer
emailException(exception);
}
}
/**
* create full index - wiping old index
*
*
* @param c context to use
*/
public static void createIndex(Context c) throws SQLException, IOException
@@ -367,15 +372,15 @@ public class DSIndexer
/* Create a new index, blowing away the old. */
openIndex(true).close();
/* Reindex all content preemptively. */
DSIndexer.updateIndex(c, true);
}
/**
* Optimize the existing index. Important to do regularly to reduce
* Optimize the existing index. Important to do regularly to reduce
* filehandle usage and keep performance fast!
*
*
* @param c Users Context
* @throws SQLException
* @throws IOException
@@ -387,7 +392,11 @@ public class DSIndexer
try
{
flushIndexingTaskQueue(writer);
writer.optimize();
//With lucene 4.0 this method has been deleted , as it is horribly inefficient and very
//rarely justified. Lucene's multi-segment search performance has improved
//over time, and the default TieredMergePolicy now targets segments with
//deletions. For more info see http://blog.trifork.com/2011/11/21/simon-says-optimize-is-bad-for-you/
//writer.optimize();
}
finally
{
@@ -396,13 +405,13 @@ public class DSIndexer
}
/**
* When invoked as a command-line tool, creates, updates, removes
* When invoked as a command-line tool, creates, updates, removes
* content from the whole index
*
* @param args
* the command-line arguments, none used
* @throws IOException
* @throws SQLException
* @throws IOException
* @throws SQLException
*/
public static void main(String[] args) throws SQLException, IOException
{
@@ -508,25 +517,25 @@ public class DSIndexer
* Iterates over all Items, Collections and Communities. And updates
* them in the index. Uses decaching to control memory footprint.
* Uses indexContent and isStale ot check state of item in index.
*
*
* @param context
*/
public static void updateIndex(Context context) {
updateIndex(context,false);
}
/**
* Iterates over all Items, Collections and Communities. And updates
* them in the index. Uses decaching to control memory footprint.
* Uses indexContent and isStale to check state of item in index.
*
*
* At first it may appear counterintuitive to have an IndexWriter/Reader
* opened and closed on each DSO. But this allows the UI processes
* to step in and attain a lock and write to the index even if other
* processes/jvms are running a reindex.
*
*
* @param context
* @param force
* @param force
*/
public static void updateIndex(Context context, boolean force) {
try
@@ -568,24 +577,30 @@ public class DSIndexer
log.error(e.getMessage(), e);
}
}
/**
* Iterates over all documents in the Lucene index and verifies they
* Iterates over all documents in the Lucene index and verifies they
* are in database, if not, they are removed.
*
*
* @param context
* @throws IOException
* @throws SQLException
* @throws IOException
* @throws SQLException
*/
public static void cleanIndex(Context context) throws IOException, SQLException {
IndexReader reader = DSQuery.getIndexReader();
Bits liveDocs = MultiFields.getLiveDocs(reader);
for(int i = 0 ; i < reader.numDocs(); i++)
{
if(!reader.isDeleted(i))
{
Document doc = reader.document(i);
if (!liveDocs.get(i))
{
// document is deleted...
log.debug("Encountered deleted doc: " + i);
}
else {
Document doc = reader.document(i);
String handle = doc.get("handle");
if (!StringUtils.isEmpty(handle))
{
@@ -603,14 +618,10 @@ public class DSIndexer
log.debug("Keeping: " + handle);
}
}
}
else
{
log.debug("Encountered deleted doc: " + i);
}
}
}
}
/**
* Get the Lucene analyzer to use according to current configuration (or
* default). TODO: Should have multiple analyzers (and maybe indices?) for
@@ -843,8 +854,8 @@ public class DSIndexer
String recipient = ConfigurationManager
.getProperty("alert.recipient");
if (recipient != null) {
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "internal_error"));
if (StringUtils.isNotBlank(recipient)) {
Email email = Email.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "internal_error"));
email.addRecipient(recipient);
email.addArgument(ConfigurationManager
.getProperty("dspace.url"));
@@ -871,11 +882,11 @@ public class DSIndexer
}
}
/**
* Is stale checks the lastModified time stamp in the database and the index
* to determine if the index is stale.
*
*
* @param lastModified
* @throws SQLException
* @throws IOException
@@ -883,28 +894,32 @@ public class DSIndexer
private static boolean requiresIndexing(Term t, Date lastModified)
throws SQLException, IOException
{
boolean reindexItem = false;
boolean inIndex = false;
IndexReader ir = DSQuery.getIndexReader();
TermDocs docs = ir.termDocs(t);
while(docs.next())
{
inIndex = true;
int id = docs.doc();
Document doc = ir.document(id);
Bits liveDocs = MultiFields.getLiveDocs(ir);
DocsEnum docs = MultiFields.getTermDocsEnum(ir, liveDocs, t.field(), t.bytes());
Field lastIndexed = doc.getField(LAST_INDEXED_FIELD);
int id;
if (docs != null)
{
while ((id = docs.nextDoc()) != DocsEnum.NO_MORE_DOCS)
{
inIndex = true;
Document doc = ir.document(id);
if (lastIndexed == null || Long.parseLong(lastIndexed.stringValue()) <
lastModified.getTime()) {
reindexItem = true;
}
}
IndexableField lastIndexed = doc.getField(LAST_INDEXED_FIELD);
if (lastIndexed == null
|| Long.parseLong(lastIndexed.stringValue()) < lastModified
.getTime())
{
reindexItem = true;
}
}
}
return reindexItem || !inIndex;
}
@@ -915,7 +930,20 @@ public class DSIndexer
throws IOException
{
Directory dir = FSDirectory.open(new File(indexDirectory));
IndexWriterConfig iwc = new IndexWriterConfig(luceneVersion, getAnalyzer());
LimitTokenCountAnalyzer decoratorAnalyzer = null;
/* Set maximum number of terms to index if present in dspace.cfg */
if (maxfieldlength == -1)
{
decoratorAnalyzer = new LimitTokenCountAnalyzer(getAnalyzer(), Integer.MAX_VALUE);
}
else
{
decoratorAnalyzer = new LimitTokenCountAnalyzer(getAnalyzer(), maxfieldlength);
}
IndexWriterConfig iwc = new IndexWriterConfig(luceneVersion, decoratorAnalyzer);
if(wipeExisting){
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
}else{
@@ -924,16 +952,6 @@ public class DSIndexer
IndexWriter writer = new IndexWriter(dir, iwc);
/* Set maximum number of terms to index if present in dspace.cfg */
if (maxfieldlength == -1)
{
writer.setMaxFieldLength(Integer.MAX_VALUE);
}
else
{
writer.setMaxFieldLength(maxfieldlength);
}
return writer;
}
@@ -1069,7 +1087,7 @@ public class DSIndexer
mydc = item.getMetadata(indexConfigArr[i].schema, indexConfigArr[i].element, indexConfigArr[i].qualifier, Item.ANY);
}
//Index the controlled vocabularies localized display values for all localized input-forms.xml (e.g. input-forms_el.xml)
if ("inputform".equalsIgnoreCase(indexConfigArr[i].type)){
@@ -1110,7 +1128,7 @@ public class DSIndexer
}
for (j = 0; j < mydc.length; j++)
{
if (!StringUtils.isEmpty(mydc[j].value))
@@ -1389,7 +1407,7 @@ public class DSIndexer
/**
* Helper function to retrieve a date using a best guess of the potential date encodings on a field
*
*
* @param t
* @return
*/
@@ -1441,7 +1459,7 @@ public class DSIndexer
log.error("Unable to parse date format", pe);
}
}
return null;
}

View File

@@ -9,8 +9,8 @@ package org.dspace.search;
import java.io.Reader;
import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardFilter;

View File

@@ -16,10 +16,11 @@ import java.util.List;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.TokenMgrError;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.classic.TokenMgrError;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
@@ -221,16 +222,16 @@ public class DSQuery
if (args.getSortOption() == null)
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", SortField.INT, true),
new SortField(null, SortField.SCORE, SortOption.ASCENDING.equals(args.getSortOrder()))
new SortField("search.resourcetype", SortField.Type.INT, true),
new SortField(null, SortField.FIELD_SCORE.getType(), SortOption.ASCENDING.equals(args.getSortOrder()))
};
hits = searcher.search(myquery, max, new Sort(sortFields));
}
else
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", SortField.INT, true),
new SortField("sort_" + args.getSortOption().getName(), SortField.STRING, SortOption.DESCENDING.equals(args.getSortOrder())),
new SortField("search.resourcetype", SortField.Type.INT, true),
new SortField("sort_" + args.getSortOption().getName(), SortField.Type.STRING, SortOption.DESCENDING.equals(args.getSortOrder())),
SortField.FIELD_SCORE
};
hits = searcher.search(myquery, max, new Sort(sortFields));
@@ -396,7 +397,7 @@ public class DSQuery
{
try
{
searcher.close();
searcher.getIndexReader().close();
searcher = null;
}
catch (IOException ioe)
@@ -439,13 +440,13 @@ public class DSQuery
// If it has, we need to close the existing searcher - we will open a new one later
Directory searchDir = FSDirectory.open(new File(indexDir));
if (searcher != null && lastModified != IndexReader.getCurrentVersion(searchDir))
DirectoryReader reader = DirectoryReader.open(searchDir);
if (searcher != null && lastModified != reader.getVersion())
{
try
{
// Close the cached IndexSearcher
searcher.close();
searcher.getIndexReader().close();
}
catch (IOException ioe)
{
@@ -462,30 +463,11 @@ public class DSQuery
// There is no existing searcher - either this is the first execution,
// or the index has been updated and we closed the old index.
if (searcher == null)
{
{
// So, open a new searcher
lastModified = IndexReader.getCurrentVersion(searchDir);
String osName = System.getProperty("os.name");
if (osName != null && osName.toLowerCase().contains("windows"))
{
searcher = new IndexSearcher(searchDir){
/*
* TODO: Has Lucene fixed this bug yet?
* Lucene doesn't release read locks in
* windows properly on finalize. Our hack
* extend IndexSearcher to force close().
*/
@Override
protected void finalize() throws Throwable {
this.close();
super.finalize();
}
};
}
else
{
searcher = new IndexSearcher(searchDir);
}
lastModified = reader.getVersion();
searcher = new IndexSearcher(reader);
}
return searcher;

View File

@@ -9,7 +9,7 @@ package org.dspace.search;
import java.io.Reader;
import org.apache.lucene.analysis.CharTokenizer;
import org.apache.lucene.analysis.util.CharTokenizer;
import org.apache.lucene.util.Version;
/**

View File

@@ -22,12 +22,14 @@ import org.dspace.statistics.util.DnsLookup;
import org.dspace.statistics.util.LocationUtils;
import org.dspace.statistics.util.SpiderDetector;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.exists.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.client.action.index.IndexRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
@@ -242,7 +244,7 @@ public class ElasticSearchLogger {
putMappingRequestBuilder.setSource(stringMappingJSON);
PutMappingResponse response = putMappingRequestBuilder.execute().actionGet();
if(!response.getAcknowledged()) {
if(!response.isAcknowledged()) {
log.info("Could not define mapping for type ["+indexName+"]/["+indexType+"]");
} else {
log.info("Successfully put mapping for ["+indexName+"]/["+indexType+"]");

View File

@@ -24,7 +24,7 @@ import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.request.CoreAdminRequest;
@@ -70,7 +70,7 @@ public class SolrLogger
{
private static final Logger log = Logger.getLogger(SolrLogger.class);
private static final CommonsHttpSolrServer solr;
private static final HttpSolrServer solr;
public static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
@@ -105,13 +105,13 @@ public class SolrLogger
log.info("solr-statistics.server:" + ConfigurationManager.getProperty("solr-statistics", "server"));
log.info("usage-statistics.dbfile:" + ConfigurationManager.getProperty("usage-statistics", "dbfile"));
CommonsHttpSolrServer server = null;
HttpSolrServer server = null;
if (ConfigurationManager.getProperty("solr-statistics", "server") != null)
{
try
{
server = new CommonsHttpSolrServer(ConfigurationManager.getProperty("solr-statistics", "server"));
server = new HttpSolrServer(ConfigurationManager.getProperty("solr-statistics", "server"));
SolrQuery solrQuery = new SolrQuery()
.setQuery("type:2 AND id:1");
server.query(solrQuery);
@@ -1213,7 +1213,7 @@ public class SolrLogger
//Start by creating a new core
String coreName = "statistics-" + dcStart.getYear();
CommonsHttpSolrServer statisticsYearServer = createCore(solr, coreName);
HttpSolrServer statisticsYearServer = createCore(solr, coreName);
System.out.println("Moving: " + totalRecords + " into core " + coreName);
log.info("Moving: " + totalRecords + " records into core " + coreName);
@@ -1240,7 +1240,7 @@ public class SolrLogger
ContentStreamUpdateRequest contentStreamUpdateRequest = new ContentStreamUpdateRequest("/update/csv");
contentStreamUpdateRequest.setParam("stream.contentType", "text/plain;charset=utf-8");
contentStreamUpdateRequest.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
contentStreamUpdateRequest.addFile(tempCsv);
contentStreamUpdateRequest.addFile(tempCsv, "text/plain;charset=utf-8");
statisticsYearServer.request(contentStreamUpdateRequest);
}
@@ -1257,17 +1257,17 @@ public class SolrLogger
FileUtils.deleteDirectory(tempDirectory);
}
private static CommonsHttpSolrServer createCore(CommonsHttpSolrServer solr, String coreName) throws IOException, SolrServerException {
private static HttpSolrServer createCore(HttpSolrServer solr, String coreName) throws IOException, SolrServerException {
String solrDir = ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr" +File.separator;
String baseSolrUrl = solr.getBaseURL().replace("statistics", "");
CoreAdminRequest.Create create = new CoreAdminRequest.Create();
create.setCoreName(coreName);
create.setInstanceDir("statistics");
create.setDataDir(solrDir + coreName + File.separator + "data");
CommonsHttpSolrServer solrServer = new CommonsHttpSolrServer(baseSolrUrl);
HttpSolrServer solrServer = new HttpSolrServer(baseSolrUrl);
create.process(solrServer);
log.info("Created core with name: " + coreName);
return new CommonsHttpSolrServer(baseSolrUrl + "/" + coreName);
return new HttpSolrServer(baseSolrUrl + "/" + coreName);
}
@@ -1378,7 +1378,7 @@ public class SolrLogger
ContentStreamUpdateRequest contentStreamUpdateRequest = new ContentStreamUpdateRequest("/update/csv");
contentStreamUpdateRequest.setParam("stream.contentType", "text/plain;charset=utf-8");
contentStreamUpdateRequest.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
contentStreamUpdateRequest.addFile(tempCsv);
contentStreamUpdateRequest.addFile(tempCsv, "text/plain;charset=utf-8");
solr.request(contentStreamUpdateRequest);
}

View File

@@ -80,7 +80,7 @@ public class ApacheLogRobotsProcessor {
if (spiderIpFile.exists())
{
logSpiders = SpiderDetector.readIpAddresses(spiderIpFile);
logSpiders = SpiderDetector.readPatterns(spiderIpFile);
}
else
{

View File

@@ -14,12 +14,20 @@ import java.io.IOException;
/**
* XBill DNS resolver to retrieve hostnames for client IP addresses.
* TODO: deal with IPv6 addresses.
*
* @author kevinvandevelde at atmire.com
* @author ben at atmire.com
*/
public class DnsLookup {
/**
* Resolve an IP address to a host name.
*
* @param hostIp dotted decimal IPv4 address.
* @return name if resolved, or the address.
* @throws IOException from infrastructure.
*/
public static String reverseDns(String hostIp) throws IOException {
Resolver res = new ExtendedResolver();
@@ -44,4 +52,45 @@ public class DnsLookup {
return answers[0].rdataToString();
}
}
/**
* Resolve a host name to an IPv4 address.
* @throws IOException from infrastructure or no resolution.
*/
public static String forward(String hostname)
throws IOException
{
Resolver res = new ExtendedResolver();
int timeout = ConfigurationManager.getIntProperty("usage-statistics",
"resolver.timeout", 200);
res.setTimeout(0, timeout);
Name name = Name.fromString(hostname, Name.root);
Record rec = Record.newRecord(name, Type.A, DClass.IN);
Message query = Message.newQuery(rec);
Message response = res.send(query);
Record[] answers = response.getSectionArray(Section.ANSWER);
if (answers.length == 0)
{
throw new IOException("Unresolvable host name (empty response)");
}
String resolution = null;
for (Record answer : answers)
{
if (answer.getType() == Type.A)
{
resolution = answer.rdataToString();
break;
}
}
if (null == resolution)
{
throw new IOException("Unresolvable host name (no A record)");
}
return resolution;
}
}

View File

@@ -7,20 +7,23 @@
*/
package org.dspace.statistics.util;
import org.apache.log4j.Logger;
import org.dspace.core.ConfigurationManager;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.dspace.core.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* SpiderDetector is used to find IP's that are spiders...
* In future someone may add UserAgents and Host Domains
* In future someone may add Host Domains
* to the detection criteria here.
*
* @author kevinvandevelde at atmire.com
@@ -29,7 +32,7 @@ import java.util.Set;
*/
public class SpiderDetector {
private static Logger log = Logger.getLogger(SpiderDetector.class);
private static Logger log = LoggerFactory.getLogger(SpiderDetector.class);
private static Boolean useProxies;
@@ -38,34 +41,38 @@ public class SpiderDetector {
*/
private static IPTable table = null;
/** Collection of regular expressions to match known spiders' agents. */
private static List<Pattern> agents = new ArrayList<Pattern>();
/** Collection of regular expressions to match known spiders' domain names. */
private static List<Pattern> domains = new ArrayList<Pattern>();
/**
* Utility method which Reads the ip addresses out a file & returns them in a Set
* Utility method which reads lines from a file & returns them in a Set.
*
* @param spiderIpFile the location of our spider file
* @return a vector full of ip's
* @param patternFile the location of our spider file
* @return a vector full of patterns
* @throws IOException could not happen since we check the file be4 we use it
*/
public static Set<String> readIpAddresses(File spiderIpFile) throws IOException {
Set<String> ips = new HashSet<String>();
public static Set<String> readPatterns(File patternFile)
throws IOException
{
Set<String> patterns = new HashSet<String>();
if (!spiderIpFile.exists() || !spiderIpFile.isFile())
if (!patternFile.exists() || !patternFile.isFile())
{
return ips;
return patterns;
}
//Read our file & get all them ip's
BufferedReader in = new BufferedReader(new FileReader(spiderIpFile));
//Read our file & get all them patterns.
BufferedReader in = new BufferedReader(new FileReader(patternFile));
String line;
while ((line = in.readLine()) != null) {
if (!line.startsWith("#")) {
line = line.trim();
if (!line.equals("") && !Character.isDigit(line.charAt(0))) {
// is a hostname
// add this functionality later...
} else if (!line.equals("")) {
ips.add(line);
// is full v4 ip (too tired to deal with v6)...
if (!line.equals("")) {
patterns.add(line);
}
} else {
// ua.add(line.replaceFirst("#","").replaceFirst("UA","").trim());
@@ -73,11 +80,13 @@ public class SpiderDetector {
}
}
in.close();
return ips;
return patterns;
}
/**
* Get an immutable Set representing all the Spider Addresses here.
* Get an immutable Set representing all the Spider Addresses here
*
* @return
*/
public static Set<String> getSpiderIpAddresses() {
@@ -86,12 +95,11 @@ public class SpiderDetector {
}
/*
private loader to populate the table from files.
* private loader to populate the table from files.
*/
private static void loadSpiderIpAddresses() {
if (table == null) {
table = new IPTable();
@@ -102,44 +110,112 @@ public class SpiderDetector {
if (spidersDir.exists() && spidersDir.isDirectory()) {
for (File file : spidersDir.listFiles()) {
for (String ip : readIpAddresses(file)) {
table.add(ip);
if (file.isFile())
{
for (String ip : readPatterns(file)) {
log.debug("Loading {}", ip);
if (!Character.isDigit(ip.charAt(0)))
{
try {
ip = DnsLookup.forward(ip);
log.debug("Resolved to {}", ip);
} catch (IOException e) {
log.warn("Not loading {}: {}", ip, e.getMessage());
continue;
}
}
table.add(ip);
}
log.info("Loaded Spider IP file: " + file);
}
log.info("Loaded Spider IP file: " + file);
}
} else {
log.info("No spider file loaded");
}
}
catch (Exception e) {
log.error("Error Loading Spiders:" + e.getMessage(), e);
}
}
}
/**
* Load agent name patterns from all files in a single subdirectory of config/spiders.
*
* @param directory simple directory name (e.g. "agents").
* "${dspace.dir}/config/spiders" will be prepended to yield the path to
* the directory of pattern files.
* @param patternList patterns read from the files in {@code directory} will
* be added to this List.
*/
private static void loadPatterns(String directory, List<Pattern> patternList)
{
String dspaceHome = ConfigurationManager.getProperty("dspace.dir");
File spidersDir = new File(dspaceHome, "config/spiders");
File patternsDir = new File(spidersDir, directory);
if (patternsDir.exists() && patternsDir.isDirectory())
{
for (File file : patternsDir.listFiles())
{
Set<String> patterns;
try
{
patterns = readPatterns(file);
} catch (IOException ex)
{
log.error("Patterns not read from {}: {}",
file.getPath(), ex.getMessage());
continue;
}
for (String pattern : patterns)
{
patternList.add(Pattern.compile(pattern));
}
log.info("Loaded pattern file: {}", file.getPath());
}
}
else
{
log.info("No patterns loaded from {}", patternsDir.getPath());
}
}
/**
* Static Service Method for testing spiders against existing spider files.
* <p/>
* In the future this will be extended to support User Agent and
* domain Name detection.
* <p/>
* <p>
* In future spiders HashSet may be optimized as byte offset array to
* improve performance and memory footprint further.
*
* @param request
* @return true|false if the request was detected to be from a spider
* @param clientIP address of the client.
* @param proxyIPs comma-list of X-Forwarded-For addresses, or null.
* @param hostname domain name of host, or null.
* @param agent User-Agent header value, or null.
* @return true if the client matches any spider characteristics list.
*/
public static boolean isSpider(HttpServletRequest request) {
public static boolean isSpider(String clientIP, String proxyIPs,
String hostname, String agent)
{
// See if any agent patterns match
if (null != agent)
{
if (agents.isEmpty())
loadPatterns("agents", agents);
if (isUseProxies() && request.getHeader("X-Forwarded-For") != null) {
for (Pattern candidate : agents)
{
if (candidate.matcher(agent).find())
{
return true;
}
}
}
// No. See if any IP addresses match
if (isUseProxies() && proxyIPs != null) {
/* This header is a comma delimited list */
for (String xfip : request.getHeader("X-Forwarded-For").split(",")) {
for (String xfip : proxyIPs.split(",")) {
if (isSpider(xfip))
{
return true;
@@ -147,8 +223,42 @@ public class SpiderDetector {
}
}
return isSpider(request.getRemoteAddr());
if (isSpider(clientIP))
return true;
// No. See if any DNS names match
if (null != hostname)
{
if (domains.isEmpty())
{
loadPatterns("domains", domains);
}
for (Pattern candidate : domains)
{
if (candidate.matcher(hostname).find())
{
return true;
}
}
}
// Not a known spider.
return false;
}
/**
* Static Service Method for testing spiders against existing spider files.
*
* @param request
* @return true|false if the request was detected to be from a spider.
*/
public static boolean isSpider(HttpServletRequest request)
{
return isSpider(request.getRemoteAddr(),
request.getHeader("X-Forwarded-For"),
request.getRemoteHost(),
request.getHeader("User-Agent"));
}
/**
@@ -191,5 +301,4 @@ public class SpiderDetector {
return useProxies;
}
}

View File

@@ -10,7 +10,7 @@ package org.dspace.statistics.util;
import org.apache.commons.cli.*;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.core.ConfigurationManager;
@@ -191,7 +191,7 @@ public class StatisticsDataGenerator {
// We got all our parameters now get the rest
Context context = new Context();
// Find our solr server
CommonsHttpSolrServer solr = new CommonsHttpSolrServer(
HttpSolrServer solr = new HttpSolrServer(
ConfigurationManager.getProperty("solr-statistics", "server"));
solr.deleteByQuery("*:*");
solr.commit();

View File

@@ -11,7 +11,7 @@ import org.apache.commons.cli.*;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.dspace.content.*;
import org.dspace.content.Collection;
@@ -41,7 +41,7 @@ public class StatisticsImporter
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
/** Solr server connection */
private static CommonsHttpSolrServer solr;
private static HttpSolrServer solr;
/** GEOIP lookup service */
private static LookupService geoipLookup;
@@ -467,7 +467,7 @@ public class StatisticsImporter
{
System.out.println("Writing to solr server at: " + sserver);
}
solr = new CommonsHttpSolrServer(sserver);
solr = new HttpSolrServer(sserver);
metadataStorageInfo = SolrLogger.getMetadataStorageInfo();
String dbfile = ConfigurationManager.getProperty("usage-statistics", "dbfile");

View File

@@ -21,12 +21,14 @@ import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.statistics.ElasticSearchLogger;
import org.dspace.statistics.SolrLogger;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.action.bulk.BulkRequestBuilder;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.mapper.geo.GeoPoint;
import java.io.*;
import java.text.DecimalFormat;

View File

@@ -0,0 +1,15 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
/**
* Mostly classes for dealing with detection of spiders, and command line tools.
* <p>
* One can find a database of User-Agent strings classified as clients, bots,
* etc. at <a href='http://www.user-agents.org/'>www.user-agents.org</a>.
*/
package org.dspace.statistics.util;

View File

@@ -153,12 +153,17 @@ public class AccessStep extends AbstractProcessingStep
// if arrive here Next, Previous or Save has been pressed
boolean isAdvancedFormEnabled= ConfigurationManager.getBooleanProperty("xmlui.submission.restrictstep.enableAdvancedForm", false);
boolean isAdvancedFormEnabled= ConfigurationManager.getBooleanProperty("webui.submission.restrictstep.enableAdvancedForm", false);
// if it is a simple form we should create the policy for Anonymous
// if Anonymous does not have right on this collection, create policies for any other groups with
// DEFAULT_ITEM_READ specified.
if(!isAdvancedFormEnabled){
int result = checkForm(request);
if (result != 0)
{
return result;
}
AuthorizeManager.generateAutomaticPolicies(context, getEmbargoUntilDate(request), reason, item, (Collection)HandleManager.resolveToObject(context, subInfo.getCollectionHandle()));
}
// else{

View File

@@ -95,7 +95,7 @@ public class UploadStep extends AbstractProcessingStep
private static Logger log = Logger.getLogger(UploadStep.class);
/** is the upload required? */
private boolean fileRequired = ConfigurationManager.getBooleanProperty("webui.submit.upload.required", true);
protected boolean fileRequired = ConfigurationManager.getBooleanProperty("webui.submit.upload.required", true);
/**
* Do any processing of the information input by the user, and/or perform
@@ -316,7 +316,8 @@ public class UploadStep extends AbstractProcessingStep
// files have been uploaded.
// ---------------------------------------------------
//check if a file is required to be uploaded
if (fileRequired && !item.hasUploadedFiles())
if (fileRequired && !item.hasUploadedFiles()
&& !buttonPressed.equals(SUBMIT_MORE_BUTTON))
{
return STATUS_NO_FILES_ERROR;
}
@@ -470,7 +471,7 @@ public class UploadStep extends AbstractProcessingStep
String fileDescription = (String) request.getAttribute(param + "-description");
if(fileDescription==null ||fileDescription.length()==0)
{
request.getParameter("description");
fileDescription = request.getParameter("description");
}
// if information wasn't passed by User Interface, we had a problem
@@ -584,7 +585,7 @@ public class UploadStep extends AbstractProcessingStep
/*
If we created a new Bitstream but now realised there is a problem then remove it.
*/
private void backoutBitstream(SubmissionInfo subInfo, Bitstream b, Item item) throws SQLException, AuthorizeException, IOException
protected void backoutBitstream(SubmissionInfo subInfo, Bitstream b, Item item) throws SQLException, AuthorizeException, IOException
{
// remove bitstream from bundle..
// delete bundle if it's now empty

View File

@@ -30,11 +30,10 @@ import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.curate.Curator;
import org.dspace.handle.HandleManager;
import org.dspace.submit.AbstractProcessingStep;
/**
* Upload step for DSpace. Processes the actual upload of files
* for an item being submitted into DSpace.
* Upload step with the advanced embargo system for DSpace. Processes the actual
* upload of files for an item being submitted into DSpace.
* <P>
* This class performs all the behind-the-scenes processing that
* this particular step requires. This class's methods are utilized
@@ -42,57 +41,15 @@ import org.dspace.submit.AbstractProcessingStep;
*
* @see org.dspace.app.util.SubmissionConfig
* @see org.dspace.app.util.SubmissionStepConfig
* @see org.dspace.submit.step.UploadStep
* @see org.dspace.submit.AbstractProcessingStep
*
* @author Tim Donohue
* @author Keiji Suzuki
* @version $Revision$
*/
public class UploadWithEmbargoStep extends AbstractProcessingStep
public class UploadWithEmbargoStep extends UploadStep
{
/** Button to upload a file * */
public static final String SUBMIT_UPLOAD_BUTTON = "submit_upload";
/** Button to skip uploading a file * */
public static final String SUBMIT_SKIP_BUTTON = "submit_skip";
/** Button to submit more files * */
public static final String SUBMIT_MORE_BUTTON = "submit_more";
/** Button to cancel editing of file info * */
public static final String CANCEL_EDIT_BUTTON = "submit_edit_cancel";
/***************************************************************************
* STATUS / ERROR FLAGS (returned by doProcessing() if an error occurs or
* additional user interaction may be required)
*
* (Do NOT use status of 0, since it corresponds to STATUS_COMPLETE flag
* defined in the JSPStepManager class)
**************************************************************************/
// integrity error occurred
public static final int STATUS_INTEGRITY_ERROR = 1;
// error in uploading file
public static final int STATUS_UPLOAD_ERROR = 2;
// error - no files uploaded!
public static final int STATUS_NO_FILES_ERROR = 5;
// format of uploaded file is unknown
public static final int STATUS_UNKNOWN_FORMAT = 10;
// virus checker unavailable ?
public static final int STATUS_VIRUS_CHECKER_UNAVAILABLE = 14;
// file failed virus check
public static final int STATUS_CONTAINS_VIRUS = 16;
// edit file information
public static final int STATUS_EDIT_BITSTREAM = 20;
// return from editing file information
public static final int STATUS_EDIT_COMPLETE = 25;
public static final int STATUS_EDIT_POLICIES = 30;
public static final int STATUS_EDIT_POLICIES_ERROR_SELECT_GROUP = 31;
@@ -103,10 +60,7 @@ public class UploadWithEmbargoStep extends AbstractProcessingStep
/** log4j logger */
private static Logger log = Logger.getLogger(UploadStep.class);
/** is the upload required? */
private boolean fileRequired = ConfigurationManager.getBooleanProperty("webui.submit.upload.required", true);
private static Logger log = Logger.getLogger(UploadWithEmbargoStep.class);
/**
* Do any processing of the information input by the user, and/or perform
@@ -345,98 +299,6 @@ public class UploadWithEmbargoStep extends AbstractProcessingStep
return STATUS_COMPLETE;
}
/**
* Retrieves the number of pages that this "step" extends over. This method
* is used to build the progress bar.
* <P>
* This method may just return 1 for most steps (since most steps consist of
* a single page). But, it should return a number greater than 1 for any
* "step" which spans across a number of HTML pages. For example, the
* configurable "Describe" step (configured using input-forms.xml) overrides
* this method to return the number of pages that are defined by its
* configuration file.
* <P>
* Steps which are non-interactive (i.e. they do not display an interface to
* the user) should return a value of 1, so that they are only processed
* once!
*
* @param request
* The HTTP Request
* @param subInfo
* The current submission information object
*
* @return the number of pages in this step
*/
public int getNumberOfPages(HttpServletRequest request,
SubmissionInfo subInfo) throws ServletException
{
// Despite using many JSPs, this step only appears
// ONCE in the Progress Bar, so it's only ONE page
return 1;
}
// ****************************************************************
// ****************************************************************
// METHODS FOR UPLOADING FILES (and associated information)
// ****************************************************************
// ****************************************************************
/**
* Remove a file from an item
*
* @param context
* current DSpace context
* @param item
* Item where file should be removed from
* @param bitstreamID
* The id of bitstream representing the file to remove
* @return Status or error flag which will be processed by
* UI-related code! (if STATUS_COMPLETE or 0 is returned,
* no errors occurred!)
*/
protected int processRemoveFile(Context context, Item item, int bitstreamID)
throws IOException, SQLException, AuthorizeException
{
Bitstream bitstream;
// Try to find bitstream
try
{
bitstream = Bitstream.find(context, bitstreamID);
}
catch (NumberFormatException nfe)
{
bitstream = null;
}
if (bitstream == null)
{
// Invalid or mangled bitstream ID
// throw an error and return immediately
return STATUS_INTEGRITY_ERROR;
}
// remove bitstream from bundle..
// delete bundle if it's now empty
Bundle[] bundles = bitstream.getBundles();
bundles[0].removeBitstream(bitstream);
Bitstream[] bitstreams = bundles[0].getBitstreams();
// remove bundle if it's now empty
if (bitstreams.length < 1)
{
item.removeBundle(bundles[0]);
item.update();
}
// no errors occurred
return STATUS_COMPLETE;
}
/**
* Process the upload of a new file!
*
@@ -611,7 +473,7 @@ public class UploadWithEmbargoStep extends AbstractProcessingStep
private void processAccessFields(Context context, HttpServletRequest request, SubmissionInfo subInfo, Bitstream b) throws SQLException, AuthorizeException {
// ResourcePolicy Management
boolean isAdvancedFormEnabled= ConfigurationManager.getBooleanProperty("xmlui.submission.restrictstep.enableAdvancedForm", false);
boolean isAdvancedFormEnabled= ConfigurationManager.getBooleanProperty("webui.submission.restrictstep.enableAdvancedForm", false);
// if it is a simple form we should create the policy for Anonymous
// if Anonymous does not have right on this collection, create policies for any other groups with
// DEFAULT_ITEM_READ specified.
@@ -628,116 +490,6 @@ public class UploadWithEmbargoStep extends AbstractProcessingStep
}
/*
If we created a new Bitstream but now realised there is a problem then remove it.
*/
private void backoutBitstream(SubmissionInfo subInfo, Bitstream b, Item item) throws SQLException, AuthorizeException, IOException
{
// remove bitstream from bundle..
// delete bundle if it's now empty
Bundle[] bnd = b.getBundles();
bnd[0].removeBitstream(b);
Bitstream[] bitstreams = bnd[0].getBitstreams();
// remove bundle if it's now empty
if (bitstreams.length < 1)
{
item.removeBundle(bnd[0]);
item.update();
}
subInfo.setBitstream(null);
}
/**
* Process input from get file type page
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*
* @return Status or error flag which will be processed by
* UI-related code! (if STATUS_COMPLETE or 0 is returned,
* no errors occurred!)
*/
protected int processSaveFileFormat(Context context,
HttpServletRequest request, HttpServletResponse response,
SubmissionInfo subInfo) throws ServletException, IOException,
SQLException, AuthorizeException
{
if (subInfo.getBitstream() != null)
{
// Did the user select a format?
int typeID = Util.getIntParameter(request, "format");
BitstreamFormat format = BitstreamFormat.find(context, typeID);
if (format != null)
{
subInfo.getBitstream().setFormat(format);
}
else
{
String userDesc = request.getParameter("format_description");
subInfo.getBitstream().setUserFormatDescription(userDesc);
}
// update database
subInfo.getBitstream().update();
}
else
{
return STATUS_INTEGRITY_ERROR;
}
return STATUS_COMPLETE;
}
/**
* Process input from the "change file description" page
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
*
* @return Status or error flag which will be processed by
* UI-related code! (if STATUS_COMPLETE or 0 is returned,
* no errors occurred!)
*/
protected int processSaveFileDescription(Context context,
HttpServletRequest request, HttpServletResponse response,
SubmissionInfo subInfo) throws ServletException, IOException,
SQLException, AuthorizeException
{
if (subInfo.getBitstream() != null)
{
subInfo.getBitstream().setDescription(
request.getParameter("description"));
subInfo.getBitstream().update();
context.commit();
}
else
{
return STATUS_INTEGRITY_ERROR;
}
return STATUS_COMPLETE;
}
private int editBitstreamPolicies(HttpServletRequest request, Context context, SubmissionInfo subInfo, String buttonPressed)
throws SQLException, AuthorizeException {

View File

@@ -46,26 +46,26 @@ import org.dspace.utils.DSpace;
/**
* Workflow state machine
*
*
* Notes:
*
*
* Determining item status from the database:
*
*
* When an item has not been submitted yet, it is in the user's personal
* workspace (there is a row in PersonalWorkspace pointing to it.)
*
*
* When an item is submitted and is somewhere in a workflow, it has a row in the
* WorkflowItem table pointing to it. The state of the workflow can be
* determined by looking at WorkflowItem.getState()
*
*
* When a submission is complete, the WorkflowItem pointing to the item is
* destroyed and the archive() method is called, which hooks the item up to the
* archive.
*
*
* Notification: When an item enters a state that requires notification,
* (WFSTATE_STEP1POOL, WFSTATE_STEP2POOL, WFSTATE_STEP3POOL,) the workflow needs
* to notify the appropriate groups that they have a pending task to claim.
*
*
* Revealing lists of approvers, editors, and reviewers. A method could be added
* to do this, but it isn't strictly necessary. (say public List
* getStateEPeople( WorkflowItem wi, int state ) could return people affected by
@@ -138,7 +138,7 @@ public class WorkflowManager
/**
* startWorkflow() begins a workflow - in a single transaction do away with
* the PersonalWorkspace entry and turn it into a WorkflowItem.
*
*
* @param c
* Context
* @param wsi
@@ -176,7 +176,7 @@ public class WorkflowManager
// now get the workflow started
wfi.setState(WFSTATE_SUBMIT);
advance(c, wfi, null);
advance(c, wfi, null);
// Return the workflow item
return wfi;
@@ -201,7 +201,7 @@ public class WorkflowManager
* getOwnedTasks() returns a List of WorkflowItems containing the tasks
* claimed and owned by an EPerson. The GUI displays this info on the
* MyDSpace page.
*
*
* @param e
* The EPerson we want to fetch owned tasks for.
*/
@@ -212,7 +212,7 @@ public class WorkflowManager
String myquery = "SELECT * FROM WorkflowItem WHERE owner= ? ";
TableRowIterator tri = DatabaseManager.queryTable(c,
TableRowIterator tri = DatabaseManager.queryTable(c,
"workflowitem", myquery,e.getID());
try
@@ -236,7 +236,7 @@ public class WorkflowManager
/**
* getPooledTasks() returns a List of WorkflowItems an EPerson could claim
* (as a reviewer, etc.) for display on a user's MyDSpace page.
*
*
* @param e
* The Eperson we want to fetch the pooled tasks for.
*/
@@ -265,13 +265,13 @@ public class WorkflowManager
tri.close();
}
}
return mylist;
}
/**
* claim() claims a workflow task for an EPerson
*
*
* @param wi
* WorkflowItem to do the claim on
* @param e
@@ -322,7 +322,7 @@ public class WorkflowManager
* the item arrives at the submit state, then remove the WorkflowItem and
* call the archive() method to put it in the archive, and email notify the
* submitter of a successful submission
*
*
* @param c
* Context
* @param wi
@@ -335,26 +335,26 @@ public class WorkflowManager
{
advance(c, wi, e, true, true);
}
/**
* advance() sends an item forward in the workflow (reviewers,
* approvers, and editors all do an 'approve' to move the item forward) if
* the item arrives at the submit state, then remove the WorkflowItem and
* call the archive() method to put it in the archive, and email notify the
* submitter of a successful submission
*
*
* @param c
* Context
* @param wi
* WorkflowItem do do the approval on
* @param e
* EPerson doing the approval
*
*
* @param curate
* boolean indicating whether curation tasks should be done
*
*
* @param record
* boolean indicating whether to record action
* boolean indicating whether to record action
*/
public static boolean advance(Context c, WorkflowItem wi, EPerson e,
boolean curate, boolean record)
@@ -362,7 +362,7 @@ public class WorkflowManager
{
int taskstate = wi.getState();
boolean archived = false;
// perform curation tasks if needed
if (curate && WorkflowCurator.needsCuration(wi))
{
@@ -381,9 +381,9 @@ public class WorkflowManager
{
case WFSTATE_SUBMIT:
archived = doState(c, wi, WFSTATE_STEP1POOL, e);
break;
case WFSTATE_STEP1:
// authorize DSpaceActions.SUBMIT_REVIEW
@@ -430,7 +430,7 @@ public class WorkflowManager
/**
* unclaim() returns an owned task/item to the pool
*
*
* @param c
* Context
* @param wi
@@ -481,7 +481,7 @@ public class WorkflowManager
* abort() aborts a workflow, completely deleting it (administrator do this)
* (it will basically do a reject from any state - the item ends up back in
* the user's PersonalWorkspace
*
*
* @param c
* Context
* @param wi
@@ -540,7 +540,7 @@ public class WorkflowManager
{
// get a list of all epeople in group (or any subgroups)
EPerson[] epa = Group.allMembers(c, mygroup);
// there were reviewers, change the state
// and add them to the list
createTasks(c, wi, epa);
@@ -582,7 +582,7 @@ public class WorkflowManager
{
//get a list of all epeople in group (or any subgroups)
EPerson[] epa = Group.allMembers(c, mygroup);
// there were approvers, change the state
// timestamp, and add them to the list
createTasks(c, wi, epa);
@@ -619,7 +619,7 @@ public class WorkflowManager
{
// get a list of all epeople in group (or any subgroups)
EPerson[] epa = Group.allMembers(c, mygroup);
// there were editors, change the state
// timestamp, and add them to the list
createTasks(c, wi, epa);
@@ -707,7 +707,7 @@ public class WorkflowManager
* Commit the contained item to the main archive. The item is associated
* with the relevant collection, added to the search index, and any other
* tasks such as assigning dates are performed.
*
*
* @return the fully archived item.
*/
private static Item archive(Context c, WorkflowItem wfi)
@@ -742,8 +742,8 @@ public class WorkflowManager
EPerson ep = i.getSubmitter();
// Get the Locale
Locale supportedLocale = I18nUtil.getEPersonLocale(ep);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));
// Get the item handle to email to user
String handle = HandleManager.findHandle(c, i);
@@ -780,7 +780,7 @@ public class WorkflowManager
/**
* Return the workflow item to the workspace of the submitter. The workflow
* item is removed, and a workspace item created.
*
*
* @param c
* Context
* @param wfi
@@ -825,7 +825,7 @@ public class WorkflowManager
* rejects an item - rejection means undoing a submit - WorkspaceItem is
* created, and the WorkflowItem is removed, user is emailed
* rejection_message.
*
*
* @param c
* Context
* @param wi
@@ -899,10 +899,10 @@ public class WorkflowManager
static void deleteTasks(Context c, WorkflowItem wi) throws SQLException
{
String myrequest = "DELETE FROM TaskListItem WHERE workflow_id= ? ";
DatabaseManager.updateQuery(c, myrequest, wi.getID());
}
// send notices of curation activity
public static void notifyOfCuration(Context c, WorkflowItem wi, EPerson[] epa,
String taskName, String action, String message) throws SQLException, IOException
@@ -921,7 +921,7 @@ public class WorkflowManager
for (int i = 0; i < epa.length; i++)
{
Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale,
"flowtask_notify"));
email.addArgument(title);
email.addArgument(coll.getMetadata("name"));
@@ -935,7 +935,7 @@ public class WorkflowManager
}
catch (MessagingException e)
{
log.warn(LogManager.getHeader(c, "notifyOfCuration", "cannot email users" +
log.warn(LogManager.getHeader(c, "notifyOfCuration", "cannot email users" +
" of workflow_item_id" + wi.getID()));
}
}
@@ -971,7 +971,7 @@ public class WorkflowManager
for (int i = 0; i < epa.length; i++)
{
Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
email.addArgument(title);
email.addArgument(coll.getMetadata("name"));
email.addArgument(submitter);
@@ -981,17 +981,17 @@ public class WorkflowManager
{
case WFSTATE_STEP1POOL:
message = messages.getString("org.dspace.workflow.WorkflowManager.step1");
break;
case WFSTATE_STEP2POOL:
message = messages.getString("org.dspace.workflow.WorkflowManager.step2");
break;
case WFSTATE_STEP3POOL:
message = messages.getString("org.dspace.workflow.WorkflowManager.step3");
break;
}
email.addArgument(message);
@@ -1030,7 +1030,7 @@ public class WorkflowManager
// Get rejector's name
String rejector = getEPersonName(e);
Locale supportedLocale = I18nUtil.getEPersonLocale(e);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject"));
email.addRecipient(getSubmitterEPerson(wi).getEmail());
email.addArgument(title);
@@ -1072,7 +1072,7 @@ public class WorkflowManager
/**
* get the title of the item in this workflow
*
*
* @param wi the workflow item object
*/
public static String getItemTitle(WorkflowItem wi) throws SQLException
@@ -1093,7 +1093,7 @@ public class WorkflowManager
/**
* get the name of the eperson who started this workflow
*
*
* @param wi the workflow item
*/
public static String getSubmitterName(WorkflowItem wi) throws SQLException

View File

@@ -14,12 +14,14 @@ import org.dspace.core.Context;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Email;
import org.dspace.core.I18nUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.eperson.Group;
import org.dspace.xmlworkflow.state.Workflow;
import org.dspace.xmlworkflow.storedcomponents.CollectionRole;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
@@ -154,9 +156,9 @@ public class WorkflowUtils extends Util{
String recipient = ConfigurationManager
.getProperty("alert.recipient");
if (recipient != null)
if (StringUtils.isNotBlank(recipient))
{
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), "internal_error"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), "internal_error"));
email.addRecipient(recipient);
email.addArgument(ConfigurationManager

View File

@@ -107,7 +107,7 @@ public class XmlWorkflowManager {
// suppress email, and delete key
noEMail.remove(wfi.getItem().getID());
} else {
Email mail = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), emailTemplate));
Email mail = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), emailTemplate));
for (String argument : arguments) {
mail.addArgument(argument);
}
@@ -396,7 +396,7 @@ public class XmlWorkflowManager {
EPerson ep = i.getSubmitter();
// Get the Locale
Locale supportedLocale = I18nUtil.getEPersonLocale(ep);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));
// Get the item handle to email to user
String handle = HandleManager.findHandle(c, i);
@@ -856,7 +856,7 @@ public class XmlWorkflowManager {
// Get rejector's name
String rejector = getEPersonName(e);
Locale supportedLocale = I18nUtil.getEPersonLocale(e);
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject"));
email.addRecipient(wi.getSubmitter().getEmail());
email.addArgument(title);

View File

@@ -78,9 +78,10 @@ itemlist.dc.type.degree = Degree
itemlist.et-al = et al
itemlist.thumbnail = Preview
jsp.adminhelp = Admin Help...
jsp.adminhelp = <span class="glyphicon glyphicon-question-sign"></span>
jsp.administer = Administer
jsp.admintools = Admin Tools
jsp.actiontools = Actions
jsp.browse.authors.enter = or enter first few letters:
jsp.browse.authors.jump = Jump to:
jsp.browse.authors.show = Showing authors {0}-{1} of {2}.
@@ -127,6 +128,7 @@ jsp.browse.subject.jump = Jump to:
jsp.browse.subject.show = Showing subjects {0}-{1} of {2}.
jsp.browse.subject.title = Browse by Subject
jsp.collection-home.editsub.button = Edit Submitters
jsp.collection-home.content.range = Collection&#39;s Items (Sorted by {0} in {1} order): {2} to {3} of {4}
jsp.collection-home.feeds = RSS Feeds
jsp.collection-home.heading1 = Collection home page
jsp.collection-home.info = See&nbsp;Subscriptions
@@ -137,7 +139,7 @@ jsp.collection-home.subscribe = Subscribe
jsp.collection-home.subscribe.msg = Subscribe to this collection to receive daily e-mail notification of new additions
jsp.collection-home.subscribed = You are subscribed to this collection.
jsp.collection-home.unsub = Unsubscribe
jsp.collection-home.display-statistics = View Statistics
jsp.collection-home.display-statistics = <span class="glyphicon glyphicon-stats"></span>
jsp.community-home.create1.button = Create collection
jsp.community-home.create2.button = Create Sub-community
jsp.community-home.feeds = RSS Feeds
@@ -145,7 +147,7 @@ jsp.community-home.heading1 = Community home
jsp.community-home.heading2 = Collections in this community
jsp.community-home.heading3 = Sub-communities within this community
jsp.community-home.recentsub = Recent&nbsp;Submissions
jsp.community-home.display-statistics = View Statistics
jsp.community-home.display-statistics = <span class="glyphicon glyphicon-stats"></span>
jsp.community-list.create.button = Create Top-Level Community...
jsp.community-list.text1 = Shown below is a list of communities and the collections and sub-communities within them. Click on a name to view that community or collection home page.
jsp.community-list.title = Communities and Collections
@@ -187,12 +189,12 @@ jsp.display-item.suggest = Recommend this
jsp.display-item.text1 = Show simple item record
jsp.display-item.text2 = Show full item record
jsp.display-item.text3 = This item is licensed under a
jsp.display-item.display-statistics = View Statistics
jsp.display-item.display-statistics = <span class="glyphicon glyphicon-stats"></span>
jsp.dspace-admin.authorize-advanced.add = Add Policy
jsp.dspace-admin.authorize-advanced.advanced = Advanced Policy Manager
jsp.dspace-admin.authorize-advanced.clear = Clear Policies
jsp.dspace-admin.authorize-advanced.col = Collection:
jsp.dspace-admin.authorize-advanced.text = Allows you to do wildcard additions to and clearing of policies for types of content contained in a collection. Warning, dangerous - removing READ permissions from items will make them not viewable!
jsp.dspace-admin.authorize-advanced.text = Allows you to do wildcard additions to and clearing of policies for items or bitstreams contained in a collection. Warning, dangerous - removing READ permissions from items will make them not viewable!
jsp.dspace-admin.authorize-advanced.type = Content Type:
jsp.dspace-admin.authorize-advanced.type1 = item
jsp.dspace-admin.authorize-advanced.type2 = bitstream
@@ -236,6 +238,10 @@ jsp.dspace-admin.confirm-delete-mdschema.confirm = Are you sure t
jsp.dspace-admin.confirm-delete-mdschema.heading = Delete Metadata Schema: <code>{0}</code>
jsp.dspace-admin.confirm-delete-mdschema.title = Delete Metadata Schema
jsp.dspace-admin.confirm-delete-mdschema.warning = This will result in an error if any metadata fields exist within this schema
jsp.dspace-admin.curate.main.title = Curation Tasks
jsp.dspace-admin.curate.main.heading = System Curation Tasks
jsp.dspace-admin.curate.main.info1 = Handle of DSpace Object
jsp.dspace-admin.curate.main.info2 = Hint: Enter [your-handle-prefix]/0 to run a task across entire site (not all tasks may support this capability)
jsp.dspace-admin.eperson-browse.canlogin = Can Log In?
jsp.dspace-admin.eperson-browse.email = E-mail Address
jsp.dspace-admin.eperson-browse.heading = Browse EPeople {0}-{1} of {2}
@@ -322,7 +328,7 @@ jsp.dspace-admin.metadataimport.reinstated = Item Reinstate
jsp.dspace-admin.metadataimport.toomany = There are too many changes. Please import fewer changes, adjust the limit, or perform the input directly on the server.
jsp.dspace-admin.metadataimport.finished = {0} changes completed successfully.
jsp.dspace-admin.index.heading = Administration Tools
jsp.dspace-admin.index.text = Please select an operation from the navigation bar on the left.
jsp.dspace-admin.index.text = Please select an operation from the main menu.
jsp.dspace-admin.item-select.enter = Enter the Handle or internal item ID of the item you wish to select.
jsp.dspace-admin.item-select.find = Find
jsp.dspace-admin.item-select.handle = Handle:
@@ -524,6 +530,7 @@ jsp.feedback.form.text1 = Thanks for tak
jsp.feedback.form.text2 = Please fill out all of the information below.
jsp.feedback.form.title = Feedback Form
jsp.general.authors.button = Authors
jsp.general.browse = Browse
jsp.general.date.button = By Date
jsp.general.edit.button = Edit...
jsp.general.genericScope = All of DSpace
@@ -544,7 +551,7 @@ jsp.general.untitled = Untitled
jsp.general.update = Update
jsp.general.without-contributor = Anonymous
jsp.general.without-date = No date given
jsp.help = Help...
jsp.help = <span class="glyphicon glyphicon-question-sign"></span>
jsp.help.formats.contact1 = Please contact your
jsp.help.formats.contact2 = DSpace Administrator
jsp.help.formats.contact3 = if you have questions about a particular format.
@@ -569,11 +576,13 @@ jsp.home.search1 = Search
jsp.home.search2 = Enter some text in the box below to search DSpace.
jsp.home.title = Home
jsp.layout.footer-default.feedback = Feedback
jsp.layout.footer-default.text = <a target="_blank" href="http://www.dspace.org/">DSpace Software</a> Copyright&nbsp;&copy;&nbsp;2002-2010&nbsp; <a target="_blank" href="http://www.duraspace.org/">Duraspace</a>
jsp.layout.footer-default.text = <a target="_blank" href="http://www.dspace.org/">DSpace Software</a> Copyright&nbsp;&copy;&nbsp;2002-2013&nbsp; <a target="_blank" href="http://www.duraspace.org/">Duraspace</a>
jsp.layout.footer-default.theme-by = Theme by
jsp.layout.header-default.about = About DSpace Software
jsp.layout.header-default.alt = DSpace
jsp.layout.navbar-admin.authorization = Authorization
jsp.layout.navbar-admin.communities-collections = Communities/<br/>Collections
jsp.layout.navbar-admin.curate = Curation Tasks
jsp.layout.navbar-admin.editlicense = Edit Default<br />License
jsp.layout.navbar-admin.editnews = Edit News
jsp.layout.navbar-admin.epeople = E-people
@@ -582,6 +591,7 @@ jsp.layout.navbar-admin.groups = Groups
jsp.layout.navbar-admin.help = Help
jsp.layout.navbar-admin.items = Items
jsp.layout.navbar-admin.logout = Log Out
jsp.layout.navbar-admin.privateitems = Private Items
jsp.layout.navbar-admin.metadataimport = Import metadata
jsp.layout.navbar-admin.metadataregistry = Metadata<br/>Registry
jsp.layout.navbar-admin.statistics = Statistics
@@ -630,7 +640,7 @@ jsp.login.not-in-records.text = You have a val
jsp.login.not-in-records.title = No User Record Available
jsp.login.password.heading = Log In to DSpace
jsp.login.password.title = Log In
jsp.morehelp = More Help...
jsp.morehelp = <span class="glyphicon glyphicon-question-sign"></span>
jsp.mydspace = My DSpace
jsp.mydspace.general.approve = Approve
jsp.mydspace.general.backto-mydspace = Back to My DSpace
@@ -841,6 +851,7 @@ jsp.search.filter.heading = Add filters:
jsp.search.filter.hint = Use filters to refine the search results.
jsp.search.filter.add = Add
jsp.search.filter.applied = Current filters:
jsp.search.filter.any = Any fields
jsp.search.filter.title = Title
jsp.search.filter.author = Author
jsp.search.filter.subject = Subject
@@ -851,6 +862,40 @@ jsp.search.filter.op.contains = Contains
jsp.search.filter.op.notcontains = Not Contains
jsp.search.filter.op.authority = ID
jsp.search.filter.op.notauthority = Not ID
jsp.sherpa.title = SHERPA/RoMEO Publisher Policy Database
jsp.sherpa.loading = <p>Fetching policy information from the SHERPA/RoMEO database</p><img alt="loading" src="{0}/sherpa/image/ajax-loader-big.gif" />
jsp.sherpa.heading = <p class="sherpaDisclaimer"><a href="http://www.sherpa.ac.uk/romeo.php" target="_blank"><img align="left" src="{0}/sherpa/image/romeosmall.gif" width="100" height="54" alt="SHERPA/RoMEO Database" border="0"></a> All SHERPA/RoMEO information is correct to the best of our knowledge but should not be relied upon for legal advice. SHERPA cannot be held responsible for the re-use of RoMEO data, or for alternative interpretations which are derived from this information.</p>
jsp.sherpa.error = <p class="sherpaError">Sorry, we have had trouble querying the SHERPA/RoMEO Database. No data are availables, try later or check directly the <a href="http://www.sherpa.ac.uk/romeo.php" target="_blank">SHERPA/RoMEO WebSite</a>.</p>
jsp.sherpa.noresult = <p class="sherpaNoResult">Sorry, there are not data in the <a href="http://www.sherpa.ac.uk/romeo.php" target="_blank">SHERPA/RoMEO Database</a> for the ISSNs that you have entered.</p>
jsp.sherpa.oneresult = <p>The <a href="http://www.sherpa.ac.uk/romeo.php" target="_blank">SHERPA/RoMEO</a> Database provide the following data for the journal that you have entered.</p>
jsp.sherpa.moreresults = <p>The ISSNs that you have entered match with multiple journals, please review them. For any journals you can find below the publisher policy.</p>
jsp.sherpa.jornaltitle = <p><b>Journal:</b> {0}
jsp.sherpa.jornalissn = (ISSN: {0})</p>
jsp.sherpa.publisher = <p><b>Publisher:</b> <a href="{1}" target="_blank">{0}</a></p>
jsp.sherpa.publisher.onlyname = <p><b>Publisher:</b> {0}</p>
jsp.sherpa.publisher.unknow = <p><b>Publisher:</b> Unknow</p>
jsp.sherpa.publisher.nodata = <p>Sorry, there are not data about this publisher in the <a href="http://www.sherpa.ac.uk/romeo.php" target="_blank">SHERPA/RoMEO</a> Database. If you know its policies or you want suggest to add the Publisher to the SHERPA/RoMEO Database you can use <a href="http://www.sherpa.ac.uk/romeoupdate.php" target="_blank">this form</a></p>
jsp.sherpa.pre-print.can = <p><b>Author''s Pre-prints:</b><img src="{0}/sherpa/image/can.gif" alt="can" border="0" /> Author <b>can</b> archive pre-print (ie pre-refereeing)</p>
jsp.sherpa.pre-print.cannot = <p><b>Author''s Pre-prints:</b><img src="{0}/sherpa/image/cannot.gif" alt="cannot" border="0" /> Author <b>cannot</b> archive pre-print (ie pre-refereeing)</p>
jsp.sherpa.pre-print.restricted = <p><b>Author''s Pre-prints:</b><img src="{0}/sherpa/image/restricted.gif" alt="restricted" border="0" /> <b>Subject to Restrictions below</b>, author <b>can</b> archive pre-print (ie pre-refereeing)</p>
jsp.sherpa.pre-print.unclear = <p><b>Author''s Pre-prints:</b><img src="{0}/sherpa/image/unclear.gif" alt="unclear" border="0" /> Archiving status unclear</p>
jsp.sherpa.pre-print.unknown = <p><b>Author''s Pre-prints:</b> - No information</p>
jsp.sherpa.post-print.can = <p><b>Author''s Post-prints:</b><img src="{0}/sherpa/image/can.gif" alt="can" border="0" /> Author <b>can</b> archive post-print (ie final draft post-refereeing)</p>
jsp.sherpa.post-print.cannot = <p><b>Author''s Post-prints:</b><img src="{0}/sherpa/image/cannot.gif" alt="cannot" border="0" /> Author <b>cannot</b> archive post-print (ie final draft post-refereeing)</p>
jsp.sherpa.post-print.restricted = <p><b>Author''s Post-prints:</b><img src="{0}/sherpa/image/restricted.gif" alt="restricted" border="0" /> <b>Subject to Restrictions below</b>, author <b>can</b> archive post-print (ie final draft post-refereeing)</p>
jsp.sherpa.post-print.unclear = <p><b>Author''s Post-prints:</b><img src="{0}/sherpa/image/unclear.gif" alt="unclear" border="0" /> Archiving status unclear</p>
jsp.sherpa.post-print.unknown = <p><b>Author''s Post-prints:</b> - No information</p>
jsp.sherpa.publisher-version.can = <p><b>Publisher''s Version:</b><img src="{0}/sherpa/image/can.gif" alt="can" border="0" /> Author <b>can</b> archive publisher''s version/PDF</p>
jsp.sherpa.publisher-version.cannot = <p><b>Publisher''s Version:</b><img src="{0}/sherpa/image/cannot.gif" alt="cannot" border="0" /> Author <b>cannot</b> archive publisher''s version/PDF</p>
jsp.sherpa.publisher-version.restricted = <p><b>Publisher''s Version:</b><img src="{0}/sherpa/image/restricted.gif" alt="restricted" border="0" /> <b>Subject to Restrictions below</b>, author <b>can</b> archive publisher''s version/PDF</p>
jsp.sherpa.publisher-version.unclear = <p><b>Publisher''s Version:</b><img src="{0}/sherpa/image/unclear.gif" alt="unclear" border="0" /> Archiving status unclear</p>
jsp.sherpa.publisher-version.unknown = <p><b>Publisher''s Version:</b> - No information</p>
jsp.sherpa.generalconditions = <p><b>General conditions:</b></p>
jsp.sherpa.paidoption = <p><b>Paid open access:</b> <a href="{1}" target="_blank">{0}</a>. {2}</p>
jsp.sherpa.copyright = <p><b>Copyright:</b></p>
jsp.sherpa.publisher.romeocolour = <p><b>RoMEO:</b> This is a RoMEO {0} publisher</p>
jsp.sherpa.legend = <div class="sherpaLegend"><table class="romeoColour table"><thead><tr><th>ROMEO colour</th><th>Archiving policy</th></tr></thead><tbody><tr><td class="greenRomeoPublisher">green</td><td>can archive pre-print <i>and</i> post-print or publisher's version/PDF</td></tr><tr><td class="blueRomeoPublisher">blue</td><td>can archive post-print (ie final draft post-refereeing) or publisher's version/PDF</td></tr><tr><td class="yellowRomeoPublisher">yellow</td><td>can archive pre-print (ie pre-refereeing)</td></tr><tr><td class="grayRomeoPublisher">gray</td><td>publishers found in DOAJ that have not yet been analyzed by RoMEO</td></tr><tr><td class="whiteRomeoPublisher">white</td><td>archiving not formally supported</td></tr></tbody></table></div>
jsp.statistics.title = Statistics
jsp.statistics.heading.visits = Total Visits
jsp.statistics.heading.monthlyvisits = Total Visits per Month
@@ -863,6 +908,25 @@ jsp.statistics.no-report.title = No reports cur
jsp.statistics.report.info1 = Most recent general report
jsp.statistics.report.info2 = Monthly reports:
jsp.statistics.report.title = Statistical Summary
jsp.submit.access.title = Access
jsp.submit.access.error_1 = Invalid Start Date Format
jsp.submit.access.error_2 = Missing Start Date
jsp.submit.access.error_3 = Invalid Group Selected
jsp.submit.access.error_4 = Duplicate Policy
jsp.submit.access.error_5 = Duplicate Policy
jsp.submit.access.plist.heading = Policies List
jsp.submit.access.access_setting.heading = Access Setting
jsp.submit.access.private_setting.heading = Private Item
jsp.submit.access.private_setting.help = If selected, the item won't be searchable.
jsp.submit.access.private_setting.label = Private:
jsp.submit.access.embargo_setting.heading = Embargo
jsp.submit.access.policy_setting.label_name = Name:
jsp.submit.access.policy_setting.label_group = Group:
jsp.submit.access.policy_setting.label_date = Embargo Access until Specific Date:
jsp.submit.access.policy_setting.label_date.help = Accepted format: yyyy, yyyy-mm, yyyy-mm-dd
jsp.submit.access.policy_setting.label_reason = Reason:
jsp.submit.access.submit_add_policy.button = Confirm Policy &amp; add another
jsp.submit.access.edit_policy.heading = Edit Policy
jsp.submit.cancel.continue.button = Oops, continue submission
jsp.submit.cancel.info = Do you want the half-finished submission removed, or do you want to keep it so you can carry on working on it later? You can also return to where you where during the submission process if you clicked Cancel by accident.
jsp.submit.cancel.remove.button = Remove the submission
@@ -886,7 +950,15 @@ jsp.submit.choose-file.info6 = Please also no
jsp.submit.choose-file.info7 = Information about file types and levels of support for each are available.
jsp.submit.choose-file.info9 = Please give a brief description of the contents of this file, for example "Main article", or "Experiment data readings".
jsp.submit.choose-file.title = Upload a File
jsp.submit.choose-file.skip = Skip file upload &gt;
jsp.submit.choose-file.skip = Skip file upload &gt;
jsp.submit.choose-file.upload-ajax.button.cancel = Cancel
jsp.submit.choose-file.upload-ajax.button.select-file = Select a file...
jsp.submit.choose-file.upload-ajax.dialog.close = Ok
jsp.submit.choose-file.upload-ajax.fileRequired.title = File required
jsp.submit.choose-file.upload-ajax.fileRequired.info = You must upload at least one file for this item
jsp.submit.choose-file.upload-ajax.uploadInit = Upload is starting...
jsp.submit.choose-file.upload-ajax.uploadInProgress = Upload in progress... <b>{0}%</b> [{1} bytes of {2}]
jsp.submit.choose-file.upload-ajax.uploadCompleted = Upload completed.
jsp.submit.complete.heading = Submit: Submission Complete!
jsp.submit.complete.info = Your submission will now go through the workflow process designated for the collection to which you are submitting. You will receive e-mail notification as soon as your submission has become a part of the collection, or if for some reason there is a problem with your submission. You can also check on the status of your submission by going to the My DSpace page.
jsp.submit.complete.again = Submit another item to the same collection
@@ -901,18 +973,21 @@ jsp.submit.creative-commons.info2 = To license you
jsp.submit.creative-commons.info3 = Your browser must support IFrames to use this feature
jsp.submit.creative-commons.skip.button = Skip Creative Commons &gt;
jsp.submit.creative-commons.title = Use a Creative Commons License
jsp.submit.edit-bitstream-access.title = Edit Bitstream Access
jsp.submit.edit-bitstream-access.heading = Edit Bitstream Access
jsp.submit.edit-bitstream-access.save.button = Save
jsp.submit.edit-metadata.button.add = Add More
jsp.submit.edit-metadata.button.remove = Remove This Entry
jsp.submit.edit-metadata.button.remove2 = Remove
jsp.submit.edit-metadata.cancelsave = Cancel/Save
jsp.submit.edit-metadata.controlledvocabulary = Subject Categories
jsp.submit.edit-metadata.day = Day:
jsp.submit.edit-metadata.firstname = First name(s) + "Jr"<br/> e.g. <strong>Donald Jr</strong>
jsp.submit.edit-metadata.firstname = First name(s) + "Jr", e.g. Donald Jr
jsp.submit.edit-metadata.heading = Submit: Describe this Item
jsp.submit.edit-metadata.help = (More Help...)
jsp.submit.edit-metadata.help = <span class="glyphicon glyphicon-question-sign"></span>
jsp.submit.edit-metadata.info1 = Please fill in the requested information about this submission below. In most browsers, you can use the tab key to move the cursor to the next input box or button, to save you having to use the mouse each time.
jsp.submit.edit-metadata.info2 = Please fill further information about this submission below.
jsp.submit.edit-metadata.lastname = Last name<br/>e.g. <strong>Smith</strong>
jsp.submit.edit-metadata.lastname = Last name, e.g. Smith
jsp.submit.edit-metadata.month = Month:
jsp.submit.edit-metadata.next = Next &gt;
jsp.submit.edit-metadata.no_month = (No Month)
@@ -925,6 +1000,8 @@ jsp.submit.general.cancel-or-save.button = Cancel/Save
jsp.submit.general.next = Next &gt;
jsp.submit.general.previous = &lt; Previous
jsp.submit.general.submit = Submit
jsp.submit.general.cancel = Cancel
jsp.submit.general.save = Save
jsp.submit.get-file-format.choose.button = Choose automatically-recognized type
jsp.submit.get-file-format.format = File Format:
jsp.submit.get-file-format.heading = Submit: Select File Format
@@ -954,6 +1031,7 @@ jsp.submit.no-theses.info3 = Please note th
jsp.submit.no-theses.info4 = For more information please <strong>contact the DSpace site administrators</strong>:
jsp.submit.no-theses.info5 = Thank you for your interest in DSpace!
jsp.submit.no-theses.title = Theses Not Accepted in DSpace
jsp.submit.progressbar.access = Access
jsp.submit.progressbar.complete = Complete
jsp.submit.progressbar.CClicense = License
jsp.submit.progressbar.describe = Describe
@@ -1002,8 +1080,9 @@ jsp.submit.show-license.info2 = <strong>Not gr
jsp.submit.show-license.notgrant.button = I Do Not Grant the License
jsp.submit.show-license.title = DSpace Distribution License
jsp.submit.show-uploaded-file.checksum = Checksum
jsp.submit.show-uploaded-file.click1.button = Click here if this is the wrong format
jsp.submit.show-uploaded-file.click2.button = Click here if this is the wrong file
jsp.submit.show-uploaded-file.click1.button = Change format
jsp.submit.show-uploaded-file.click2.button = Change file
jsp.submit.show-uploaded-file.click3.button = Embargo settings
jsp.submit.show-uploaded-file.file = File
jsp.submit.show-uploaded-file.format = File Format
jsp.submit.show-uploaded-file.heading1 = Submit: File Uploaded Successfully
@@ -1040,6 +1119,7 @@ jsp.submit.upload-file-list.button4 = Add Another Fi
jsp.submit.upload-file-list.button5 = &lt; Previous
jsp.submit.upload-file-list.button6 = Next &gt;
jsp.submit.upload-file-list.button7 = Cancel/Save
jsp.submit.upload-file-list.button8 = Policies
jsp.submit.upload-file-list.empty1 = <em>None</em>
jsp.submit.upload-file-list.heading1 = Submit: File Uploaded Successfully
jsp.submit.upload-file-list.heading2 = Submit: Uploaded Files
@@ -1060,6 +1140,7 @@ jsp.submit.upload-file-list.tableheading3 = Size
jsp.submit.upload-file-list.tableheading4 = Description
jsp.submit.upload-file-list.tableheading5 = File Format
jsp.submit.upload-file-list.tableheading6 = Checksum
jsp.submit.upload-file-list.tableheading7 = Access Settings
jsp.submit.upload-file-list.title = Uploaded Files
jsp.submit.verify-prune.heading = Submit: Caution
jsp.submit.verify-prune.info1 = The changes you've made to the first "Describe Your Item" page will affect your submission:
@@ -1104,9 +1185,36 @@ jsp.tools.confirm-delete-item.title = Delete Item
jsp.tools.confirm-withdraw-item.question = Are you sure this item should be withdrawn from the archive?
jsp.tools.confirm-withdraw-item.title = Withdraw Item
jsp.tools.confirm-withdraw-item.withdraw.button = Withdraw
jsp.tools.confirm-privating-item.question = Are you sure this item should be made private?
jsp.tools.confirm-privating-item.title = Make item Private
jsp.tools.confirm-privating-item.privating.button = Make item Private
jsp.tools.creative-commons-edit.heading1 = Add or Replace Creative Commons License
jsp.tools.creative-commons-edit.title = DSpace Distribution License
jsp.tools.curate.collection.title = Curate Collection
jsp.tools.curate.collection.heading = Curate Collection: {0}
jsp.tools.curate.community.title = Curate Community
jsp.tools.curate.community.heading = Curate Community: {0}
jsp.tools.curate.item.title = Curate Item
jsp.tools.curate.item.heading = Curate Item: {0}
jsp.tools.curate.perform.button = Perform
jsp.tools.curate.perform.failure = The task exited unexpectedly or failed. For more information, please contact the site administrator or check your system logs.
jsp.tools.curate.perform.message.failure = STATUS: Failure, RESULT: {1}
jsp.tools.curate.perform.message.success = STATUS: {0}, RESULT: {1}
jsp.tools.curate.perform.success = The task was completed successfully.
jsp.tools.curate.queue.button = Queue
jsp.tools.curate.queue.failure = The task could not be queued. An error occurred. For more information, please contact the site administrator or check your system logs.
jsp.tools.curate.queue.message.failure = RESULT: FAILED to queue Object ''{0}'' in ''{1}'' Queue
jsp.tools.curate.queue.message.success = RESULT: Object ''{0}'' queued in ''{1}'' Queue
jsp.tools.curate.queue.success = The task was queued successfully.
jsp.tools.curate.return.collection.button = Return to Edit Collection Page
jsp.tools.curate.return.community.button = Return to Edit Community Page
jsp.tools.curate.return.item.button = Return to Edit Item Page
jsp.tools.curate.select-group.tag = Choose from the following groups
jsp.tools.curate.select-task.tag = Task
jsp.tools.curate.task.name = Task: {0}
jsp.tools.edit-collection.button.delete = Delete this Collection...
jsp.tools.edit-collection.form.basic-metadata = Collection's Metadata
jsp.tools.edit-collection.form.collection-settings = Collection's settings
jsp.tools.edit-collection.form.button.add-logo = Upload new logo...
jsp.tools.edit-collection.form.button.cancel = Cancel
jsp.tools.edit-collection.form.button.create = Create...
@@ -1116,6 +1224,7 @@ jsp.tools.edit-collection.form.button.delete-logo = Delete (no log
jsp.tools.edit-collection.form.button.edit = Edit...
jsp.tools.edit-collection.form.button.set-logo = Upload a logo...
jsp.tools.edit-collection.form.button.update = Update
jsp.tools.edit-collection.form.button.curate = Curate...
jsp.tools.edit-collection.form.label1 = Name:
jsp.tools.edit-collection.form.label10 = Submitters:
jsp.tools.edit-collection.form.label11 = Step:
@@ -1123,7 +1232,7 @@ jsp.tools.edit-collection.form.label12 = Collection Adm
jsp.tools.edit-collection.form.label13 = Item template:
jsp.tools.edit-collection.form.label14 = Collection's Authorizations:
jsp.tools.edit-collection.form.label15 = Harvesting Settings
jsp.tools.edit-collection.form.label16 = Content Source
jsp.tools.edit-collection.form.label16 = Content<br/> Source
jsp.tools.edit-collection.form.label17 = This is a standard DSpace collection
jsp.tools.edit-collection.form.label18 = This collection harvests its content from an external source
jsp.tools.edit-collection.form.label19 = OAI Provider
@@ -1132,11 +1241,12 @@ jsp.tools.edit-collection.form.label21 = Metadata Forma
jsp.tools.edit-collection.form.label21.select.qdc = Qualified Dublin Core
jsp.tools.edit-collection.form.label21.select.dc = Dublin Core
jsp.tools.edit-collection.form.label21.select.dim = DSpace Intermediate Format
jsp.tools.edit-collection.form.label22 = Content being Harvested
jsp.tools.edit-collection.form.label22 = Content<br/> being<br/> Harvested
jsp.tools.edit-collection.form.label23 = Harvest metadata only.
jsp.tools.edit-collection.form.label24 = Harvest metadata and references to bitstreams (requires ORE support).
jsp.tools.edit-collection.form.label25 = Harvest metadata and bitstreams (requires ORE support).
jsp.tools.edit-collection.form.label26 = Last Harvest Result
jsp.tools.edit-collection.form.label27 = Collection's Curations:
jsp.tools.edit-collection.form.label2 = Short Description
jsp.tools.edit-collection.form.label3 = Introductory text (HTML):
jsp.tools.edit-collection.form.label4 = Copyright text (plain text):
@@ -1152,6 +1262,8 @@ jsp.tools.edit-collection.wf-role1 = Accept/Reject
jsp.tools.edit-collection.wf-role2 = Accept/Reject/Edit Metadata
jsp.tools.edit-collection.wf-role3 = Edit Metadata
jsp.tools.edit-community.button.delete = Delete this Community...
jsp.tools.edit-community.form.basic-metadata = Community's metadata
jsp.tools.edit-community.form.community-settings = Community's settings
jsp.tools.edit-community.form.button.add-logo = Upload new logo...
jsp.tools.edit-community.form.button.cancel = Cancel
jsp.tools.edit-community.form.button.create = Create
@@ -1160,6 +1272,7 @@ jsp.tools.edit-community.form.button.delete-logo = Delete (no log
jsp.tools.edit-community.form.button.edit = Edit...
jsp.tools.edit-community.form.button.set-logo = Upload a logo...
jsp.tools.edit-community.form.button.update = Update
jsp.tools.edit-community.form.button.curate = Curate...
jsp.tools.edit-community.form.label1 = Name:
jsp.tools.edit-community.form.label2 = Short Description
jsp.tools.edit-community.form.label3 = Introductory text (HTML):
@@ -1167,12 +1280,14 @@ jsp.tools.edit-community.form.label4 = Copyright text
jsp.tools.edit-community.form.label5 = Side bar text (HTML):
jsp.tools.edit-community.form.label6 = Logo:
jsp.tools.edit-community.form.label7 = Community's Authorizations:
jsp.tools.edit-community.form.label8 = Community Administrators:
jsp.tools.edit-community.form.label8 = Community Administrators:
jsp.tools.edit-community.form.label9 = Community's Curations:
jsp.tools.edit-community.heading1 = Create Community
jsp.tools.edit-community.heading2 = Edit Community {0}
jsp.tools.edit-community.title = Edit Community
jsp.tools.edit-item-form.addbit.button = Add Bitstream
jsp.tools.edit-item-form.addcc.button = Add Creative Commons License
jsp.tools.edit-item-form.form.button.curate = Curate...
jsp.tools.edit-item-form.collections = In Collections:
jsp.tools.edit-item-form.delete-w-confirm.button = Delete (Expunge)...
jsp.tools.edit-item-form.elem0 = Schema
@@ -1187,9 +1302,11 @@ jsp.tools.edit-item-form.elem7 = Name
jsp.tools.edit-item-form.elem8 = Source
jsp.tools.edit-item-form.elem9 = Description
jsp.tools.edit-item-form.elem12 = Order
jsp.tools.edit-item-form.form.label1 = Item's Curations:
jsp.tools.edit-item-form.handle = Handle:
jsp.tools.edit-item-form.heading = Bitstreams
jsp.tools.edit-item-form.item = Item's Authorizations:
jsp.tools.edit-item-form.details = Item's Details
jsp.tools.edit-item-form.item = Authorizations...
jsp.tools.edit-item-form.itemID = Item&nbsp;internal&nbsp;ID:
jsp.tools.edit-item-form.itempage = Item page:
jsp.tools.edit-item-form.modified = Last modified:
@@ -1206,6 +1323,8 @@ jsp.tools.edit-item-form.unlock = Unlock the aut
jsp.tools.edit-item-form.move-up = Move up
jsp.tools.edit-item-form.move-down = Move down
jsp.tools.edit-item-form.order-update = Update bitstream order
jsp.tools.edit-item-form.privating-w-confirm.button = Make item Private...
jsp.tools.edit-item-form.publicize.button = Make item Public
jsp.tools.eperson-list.close.button = Close
jsp.tools.eperson-list.heading = E-people {0}-{1} of {2}
jsp.tools.eperson-list.info1 = Clicking on the 'Add' button next to an e-person will add that e-person to the list on the main form.
@@ -1271,7 +1390,7 @@ jsp.tools.group-select-list.th.name = Name
jsp.tools.group-select-list.th.name.sortedby = Name &uarr;
jsp.tools.group-select-list.title = Select Groups
jsp.tools.itemmap-browse.add = Check the box next to items you wish to add to {0}, and choose ''Add''.
jsp.tools.itemmap-browse.heading-authors = Browse Items matching author ''{0}''
jsp.tools.itemmap-browse.heading-search = Browse Items matching query: ''{0}''
jsp.tools.itemmap-browse.heading-collection = Items Mapped to Collection {1} from Collection {0}
jsp.tools.itemmap-browse.remove = Check the box next to items you wish to unmap from {0}, and choose ''Remove''.
jsp.tools.itemmap-browse.th.action = Action
@@ -1280,6 +1399,9 @@ jsp.tools.itemmap-browse.th.date = Date
jsp.tools.itemmap-browse.th.remove = Unmap
jsp.tools.itemmap-browse.th.title = Title
jsp.tools.itemmap-browse.title = Browse Items
jsp.tools.itemmap-browse.info.change-page = Your query return lot of results. You can navigate your result with the following buttons. Please note that checked items will be mapped only clicking on the Add button.
jsp.tools.itemmap-browse.previous.button = Previous page
jsp.tools.itemmap-browse.next.button = Next page
jsp.tools.itemmap-info.button.continue = Continue
jsp.tools.itemmap-info.heading = Item Map Info
jsp.tools.itemmap-info.msg.added = Add item {0}
@@ -1291,12 +1413,12 @@ jsp.tools.itemmap-info.title = Item Map Info
jsp.tools.itemmap-main.collection = Collection: "{0}"
jsp.tools.itemmap-main.heading = Item Mapper - Map Items from Other Collections
jsp.tools.itemmap-main.info1 = There are {0} items owned by this collection, and {1} items mapped in from other collections.
jsp.tools.itemmap-main.info4 = Import By Author Match
jsp.tools.itemmap-main.info5 = Enter part of an author's name for a list of matching items
jsp.tools.itemmap-main.info4 = Import By Search
jsp.tools.itemmap-main.info5 = Enter a search query for a list of matching items
jsp.tools.itemmap-main.info6 = Browse Items Imported From Collections:
jsp.tools.itemmap-main.info7 = Click on collection names to browse for items to remove that were mapped in from that collection.
jsp.tools.itemmap-main.info8 = This collection has no items mapped into it.
jsp.tools.itemmap-main.search.button = Search Authors
jsp.tools.itemmap-main.search.button = Search
jsp.tools.itemmap-main.title = Item Mapper
jsp.tools.move-item.button = Move
jsp.tools.move-item.collection.from.msg = Collection to move from
@@ -1350,6 +1472,7 @@ news-side.html = news-side.html
news-top.html = news-top.html
org.dspace.app.itemexport.no-result = The DSpaceObject that you specified has no items.
org.dspace.app.webui.jsptag.CollectionListTag.collectionName = Collection Name
org.dspace.app.webui.jsptag.CommunityListTag.communityName = Community Name
org.dspace.app.webui.jsptag.ItemListTag.authors = Authors
@@ -1393,6 +1516,7 @@ org.dspace.app.webui.servlet.FeedServlet.search.title
org.dspace.app.webui.servlet.FeedServlet.search.title.default = The DSpace search engine
org.dspace.app.webui.servlet.SuggestServlet.recipient = colleague
org.dspace.app.webui.servlet.SuggestServlet.sender = A DSpace user
org.dspace.app.webui.servlet.admin.CurationServlet.null-result = Nothing to do for this DSpace object.
org.dspace.app.webui.servlet.admin.MetadataFieldRegistryServlet.badelemchar = The element cannot contain periods, underscores or spaces.
org.dspace.app.webui.servlet.admin.MetadataFieldRegistryServlet.badqualchar = The qualifier cannot contain periods, underscores or spaces.
org.dspace.app.webui.servlet.admin.MetadataFieldRegistryServlet.createfailed = The requested field could not be created due to an already existing field with an identical name.
@@ -1517,3 +1641,38 @@ jsp.tools.lookup.field.dc_contributor_author.help.last = Last name, e.g. "Smith"
jsp.tools.lookup.field.dc_contributor_author.help.first = First name(s) e.g. "Fred"
jsp.tools.lookup.field.dc_contributor_author.title = LC Name Authority author lookup
jsp.tools.lookup.field.dc_contributor_author.nonauthority = Local value '@1@' (not in Naming Authority)
# reset password
jsp.dspace-admin.eperson-main.ResetPassword.title = Reset password
jsp.dspace-admin.eperson-main.ResetPassword.head = Reset password
jsp.dspace-admin.eperson-main.ResetPassword.submit = Reset password
jsp.dspace-admin.eperson-main.ResetPassword.success_notice = An email message has been sent to the user containing a token that may be used to choose a new password.
jsp.dspace-admin.eperson-main.ResetPassword-error.errormsg = Sorry, an error has occurred when the system try to send email with instructions.
jsp.dspace-admin.eperson-main.ResetPassword.returntoedit = Return to the Administer EPeople page
# login as
jsp.dspace-admin.eperson-main.LoginAs.submit = Login As
jsp.dspace-admin.eperson-main.loginAs.authorize.errormsg = Reason: you may not assume the login as another administrator.
jsp.dspace-admin.eperson-main.loginAs.authorize.title = Authorization Error
jsp.dspace-admin.eperson-main.loginAs.backtoeditpeople = Back to E-people Admin page
org.dspace.app.webui.jsptag.access-setting.legend = Embargo
org.dspace.app.webui.jsptag.access-setting.label_name = Name:
org.dspace.app.webui.jsptag.access-setting.label_group = Groups:
org.dspace.app.webui.jsptag.access-setting.label_embargo = Visible/Embargoed:
org.dspace.app.webui.jsptag.access-setting.label_reason = Reason:
org.dspace.app.webui.jsptag.access-setting.label_date = Embargo Date:
org.dspace.app.webui.jsptag.access-setting.radio0 = Item will be visible once accepted into archive
org.dspace.app.webui.jsptag.access-setting.radio1 = Embargo Access until Specific Date
org.dspace.app.webui.jsptag.access-setting.radio_help = Accepted format: yyyy, yyyy-mm, yyyy-mm-dd
org.dspace.app.webui.jsptag.access-setting.button_confirm = Confirm Policy &amp; another
org.dspace.app.webui.jsptag.policies-list.label_name = Name
org.dspace.app.webui.jsptag.policies-list.label_action = Action
org.dspace.app.webui.jsptag.policies-list.label_group = Group
org.dspace.app.webui.jsptag.policies-list.label_sdate = Start Date
org.dspace.app.webui.jsptag.policies-list.label_edate = End Date
jsp.layout.navbar-admin.accesscontrol = Access Control
jsp.layout.navbar-admin.contents = Content
jsp.layout.navbar-admin.items = Items
jsp.layout.navbar-admin.settings = General Settings

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The contents of this file are subject to the license and copyright
detailed in the LICENSE and NOTICE files at the root of the source
tree and available online at
http://www.dspace.org/license/
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire-candidates="*Service,*DAO,javax.sql.DataSource">
<context:annotation-config /> <!-- allows us to use spring annotations in beans -->
<bean class="org.dspace.app.sherpa.submit.SHERPASubmitConfigurationService"
id="org.dspace.app.sherpa.submit.SHERPASubmitConfigurationService">
<property name="issnItemExtractors">
<list>
<bean class="org.dspace.app.sherpa.submit.MetadataValueISSNExtractor">
<property name="metadataList">
<list>
<value>dc.identifier.issn</value>
</list>
</property>
</bean>
<!-- Use the follow if you have the SHERPARoMEOJournalTitle enabled
<bean class="org.dspace.app.sherpa.submit.MetadataAuthorityISSNExtractor">
<property name="metadataList">
<list>
<value>dc.title.alternative</value>
</list>
</property>
</bean> -->
</list>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The contents of this file are subject to the license and copyright
detailed in the LICENSE and NOTICE files at the root of the source
tree and available online at
http://www.dspace.org/license/
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire-candidates="*Service,*DAO,javax.sql.DataSource">
<context:annotation-config /> <!-- allows us to use spring annotations in beans -->
<bean class="org.dspace.app.sherpa.SHERPAService" id="org.dspace.app.sherpa.SHERPAService"/>
<bean class="org.dspace.app.sherpa.submit.SHERPASubmitService" id="org.dspace.app.sherpa.submit.SHERPASubmitService">
<property name="sherpaService" ref="org.dspace.app.sherpa.SHERPAService" />
<property name="configuration" ref="org.dspace.app.sherpa.submit.SHERPASubmitConfigurationService" />
</bean>
</beans>

View File

@@ -0,0 +1 @@
^baiduspider-.*\.crawl\.baidu\.com

View File

@@ -0,0 +1,2 @@
# For testing
192.168.2.1

View File

@@ -10,16 +10,20 @@
*/
package org.dspace.authenticate;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.dspace.AbstractUnitTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Mark Wood
* @author Ben Bosman
* @author Roeland Dillen
*/
public class IPMatcherTest extends AbstractUnitTest
{
@@ -27,6 +31,8 @@ public class IPMatcherTest extends AbstractUnitTest
private static final String IP6_FULL_ADDRESS2 = "2001:18e8:3:171:218:8bff:fe2a:56a3";
private static final String IP6_MASKED_ADDRESS = "2001:18e8:3::/48";
private final static int increment = 6;
private static IPMatcher ip6FullMatcher;
private static IPMatcher ip6MaskedMatcher;
@@ -116,7 +122,221 @@ public class IPMatcherTest extends AbstractUnitTest
assertTrue("IPv6 masked match fails", ip6MaskedMatcher
.match(IP6_FULL_ADDRESS2));
}
@Test
public void testIPv4MatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("1.1.1.1");
assertTrue(ipMatcher.match("1.1.1.1"));
ArrayList<String> exceptions = new ArrayList<String>();
exceptions.add("1.1.1.1");
verifyAllIp4Except(exceptions, false, ipMatcher);
}
@Test
public void testIPv4MatchingFailure() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("1.1.1.1");
assertFalse(ipMatcher.match("1.1.1.0"));
}
@Test
public void testIPv6MatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("::2");
assertTrue(ipMatcher.match("0:0:0:0:0:0:0:2"));
}
@Test
public void testShortFormIPv6MatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("::2");
assertTrue(ipMatcher.match("::2"));
}
@Test
public void testIPv6MatchingFailure() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("::2");
assertFalse(ipMatcher.match("0:0:0:0:0:0:0:1"));
}
@Test
public void testAsteriskMatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("172.16");
assertTrue(ipMatcher.match("172.16.1.1"));
}
@Test
public void testAsteriskMatchingFailure() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("172.16");
assertFalse(ipMatcher.match("172.15.255.255"));
}
@Test
public void testIPv4CIDRMatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("192.1.2.3/8");
assertTrue(ipMatcher.match("192.1.1.1"));
}
@Test
public void testIPv4CIDRMatchingFailure() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("192.1.2.3/8");
assertTrue(ipMatcher.match("192.2.0.0"));
}
@Test
public void test2IPv4CIDRMatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("192.86.100.72/29");
assertTrue(ipMatcher.match("192.86.100.75"));
assertFalse(ipMatcher.match("192.86.100.71"));
assertFalse(ipMatcher.match("192.86.100.80"));
ArrayList<String> exceptions = new ArrayList<String>();
exceptions.add("192.86.100.72");
exceptions.add("192.86.100.73");
exceptions.add("192.86.100.74");
exceptions.add("192.86.100.75");
exceptions.add("192.86.100.76");
exceptions.add("192.86.100.77");
exceptions.add("192.86.100.78");
exceptions.add("192.86.100.79");
verifyAllIp4Except(exceptions, false, ipMatcher);
}
@Test
public void test3IPv4CIDRMatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("192.86.100.72/255.255.255.248");
assertTrue(ipMatcher.match("192.86.100.75"));
assertFalse(ipMatcher.match("192.86.100.71"));
assertFalse(ipMatcher.match("192.86.100.80"));
ArrayList<String> exceptions = new ArrayList<String>();
exceptions.add("192.86.100.72");
exceptions.add("192.86.100.73");
exceptions.add("192.86.100.74");
exceptions.add("192.86.100.75");
exceptions.add("192.86.100.76");
exceptions.add("192.86.100.77");
exceptions.add("192.86.100.78");
exceptions.add("192.86.100.79");
verifyAllIp4Except(exceptions, false, ipMatcher);
}
@Test
public void testIPv6CIDRMatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("0:0:0:1::/64");
assertTrue(ipMatcher.match("0:0:0:1:ffff:ffff:ffff:ffff"));
}
@Test
public void testIPv6CIDRMatchingFailure() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("0:0:0:1::/64");
assertFalse(ipMatcher.match("0:0:0:2::"));
}
@Test
public void testIPv4IPv6Matching() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("0.0.0.1");
assertTrue(ipMatcher.match("::1"));
}
@Test
public void testSubnetZeroIPv6CIDRMatching() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("::1/0");
assertTrue(ipMatcher.match("::2"));
}
@Test
public void testAllOnesSubnetIPv4CIDRMatchingSuccess() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("192.1.2.3/32");
assertTrue(ipMatcher.match("192.1.2.3"));
}
@Test
public void testAllOnesSubnetIPv4CIDRMatchingFailure() throws Exception
{
final IPMatcher ipMatcher = new IPMatcher("192.1.2.3/32");
assertFalse(ipMatcher.match("192.1.2.2"));
}
private ArrayList<String> getAllIp4Except(ArrayList<String> exceptions) {
int d1 = 0, d2 = 0, d3 = 0, d4 = 0;
ArrayList<String> ips = new ArrayList<String>();
for (d1 = 0; d1 <= 255; d1+=increment)
for (d2 = 0; d2 <= 255; d2+=increment)
for (d3 = 0; d3 <= 255; d3+=increment)
for (d4 = 0; d4 <= 255; d4+=increment) {
String IP = d1+"."+d2+"."+d3+"."+d4;
if (exceptions == null || !exceptions.contains(IP)) {
ips.add(IP);
}
}
return ips;
}
private void verifyAllIp4Except(ArrayList<String> exceptions, boolean asserted, IPMatcher ipMatcher) throws IPMatcherException {
int d1 = 0, d2 = 0, d3 = 0, d4 = 0;
for (d1 = 0; d1 <= 255; d1+=increment)
for (d2 = 0; d2 <= 255; d2+=increment)
for (d3 = 0; d3 <= 255; d3+=increment)
for (d4 = 0; d4 <= 255; d4+=increment) {
String IP = d1+"."+d2+"."+d3+"."+d4;
if (exceptions != null && exceptions.contains(IP)) {
if (asserted) {
assertFalse(ipMatcher.match(IP));
} else {
assertTrue(ipMatcher.match(IP));
}
} else {
if (asserted) {
assertTrue(ipMatcher.match(IP));
} else {
assertFalse(ipMatcher.match(IP));
}
}
}
}
@AfterClass
static public void cleanup()
{

View File

@@ -20,8 +20,8 @@ import static org.hamcrest.CoreMatchers.*;
import mockit.*;
import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.LicenseManager;
/**
* Unit Tests for class Collection
@@ -198,7 +198,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
*/
@Test
@Override
public void testGetID()
public void testGetID()
{
assertTrue("testGetID 0", c.getID() >= 1);
}
@@ -208,7 +208,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
*/
@Test
@Override
public void testGetHandle()
public void testGetHandle()
{
//default instance has a random handle
assertTrue("testGetHandle 0", c.getHandle().contains("123456789/"));
@@ -662,17 +662,17 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of getLicense method, of class Collection.
*/
@Test
public void testGetLicense()
public void testGetLicense()
{
assertThat("testGetLicense 0", c.getLicense(), notNullValue());
assertThat("testGetLicense 1", c.getLicense(), equalTo(ConfigurationManager.getDefaultSubmissionLicense()));
assertThat("testGetLicense 1", c.getLicense(), equalTo(LicenseManager.getDefaultSubmissionLicense()));
}
/**
* Test of getLicenseCollection method, of class Collection.
*/
@Test
public void testGetLicenseCollection()
public void testGetLicenseCollection()
{
assertThat("testGetLicenseCollection 0", c.getLicenseCollection(), notNullValue());
assertThat("testGetLicenseCollection 1", c.getLicenseCollection(), equalTo(""));
@@ -682,7 +682,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of hasCustomLicense method, of class Collection.
*/
@Test
public void testHasCustomLicense()
public void testHasCustomLicense()
{
assertFalse("testHasCustomLicense 0", c.hasCustomLicense());
}
@@ -691,7 +691,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of setLicense method, of class Collection.
*/
@Test
public void testSetLicense()
public void testSetLicense()
{
String license = "license for test";
c.setLicense(license);
@@ -705,7 +705,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of getTemplateItem method, of class Collection.
*/
@Test
public void testGetTemplateItem() throws Exception
public void testGetTemplateItem() throws Exception
{
assertThat("testGetTemplateItem 0", c.getTemplateItem(), nullValue());
}
@@ -1336,7 +1336,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
assertFalse("testCanEditBooleanNoAuth_boolean 0",c.canEditBoolean(false));
}
/**
* Test of canEditBoolean method, of class Collection.
*/
@@ -1789,7 +1789,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
*/
@Test
@Override
public void testGetType()
public void testGetType()
{
assertThat("testGetType 0", c.getType(), equalTo(Constants.COLLECTION));
}
@@ -1798,7 +1798,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest
* Test of findAuthorized method, of class Collection.
*/
@Test
public void testFindAuthorized() throws Exception
public void testFindAuthorized() throws Exception
{
context.turnOffAuthorisationSystem();
Community com = Community.create(null, context);

View File

@@ -766,6 +766,37 @@ public class CommunityTest extends AbstractDSpaceObjectTest
assertThat("testGetAllParents 4", son.getAllParents()[0], equalTo(c));
}
/**
* Test of getAllCollections method, of class Community.
*/
@Test
public void testGetAllCollections() throws Exception
{
new NonStrictExpectations()
{
AuthorizeManager authManager;
{
AuthorizeManager.authorizeAction((Context) any, (Community) any,
Constants.ADD); result = null;
AuthorizeManager.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD); result = true;
}
};
//empty by default
assertThat("testGetAllCollections 0",c.getAllCollections(), notNullValue());
assertTrue("testGetAllCollections 1", c.getAllCollections().length == 0);
//community has a collection and a subcommunity, subcommunity has a collection
Collection collOfC = c.createCollection();
Community sub = Community.create(c, context);
Collection collOfSub = sub.createCollection();
assertThat("testGetAllCollections 2",c.getAllCollections(), notNullValue());
assertTrue("testGetAllCollections 3", c.getAllCollections().length == 2);
assertThat("testGetAllCollections 4", c.getAllCollections()[0], equalTo(collOfSub));
assertThat("testGetAllCollections 5", c.getAllCollections()[1], equalTo(collOfC));
}
/**
* Test of createCollection method, of class Community.
*/

View File

@@ -13,13 +13,13 @@ import java.sql.SQLException;
import java.util.HashMap;
import org.dspace.authorize.AuthorizeException;
import org.dspace.eperson.EPerson;
import org.dspace.core.ConfigurationManager;
import org.dspace.AbstractUnitTest;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dspace.core.LicenseManager;
import org.junit.*;
import static org.junit.Assert.* ;
import static org.hamcrest.CoreMatchers.*;
@@ -81,7 +81,7 @@ public class LicenseUtilsTest extends AbstractUnitTest
String templateLong = "Template license: %1$s %2$s %3$s %5$s %6$s %8$s %9$s %10$s %11$s";
String templateResult = "Template license: first name last name test@email.com ";
String templateLongResult = "Template license: first name last name test@email.com arg1 arg2 arg3 arg4";
String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense();
String defaultLicense = LicenseManager.getDefaultSubmissionLicense();
context.turnOffAuthorisationSystem();
//TODO: the tested method doesn't verify the input, will throw NPE if any parameter is null
@@ -154,10 +154,10 @@ public class LicenseUtilsTest extends AbstractUnitTest
additionalInfo = new LinkedHashMap<String, Object>();
additionalInfo.put("arg1", "arg1");
additionalInfo.put("arg2", "arg2");
additionalInfo.put("arg3", "arg3");
additionalInfo.put("arg3", "arg3");
additionalInfo.put("arg4", "arg4");
assertThat("testGetLicenseText_5args 5", LicenseUtils.getLicenseText(locale, collection, item, person, additionalInfo), equalTo(templateLongResult));
context.restoreAuthSystemState();
}
@@ -175,7 +175,7 @@ public class LicenseUtilsTest extends AbstractUnitTest
String template = "Template license: %1$s %2$s %3$s %5$s %6$s";
String templateResult = "Template license: first name last name test@email.com ";
String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense();
String defaultLicense = LicenseManager.getDefaultSubmissionLicense();
context.turnOffAuthorisationSystem();
//TODO: the tested method doesn't verify the input, will throw NPE if any parameter is null
@@ -207,7 +207,7 @@ public class LicenseUtilsTest extends AbstractUnitTest
person = EPerson.create(context);
person.setFirstName("first name");
person.setLastName("last name");
person.setEmail("test@email.com");
person.setEmail("test@email.com");
assertThat("testGetLicenseText_5args 3", LicenseUtils.getLicenseText(locale, collection, item, person), equalTo(templateResult));
locale = Locale.GERMAN;
@@ -227,11 +227,11 @@ public class LicenseUtilsTest extends AbstractUnitTest
* Test of grantLicense method, of class LicenseUtils.
*/
@Test
public void testGrantLicense() throws Exception
public void testGrantLicense() throws Exception
{
context.turnOffAuthorisationSystem();
Item item = Item.create(context);
String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense();
String defaultLicense = LicenseManager.getDefaultSubmissionLicense();
LicenseUtils.grantLicense(context, item, defaultLicense);

View File

@@ -0,0 +1,578 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.statistics.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* A mock request for testing.
*
* @author mwood
*/
class DummyHttpServletRequest implements HttpServletRequest
{
private String agent = null;
private String address = null;
private String remoteHost = null;
public void setAgent(String agent)
{
this.agent = agent;
}
public void setAddress(String address)
{
this.address = address;
}
public void setRemoteHost(String host)
{
this.remoteHost = host;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getAuthType()
*/
@Override
public String getAuthType()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getContextPath()
*/
@Override
public String getContextPath()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getCookies()
*/
@Override
public Cookie[] getCookies()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
*/
@Override
public long getDateHeader(String arg0)
{
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
*/
@Override
public String getHeader(String key)
{
if ("User-Agent".equals(key))
{
return agent;
}
else
{
return null;
}
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getHeaderNames()
*/
@Override
public Enumeration getHeaderNames()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
*/
@Override
public Enumeration getHeaders(String arg0)
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
*/
@Override
public int getIntHeader(String arg0)
{
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getMethod()
*/
@Override
public String getMethod()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getPathInfo()
*/
@Override
public String getPathInfo()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getPathTranslated()
*/
@Override
public String getPathTranslated()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getQueryString()
*/
@Override
public String getQueryString()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getRemoteUser()
*/
@Override
public String getRemoteUser()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getRequestURI()
*/
@Override
public String getRequestURI()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getRequestURL()
*/
@Override
public StringBuffer getRequestURL()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
*/
@Override
public String getRequestedSessionId()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getServletPath()
*/
@Override
public String getServletPath()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getSession()
*/
@Override
public HttpSession getSession()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getSession(boolean)
*/
@Override
public HttpSession getSession(boolean arg0)
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
*/
@Override
public Principal getUserPrincipal()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
*/
@Override
public boolean isRequestedSessionIdFromCookie()
{
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
*/
@Override
public boolean isRequestedSessionIdFromURL()
{
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
*/
@Override
public boolean isRequestedSessionIdFromUrl()
{
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
*/
@Override
public boolean isRequestedSessionIdValid()
{
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
*/
@Override
public boolean isUserInRole(String arg0)
{
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getAttribute(java.lang.String)
*/
@Override
public Object getAttribute(String arg0)
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getAttributeNames()
*/
@Override
public Enumeration getAttributeNames()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getCharacterEncoding()
*/
@Override
public String getCharacterEncoding()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getContentLength()
*/
@Override
public int getContentLength()
{
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getContentType()
*/
@Override
public String getContentType()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getInputStream()
*/
@Override
public ServletInputStream getInputStream() throws IOException
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getLocale()
*/
@Override
public Locale getLocale()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getLocales()
*/
@Override
public Enumeration getLocales()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameter(java.lang.String)
*/
@Override
public String getParameter(String arg0)
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameterMap()
*/
@Override
public Map getParameterMap()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameterNames()
*/
@Override
public Enumeration getParameterNames()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
*/
@Override
public String[] getParameterValues(String arg0)
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getProtocol()
*/
@Override
public String getProtocol()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getReader()
*/
@Override
public BufferedReader getReader() throws IOException
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getRealPath(java.lang.String)
*/
@Override
public String getRealPath(String arg0)
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getRemoteAddr()
*/
@Override
public String getRemoteAddr()
{
return address;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getRemoteHost()
*/
@Override
public String getRemoteHost()
{
return remoteHost;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
*/
@Override
public RequestDispatcher getRequestDispatcher(String arg0)
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getScheme()
*/
@Override
public String getScheme()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getServerName()
*/
@Override
public String getServerName()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#getServerPort()
*/
@Override
public int getServerPort()
{
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#isSecure()
*/
@Override
public boolean isSecure()
{
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
*/
@Override
public void removeAttribute(String arg0)
{
throw new UnsupportedOperationException("Not supported yet.");
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#setAttribute(java.lang.String, java.lang.Object)
*/
@Override
public void setAttribute(String arg0, Object arg1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
*/
@Override
public void setCharacterEncoding(String arg0)
throws UnsupportedEncodingException
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getRemotePort()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLocalName()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLocalAddr()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getLocalPort()
{
throw new UnsupportedOperationException("Not supported yet.");
}
}

View File

@@ -0,0 +1,170 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.statistics.util;
import mockit.Mock;
import mockit.MockClass;
import mockit.Mockit;
import org.dspace.statistics.SolrLogger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author mwood
*/
public class SpiderDetectorTest
{
private static final String NOT_A_BOT_ADDRESS = "192.168.0.1";
@BeforeClass
static public void beforeClass()
{
Mockit.setUpMocks(MockSolrLogger.class); // Don't test SolrLogger here
}
@AfterClass
static public void afterClass()
{
Mockit.tearDownMocks(SolrLogger.class);
}
/**
* Test method for {@link org.dspace.statistics.util.SpiderDetector#readPatterns(java.io.File)}.
*/
@Test
public void testReadPatterns()
{
// FIXME fail("Not yet implemented");
}
/**
* Test method for {@link org.dspace.statistics.util.SpiderDetector#getSpiderIpAddresses()}.
*/
@Test
public void testGetSpiderIpAddresses()
{
// FIXME fail("Not yet implemented");
}
/**
* Test method for {@link org.dspace.statistics.util.SpiderDetector#isSpider(javax.servlet.http.HttpServletRequest)}.
*/
@Test
public void testIsSpiderHttpServletRequest()
{
DummyHttpServletRequest req = new DummyHttpServletRequest();
req.setAddress(NOT_A_BOT_ADDRESS); // avoid surprises
req.setRemoteHost("notabot.example.com"); // avoid surprises
req.setAgent("Firefox"); // avoid surprises
String candidate;
// Test agent patterns
req.setAgent("msnbot is watching you");
assertTrue("'msnbot' did not match any pattern", SpiderDetector.isSpider(req));
req.setAgent("Firefox");
assertFalse("'Firefox' matched a pattern", SpiderDetector.isSpider(req));
// Test IP patterns
candidate = "192.168.2.1";
req.setAddress(candidate);
assertTrue(candidate + " did not match IP patterns", SpiderDetector.isSpider(req));
req.setAddress(NOT_A_BOT_ADDRESS);
assertFalse(NOT_A_BOT_ADDRESS + " matched IP patterns", SpiderDetector.isSpider(req));
// Test DNS patterns
candidate = "baiduspider-dspace-test.crawl.baidu.com";
req.setRemoteHost(candidate);
assertTrue(candidate + " did not match DNS patterns", SpiderDetector.isSpider(req));
candidate = "wiki.dspace.org";
req.setRemoteHost(candidate);
assertFalse(candidate + " matched DNS patterns", SpiderDetector.isSpider(req));
}
/**
* Test method for {@link org.dspace.statistics.util.SpiderDetector#isSpider(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
public void testIsSpiderStringStringStringString()
{
String candidate;
// Test IP patterns
candidate = "192.168.2.1";
assertTrue(candidate + " did not match IP patterns",
SpiderDetector.isSpider(candidate, null, null, null));
candidate = NOT_A_BOT_ADDRESS;
assertFalse(candidate + " matched IP patterns",
SpiderDetector.isSpider(candidate, null, null, null));
// Test DNS patterns
candidate = "baiduspider-dspace-test.crawl.baidu.com";
assertTrue(candidate + " did not match DNS patterns",
SpiderDetector.isSpider(NOT_A_BOT_ADDRESS, null, candidate, null));
candidate = "wiki.dspace.org";
assertFalse(candidate + " matched DNS patterns",
SpiderDetector.isSpider(NOT_A_BOT_ADDRESS, null, candidate, null));
// Test agent patterns
candidate = "msnbot is watching you";
assertTrue("'" + candidate + "' did not match agent patterns",
SpiderDetector.isSpider(NOT_A_BOT_ADDRESS, null, null, candidate));
candidate = "Firefox";
assertFalse("'" + candidate + "' matched agent patterns",
SpiderDetector.isSpider(NOT_A_BOT_ADDRESS, null, null, candidate));
}
/**
* Test method for {@link org.dspace.statistics.util.SpiderDetector#isSpider(java.lang.String)}.
*/
@Test
public void testIsSpiderString()
{
String candidate;
candidate = "192.168.2.1";
assertTrue(candidate + " did not match IP patterns",
SpiderDetector.isSpider(candidate, null, null, null));
candidate = NOT_A_BOT_ADDRESS;
assertFalse(candidate + " matched IP patterns",
SpiderDetector.isSpider(candidate, null, null, null));
}
/**
* Dummy SolrLogger for testing.
* @author mwood
*/
@MockClass (realClass = org.dspace.statistics.SolrLogger.class)
static public class MockSolrLogger
{
@Mock
public void $init() {}
@Mock
public void $clinit() {}
@Mock
public boolean isUseProxies()
{
return false;
}
}
}

View File

@@ -0,0 +1,137 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.content.Collection;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.plugin.CollectionHomeProcessor;
import org.dspace.plugin.PluginException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowserScope;
import org.dspace.browse.BrowseException;
import org.dspace.sort.SortException;
import org.dspace.sort.SortOption;
/**
* This class obtains item list of the given collection by
* implementing the CollectionHomeProcessor.
*
* @author Keiji Suzuki
*
*/
public class CollectionItemList implements CollectionHomeProcessor
{
// the name of a browse index to display collection's items
private static String name = ConfigurationManager.getProperty("webui.collectionhome.browse-name");
// the number of authors to display before trncating
private static final int etal = ConfigurationManager.getIntProperty("webui.browse.author-limit", -1);
// the number of items to display per page
private static final int perpage = ConfigurationManager.getIntProperty("webui.collectionhome.perpage", 20);
// whether does use "dateaccessioned" as a sort option
// If true and the sort option "dateaccessioned" exists, use "dateaccessioned" as a sort option.
// Otherwise use the sort option pertaining the specified browse index
private static boolean useDateaccessioned = ConfigurationManager.getBooleanProperty("webui.collectionhome.use.dateaccessioned", true);
// the number of sort option "dateaccessioned"
private static int number = -1;
static
{
if (name == null)
{
name = "title";
}
if (useDateaccessioned)
{
try
{
for (SortOption option : SortOption.getSortOptions())
{
if ("dateaccessioned".equals(option.getName()))
{
number = option.getNumber();
break;
}
}
}
catch (SortException e)
{
// does nothing
}
}
}
/**
* blank constructor - does nothing.
*
*/
public CollectionItemList()
{
}
/* (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
{
int offset = UIUtil.getIntParameter(request, "offset");
if (offset < 0)
{
offset = 0;
}
try
{
BrowseIndex bi = BrowseIndex.getBrowseIndex(name);
if (bi == null || !"item".equals(bi.getDisplayType()))
{
request.setAttribute("show.items", Boolean.FALSE);
return;
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseContainer(collection);
scope.setBrowseIndex(bi);
scope.setEtAl(etal);
scope.setOffset(offset);
scope.setResultsPerPage(perpage);
if (number != -1)
{
scope.setSortBy(number);
scope.setOrder(SortOption.DESCENDING);
}
BrowseEngine be = new BrowseEngine(context);
BrowseInfo binfo = be.browse(scope);
request.setAttribute("browse.info", binfo);
if (binfo.hasResults())
{
request.setAttribute("show.items", Boolean.TRUE);
}
else
{
request.setAttribute("show.items", Boolean.FALSE);
}
}
catch (BrowseException e)
{
request.setAttribute("show.items", Boolean.FALSE);
}
}
}

View File

@@ -0,0 +1,56 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.plugin.SiteHomeProcessor;
import org.dspace.plugin.PluginException;
/**
* This class obtains recent submissions to the site by
* implementing the SiteHomeProcessor.
*
* @author Keiji Suzuki
*
*/
public class RecentSiteSubmissions implements SiteHomeProcessor
{
/**
* blank constructor - does nothing.
*
*/
public RecentSiteSubmissions()
{
}
/* (non-Javadoc)
* @see org.dspace.plugin.CommunityHomeProcessor#process(org.dspace.core.Context, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.dspace.content.Community)
*/
@Override
public void process(Context context, HttpServletRequest request, HttpServletResponse response)
throws PluginException, AuthorizeException
{
try
{
RecentSubmissionsManager rsm = new RecentSubmissionsManager(context);
RecentSubmissions recent = rsm.getRecentSubmissions(null);
request.setAttribute("recent.submissions", recent);
}
catch (RecentSubmissionsException e)
{
throw new PluginException(e);
}
}
}

View File

@@ -52,7 +52,7 @@ public class RecentSubmissionsManager
* 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
* @param dso DSpaceObject: Community, Collection or null for SITE
* @return The recently submitted items
* @throws RecentSubmissionsException
*/
@@ -74,7 +74,10 @@ public class RecentSubmissionsManager
bs.setBrowseIndex(bi);
bs.setOrder(SortOption.DESCENDING);
bs.setResultsPerPage(Integer.parseInt(count));
bs.setBrowseContainer(dso);
if (dso != null)
{
bs.setBrowseContainer(dso);
}
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(source))

View File

@@ -0,0 +1,58 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.components;
import java.sql.SQLException;
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.PluginException;
import org.dspace.plugin.SiteHomeProcessor;
/**
* This class add top communities object to the request attributes to use in
* the site home page implementing the SiteHomeProcessor.
*
* @author Andrea Bollini
*
*/
public class TopCommunitiesSiteProcessor implements SiteHomeProcessor
{
/**
* blank constructor - does nothing.
*
*/
public TopCommunitiesSiteProcessor()
{
}
@Override
public void process(Context context, HttpServletRequest request,
HttpServletResponse response) throws PluginException,
AuthorizeException
{
// Get the top communities to shows in the community list
Community[] communities;
try
{
communities = Community.findAllTop(context);
}
catch (SQLException e)
{
throw new PluginException(e.getMessage(), e);
}
request.setAttribute("communities", communities);
}
}

View File

@@ -541,7 +541,7 @@ public class DiscoverUtility
// Create facet queries but limit then to 11
// (11
// == when we need to show a show more url)
for (int year = topYear - gap; year > oldestYear
for (int year = topYear; year > oldestYear
&& (facetQueries.size() < 11); year -= gap)
{
// Add a filter to remove the last year

View File

@@ -25,6 +25,7 @@ import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.bulkedit.DSpaceCSV;
import org.dspace.app.bulkedit.MetadataExport;
@@ -41,6 +42,7 @@ import org.dspace.content.DSpaceObject;
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.core.I18nUtil;
import org.dspace.core.LogManager;
@@ -56,6 +58,8 @@ import org.w3c.dom.Document;
public class DiscoverySearchRequestProcessor implements SearchRequestProcessor
{
private static final int ITEMMAP_RESULT_PAGE_SIZE = 50;
private static String msgKey = "org.dspace.app.webui.servlet.FeedServlet";
/** log4j category */
@@ -64,12 +68,26 @@ public class DiscoverySearchRequestProcessor implements SearchRequestProcessor
// locale-sensitive metadata labels
private Map<String, Map<String, String>> localeLabels = null;
private List<String> searchIndices = null;
public synchronized void init()
{
if (localeLabels == null)
{
localeLabels = new HashMap<String, Map<String, String>>();
}
if (searchIndices == null)
{
searchIndices = new ArrayList<String>();
DiscoveryConfiguration discoveryConfiguration = SearchUtils
.getDiscoveryConfiguration();
searchIndices.add("any");
for (DiscoverySearchFilter sFilter : discoveryConfiguration.getSearchFilters())
{
searchIndices.add(sFilter.getIndexFieldName());
}
}
}
public void doOpenSearch(Context context, HttpServletRequest request,
@@ -480,4 +498,72 @@ public class DiscoverySearchRequestProcessor implements SearchRequestProcessor
response.sendRedirect(request.getContextPath() + "/simple-search");
}
/**
* Method for searching authors in item map
*
* author: gam
*/
@Override
public void doItemMapSearch(Context context, HttpServletRequest request,
HttpServletResponse response) throws SearchProcessorException, ServletException, IOException
{
String queryString = (String) request.getParameter("query");
Collection collection = (Collection) request.getAttribute("collection");
int page = UIUtil.getIntParameter(request, "page")-1;
int offset = page > 0? page * ITEMMAP_RESULT_PAGE_SIZE:0;
String idx = (String) request.getParameter("index");
if (StringUtils.isNotBlank(idx) && !idx.equalsIgnoreCase("any"))
{
queryString = idx + ":(" + queryString + ")";
}
DiscoverQuery query = new DiscoverQuery();
query.setQuery(queryString);
query.addFilterQueries("-location:l"+collection.getID());
query.setMaxResults(ITEMMAP_RESULT_PAGE_SIZE);
query.setStart(offset);
DiscoverResult results = null;
try
{
results = SearchUtils.getSearchService().search(context, query);
}
catch (SearchServiceException e)
{
throw new SearchProcessorException(e.getMessage(), e);
}
Map<Integer, Item> items = new HashMap<Integer, Item>();
List<DSpaceObject> resultDSOs = results.getDspaceObjects();
for (DSpaceObject dso : resultDSOs)
{
if (dso != null && dso.getType() == Constants.ITEM)
{
// no authorization check is required as discovery is right aware
Item item = (Item) dso;
items.put(Integer.valueOf(item.getID()), item);
}
}
request.setAttribute("browsetext", queryString);
request.setAttribute("items", items);
request.setAttribute("more", results.getTotalSearchResults() > offset + ITEMMAP_RESULT_PAGE_SIZE);
request.setAttribute("browsetype", "Add");
request.setAttribute("page", page > 0 ? page + 1 : 1);
JSPManager.showJSP(request, response, "itemmap-browse.jsp");
}
@Override
public String getI18NKeyPrefix()
{
return "jsp.search.filter.";
}
@Override
public List<String> getSearchIndices()
{
init();
return searchIndices;
}
}

View File

@@ -0,0 +1,62 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.json;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.dspace.app.webui.util.FileUploadListener;
import org.dspace.app.webui.util.FileUploadRequest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import com.google.gson.Gson;
public class UploadProgressJSON extends JSONRequest
{
@Override
public void doJSONRequest(Context context, HttpServletRequest req,
HttpServletResponse resp) throws AuthorizeException, IOException
{
HttpSession session = req.getSession(false);
if (session == null)
{
return;
}
FileUploadListener listner = (FileUploadListener) session
.getAttribute(FileUploadRequest.FILE_UPLOAD_LISTNER);
if (listner == null || listner.getContentLength() == 0)
{
return;
}
else
{
long contentLength = listner.getContentLength();
UploadProgressDTO dto = new UploadProgressDTO();
long bytesRead = listner.getBytesRead();
dto.readBytes = bytesRead;
dto.totalBytes = contentLength;
Gson gson = new Gson();
resp.getWriter().write(gson.toJson(dto));
if (listner.isCompleted())
{
session.removeAttribute(FileUploadRequest.FILE_UPLOAD_LISTNER);
}
}
}
}
class UploadProgressDTO {
long totalBytes;
long readBytes;
}

View File

@@ -0,0 +1,372 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.jsptag;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.eperson.Group;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.sql.SQLException;
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;
/**
* Tag to display embargo settings
*
* @author Keiji Suzuki
* @version $Revision$
*/
public class AccessSettingTag extends TagSupport
{
/** log4j category */
private static Logger log = Logger.getLogger(AccessSettingTag.class);
/** is advanced form enabled? */
private static final boolean advanced = ConfigurationManager.getBooleanProperty("webui.submission.restrictstep.enableAdvancedForm", false);
/** Name of the restricted group */
private static final String restrictedGroup = ConfigurationManager.getProperty("webui.submission.restrictstep.groups");
/** the SubmittionInfo */
private transient SubmissionInfo subInfo = null;
/** the target DSpaceObject */
private transient DSpaceObject dso = null;
/** the target ResourcePolicy */
private transient ResourcePolicy rp = null;
/** disable the radio button for open/embargo access */
private boolean embargo = false;
/** hide the embargo date and reason fields */
private boolean hidden = false;
/** add the policy button */
private boolean addpolicy = false;
public AccessSettingTag()
{
super();
}
public int doStartTag() throws JspException
{
String legend = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.legend");
String label_name = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.label_name");
String label_group = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.label_group");
String label_embargo = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.label_embargo");
String label_date = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.label_date");
String radio0 = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.radio0");
String radio1 = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.radio1");
String radio_help = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.radio_help");
String label_reason = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.label_reason");
String button_confirm = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.access-setting.button_confirm");
JspWriter out = pageContext.getOut();
StringBuffer sb = new StringBuffer();
try
{
HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();
Context context = UIUtil.obtainContext(hrq);
// get startDate and reason of the resource policy of the target DSpaceObject
List<ResourcePolicy> policies = null;
if (!advanced && dso != null)
{
policies = AuthorizeManager.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM);
}
else if (rp != null)
{
policies = new ArrayList<ResourcePolicy>();
policies.add(rp);
}
String name = "";
int group_id = 0;
String startDate = "";
String reason = "";
String radio0Checked = " checked=\"checked\"";
String radio1Checked = "";
String disabled = " disabled=\"disabled\"";
if (policies != null && policies.size() > 0)
{
ResourcePolicy rp = policies.get(0);
name = (rp.getRpName() == null ? "" : rp.getRpName());
group_id = rp.getGroup().getID();
startDate = (rp.getStartDate() != null ? DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd") : "");
reason = (rp.getRpDescription() == null ? "" : rp.getRpDescription());
if (!startDate.equals(""))
{
radio0Checked = "";
radio1Checked = " checked=\"checked\"";
disabled = "";
}
}
// if advanced embargo is disabled, embargo date and reason fields are always enabled
if (!advanced) {
disabled = "";
}
if (embargo)
{
// Name
sb.append("<div class=\"form-group\">");
sb.append(label_name).append("\n");
sb.append("<input class=\"form-control\" name=\"name\" id=\"policy_name\" type=\"text\" value=\"").append(name).append("\" />\n");
sb.append("</div>");
// Group
sb.append("<div class=\"form-group\">");
sb.append(label_group).append("\n");
sb.append("<select class=\"form-control\" name=\"group_id\" id=\"select_group\">\n");
Group[] groups = getGroups(context, hrq, subInfo);
if (groups != null)
{
for (Group group : groups)
{
sb.append("<option value=\"").append(group.getID()).append("\"");
if (group_id == group.getID()) {
sb.append(" selected=\"selected\"");
}
sb.append(">").append(group.getName()).append("</option>\n");
}
}
else
{
sb.append("<option value=\"0\" selected=\"selected\">Anonymous</option>\n");
}
sb.append("</select>\n");
sb.append("</div>");
// Select open or embargo
sb.append(label_embargo).append("\n");
sb.append("<div class=\"radio\">");
sb.append("<label><input name=\"open_access_radios\" type=\"radio\" value=\"0\"").append(radio0Checked).append(" />").append(radio0).append("</label>\n");
sb.append("</div>");
sb.append("<div class=\"radio\">");
sb.append("<label><input name=\"open_access_radios\" type=\"radio\" value=\"1\"").append(radio1Checked).append(" />").append(radio1).append("</label>\n");
sb.append("</div>");
}
// Embargo Date
if (hidden)
{
sb.append("<input name=\"embargo_until_date\" id=\"embargo_until_date_hidden\" type=\"hidden\" value=\"").append(startDate).append("\" />\n");;
sb.append("<input name=\"reason\" id=\"reason_hidden\" type=\"hidden\" value=\"").append(reason).append("\" />\n");
}
else
{
sb.append("<div class=\"form-group\">");
sb.append(label_date).append("\n");
sb.append("<input class=\"form-control\" name=\"embargo_until_date\" id=\"embargo_until_date\" type=\"text\" value=\"").append(startDate).append("\"").append(disabled).append(" />\n");;
sb.append("<span class=\"help-block\">"+radio_help+"</span><br/>");
// Reason
sb.append(label_reason).append("\n");
sb.append("<textarea class=\"form-control\" name=\"reason\" id=\"reason\" cols=\"30\" rows=\"5\"").append(disabled).append(">").append(reason).append("</textarea>\n");
sb.append("</div>");
}
// Add policy button
if (addpolicy)
{
sb.append("<input class=\"btn btn-success col-md-offset-5\" name=\"submit_add_policy\" type=\"submit\" value=\"").append(button_confirm).append("\" />\n");
}
out.println(sb.toString());
}
catch (IOException ie)
{
throw new JspException(ie);
}
catch (SQLException e)
{
throw new JspException(e);
}
return SKIP_BODY;
}
/**
* Get the browseInfo
*
* @return the browseInfo
*/
public SubmissionInfo getSubInfo()
{
return subInfo;
}
/**
* Set the browseInfo
*
* @param browseInfo
* the browseInfo
*/
public void setSubInfo(SubmissionInfo subInfo)
{
this.subInfo = subInfo;
}
/**
* Get the dso
*
* @return the dso
*/
public DSpaceObject getDso()
{
return dso;
}
/**
* Set the the dso
*
* @param the dso
* the dso
*/
public void setDso(DSpaceObject dso)
{
this.dso = dso;
}
/**
* Get the rp
*
* @return the rp
*/
public ResourcePolicy getRp()
{
return rp;
}
/**
* Set the the rp
*
* @param the rp
* the rp
*/
public void setRp(ResourcePolicy rp)
{
this.rp = rp;
}
/**
* Get the display open/embargo setting radio flag
*
* @return radio
*/
public boolean getEmbargo()
{
return embargo;
}
/**
* Set the display open/embargo setting radio flag
*
* @param embargo
* boolean
*/
public void setEmbargo(boolean embargo)
{
this.embargo = embargo;
}
/**
* Get the hidden flag
*
* @return hidden
*/
public boolean getHidden()
{
return hidden;
}
/**
* Set the hidden flag
*
* @param hidden
* boolean
*/
public void setHidden(boolean hidden)
{
this.hidden = hidden;
}
/**
* Set the add_policy button flag
*
* @param addpolicy
* boolean
*/
public void setAddpolicy(boolean addpolicy)
{
this.addpolicy = addpolicy;
}
/**
* Get the add_policy button flag
*
* @return addpolicy
*/
public boolean getAddpolicy()
{
return addpolicy;
}
public void release()
{
dso = null;
subInfo = null;
rp = null;
embargo = false;
hidden = false;
addpolicy = false;
}
private Group[] getGroups(Context context, HttpServletRequest request, SubmissionInfo subInfo)
throws SQLException
{
Group[] groups = null;
// retrieve groups
if (restrictedGroup != null)
{
Group uiGroup = Group.findByName(context, restrictedGroup);
if (uiGroup != null)
{
groups = uiGroup.getMemberGroups();
}
}
if (groups == null || groups.length == 0){
groups = Group.findAll(context, Group.NAME);
}
return groups;
}
}

View File

@@ -300,12 +300,12 @@ public class BrowseListTag extends TagSupport
// If the table width has been specified, we can make this a fixed layout
if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
else
{
// Otherwise, don't constrain the width
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
// Output the known column widths
@@ -332,11 +332,11 @@ public class BrowseListTag extends TagSupport
}
else if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
else
{
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
// Output the table headers
@@ -482,8 +482,8 @@ public class BrowseListTag extends TagSupport
DCDate dd = new DCDate(metadataArray[0].value);
metadata = UIUtil.displayDate(dd, false, false, hrq);
}
// format the title field correctly for withdrawn items (ie. don't link)
else if (field.equals(titleField) && items[i].isWithdrawn())
// format the title field correctly for withdrawn and private items (ie. don't link)
else if (field.equals(titleField) && (items[i].isWithdrawn() || !isDiscoverable(hrq, items[i])))
{
metadata = Utils.addEntities(metadataArray[0].value);
}
@@ -887,4 +887,21 @@ public class BrowseListTag extends TagSupport
throw new JspException("Server does not support DSpace's default encoding. ", e);
}
}
/* whether the embedded item of the bitem is discoverable or not? */
private boolean isDiscoverable(HttpServletRequest hrq, BrowseItem bitem)
throws JspException
{
try
{
Context c = UIUtil.obtainContext(hrq);
Item item = Item.find(c, bitem.getID());
return item.isDiscoverable();
}
catch (SQLException sqle)
{
throw new JspException(sqle.getMessage(), sqle);
}
}
}

View File

@@ -42,7 +42,7 @@ public class CollectionListTag extends TagSupport
try
{
out.println("<table align=\"center\" class=\"miscTable\" title=\"Collection List\">");
out.println("<table align=\"center\" class=\"table\" title=\"Collection List\">");
// Write column headings
out.print("<tr><th id=\"t4\" class=\"oddRowOddCol\">"

View File

@@ -42,7 +42,7 @@ public class CommunityListTag extends TagSupport
try
{
out.println("<table align=\"center\" class=\"miscTable\" title=\"Community List\">");
out.println("<table align=\"center\" class=\"table\" title=\"Community List\">");
// Write column headings
out.print("<tr><th id=\"t5\" class=\"oddRowOddCol\">"

View File

@@ -267,12 +267,12 @@ public class ItemListTag extends TagSupport
// If the table width has been specified, we can make this a fixed layout
if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
else
{
// Otherwise, don't constrain the width
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
// Output the known column widths
@@ -299,11 +299,11 @@ public class ItemListTag extends TagSupport
}
else if (!StringUtils.isEmpty(tablewidth))
{
out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
else
{
out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
out.println("<table align=\"center\" class=\"table\" summary=\"This table browses all dspace content\">");
}
// Output the table headers

View File

@@ -391,7 +391,7 @@ public class ItemTag extends TagSupport
configLine = defaultFields;
}
out.println("<center><table class=\"itemDisplayTable\">");
out.println("<table class=\"table itemDisplayTable\">");
/*
* Break down the configuration into fields and display them
@@ -623,7 +623,7 @@ public class ItemTag extends TagSupport
listCollections();
out.println("</table></center><br/>");
out.println("</table><br/>");
listBitstreams();
@@ -648,12 +648,12 @@ public class ItemTag extends TagSupport
// Get all the metadata
DCValue[] values = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
out.println("<p align=\"center\">"
out.println("<div class=\"panel panel-info\"><div class=\"panel-heading\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.full") + "</p>");
"org.dspace.app.webui.jsptag.ItemTag.full") + "</div>");
// Three column table - DC field, value, language
out.println("<center><table class=\"itemDisplayTable\">");
out.println("<table class=\"panel-body table itemDisplayTable\">");
out.println("<tr><th id=\"s1\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.dcfield")
@@ -697,7 +697,7 @@ public class ItemTag extends TagSupport
listCollections();
out.println("</table></center><br/>");
out.println("</table></div><br/>");
listBitstreams();
@@ -757,11 +757,11 @@ public class ItemTag extends TagSupport
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
out.print("<table align=\"center\" class=\"miscTable\"><tr>");
out.println("<td class=\"evenRowEvenCol\"><p><strong>"
out.print("<div class=\"panel panel-info\">");
out.println("<div class=\"panel-heading\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files")
+ "</strong></p>");
+ "</div>");
try
{
@@ -781,10 +781,10 @@ public class ItemTag extends TagSupport
// if user already has uploaded at least one file
if (!filesExist)
{
out.println("<p>"
out.println("<div class=\"panel-body\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.files.no")
+ "</p>");
+ "</div>");
}
else
{
@@ -824,7 +824,7 @@ public class ItemTag extends TagSupport
}
out
.println("<table cellpadding=\"6\"><tr><th id=\"t1\" class=\"standard\">"
.println("<table class=\"table panel-body\"><tr><th id=\"t1\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.file")
+ "</th>");
@@ -846,7 +846,7 @@ public class ItemTag extends TagSupport
+ "</th><th id=\"t4\" class=\"standard\">"
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.ItemTag.fileformat")
+ "</th></tr>");
+ "</th><th>&nbsp;</th></tr>");
// if primary bitstream is html, display a link for only that one to
// HTMLServlet
@@ -886,7 +886,7 @@ public class ItemTag extends TagSupport
out.print("</td><td headers=\"t4\" class=\"standard\">");
out.print(primaryBitstream.getFormatDescription());
out
.print("</td><td class=\"standard\"><a target=\"_blank\" href=\"");
.print("</td><td class=\"standard\"><a class=\"btn btn-primary\" target=\"_blank\" href=\"");
out.print(request.getContextPath());
out.print("/html/");
out.print(handle + "/");
@@ -913,7 +913,7 @@ public class ItemTag extends TagSupport
// Work out what the bitstream link should be
// (persistent
// ID if item has Handle)
String bsLink = "<a target=\"_blank\" href=\""
String bsLink = "target=\"_blank\" href=\""
+ request.getContextPath();
if ((handle != null)
@@ -936,7 +936,8 @@ public class ItemTag extends TagSupport
out
.print("<tr><td headers=\"t1\" class=\"standard\">");
out.print(bsLink);
out.print("<a ");
out.print(bsLink);
out.print(bitstreams[k].getName());
out.print("</a>");
@@ -977,6 +978,7 @@ public class ItemTag extends TagSupport
.getName(),
Constants.DEFAULT_ENCODING);
out.print("<a ");
out.print(bsLink);
out.print("<img src=\"" + myPath + "\" ");
out.print("alt=\"" + tAltText
@@ -984,6 +986,7 @@ public class ItemTag extends TagSupport
}
}
out.print("<a class=\"btn btn-primary\" ");
out
.print(bsLink
+ LocaleSupport
@@ -1004,7 +1007,7 @@ public class ItemTag extends TagSupport
throw new IOException(sqle.getMessage(), sqle);
}
out.println("</td></tr></table>");
out.println("</div>");
}
private void getThumbSettings()
@@ -1032,7 +1035,7 @@ public class ItemTag extends TagSupport
throw new IOException(sqle.getMessage(), sqle);
}
out.println("<table align=\"center\" class=\"attentionTable\"><tr>");
out.println("<table align=\"center\" class=\"table attentionTable\"><tr>");
out.println("<td class=\"attentionCell\"><p><strong>"
+ LocaleSupport.getLocalizedMessage(pageContext,
@@ -1046,7 +1049,7 @@ public class ItemTag extends TagSupport
for (int k = 0; k < bitstreams.length; k++)
{
out.print("<div align=\"center\" class=\"standard\">");
out.print("<strong><a target=\"_blank\" href=\"");
out.print("<strong><a class=\"btn btn-primary\" target=\"_blank\" href=\"");
out.print(request.getContextPath());
out.print("/retrieve/");
out.print(bitstreams[k].getID() + "/");

View File

@@ -19,13 +19,14 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.webui.servlet.FeedServlet;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
import org.dspace.app.webui.servlet.FeedServlet;
/**
* Tag for HTML page layout ("skin").
@@ -74,7 +75,7 @@ import org.dspace.app.webui.servlet.FeedServlet;
* @author Robert Tansley
* @version $Revision$
*/
public class LayoutTag extends TagSupport
public class LayoutTag extends BodyTagSupport
{
/** log4j logger */
private static Logger log = Logger.getLogger(LayoutTag.class);
@@ -112,24 +113,27 @@ public class LayoutTag extends TagSupport
/** Syndication feed "autodiscovery" link data */
private String feedData;
private String templatePath;
public LayoutTag()
{
super();
String template = ConfigurationManager.getProperty("jspui", "template.name");
if (StringUtils.isNotBlank(template)
&& !"default".equalsIgnoreCase(template))
{
templatePath = "/layout/" + template + "/";
}
else
{
templatePath = "/layout/";
}
}
public int doStartTag() throws JspException
{
ServletRequest request = pageContext.getRequest();
// header file
String header = "/layout/header-default.jsp";
// Choose default style unless one is specified
if (style != null)
{
header = "/layout/header-" + style.toLowerCase() + ".jsp";
}
// Sort out location bar
if (locbar == null)
{
@@ -246,7 +250,7 @@ public class LayoutTag extends TagSupport
}
else
{
request.setAttribute("dspace.layout.navbar", "/layout/navbar-"
request.setAttribute("dspace.layout.navbar", templatePath + "navbar-"
+ navbar + ".jsp");
}
@@ -323,12 +327,34 @@ public class LayoutTag extends TagSupport
request.setAttribute("dspace.layout.feedref", "NONE" );
}
return EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspException
{
// Context objects
ServletRequest request = pageContext.getRequest();
HttpServletResponse response = (HttpServletResponse) pageContext
.getResponse();
ServletConfig config = pageContext.getServletConfig();
// header file
String header = templatePath + "header-default.jsp";
// Choose default style unless one is specified
if (style != null)
{
header = templatePath + "header-" + style.toLowerCase() + ".jsp";
}
if (sidebar != null)
{
request.setAttribute("dspace.layout.sidebar", sidebar);
}
// Now include the header
try
{
HttpServletResponse response = (HttpServletResponse) pageContext
.getResponse();
// Set headers to prevent browser caching, if appropriate
if ((noCache != null) && noCache.equalsIgnoreCase("true"))
{
@@ -341,12 +367,13 @@ public class LayoutTag extends TagSupport
// in the response.
response.setContentType("text/html; charset=UTF-8");
ServletConfig config = pageContext.getServletConfig();
RequestDispatcher rd = config.getServletContext()
.getRequestDispatcher(header);
rd.include(request, response);
//pageContext.getOut().write(getBodyContent().getString());
getBodyContent().writeOut(pageContext.getOut());
}
catch (IOException ioe)
{
@@ -357,19 +384,14 @@ public class LayoutTag extends TagSupport
log.warn("Exception", se.getRootCause());
throw new JspException("Got ServletException: " + se);
}
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException
{
// Footer file to use
String footer = "/layout/footer-default.jsp";
String footer = templatePath + "footer-default.jsp";
// Choose default flavour unless one is specified
if (style != null)
{
footer = "/layout/footer-" + style.toLowerCase() + ".jsp";
footer = templatePath + "footer-" + style.toLowerCase() + ".jsp";
}
try
@@ -377,16 +399,6 @@ public class LayoutTag extends TagSupport
// Ensure body is included before footer
pageContext.getOut().flush();
// Context objects
ServletRequest request = pageContext.getRequest();
ServletResponse response = pageContext.getResponse();
ServletConfig config = pageContext.getServletConfig();
if (sidebar != null)
{
request.setAttribute("dspace.layout.sidebar", sidebar);
}
RequestDispatcher rd = config.getServletContext()
.getRequestDispatcher(footer);
@@ -401,6 +413,15 @@ public class LayoutTag extends TagSupport
throw new JspException("Got IOException: " + ioe);
}
style = null;
title = null;
sidebar = null;
navbar = null;
locbar = null;
parentTitle = null;
parentLink = null;
noCache = null;
feedData = null;
return EVAL_PAGE;
}
@@ -628,17 +649,4 @@ public class LayoutTag extends TagSupport
{
this.feedData = v;
}
public void release()
{
style = null;
title = null;
sidebar = null;
navbar = null;
locbar = null;
parentTitle = null;
parentLink = null;
noCache = null;
feedData = null;
}
}

View File

@@ -0,0 +1,132 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.jsptag;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
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.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.dspace.authorize.ResourcePolicy;
/**
* Tag to display embargo settings
*
* @author Keiji Suzuki
* @version $Revision$
*/
public class PoliciesListTag extends TagSupport
{
/** log4j category */
private static Logger log = Logger.getLogger(PoliciesListTag.class);
/** Groups to make options list */
private transient List<ResourcePolicy> policies = null;
public PoliciesListTag()
{
super();
}
public int doStartTag() throws JspException
{
String label_name = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.policies-list.label_name");
String label_action = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.policies-list.label_action");
String label_group = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.policies-list.label_group");
String label_sdate = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.policies-list.label_sdate");
String label_edate = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.policies-list.label_edate");
JspWriter out = pageContext.getOut();
StringBuffer sb = new StringBuffer();
try
{
sb.append("<table class=\"table\">\n");
sb.append("<tr>\n");
sb.append("<th class=\"accessHeadOdd\">").append(label_name).append("</th>\n");
sb.append("<th class=\"accessHeadEven\">").append(label_action).append("</th>\n");
sb.append("<th class=\"accessHeadOdd\">").append(label_group).append("</th>\n");
sb.append("<th class=\"accessHeadEven\">").append(label_sdate).append("</th>\n");
sb.append("<th class=\"accessHeadOdd\">").append(label_edate).append("</th>\n");
sb.append("<th class=\"accessButton\">&nbsp;</th>\n");
sb.append("</tr>\n");
if (policies != null && policies.size() > 0)
{
String column1 = "Even";
String column2 = "Odd";
for (ResourcePolicy policy : policies)
{
column1 = (column1.equals("Even") ? "Odd" : "Even");
column2 = (column2.equals("Even") ? "Odd" : "Even");
String rpName = (policy.getRpName() == null ? "" : policy.getRpName());
String startDate = (policy.getStartDate() == null ? "" : DateFormatUtils.format(policy.getStartDate(), "yyyy-MM-dd"));
String endDate = (policy.getEndDate() == null ? "" : DateFormatUtils.format(policy.getEndDate(), "yyyy-MM-dd"));
sb.append("<tr>\n");
sb.append("<td class=\"access").append(column1).append("\">").append(rpName).append("</td>\n");
sb.append("<td class=\"access").append(column2).append("\">").append(policy.getActionText()).append("</td>\n");
sb.append("<td class=\"access").append(column1).append("\">").append(policy.getGroup().getName()).append("</td>\n");
sb.append("<td class=\"access").append(column2).append("\">").append(startDate).append("</td>\n");
sb.append("<td class=\"access").append(column1).append("\">").append(endDate).append("</td>\n");
sb.append("<td class=\"accessButton\">\n");
sb.append("<input class=\"btn btn-default\" name=\"submit_edit_edit_policies_").append(policy.getID()).append("\" type=\"submit\" value=\"Edit\" /> <input class=\"btn btn-danger\" name=\"submit_delete_edit_policies_").append(policy.getID()).append("\" type=\"submit\" value=\"Remove\" />\n");
sb.append("</td></tr>\n");
}
}
sb.append("</table>\n");
out.println(sb.toString());
}
catch (IOException ie)
{
throw new JspException(ie);
}
catch (SQLException e)
{
throw new JspException(e);
}
return SKIP_BODY;
}
/**
* Get the policies to list
*
* @return the policies
*/
public List<ResourcePolicy> getPolicies()
{
return policies;
}
/**
* Set the policies to list
*
* @param itemsIn
* the policies
*/
public void setPolicies(List<ResourcePolicy> policies)
{
this.policies = policies;
}
public void release()
{
policies = null;
}
}

View File

@@ -108,7 +108,7 @@ public class SelectEPersonTag extends TagSupport
HttpServletRequest req = (HttpServletRequest) pageContext
.getRequest();
out.print("<table><tr><td colspan=\"2\" align=\"center\"><select multiple=\"multiple\" name=\"eperson_id\" size=\"");
out.print("<select class=\"form-control\" multiple=\"multiple\" name=\"eperson_id\" size=\"");
out.print(multiple ? "10" : "1");
out.println("\">");
// ensure that if no eperson is selected that a blank option is displayed - xhtml compliance
@@ -129,37 +129,27 @@ public class SelectEPersonTag extends TagSupport
}
// add blank option value if no person selected to ensure that code is xhtml compliant
//out.print("<option/>");
out.print("</select></td>");
if (multiple)
{
out.print("</tr><tr><td width=\"50%\" align=\"center\">");
}
else
{
out.print("<td>");
}
out.print("</select>");
out.print("<br/><div class=\"row container\">");
String p = (multiple ?
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectEPersonTag.selectPeople")
: LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectEPersonTag.selectPerson") );
out.print("<input type=\"button\" value=\"" + p
+ "\" onclick=\"javascript:popup_window('"
+ req.getContextPath() + "/tools/eperson-list?multiple="
+ multiple + "', 'eperson_popup');\" />");
if (multiple)
{
out.print("</td><td width=\"50%\" align=\"center\">");
out.print("<input type=\"button\" value=\""
out.print("<input class=\"btn btn-danger\" type=\"button\" value=\""
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectEPersonTag.removeSelected")
+ "\" onclick=\"javascript:removeSelected(window.document.epersongroup.eperson_id);\"/>");
}
out.println("</td></tr></table>");
out.print("<input class=\"btn btn-primary pull-right\" type=\"button\" value=\"" + p
+ "\" onclick=\"javascript:popup_window('"
+ req.getContextPath() + "/tools/eperson-list?multiple="
+ multiple + "', 'eperson_popup');\" />");
out.print("</div>");
}
catch (IOException ie)
{

View File

@@ -104,7 +104,7 @@ public class SelectGroupTag extends TagSupport
JspWriter out = pageContext.getOut();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
out.print("<table><tr><td colspan=\"2\" align=\"center\"><select multiple=\"multiple\" name=\"group_ids\" size=\"");
out.print("<select class=\"form-control\" multiple=\"multiple\" name=\"group_ids\" size=\"");
out.print(multiple ? "10" : "1");
out.println("\">");
@@ -124,37 +124,27 @@ public class SelectGroupTag extends TagSupport
}
}
out.print("</select></td>");
if (multiple)
{
out.print("</tr><tr><td width=\"50%\" align=\"center\">");
}
else
{
out.print("<td>");
}
out.print("</select>");
out.print("<br/><div class=\"row container\">");
String p = (multiple ?
LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectGroupTag.selectGroups")
: LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectGroupTag.selectGroup") );
out.print("<input type=\"button\" value=\"" + p
+ "\" onclick=\"javascript:popup_window('"
+ req.getContextPath() + "/tools/group-select-list?multiple="
+ multiple + "', 'group_popup');\" />");
if (multiple)
if (multiple)
{
out.print("</td><td width=\"50%\" align=\"center\">");
out.print("<input type=\"button\" value=\""
out.print("<input class=\"btn btn-danger\" type=\"button\" value=\""
+ LocaleSupport.getLocalizedMessage(pageContext,
"org.dspace.app.webui.jsptag.SelectGroupTag.removeSelected")
+ "\" onclick=\"javascript:removeSelected(window.document.epersongroup.group_ids);\"/>");
}
out.println("</td></tr></table>");
out.print("<input class=\"btn btn-primary pull-right\" type=\"button\" value=\"" + p
+ "\" onclick=\"javascript:popup_window('"
+ req.getContextPath() + "/tools/group-select-list?multiple="
+ multiple + "', 'group_popup');\" />");
out.print("</div>");
}
catch (IOException ie)
{

View File

@@ -38,6 +38,7 @@ import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
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.core.I18nUtil;
@@ -54,6 +55,8 @@ import org.w3c.dom.Document;
public class LuceneSearchRequestProcessor implements SearchRequestProcessor
{
private static final int ITEMMAP_RESULT_PAGE_SIZE = 50;
/** log4j category */
private static Logger log = Logger.getLogger(SimpleSearchServlet.class);
@@ -62,12 +65,42 @@ public class LuceneSearchRequestProcessor implements SearchRequestProcessor
private static String msgKey = "org.dspace.app.webui.servlet.FeedServlet";
private List<String> searchIndices = null;
public synchronized void init()
{
if (localeLabels == null)
{
localeLabels = new HashMap<String, Map<String, String>>();
}
if (searchIndices == null)
{
searchIndices = new ArrayList<String>();
String definition;
int idx = 1;
while ( ((definition = ConfigurationManager.getProperty("jspui.search.index.display." + idx))) != null){
String index = definition;
searchIndices.add(index);
idx++;
}
// backward compatibility
if (searchIndices.size() == 0)
{
searchIndices.add("ANY");
searchIndices.add("author");
searchIndices.add("title");
searchIndices.add("keyword");
searchIndices.add("abstract");
searchIndices.add("series");
searchIndices.add("sponsor");
searchIndices.add("identifier");
searchIndices.add("language");
}
}
}
/**
@@ -667,6 +700,62 @@ public class LuceneSearchRequestProcessor implements SearchRequestProcessor
}
}
/**
* Method for searching authors in item map
*
* author: gam
*/
@Override
public void doItemMapSearch(Context context, HttpServletRequest request,
HttpServletResponse response) throws SearchProcessorException, ServletException, IOException
{
String query = (String) request.getParameter("query");
int page = UIUtil.getIntParameter(request, "page")-1;
int offset = page > 0? page * ITEMMAP_RESULT_PAGE_SIZE:0;
Collection collection = (Collection) request.getAttribute("collection");
String idx = (String) request.getParameter("index");
if (StringUtils.isNotBlank(idx) && !idx.equalsIgnoreCase("any"))
{
query = idx + ":(" + query + ")";
}
QueryArgs queryArgs = new QueryArgs();
queryArgs.setQuery(query + " -location:l" + collection.getID());
queryArgs.setPageSize(ITEMMAP_RESULT_PAGE_SIZE);
queryArgs.setStart(offset);
QueryResults results = DSQuery.doQuery(context, queryArgs);
Map<Integer, Item> items = new HashMap<Integer, Item>();
List<String> handles = results.getHitHandles();
try
{
for (String handle : handles)
{
DSpaceObject resultDSO = HandleManager.resolveToObject(context, handle);
if (resultDSO.getType() == Constants.ITEM)
{
Item item = (Item) resultDSO;
if (AuthorizeManager.authorizeActionBoolean(context, item, Constants.READ))
{
items.put(Integer.valueOf(item.getID()), item);
}
}
}
}
catch (SQLException e)
{
throw new SearchProcessorException(e.getMessage(), e);
}
request.setAttribute("browsetext", query);
request.setAttribute("items", items);
request.setAttribute("more", results.getHitCount() > offset + ITEMMAP_RESULT_PAGE_SIZE);
request.setAttribute("browsetype", "Add");
request.setAttribute("page", page > 0 ? page + 1 : 1);
JSPManager.showJSP(request, response, "itemmap-browse.jsp");
}
/**
* Export the search results as a csv file
*
@@ -731,4 +820,17 @@ public class LuceneSearchRequestProcessor implements SearchRequestProcessor
}
return labelMap;
}
@Override
public String getI18NKeyPrefix()
{
return "jsp.search.advanced.type.";
}
@Override
public List<String> getSearchIndices()
{
init();
return searchIndices;
}
}

View File

@@ -8,6 +8,7 @@
package org.dspace.app.webui.search;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -29,4 +30,12 @@ public interface SearchRequestProcessor
HttpServletResponse response) throws SearchProcessorException,
IOException, ServletException;
public void doItemMapSearch(Context context, HttpServletRequest request,
HttpServletResponse response) throws SearchProcessorException,
IOException, ServletException;
public List<String> getSearchIndices();
public String getI18NKeyPrefix();
}

View File

@@ -15,6 +15,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.discovery.DiscoverySearchRequestProcessor;
import org.dspace.app.webui.search.LuceneSearchRequestProcessor;
import org.dspace.app.webui.search.SearchProcessorException;
import org.dspace.app.webui.search.SearchRequestProcessor;
@@ -48,8 +49,8 @@ public class AdvancedSearchServlet extends DSpaceServlet
e);
}
if (internalLogic == null)
{ // backward compatibility
internalLogic = new LuceneSearchRequestProcessor();
{ // Discovery is the default search provider since DSpace 4.0
internalLogic = new DiscoverySearchRequestProcessor();
}
}

View File

@@ -109,7 +109,7 @@ public class FeedbackServlet extends DSpaceServlet
// All data is there, send the email
try
{
Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback"));
Email email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback"));
email.addRecipient(ConfigurationManager
.getProperty("feedback.recipient"));

View File

@@ -45,8 +45,8 @@ public class LDAPServlet extends DSpaceServlet
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
// check if ldap is enables and forward to the correct login form
boolean ldap_enabled = ConfigurationManager.getBooleanProperty("ldap.enable");
// check if ldap is enables and forward to the correct login form
boolean ldap_enabled = ConfigurationManager.getBooleanProperty("authentication-ldap", "enable");
if (ldap_enabled)
{
JSPManager.showJSP(request, response, "/login/ldap.jsp");
@@ -104,4 +104,4 @@ public class LDAPServlet extends DSpaceServlet
"netid=" + netid + ", result=" + String.valueOf(status)));
JSPManager.showJSP(request, response, jsp);
}
}
}

View File

@@ -40,6 +40,14 @@ public class LogoutServlet extends DSpaceServlet
Authenticate.loggedOut(context, request);
// if the user still logged in (i.e. it was a login as)?
if (context.getCurrentUser() != null)
{
// redirect to the admin home page
response.sendRedirect(request.getContextPath()+"/dspace-admin/");
return;
}
// Display logged out message
JSPManager.showJSP(request, response, "/login/logged-out.jsp");
}

View File

@@ -15,6 +15,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.discovery.DiscoverySearchRequestProcessor;
import org.dspace.app.webui.search.LuceneSearchRequestProcessor;
import org.dspace.app.webui.search.SearchProcessorException;
import org.dspace.app.webui.search.SearchRequestProcessor;
@@ -57,8 +58,8 @@ public class OpenSearchServlet extends DSpaceServlet
e);
}
if (internalLogic == null)
{ // backward compatibility
internalLogic = new LuceneSearchRequestProcessor();
{ // Discovery is the default search provider since DSpace 4.0
internalLogic = new DiscoverySearchRequestProcessor();
}
}

View File

@@ -0,0 +1,101 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.sherpa.SHERPAJournal;
import org.dspace.app.sherpa.SHERPAPublisher;
import org.dspace.app.sherpa.SHERPAResponse;
import org.dspace.app.sherpa.submit.SHERPASubmitService;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.utils.DSpace;
/**
* This servlet use the SHERPASubmitService to build an html page with the
* publisher policy for the journal referred in the specified Item
*
* @author Andrea Bollini
*
*/
public class SHERPAPublisherPolicyServlet extends DSpaceServlet
{
private SHERPASubmitService sherpaSubmitService = new DSpace()
.getServiceManager().getServiceByName(
SHERPASubmitService.class.getCanonicalName(),
SHERPASubmitService.class);
/** log4j logger */
private static Logger log = Logger
.getLogger(SHERPAPublisherPolicyServlet.class);
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
int itemID = UIUtil.getIntParameter(request, "item_id");
Item item = Item.find(context, itemID);
if (item == null)
{
return;
}
SHERPAResponse shresp = sherpaSubmitService.searchRelatedJournals(
context, item);
if (shresp.isError())
{
request.setAttribute("error", new Boolean(true));
}
else
{
List<SHERPAJournal> journals = shresp.getJournals();
if (journals != null)
{
Object[][] results = new Object[journals.size()][];
if (journals.size() > 0)
{
Iterator<SHERPAJournal> ijourn = journals.iterator();
int idx = 0;
while (ijourn.hasNext())
{
SHERPAJournal journ = ijourn.next();
List<SHERPAPublisher> publishers = shresp
.getPublishers();
results[idx] = new Object[] {
journ,
publishers != null && publishers.size() > 0 ? publishers
.get(0) : null };
idx++;
}
}
request.setAttribute("result", results);
}
}
// Simply forward to the plain form
JSPManager.showJSP(request, response, "/sherpa/sherpa-policy.jsp");
}
protected void doDSPost(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}

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