Remove long-deprecated ConfigurationManager.

This commit is contained in:
Mark H. Wood
2020-09-01 10:01:23 -04:00
parent 6ac06c8a23
commit 95d0a2bf57
109 changed files with 1420 additions and 1320 deletions

View File

@@ -16,7 +16,6 @@ import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
@@ -24,6 +23,8 @@ import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.GroupService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* A command-line tool for creating an initial administrator for setting up a * A command-line tool for creating an initial administrator for setting up a
@@ -147,9 +148,10 @@ public final class CreateAdministrator {
lastName = lastName.trim(); lastName = lastName.trim();
} }
if (ConfigurationManager.getProperty("webui.supported.locales") != null) { ConfigurationService cfg = DSpaceServicesFactory.getInstance().getConfigurationService();
System.out.println("Select one of the following languages: " + ConfigurationManager if (cfg.hasProperty("webui.supported.locales")) {
.getProperty("webui.supported.locales")); System.out.println("Select one of the following languages: "
+ cfg.getProperty("webui.supported.locales"));
System.out.print("Language: "); System.out.print("Language: ");
System.out.flush(); System.out.flush();

View File

@@ -51,7 +51,6 @@ import org.dspace.content.service.MetadataValueService;
import org.dspace.content.service.RelationshipService; import org.dspace.content.service.RelationshipService;
import org.dspace.content.service.RelationshipTypeService; import org.dspace.content.service.RelationshipTypeService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
@@ -61,6 +60,8 @@ import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.scripts.DSpaceRunnable; import org.dspace.scripts.DSpaceRunnable;
import org.dspace.scripts.handler.DSpaceRunnableHandler; import org.dspace.scripts.handler.DSpaceRunnableHandler;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.utils.DSpace; import org.dspace.utils.DSpace;
import org.dspace.workflow.WorkflowException; import org.dspace.workflow.WorkflowException;
import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowItem;
@@ -116,7 +117,7 @@ public class MetadataImport extends DSpaceRunnable<MetadataImportScriptConfigura
protected static HashMap<UUID, String> entityTypeMap = new HashMap<>(); protected static HashMap<UUID, String> entityTypeMap = new HashMap<>();
/** /**
* Map of UUIDs to their relations that are referenced within any import with their referers. * Map of UUIDs to their relations that are referenced within any import with their referrers.
* *
* @see #populateEntityRelationMap(String, String, String) * @see #populateEntityRelationMap(String, String, String)
*/ */
@@ -129,7 +130,7 @@ public class MetadataImport extends DSpaceRunnable<MetadataImportScriptConfigura
protected ArrayList<String> relationValidationErrors = new ArrayList<>(); protected ArrayList<String> relationValidationErrors = new ArrayList<>();
/** /**
* Counter of rows proccssed in a CSV. * Counter of rows processed in a CSV.
*/ */
protected Integer rowCount = 1; protected Integer rowCount = 1;
@@ -158,6 +159,8 @@ public class MetadataImport extends DSpaceRunnable<MetadataImportScriptConfigura
protected EntityService entityService = ContentServiceFactory.getInstance().getEntityService(); protected EntityService entityService = ContentServiceFactory.getInstance().getEntityService();
protected AuthorityValueService authorityValueService = AuthorityServiceFactory.getInstance() protected AuthorityValueService authorityValueService = AuthorityServiceFactory.getInstance()
.getAuthorityValueService(); .getAuthorityValueService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Create an instance of the metadata importer. Requires a context and an array of CSV lines * Create an instance of the metadata importer. Requires a context and an array of CSV lines
@@ -419,7 +422,7 @@ public class MetadataImport extends DSpaceRunnable<MetadataImportScriptConfigura
// Do nothing // Do nothing
} else if ("expunge".equals(action)) { } else if ("expunge".equals(action)) {
// Does the configuration allow deletes? // Does the configuration allow deletes?
if (!ConfigurationManager.getBooleanProperty("bulkedit", "allowexpunge", false)) { if (!configurationService.getBooleanProperty("bulkedit.allowexpunge", false)) {
throw new MetadataImportException("'expunge' action denied by configuration"); throw new MetadataImportException("'expunge' action denied by configuration");
} }
@@ -1368,12 +1371,12 @@ public class MetadataImport extends DSpaceRunnable<MetadataImportScriptConfigura
* Set authority controlled fields * Set authority controlled fields
*/ */
private void setAuthorizedMetadataFields() { private void setAuthorizedMetadataFields() {
authorityControlled = new HashSet<String>(); authorityControlled = new HashSet<>();
Enumeration propertyNames = ConfigurationManager.getProperties().propertyNames(); Enumeration propertyNames = configurationService.getProperties().propertyNames();
while (propertyNames.hasMoreElements()) { while (propertyNames.hasMoreElements()) {
String key = ((String) propertyNames.nextElement()).trim(); String key = ((String) propertyNames.nextElement()).trim();
if (key.startsWith(AC_PREFIX) if (key.startsWith(AC_PREFIX)
&& ConfigurationManager.getBooleanProperty(key, false)) { && configurationService.getBooleanProperty(key, false)) {
authorityControlled.add(key.substring(AC_PREFIX.length())); authorityControlled.add(key.substring(AC_PREFIX.length()));
} }
} }
@@ -1747,11 +1750,11 @@ public class MetadataImport extends DSpaceRunnable<MetadataImportScriptConfigura
} }
/** /**
* Generates a list of potenital Relationship Types given a typeName and attempts to match the given * Generates a list of potential Relationship Types given a typeName and attempts to match the given
* targetType and originType to a Relationship Type in the list. * targetType and originType to a Relationship Type in the list.
* *
* @param targetType entity type of target. * @param targetType entity type of target.
* @param originType entity type of origin referer. * @param originType entity type of origin referrer.
* @param typeName left or right typeName of the respective Relationship. * @param typeName left or right typeName of the respective Relationship.
* @return the UUID of the item. * @return the UUID of the item.
*/ */

View File

@@ -47,7 +47,6 @@ import org.dspace.content.MetadataValue;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
@@ -57,6 +56,7 @@ import org.dspace.core.Utils;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
/** /**
@@ -93,12 +93,14 @@ public class ItemExportServiceImpl implements ItemExportService {
protected ItemService itemService; protected ItemService itemService;
@Autowired(required = true) @Autowired(required = true)
protected HandleService handleService; protected HandleService handleService;
@Autowired(required = true)
protected ConfigurationService configurationService;
/** /**
* log4j logger * log4j logger
*/ */
private Logger log = org.apache.logging.log4j.LogManager.getLogger(ItemExportServiceImpl.class); private final Logger log = org.apache.logging.log4j.LogManager.getLogger(ItemExportServiceImpl.class);
protected ItemExportServiceImpl() { protected ItemExportServiceImpl() {
@@ -605,7 +607,7 @@ public class ItemExportServiceImpl implements ItemExportService {
// check the size of all the bitstreams against the configuration file // check the size of all the bitstreams against the configuration file
// entry if it exists // entry if it exists
String megaBytes = ConfigurationManager String megaBytes = configurationService
.getProperty("org.dspace.app.itemexport.max.size"); .getProperty("org.dspace.app.itemexport.max.size");
if (megaBytes != null) { if (megaBytes != null) {
float maxSize = 0; float maxSize = 0;
@@ -730,7 +732,7 @@ public class ItemExportServiceImpl implements ItemExportService {
@Override @Override
public String getExportDownloadDirectory(EPerson ePerson) public String getExportDownloadDirectory(EPerson ePerson)
throws Exception { throws Exception {
String downloadDir = ConfigurationManager String downloadDir = configurationService
.getProperty("org.dspace.app.itemexport.download.dir"); .getProperty("org.dspace.app.itemexport.download.dir");
if (downloadDir == null) { if (downloadDir == null) {
throw new Exception( throw new Exception(
@@ -747,7 +749,7 @@ public class ItemExportServiceImpl implements ItemExportService {
@Override @Override
public String getExportWorkDirectory() throws Exception { public String getExportWorkDirectory() throws Exception {
String exportDir = ConfigurationManager String exportDir = configurationService
.getProperty("org.dspace.app.itemexport.work.dir"); .getProperty("org.dspace.app.itemexport.work.dir");
if (exportDir == null) { if (exportDir == null) {
throw new Exception( throw new Exception(
@@ -853,7 +855,7 @@ public class ItemExportServiceImpl implements ItemExportService {
return null; return null;
} }
List<String> fileNames = new ArrayList<String>(); List<String> fileNames = new ArrayList<>();
for (String fileName : downloadDir.list()) { for (String fileName : downloadDir.list()) {
if (fileName.contains("export") && fileName.endsWith(".zip")) { if (fileName.contains("export") && fileName.endsWith(".zip")) {
@@ -870,7 +872,7 @@ public class ItemExportServiceImpl implements ItemExportService {
@Override @Override
public void deleteOldExportArchives(EPerson eperson) throws Exception { public void deleteOldExportArchives(EPerson eperson) throws Exception {
int hours = ConfigurationManager int hours = configurationService
.getIntProperty("org.dspace.app.itemexport.life.span.hours"); .getIntProperty("org.dspace.app.itemexport.life.span.hours");
Calendar now = Calendar.getInstance(); Calendar now = Calendar.getInstance();
now.setTime(new Date()); now.setTime(new Date());
@@ -891,11 +893,11 @@ public class ItemExportServiceImpl implements ItemExportService {
@Override @Override
public void deleteOldExportArchives() throws Exception { public void deleteOldExportArchives() throws Exception {
int hours = ConfigurationManager.getIntProperty("org.dspace.app.itemexport.life.span.hours"); int hours = configurationService.getIntProperty("org.dspace.app.itemexport.life.span.hours");
Calendar now = Calendar.getInstance(); Calendar now = Calendar.getInstance();
now.setTime(new Date()); now.setTime(new Date());
now.add(Calendar.HOUR, (-hours)); now.add(Calendar.HOUR, (-hours));
File downloadDir = new File(ConfigurationManager.getProperty("org.dspace.app.itemexport.download.dir")); File downloadDir = new File(configurationService.getProperty("org.dspace.app.itemexport.download.dir"));
if (downloadDir.exists()) { if (downloadDir.exists()) {
// Get a list of all the sub-directories, potentially one for each ePerson. // Get a list of all the sub-directories, potentially one for each ePerson.
File[] dirs = downloadDir.listFiles(); File[] dirs = downloadDir.listFiles();
@@ -929,8 +931,8 @@ public class ItemExportServiceImpl implements ItemExportService {
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success")); Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success"));
email.addRecipient(eperson.getEmail()); email.addRecipient(eperson.getEmail());
email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/exportdownload/" + fileName); email.addArgument(configurationService.getProperty("dspace.ui.url") + "/exportdownload/" + fileName);
email.addArgument(ConfigurationManager.getProperty("org.dspace.app.itemexport.life.span.hours")); email.addArgument(configurationService.getProperty("org.dspace.app.itemexport.life.span.hours"));
email.send(); email.send();
} catch (Exception e) { } catch (Exception e) {
@@ -947,7 +949,7 @@ public class ItemExportServiceImpl implements ItemExportService {
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error")); Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error"));
email.addRecipient(eperson.getEmail()); email.addRecipient(eperson.getEmail());
email.addArgument(error); email.addArgument(error);
email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/feedback"); email.addArgument(configurationService.getProperty("dspace.ui.url") + "/feedback");
email.send(); email.send();
} catch (Exception e) { } catch (Exception e) {

View File

@@ -85,7 +85,6 @@ import org.dspace.content.service.ItemService;
import org.dspace.content.service.MetadataFieldService; import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService; import org.dspace.content.service.MetadataSchemaService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
@@ -96,6 +95,7 @@ import org.dspace.eperson.Group;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.GroupService;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.utils.DSpace; import org.dspace.utils.DSpace;
import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowItem;
import org.dspace.workflow.WorkflowService; import org.dspace.workflow.WorkflowService;
@@ -157,8 +157,11 @@ public class ItemImportServiceImpl implements ItemImportService, InitializingBea
protected WorkspaceItemService workspaceItemService; protected WorkspaceItemService workspaceItemService;
@Autowired(required = true) @Autowired(required = true)
protected WorkflowService workflowService; protected WorkflowService workflowService;
@Autowired(required = true)
protected ConfigurationService configurationService;
protected final String tempWorkDir = ConfigurationManager.getProperty("org.dspace.app.batchitemimport.work.dir"); protected final String tempWorkDir
= configurationService.getProperty("org.dspace.app.batchitemimport.work.dir");
protected boolean isTest = false; protected boolean isTest = false;
protected boolean isResume = false; protected boolean isResume = false;
@@ -217,7 +220,7 @@ public class ItemImportServiceImpl implements ItemImportService, InitializingBea
//Determine the folder where BTE will output the results //Determine the folder where BTE will output the results
String outputFolder = null; String outputFolder = null;
if (workingDir == null) { //This indicates a command line import, create a random path if (workingDir == null) { //This indicates a command line import, create a random path
File importDir = new File(ConfigurationManager.getProperty("org.dspace.app.batchitemimport.work.dir")); File importDir = new File(configurationService.getProperty("org.dspace.app.batchitemimport.work.dir"));
if (!importDir.exists()) { if (!importDir.exists()) {
boolean success = importDir.mkdir(); boolean success = importDir.mkdir();
if (!success) { if (!success) {
@@ -1481,7 +1484,7 @@ public class ItemImportServiceImpl implements ItemImportService, InitializingBea
File tempdir = new File(destinationDir); File tempdir = new File(destinationDir);
if (!tempdir.isDirectory()) { if (!tempdir.isDirectory()) {
log.error("'" + ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir") + log.error("'" + configurationService.getProperty("org.dspace.app.itemexport.work.dir") +
"' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg " + "' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg " +
"is not a valid directory"); "is not a valid directory");
} }
@@ -1646,7 +1649,7 @@ public class ItemImportServiceImpl implements ItemImportService, InitializingBea
} }
} }
importDir = ConfigurationManager.getProperty( importDir = configurationService.getProperty(
"org.dspace.app.batchitemimport.work.dir") + File.separator + "batchuploads" + File.separator "org.dspace.app.batchitemimport.work.dir") + File.separator + "batchuploads" + File.separator
+ context + context
.getCurrentUser() .getCurrentUser()
@@ -1804,7 +1807,7 @@ public class ItemImportServiceImpl implements ItemImportService, InitializingBea
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "bte_batch_import_error")); Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "bte_batch_import_error"));
email.addRecipient(eperson.getEmail()); email.addRecipient(eperson.getEmail());
email.addArgument(error); email.addArgument(error);
email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/feedback"); email.addArgument(configurationService.getProperty("dspace.ui.url") + "/feedback");
email.send(); email.send();
} catch (Exception e) { } catch (Exception e) {
@@ -1842,7 +1845,7 @@ public class ItemImportServiceImpl implements ItemImportService, InitializingBea
@Override @Override
public String getImportUploadableDirectory(EPerson ePerson) public String getImportUploadableDirectory(EPerson ePerson)
throws Exception { throws Exception {
String uploadDir = ConfigurationManager.getProperty("org.dspace.app.batchitemimport.work.dir"); String uploadDir = configurationService.getProperty("org.dspace.app.batchitemimport.work.dir");
if (uploadDir == null) { if (uploadDir == null) {
throw new Exception( throw new Exception(
"A dspace.cfg entry for 'org.dspace.app.batchitemimport.work.dir' does not exist."); "A dspace.cfg entry for 'org.dspace.app.batchitemimport.work.dir' does not exist.");

View File

@@ -38,8 +38,8 @@ import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
@@ -226,7 +226,9 @@ public class MetadataUtilities {
if (language == null) { if (language == null) {
language = "en"; language = "en";
} else if ("".equals(language)) { } else if ("".equals(language)) {
language = ConfigurationManager.getProperty("default.language"); language = DSpaceServicesFactory.getInstance()
.getConfigurationService()
.getProperty("default.language");
} }
DtoMetadata dtom = DtoMetadata.create(schema, element, qualifier, language, value); DtoMetadata dtom = DtoMetadata.create(schema, element, qualifier, language, value);

View File

@@ -12,7 +12,8 @@ import java.io.InputStream;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Filter image bitstreams, scaling the image to be within the bounds of * Filter image bitstreams, scaling the image to be within the bounds of
@@ -66,17 +67,19 @@ public class BrandedPreviewJPEGFilter extends MediaFilter {
BufferedImage buf = ImageIO.read(source); BufferedImage buf = ImageIO.read(source);
// get config params // get config params
float xmax = (float) ConfigurationManager ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
float xmax = (float) configurationService
.getIntProperty("webui.preview.maxwidth"); .getIntProperty("webui.preview.maxwidth");
float ymax = (float) ConfigurationManager float ymax = (float) configurationService
.getIntProperty("webui.preview.maxheight"); .getIntProperty("webui.preview.maxheight");
boolean blurring = (boolean) ConfigurationManager boolean blurring = (boolean) configurationService
.getBooleanProperty("webui.preview.blurring"); .getBooleanProperty("webui.preview.blurring");
boolean hqscaling = (boolean) ConfigurationManager boolean hqscaling = (boolean) configurationService
.getBooleanProperty("webui.preview.hqscaling"); .getBooleanProperty("webui.preview.hqscaling");
int brandHeight = ConfigurationManager.getIntProperty("webui.preview.brand.height"); int brandHeight = configurationService.getIntProperty("webui.preview.brand.height");
String brandFont = ConfigurationManager.getProperty("webui.preview.brand.font"); String brandFont = configurationService.getProperty("webui.preview.brand.font");
int brandFontPoint = ConfigurationManager.getIntProperty("webui.preview.brand.fontpoint"); int brandFontPoint = configurationService.getIntProperty("webui.preview.brand.fontpoint");
JPEGFilter jpegFilter = new JPEGFilter(); JPEGFilter jpegFilter = new JPEGFilter();
return jpegFilter return jpegFilter

View File

@@ -19,8 +19,9 @@ import org.dspace.content.Bundle;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.im4java.core.ConvertCmd; import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException; import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation; import org.im4java.core.IMOperation;
@@ -33,36 +34,18 @@ import org.im4java.process.ProcessStarter;
* no bigger than. Creates only JPEGs. * no bigger than. Creates only JPEGs.
*/ */
public abstract class ImageMagickThumbnailFilter extends MediaFilter { public abstract class ImageMagickThumbnailFilter extends MediaFilter {
protected static int width = 180; private static final int DEFAULT_WIDTH = 180;
protected static int height = 120; private static final int DEFAULT_HEIGHT = 120;
private static boolean flatten = true; static final String DEFAULT_PATTERN = "Generated Thumbnail";
static String bitstreamDescription = "IM Thumbnail";
static final String defaultPattern = "Generated Thumbnail";
static Pattern replaceRegex = Pattern.compile(defaultPattern);
protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
static String cmyk_profile; protected static final String PRE = ImageMagickThumbnailFilter.class.getName();
static String srgb_profile;
static { static {
String pre = ImageMagickThumbnailFilter.class.getName(); String s = configurationService.getProperty(PRE + ".ProcessStarter");
String s = ConfigurationManager.getProperty(pre + ".ProcessStarter");
ProcessStarter.setGlobalSearchPath(s); ProcessStarter.setGlobalSearchPath(s);
width = ConfigurationManager.getIntProperty("thumbnail.maxwidth", width);
height = ConfigurationManager.getIntProperty("thumbnail.maxheight", height);
flatten = ConfigurationManager.getBooleanProperty(pre + ".flatten", flatten);
String description = ConfigurationManager.getProperty(pre + ".bitstreamDescription");
cmyk_profile = ConfigurationManager.getProperty(pre + ".cmyk_profile");
srgb_profile = ConfigurationManager.getProperty(pre + ".srgb_profile");
if (description != null) {
bitstreamDescription = description;
}
try {
String patt = ConfigurationManager.getProperty(pre + ".replaceRegex");
replaceRegex = Pattern.compile(patt == null ? defaultPattern : patt);
} catch (PatternSyntaxException e) {
System.err.println("Invalid thumbnail replacement pattern: " + e.getMessage());
}
} }
public ImageMagickThumbnailFilter() { public ImageMagickThumbnailFilter() {
@@ -94,7 +77,7 @@ public abstract class ImageMagickThumbnailFilter extends MediaFilter {
*/ */
@Override @Override
public String getDescription() { public String getDescription() {
return bitstreamDescription; return configurationService.getProperty(PRE + ".bitstreamDescription", "IM Thumbnail");
} }
public File inputStreamToTempFile(InputStream source, String prefix, String suffix) throws IOException { public File inputStreamToTempFile(InputStream source, String prefix, String suffix) throws IOException {
@@ -120,7 +103,8 @@ public abstract class ImageMagickThumbnailFilter extends MediaFilter {
IMOperation op = new IMOperation(); IMOperation op = new IMOperation();
op.autoOrient(); op.autoOrient();
op.addImage(f.getAbsolutePath()); op.addImage(f.getAbsolutePath());
op.thumbnail(width, height); op.thumbnail(configurationService.getIntProperty("thumbnail.maxwidth", DEFAULT_WIDTH),
configurationService.getIntProperty("thumbnail.maxheight", DEFAULT_HEIGHT));
op.addImage(f2.getAbsolutePath()); op.addImage(f2.getAbsolutePath());
if (verbose) { if (verbose) {
System.out.println("IM Thumbnail Param: " + op); System.out.println("IM Thumbnail Param: " + op);
@@ -137,11 +121,14 @@ public abstract class ImageMagickThumbnailFilter extends MediaFilter {
IMOperation op = new IMOperation(); IMOperation op = new IMOperation();
String s = "[" + page + "]"; String s = "[" + page + "]";
op.addImage(f.getAbsolutePath() + s); op.addImage(f.getAbsolutePath() + s);
if (flatten) { if (configurationService.getBooleanProperty(PRE + ".flatten", true)) {
op.flatten(); op.flatten();
} }
// PDFs using the CMYK color system can be handled specially if // PDFs using the CMYK color system can be handled specially if
// profiles are defined // profiles are defined
String cmyk_profile = configurationService.getProperty(PRE + ".cmyk_profile");
String srgb_profile = configurationService.getProperty(PRE + ".srgb_profile");
if (cmyk_profile != null && srgb_profile != null) { if (cmyk_profile != null && srgb_profile != null) {
Info imageInfo = new Info(f.getAbsolutePath() + s, true); Info imageInfo = new Info(f.getAbsolutePath() + s, true);
String imageClass = imageInfo.getImageClass(); String imageClass = imageInfo.getImageClass();
@@ -174,24 +161,32 @@ public abstract class ImageMagickThumbnailFilter extends MediaFilter {
String description = bit.getDescription(); String description = bit.getDescription();
// If anything other than a generated thumbnail // If anything other than a generated thumbnail
// is found, halt processing // is found, halt processing
Pattern replaceRegex;
try {
String patt = configurationService.getProperty(PRE + ".replaceRegex", DEFAULT_PATTERN);
replaceRegex = Pattern.compile(patt == null ? DEFAULT_PATTERN : patt);
} catch (PatternSyntaxException e) {
System.err.println("Invalid thumbnail replacement pattern: " + e.getMessage());
throw e;
}
if (description != null) { if (description != null) {
if (replaceRegex.matcher(description).matches()) { if (replaceRegex.matcher(description).matches()) {
if (verbose) { if (verbose) {
System.out.println(description + " " + nsrc System.out.format("%s %s matches pattern and is replacable.%n",
+ " matches pattern and is replacable."); description, nsrc);
} }
continue; continue;
} }
if (description.equals(bitstreamDescription)) { if (description.equals(getDescription())) {
if (verbose) { if (verbose) {
System.out.println(bitstreamDescription + " " + nsrc System.out.format("%s %s is replaceable.%n",
+ " is replacable."); getDescription(), nsrc);
} }
continue; continue;
} }
} }
System.out.println("Custom Thumbnail exists for " + nsrc + " for item " System.out.format("Custom Thumbnail exists for %s for item %s. Thumbnail will not be generated.%n",
+ item.getHandle() + ". Thumbnail will not be generated. "); nsrc, item.getHandle());
return false; return false;
} }
} }

View File

@@ -22,7 +22,8 @@ import java.io.InputStream;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Filter image bitstreams, scaling the image to be within the bounds of * Filter image bitstreams, scaling the image to be within the bounds of
@@ -80,13 +81,15 @@ public class JPEGFilter extends MediaFilter implements SelfRegisterInputFormats
public InputStream getThumb(Item currentItem, BufferedImage buf, boolean verbose) public InputStream getThumb(Item currentItem, BufferedImage buf, boolean verbose)
throws Exception { throws Exception {
// get config params // get config params
float xmax = (float) ConfigurationManager final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
float xmax = (float) configurationService
.getIntProperty("thumbnail.maxwidth"); .getIntProperty("thumbnail.maxwidth");
float ymax = (float) ConfigurationManager float ymax = (float) configurationService
.getIntProperty("thumbnail.maxheight"); .getIntProperty("thumbnail.maxheight");
boolean blurring = (boolean) ConfigurationManager boolean blurring = (boolean) configurationService
.getBooleanProperty("thumbnail.blurring"); .getBooleanProperty("thumbnail.blurring");
boolean hqscaling = (boolean) ConfigurationManager boolean hqscaling = (boolean) configurationService
.getBooleanProperty("thumbnail.hqscaling"); .getBooleanProperty("thumbnail.hqscaling");
return getThumbDim(currentItem, buf, verbose, xmax, ymax, blurring, hqscaling, 0, 0, null); return getThumbDim(currentItem, buf, verbose, xmax, ymax, blurring, hqscaling, 0, 0, null);
@@ -169,9 +172,11 @@ public class JPEGFilter extends MediaFilter implements SelfRegisterInputFormats
g2d.drawImage(buf, 0, 0, (int) xsize, (int) ysize, null); g2d.drawImage(buf, 0, 0, (int) xsize, (int) ysize, null);
if (brandHeight != 0) { if (brandHeight != 0) {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
Brand brand = new Brand((int) xsize, brandHeight, new Font(brandFont, Font.PLAIN, brandFontPoint), 5); Brand brand = new Brand((int) xsize, brandHeight, new Font(brandFont, Font.PLAIN, brandFontPoint), 5);
BufferedImage brandImage = brand.create(ConfigurationManager.getProperty("webui.preview.brand"), BufferedImage brandImage = brand.create(configurationService.getProperty("webui.preview.brand"),
ConfigurationManager.getProperty("webui.preview.brand.abbrev"), configurationService.getProperty("webui.preview.brand.abbrev"),
currentItem == null ? "" : "hdl:" + currentItem.getHandle()); currentItem == null ? "" : "hdl:" + currentItem.getHandle());
g2d.drawImage(brandImage, (int) 0, (int) ysize, (int) xsize, (int) 20, null); g2d.drawImage(brandImage, (int) 0, (int) ysize, (int) xsize, (int) 20, null);

View File

@@ -21,7 +21,8 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.PDFTextStripper;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/* /*
* *
@@ -72,8 +73,10 @@ public class PDFFilter extends MediaFilter {
@Override @Override
public InputStream getDestinationStream(Item currentItem, InputStream source, boolean verbose) public InputStream getDestinationStream(Item currentItem, InputStream source, boolean verbose)
throws Exception { throws Exception {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
try { try {
boolean useTemporaryFile = ConfigurationManager.getBooleanProperty("pdffilter.largepdfs", false); boolean useTemporaryFile = configurationService.getBooleanProperty("pdffilter.largepdfs", false);
// get input stream from bitstream // get input stream from bitstream
// pass to filter, get string back // pass to filter, get string back
@@ -124,7 +127,7 @@ public class PDFFilter extends MediaFilter {
} }
} catch (OutOfMemoryError oome) { } catch (OutOfMemoryError oome) {
log.error("Error parsing PDF document " + oome.getMessage(), oome); log.error("Error parsing PDF document " + oome.getMessage(), oome);
if (!ConfigurationManager.getBooleanProperty("pdffilter.skiponmemoryexception", false)) { if (!configurationService.getBooleanProperty("pdffilter.skiponmemoryexception", false)) {
throw oome; throw oome;
} }
} }

View File

@@ -10,13 +10,13 @@ package org.dspace.app.requestitem;
import java.sql.SQLException; import java.sql.SQLException;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
/** /**
@@ -30,9 +30,6 @@ import org.springframework.beans.factory.annotation.Autowired;
* @author Peter Dietz * @author Peter Dietz
*/ */
public class RequestItemHelpdeskStrategy extends RequestItemSubmitterStrategy { public class RequestItemHelpdeskStrategy extends RequestItemSubmitterStrategy {
private Logger log = org.apache.logging.log4j.LogManager.getLogger(RequestItemHelpdeskStrategy.class);
@Autowired(required = true) @Autowired(required = true)
protected EPersonService ePersonService; protected EPersonService ePersonService;
@@ -41,9 +38,11 @@ public class RequestItemHelpdeskStrategy extends RequestItemSubmitterStrategy {
@Override @Override
public RequestItemAuthor getRequestItemAuthor(Context context, Item item) throws SQLException { public RequestItemAuthor getRequestItemAuthor(Context context, Item item) throws SQLException {
boolean helpdeskOverridesSubmitter = ConfigurationManager ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
boolean helpdeskOverridesSubmitter = configurationService
.getBooleanProperty("request.item.helpdesk.override", false); .getBooleanProperty("request.item.helpdesk.override", false);
String helpDeskEmail = ConfigurationManager.getProperty("mail.helpdesk"); String helpDeskEmail = configurationService.getProperty("mail.helpdesk");
if (helpdeskOverridesSubmitter && StringUtils.isNotBlank(helpDeskEmail)) { if (helpdeskOverridesSubmitter && StringUtils.isNotBlank(helpDeskEmail)) {
return getHelpDeskPerson(context, helpDeskEmail); return getHelpDeskPerson(context, helpDeskEmail);
@@ -64,10 +63,8 @@ public class RequestItemHelpdeskStrategy extends RequestItemSubmitterStrategy {
* @throws SQLException if database error * @throws SQLException if database error
*/ */
public RequestItemAuthor getHelpDeskPerson(Context context, String helpDeskEmail) throws SQLException { public RequestItemAuthor getHelpDeskPerson(Context context, String helpDeskEmail) throws SQLException {
EPerson helpdeskEPerson = null;
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
helpdeskEPerson = ePersonService.findByEmail(context, helpDeskEmail); EPerson helpdeskEPerson = ePersonService.findByEmail(context, helpDeskEmail);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
if (helpdeskEPerson != null) { if (helpdeskEPerson != null) {

View File

@@ -16,8 +16,10 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
public class SHERPAService { public class SHERPAService {
private CloseableHttpClient client = null; private CloseableHttpClient client = null;
@@ -29,7 +31,7 @@ public class SHERPAService {
/** /**
* log4j category * log4j category
*/ */
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SHERPAService.class); private static final Logger log = LogManager.getLogger(SHERPAService.class);
public SHERPAService() { public SHERPAService() {
HttpClientBuilder builder = HttpClientBuilder.create(); HttpClientBuilder builder = HttpClientBuilder.create();
@@ -43,8 +45,10 @@ public class SHERPAService {
public SHERPAResponse searchByJournalISSN(String query) { public SHERPAResponse searchByJournalISSN(String query) {
String endpoint = ConfigurationManager.getProperty("sherpa.romeo.url"); ConfigurationService configurationService
String apiKey = ConfigurationManager.getProperty("sherpa.romeo.apikey"); = DSpaceServicesFactory.getInstance().getConfigurationService();
String endpoint = configurationService.getProperty("sherpa.romeo.url");
String apiKey = configurationService.getProperty("sherpa.romeo.apikey");
HttpGet method = null; HttpGet method = null;
SHERPAResponse sherpaResponse = null; SHERPAResponse sherpaResponse = null;

View File

@@ -18,8 +18,9 @@ import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* This class allows the running of the DSpace statistic tools * This class allows the running of the DSpace statistic tools
@@ -56,7 +57,7 @@ public class CreateStatReport {
/** /**
* File suffix for log files * File suffix for log files
*/ */
private static String outputSuffix = ".dat"; private static final String outputSuffix = ".dat";
/** /**
* User context * User context
@@ -66,9 +67,6 @@ public class CreateStatReport {
/** /**
* the config file from which to configure the analyser * the config file from which to configure the analyser
*/ */
private static String configFile = ConfigurationManager.getProperty("dspace.dir") +
File.separator + "config" + File.separator +
"dstat.cfg";
/** /**
* Default constructor * Default constructor
@@ -81,8 +79,12 @@ public class CreateStatReport {
* Usage: java CreateStatReport -r <statistic to run> * Usage: java CreateStatReport -r <statistic to run>
*/ */
public static void main(String[] argv) throws Exception { public static void main(String[] argv) throws Exception {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
// Open the statistics config file // Open the statistics config file
final String configFile = configurationService.getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "dstat.cfg";
FileInputStream fis = new java.io.FileInputStream(new File(configFile)); FileInputStream fis = new java.io.FileInputStream(new File(configFile));
Properties config = new Properties(); Properties config = new Properties();
config.load(fis); config.load(fis);
@@ -108,8 +110,8 @@ public class CreateStatReport {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
//get paths to directories //get paths to directories
outputLogDirectory = ConfigurationManager.getProperty("log.report.dir") + File.separator; outputLogDirectory = configurationService.getProperty("log.report.dir") + File.separator;
outputReportDirectory = ConfigurationManager.getProperty("report.dir") + File.separator; outputReportDirectory = configurationService.getProperty("report.dir") + File.separator;
//read in command line variable to determine which statistic to run //read in command line variable to determine which statistic to run
CommandLineParser parser = new PosixParser(); CommandLineParser parser = new PosixParser();

View File

@@ -20,7 +20,8 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* This class provides HTML reports for the ReportGenerator class * This class provides HTML reports for the ReportGenerator class
@@ -34,7 +35,7 @@ public class HTMLReport implements Report {
/** /**
* a list of the statistic blocks being managed by this class * a list of the statistic blocks being managed by this class
*/ */
private List<Statistics> blocks = new ArrayList<Statistics>(); private final List<Statistics> blocks = new ArrayList<>();
/** /**
* the title for the page * the title for the page
@@ -59,7 +60,9 @@ public class HTMLReport implements Report {
/** /**
* the output file to which to write aggregation data * the output file to which to write aggregation data
*/ */
private String output = ConfigurationManager.getProperty("dspace.dir") + ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
private String output = configurationService.getProperty("dspace.dir") +
File.separator + "log" + File.separator + "report"; File.separator + "log" + File.separator + "report";
/** /**
@@ -82,7 +85,7 @@ public class HTMLReport implements Report {
*/ */
@Override @Override
public String render() { public String render() {
StringBuffer frag = new StringBuffer(); StringBuilder frag = new StringBuilder();
// get the page headings // get the page headings
frag.append(header(pageTitle)); frag.append(header(pageTitle));
@@ -140,7 +143,7 @@ public class HTMLReport implements Report {
* @return an HTML string providing internal page navigation * @return an HTML string providing internal page navigation
*/ */
public String navigation() { public String navigation() {
StringBuffer frag = new StringBuffer(); StringBuilder frag = new StringBuilder();
frag.append("<div class=\"reportNavigation\">"); frag.append("<div class=\"reportNavigation\">");
frag.append("<a href=\"#general_overview\">General Overview</a>"); frag.append("<a href=\"#general_overview\">General Overview</a>");
@@ -173,7 +176,6 @@ public class HTMLReport implements Report {
@Override @Override
public void addBlock(Statistics stat) { public void addBlock(Statistics stat) {
blocks.add(stat); blocks.add(stat);
return;
} }
@@ -207,7 +209,7 @@ public class HTMLReport implements Report {
*/ */
@Override @Override
public String dateRange() { public String dateRange() {
StringBuffer frag = new StringBuffer(); StringBuilder frag = new StringBuilder();
DateFormat df = DateFormat.getDateInstance(); DateFormat df = DateFormat.getDateInstance();
frag.append("<div class=\"reportDate\">"); frag.append("<div class=\"reportDate\">");
@@ -255,7 +257,6 @@ public class HTMLReport implements Report {
if (pageTitle == null) { if (pageTitle == null) {
pageTitle = mainTitle; pageTitle = mainTitle;
} }
return;
} }
@@ -280,7 +281,7 @@ public class HTMLReport implements Report {
// FIXME: this need to be figured out to integrate nicely into the // FIXME: this need to be figured out to integrate nicely into the
// whole JSTL thing, but for the moment it's just going to deliver // whole JSTL thing, but for the moment it's just going to deliver
// some styles // some styles
StringBuffer frag = new StringBuffer(); StringBuilder frag = new StringBuilder();
frag.append("<style type=\"text/css\">\n"); frag.append("<style type=\"text/css\">\n");
frag.append("body { font-family: Arial, Helvetica, sans-serif }"); frag.append("body { font-family: Arial, Helvetica, sans-serif }");
@@ -334,7 +335,7 @@ public class HTMLReport implements Report {
*/ */
@Override @Override
public String statBlock(Statistics content) { public String statBlock(Statistics content) {
StringBuffer frag = new StringBuffer(); StringBuilder frag = new StringBuilder();
Stat[] stats = content.getStats(); Stat[] stats = content.getStats();
// start the table // start the table
@@ -405,7 +406,7 @@ public class HTMLReport implements Report {
@Override @Override
public String floorInfo(int floor) { public String floorInfo(int floor) {
if (floor > 0) { if (floor > 0) {
StringBuffer frag = new StringBuffer(); StringBuilder frag = new StringBuilder();
frag.append("<div class=\"reportFloor\">"); frag.append("<div class=\"reportFloor\">");
frag.append("(more than " + ReportTools.numberFormat(floor) + " times)"); frag.append("(more than " + ReportTools.numberFormat(floor) + " times)");
frag.append("</div>\n"); frag.append("</div>\n");
@@ -419,12 +420,12 @@ public class HTMLReport implements Report {
* output the explanation of the report block in HTML format * output the explanation of the report block in HTML format
* *
* @param explanation some text explaining the coming report block * @param explanation some text explaining the coming report block
* @return a string containing an explanaton HTML formatted * @return a string containing an explanation HTML formatted
*/ */
@Override @Override
public String blockExplanation(String explanation) { public String blockExplanation(String explanation) {
if (explanation != null) { if (explanation != null) {
StringBuffer frag = new StringBuffer(); StringBuilder frag = new StringBuilder();
frag.append("<div class=\"reportExplanation\">"); frag.append("<div class=\"reportExplanation\">");
frag.append(explanation); frag.append(explanation);
frag.append("</div>\n\n"); frag.append("</div>\n\n");

View File

@@ -30,13 +30,14 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.core.Utils; import org.dspace.core.Utils;
import org.dspace.discovery.DiscoverQuery; import org.dspace.discovery.DiscoverQuery;
import org.dspace.discovery.SearchServiceException; import org.dspace.discovery.SearchServiceException;
import org.dspace.discovery.SearchUtils; import org.dspace.discovery.SearchUtils;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* This class performs all the actual analysis of a given set of DSpace log * This class performs all the actual analysis of a given set of DSpace log
@@ -268,7 +269,7 @@ public class LogAnalyser {
/** /**
* the log directory to be analysed * the log directory to be analysed
*/ */
private static String logDir = ConfigurationManager.getProperty("log.report.dir"); private static String logDir;
/** /**
* the regex to describe the file name format * the regex to describe the file name format
@@ -276,16 +277,14 @@ public class LogAnalyser {
private static String fileTemplate = "dspace\\.log.*"; private static String fileTemplate = "dspace\\.log.*";
/** /**
* the config file from which to configure the analyser * the configuration file from which to configure the analyser
*/ */
private static String configFile = ConfigurationManager.getProperty("dspace.dir") + private static String configFile;
File.separator + "config" + File.separator +
"dstat.cfg";
/** /**
* the output file to which to write aggregation data * the output file to which to write aggregation data
*/ */
private static String outFile = ConfigurationManager.getProperty("log.report.dir") + File.separator + "dstat.dat"; private static String outFile;
/** /**
* the starting date of the report * the starting date of the report
@@ -582,9 +581,11 @@ public class LogAnalyser {
} }
// now do the host name and url lookup // now do the host name and url lookup
hostName = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url")); ConfigurationService configurationService
name = ConfigurationManager.getProperty("dspace.name").trim(); = DSpaceServicesFactory.getInstance().getConfigurationService();
url = ConfigurationManager.getProperty("dspace.ui.url").trim(); hostName = Utils.getHostName(configurationService.getProperty("dspace.ui.url"));
name = configurationService.getProperty("dspace.name").trim();
url = configurationService.getProperty("dspace.ui.url").trim();
if ((url != null) && (!url.endsWith("/"))) { if ((url != null) && (!url.endsWith("/"))) {
url = url + "/"; url = url + "/";
} }
@@ -622,8 +623,13 @@ public class LogAnalyser {
String myConfigFile, String myOutFile, String myConfigFile, String myOutFile,
Date myStartDate, Date myEndDate, Date myStartDate, Date myEndDate,
boolean myLookUp) { boolean myLookUp) {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
if (myLogDir != null) { if (myLogDir != null) {
logDir = myLogDir; logDir = myLogDir;
} else {
logDir = configurationService.getProperty("log.report.dir");
} }
if (myFileTemplate != null) { if (myFileTemplate != null) {
@@ -632,6 +638,9 @@ public class LogAnalyser {
if (myConfigFile != null) { if (myConfigFile != null) {
configFile = myConfigFile; configFile = myConfigFile;
} else {
configFile = configurationService.getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "dstat.cfg";
} }
if (myStartDate != null) { if (myStartDate != null) {
@@ -644,9 +653,9 @@ public class LogAnalyser {
if (myOutFile != null) { if (myOutFile != null) {
outFile = myOutFile; outFile = myOutFile;
} else {
outFile = configurationService.getProperty("log.report.dir") + File.separator + "dstat.dat";
} }
return;
} }
@@ -657,7 +666,7 @@ public class LogAnalyser {
*/ */
public static String createOutput() { public static String createOutput() {
// start a string buffer to hold the final output // start a string buffer to hold the final output
StringBuffer summary = new StringBuffer(); StringBuilder summary = new StringBuilder();
// define an iterator that will be used to go over the hashmap keys // define an iterator that will be used to go over the hashmap keys
Iterator<String> keys = null; Iterator<String> keys = null;
@@ -820,7 +829,7 @@ public class LogAnalyser {
*/ */
public static void setRegex(String fileTemplate) { public static void setRegex(String fileTemplate) {
// build the exclude characters regular expression // build the exclude characters regular expression
StringBuffer charRegEx = new StringBuffer(); StringBuilder charRegEx = new StringBuilder();
charRegEx.append("["); charRegEx.append("[");
for (int i = 0; i < excludeChars.size(); i++) { for (int i = 0; i < excludeChars.size(); i++) {
charRegEx.append("\\").append(excludeChars.get(i)); charRegEx.append("\\").append(excludeChars.get(i));
@@ -864,7 +873,7 @@ public class LogAnalyser {
logRegex = Pattern.compile(fileTemplate); logRegex = Pattern.compile(fileTemplate);
// set up the pattern for matching any of the query types // set up the pattern for matching any of the query types
StringBuffer typeRXString = new StringBuffer(); StringBuilder typeRXString = new StringBuilder();
typeRXString.append("("); typeRXString.append("(");
for (int i = 0; i < excludeTypes.size(); i++) { for (int i = 0; i < excludeTypes.size(); i++) {
if (i > 0) { if (i > 0) {
@@ -876,7 +885,7 @@ public class LogAnalyser {
typeRX = Pattern.compile(typeRXString.toString()); typeRX = Pattern.compile(typeRXString.toString());
// set up the pattern for matching any of the words to exclude // set up the pattern for matching any of the words to exclude
StringBuffer wordRXString = new StringBuffer(); StringBuilder wordRXString = new StringBuilder();
wordRXString.append("("); wordRXString.append("(");
for (int i = 0; i < excludeWords.size(); i++) { for (int i = 0; i < excludeWords.size(); i++) {
if (i > 0) { if (i > 0) {
@@ -890,8 +899,6 @@ public class LogAnalyser {
} }
wordRXString.append(")"); wordRXString.append(")");
wordRX = Pattern.compile(wordRXString.toString()); wordRX = Pattern.compile(wordRXString.toString());
return;
} }
/** /**
@@ -920,18 +927,18 @@ public class LogAnalyser {
*/ */
public static void readConfig(String configFile) throws IOException { public static void readConfig(String configFile) throws IOException {
//instantiate aggregators //instantiate aggregators
actionAggregator = new HashMap<String, Integer>(); actionAggregator = new HashMap<>();
searchAggregator = new HashMap<String, Integer>(); searchAggregator = new HashMap<>();
userAggregator = new HashMap<String, Integer>(); userAggregator = new HashMap<>();
itemAggregator = new HashMap<String, Integer>(); itemAggregator = new HashMap<>();
archiveStats = new HashMap<String, Integer>(); archiveStats = new HashMap<>();
//instantiate lists //instantiate lists
generalSummary = new ArrayList<String>(); generalSummary = new ArrayList<>();
excludeWords = new ArrayList<String>(); excludeWords = new ArrayList<>();
excludeTypes = new ArrayList<String>(); excludeTypes = new ArrayList<>();
excludeChars = new ArrayList<String>(); excludeChars = new ArrayList<>();
itemTypes = new ArrayList<String>(); itemTypes = new ArrayList<>();
// prepare our standard file readers and buffered readers // prepare our standard file readers and buffered readers
FileReader fr = null; FileReader fr = null;
@@ -1002,8 +1009,6 @@ public class LogAnalyser {
// close the inputs // close the inputs
br.close(); br.close();
fr.close(); fr.close();
return;
} }
/** /**

View File

@@ -32,10 +32,11 @@ import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* This class performs the action of coordinating a usage report being * This class performs the action of coordinating a usage report being
@@ -161,7 +162,7 @@ public class ReportGenerator {
/** /**
* pattern that matches an unqualified aggregator property * pattern that matches an unqualified aggregator property
*/ */
private static Pattern real = Pattern.compile("^(.+)=(.+)"); private static final Pattern real = Pattern.compile("^(.+)=(.+)");
////////////////////////// //////////////////////////
// Miscellaneous variables // Miscellaneous variables
@@ -189,11 +190,12 @@ public class ReportGenerator {
/** /**
* the log file action to human readable action map * the log file action to human readable action map
*/ */
private static String map = ConfigurationManager.getProperty("dspace.dir") + private static String map;
File.separator + "config" + File.separator + "dstat.map";
private static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); private static final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
private static final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); private static final HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Default constructor * Default constructor
@@ -268,6 +270,9 @@ public class ReportGenerator {
throws Exception, SQLException { throws Exception, SQLException {
if (myMap != null) { if (myMap != null) {
map = myMap; map = myMap;
} else {
map = configurationService.getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "dstat.map";
} }
// create the relevant report type // create the relevant report type
@@ -302,15 +307,15 @@ public class ReportGenerator {
startTime = new GregorianCalendar(); startTime = new GregorianCalendar();
/** instantiate aggregators */ /** instantiate aggregators */
actionAggregator = new HashMap<String, String>(); actionAggregator = new HashMap<>();
searchAggregator = new HashMap<String, String>(); searchAggregator = new HashMap<>();
userAggregator = new HashMap<String, String>(); userAggregator = new HashMap<>();
itemAggregator = new HashMap<String, String>(); itemAggregator = new HashMap<>();
archiveStats = new HashMap<String, String>(); archiveStats = new HashMap<>();
actionMap = new HashMap<String, String>(); actionMap = new HashMap<>();
/** instantite lists */ /** instantiate lists */
generalSummary = new ArrayList<String>(); generalSummary = new ArrayList<>();
// set the parameters for this analysis // set the parameters for this analysis
setParameters(myInput); setParameters(myInput);
@@ -486,8 +491,6 @@ public class ReportGenerator {
report.addBlock(process); report.addBlock(process);
report.render(); report.render();
return;
} }
@@ -612,8 +615,6 @@ public class ReportGenerator {
if (myInput != null) { if (myInput != null) {
input = myInput; input = myInput;
} }
return;
} }
@@ -768,9 +769,9 @@ public class ReportGenerator {
List<MetadataValue> author = itemService List<MetadataValue> author = itemService
.getMetadata(item, MetadataSchemaEnum.DC.getName(), "contributor", "author", Item.ANY); .getMetadata(item, MetadataSchemaEnum.DC.getName(), "contributor", "author", Item.ANY);
StringBuffer authors = new StringBuffer(); StringBuilder authors = new StringBuilder();
if (author.size() > 0) { if (author.size() > 0) {
authors.append("(" + author.get(0).getValue()); authors.append("(").append(author.get(0).getValue());
} }
if (author.size() > 1) { if (author.size() > 1) {
authors.append(" et al"); authors.append(" et al");

View File

@@ -22,7 +22,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.lang3.time.DateUtils;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Helper class for loading the analysis / report files from the reports directory * Helper class for loading the analysis / report files from the reports directory
@@ -219,8 +220,8 @@ public class StatisticsLoader {
} }
// Create new maps for the monthly analysis / reports // Create new maps for the monthly analysis / reports
Map<String, StatsFile> newMonthlyAnalysis = new HashMap<String, StatsFile>(); Map<String, StatsFile> newMonthlyAnalysis = new HashMap<>();
Map<String, StatsFile> newMonthlyReports = new HashMap<String, StatsFile>(); Map<String, StatsFile> newMonthlyReports = new HashMap<>();
StatsFile newGeneralAnalysis = null; StatsFile newGeneralAnalysis = null;
StatsFile newGeneralReport = null; StatsFile newGeneralReport = null;
@@ -320,7 +321,9 @@ public class StatisticsLoader {
* @return array of files * @return array of files
*/ */
private static File[] getAnalysisAndReportFileList() { private static File[] getAnalysisAndReportFileList() {
File reportDir = new File(ConfigurationManager.getProperty("log.report.dir")); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
File reportDir = new File(configurationService.getProperty("log.report.dir"));
if (reportDir != null) { if (reportDir != null) {
return reportDir.listFiles(new AnalysisAndReportFilter()); return reportDir.listFiles(new AnalysisAndReportFilter());
} }

View File

@@ -14,8 +14,9 @@ import java.util.Date;
import org.dspace.app.util.factory.UtilServiceFactory; import org.dspace.app.util.factory.UtilServiceFactory;
import org.dspace.app.util.service.WebAppService; import org.dspace.app.util.service.WebAppService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -57,7 +58,9 @@ abstract public class AbstractDSpaceWebapp
started = new Date(); started = new Date();
url = ConfigurationManager.getProperty("dspace.ui.url"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
url = configurationService.getProperty("dspace.ui.url");
if (null == url) { if (null == url) {
throw new IllegalStateException("dspace.ui.url is undefined"); throw new IllegalStateException("dspace.ui.url is undefined");
} }

View File

@@ -16,8 +16,9 @@ import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Utility class for lists of collections. * Utility class for lists of collections.
@@ -55,8 +56,11 @@ public class CollectionDropDown {
* @return Full path to the collection (truncated) * @return Full path to the collection (truncated)
* @throws SQLException if database error * @throws SQLException if database error
*/ */
public static String collectionPath(Context context, Collection col, int maxchars) throws SQLException { public static String collectionPath(Context context, Collection col, int maxchars)
String separator = ConfigurationManager.getProperty("subcommunity.separator"); throws SQLException {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String separator = configurationService.getProperty("subcommunity.separator");
if (separator == null) { if (separator == null) {
separator = " > "; separator = " > ";
} }

View File

@@ -26,6 +26,7 @@ import java.util.Properties;
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap; import com.google.common.collect.ListMultimap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.factory.AuthorizeServiceFactory; import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
@@ -36,10 +37,11 @@ import org.dspace.content.MetadataSchema;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Element; import org.jdom.Element;
/** /**
@@ -51,7 +53,7 @@ import org.jdom.Element;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class GoogleMetadata { public class GoogleMetadata {
private final static Logger log = org.apache.logging.log4j.LogManager.getLogger(GoogleMetadata.class); private final static Logger log = LogManager.getLogger(GoogleMetadata.class);
protected static final String GOOGLE_PREFIX = "google."; protected static final String GOOGLE_PREFIX = "google.";
@@ -62,7 +64,7 @@ public class GoogleMetadata {
protected String itemURL; protected String itemURL;
// Configuration keys and fields // Configuration keys and fields
protected static Map<String, String> googleScholarSettings = new HashMap<String, String>(); protected static Map<String, String> googleScholarSettings = new HashMap<>();
// Google field names (e.g. citation_fieldname) and formatted metadata // Google field names (e.g. citation_fieldname) and formatted metadata
// values // values
@@ -132,35 +134,39 @@ public class GoogleMetadata {
private static GoogleBitstreamComparator googleBitstreamComparator = null; private static GoogleBitstreamComparator googleBitstreamComparator = null;
// Load configured fields from google-metadata.properties private final ConfigurationService configurationService
static { = DSpaceServicesFactory.getInstance().getConfigurationService();
File loadedFile = null; /**
URL url = null; * Load configured fields from google-metadata.properties.
InputStream is = null; */
private void loadGoogleScholarSettings()
String googleConfigFile = ConfigurationManager throws MalformedURLException, IOException {
String googleConfigFile = configurationService
.getProperty("google-metadata.config"); .getProperty("google-metadata.config");
log.info("Using [" + googleConfigFile log.info("Using [{}] for Google Metadata configuration", googleConfigFile);
+ "] for Google Metadata configuration");
loadedFile = new File(googleConfigFile); File loadedFile = new File(googleConfigFile);
URL url;
try { try {
url = loadedFile.toURL(); url = loadedFile.toURI().toURL();
} catch (MalformedURLException mux) { } catch (MalformedURLException mux) {
log.error("Can't find Google Metadata configuration file: " log.error("Can't find Google Metadata configuration file: {}",
+ googleConfigFile, mux); googleConfigFile, mux);
throw mux;
} }
Properties properties = new Properties(); Properties properties = new Properties();
InputStream is;
try { try {
is = url.openStream(); is = url.openStream();
properties.load(is); properties.load(is);
} catch (IOException iox) { } catch (IOException iox) {
log.error("Could not read Google Metadata configuration file: " log.error("Could not read Google Metadata configuration file: {}",
+ googleConfigFile, iox); googleConfigFile, iox);
throw iox;
} }
Enumeration propertyNames = properties.propertyNames(); Enumeration propertyNames = properties.propertyNames();
@@ -180,9 +186,7 @@ public class GoogleMetadata {
} }
} }
if (log.isDebugEnabled()) { logConfiguration();
logConfiguration();
}
} }
/** /**
@@ -192,7 +196,7 @@ public class GoogleMetadata {
log.debug("Google Metadata Configuration Mapping:"); log.debug("Google Metadata Configuration Mapping:");
for (String name : googleScholarSettings.keySet()) { for (String name : googleScholarSettings.keySet()) {
log.debug(" " + name + " => " + googleScholarSettings.get(name)); log.debug(" {} => {}", name, googleScholarSettings.get(name));
} }
} }
@@ -202,9 +206,14 @@ public class GoogleMetadata {
* *
* @param context context * @param context context
* @param item The item being viewed to extract metadata from * @param item The item being viewed to extract metadata from
* @throws SQLException if database error * @throws SQLException if database error.
* @throws java.io.IOException passed through.
*/ */
public GoogleMetadata(Context context, Item item) throws SQLException { public GoogleMetadata(Context context, Item item)
throws SQLException, IOException {
if (googleScholarSettings.isEmpty()) {
loadGoogleScholarSettings();
}
// Hold onto the item in case we need to refresh a stale parse // Hold onto the item in case we need to refresh a stale parse
this.item = item; this.item = item;
@@ -336,7 +345,7 @@ public class GoogleMetadata {
int optionMatches = 0; int optionMatches = 0;
String[] components; String[] components;
List<MetadataValue> values; List<MetadataValue> values;
ArrayList<MetadataValue> resolvedFields = new ArrayList<MetadataValue>(); ArrayList<MetadataValue> resolvedFields = new ArrayList<>();
for (String field : optionFields) { for (String field : optionFields) {
@@ -399,8 +408,8 @@ public class GoogleMetadata {
*/ */
protected ArrayList<ArrayList<String>> parseOptions(String configFilter) { protected ArrayList<ArrayList<String>> parseOptions(String configFilter) {
ArrayList<String> options = new ArrayList<String>(); ArrayList<String> options = new ArrayList<>();
ArrayList<ArrayList<String>> parsedOptions = new ArrayList<ArrayList<String>>(); ArrayList<ArrayList<String>> parsedOptions = new ArrayList<>();
if (null == configFilter || configFilter.equals("")) { if (null == configFilter || configFilter.equals("")) {
return null; return null;
@@ -414,7 +423,7 @@ public class GoogleMetadata {
options.add(option.trim()); options.add(option.trim());
} }
} else { } else {
options = new ArrayList<String>(); options = new ArrayList<>();
options.add(configFilter); options.add(configFilter);
} }
@@ -426,12 +435,12 @@ public class GoogleMetadata {
for (String option : options) { for (String option : options) {
ArrayList<String> fields; ArrayList<String> fields;
parsedFields = new ArrayList<String>(); parsedFields = new ArrayList<>();
if (option.contains(",")) { if (option.contains(",")) {
fields = parseFields(option); fields = parseFields(option);
} else { } else {
fields = new ArrayList<String>(); fields = new ArrayList<>();
fields.add(option); fields.add(option);
} }
@@ -472,7 +481,7 @@ public class GoogleMetadata {
*/ */
protected ArrayList<String> parseFields(String configString) { protected ArrayList<String> parseFields(String configString) {
ArrayList<String> fields = new ArrayList<String>(); ArrayList<String> fields = new ArrayList<>();
for (String field : configString.split("\\,")) { for (String field : configString.split("\\,")) {
fields.add(field.trim()); fields.add(field.trim());
@@ -523,7 +532,7 @@ public class GoogleMetadata {
List<MetadataValue> allMD = itemService.getMetadata(item, components[0], components[1], List<MetadataValue> allMD = itemService.getMetadata(item, components[0], components[1],
components[2], Item.ANY); components[2], Item.ANY);
ArrayList<String> expandedDC = new ArrayList<String>(); ArrayList<String> expandedDC = new ArrayList<>();
for (MetadataValue v : allMD) { for (MetadataValue v : allMD) {
// De-dup multiple occurrences of field names in item // De-dup multiple occurrences of field names in item
@@ -558,7 +567,7 @@ public class GoogleMetadata {
MetadataSchema metadataSchema = v.getMetadataField().getMetadataSchema(); MetadataSchema metadataSchema = v.getMetadataField().getMetadataSchema();
name.append(metadataSchema.getName()).append(".").append(metadataField.getElement()); name.append(metadataSchema.getName()).append(".").append(metadataField.getElement());
if (null != metadataField.getQualifier()) { if (null != metadataField.getQualifier()) {
name.append("." + metadataField.getQualifier()); name.append(".").append(metadataField.getQualifier());
} }
return name.toString(); return name.toString();
@@ -687,7 +696,7 @@ public class GoogleMetadata {
* @return List of elements * @return List of elements
*/ */
public List<Element> disseminateList() { public List<Element> disseminateList() {
List<Element> metas = new ArrayList<Element>(); List<Element> metas = new ArrayList<>();
for (Entry<String, String> m : getMappings()) { for (Entry<String, String> m : getMappings()) {
Element e = new Element("meta"); Element e = new Element("meta");
@@ -889,7 +898,7 @@ public class GoogleMetadata {
Bitstream bitstream = findLinkableFulltext(item); Bitstream bitstream = findLinkableFulltext(item);
if (bitstream != null) { if (bitstream != null) {
StringBuilder path = new StringBuilder(); StringBuilder path = new StringBuilder();
path.append(ConfigurationManager.getProperty("dspace.ui.url")); path.append(configurationService.getProperty("dspace.ui.url"));
if (item.getHandle() != null) { if (item.getHandle() != null) {
path.append("/bitstream/"); path.append("/bitstream/");
@@ -1075,7 +1084,7 @@ public class GoogleMetadata {
// FIXME: Shouldn't have to parse identifiers for every identification. // FIXME: Shouldn't have to parse identifiers for every identification.
ArrayList<ArrayList<String>> options = parseOptions(dConfig); ArrayList<ArrayList<String>> options = parseOptions(dConfig);
HashMap<String, ArrayList<String>> mdPairs = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> mdPairs = new HashMap<>();
// Parse field/value pairs from field identifier string // Parse field/value pairs from field identifier string
for (ArrayList<String> option : options) { for (ArrayList<String> option : options) {
@@ -1092,7 +1101,7 @@ public class GoogleMetadata {
} }
} else { } else {
// Otherwise, add it as the first occurrence of this field // Otherwise, add it as the first occurrence of this field
ArrayList<String> newField = new ArrayList<String>(); ArrayList<String> newField = new ArrayList<>();
newField.add(parsedPair[1].trim()); newField.add(parsedPair[1].trim());
mdPairs.put(parsedPair[0].trim(), newField); mdPairs.put(parsedPair[0].trim(), newField);
@@ -1113,7 +1122,7 @@ public class GoogleMetadata {
// Check resolved/present metadata fields against configured values // Check resolved/present metadata fields against configured values
ArrayList<MetadataValue> presentMD = resolveMetadataFields(sb.toString()); ArrayList<MetadataValue> presentMD = resolveMetadataFields(sb.toString());
if (null != presentMD && presentMD.size() != 0) { if (null != presentMD && !presentMD.isEmpty()) {
for (MetadataValue v : presentMD) { for (MetadataValue v : presentMD) {
String fieldName = buildFieldName(v); String fieldName = buildFieldName(v);
if (mdPairs.containsKey(fieldName)) { if (mdPairs.containsKey(fieldName)) {

View File

@@ -8,6 +8,7 @@
package org.dspace.app.util; package org.dspace.app.util;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@@ -49,7 +50,6 @@ import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.discovery.IndexableObject; import org.dspace.discovery.IndexableObject;
import org.dspace.discovery.indexobject.IndexableCollection; import org.dspace.discovery.indexobject.IndexableCollection;
@@ -102,7 +102,7 @@ public class SyndicationFeed {
}; };
protected String defaultExternalMedia = "dc.source.uri"; protected String defaultExternalMedia = "dc.source.uri";
private final ConfigurationService configurationService = private static final ConfigurationService configurationService =
DSpaceServicesFactory.getInstance().getConfigurationService(); DSpaceServicesFactory.getInstance().getConfigurationService();
// metadata field for Item title in entry: // metadata field for Item title in entry:
@@ -196,10 +196,10 @@ public class SyndicationFeed {
// dso is null for the whole site, or a search without scope // dso is null for the whole site, or a search without scope
if (dso == null) { if (dso == null) {
defaultTitle = ConfigurationManager.getProperty("dspace.name"); defaultTitle = configurationService.getProperty("dspace.name");
feed.setDescription(localize(labels, MSG_FEED_DESCRIPTION)); feed.setDescription(localize(labels, MSG_FEED_DESCRIPTION));
objectURL = resolveURL(request, null); objectURL = resolveURL(request, null);
logoURL = ConfigurationManager.getProperty("webui.feed.logo.url"); logoURL = configurationService.getProperty("webui.feed.logo.url");
} else { } else {
Bitstream logo = null; Bitstream logo = null;
if (dso instanceof IndexableCollection) { if (dso instanceof IndexableCollection) {
@@ -207,7 +207,7 @@ public class SyndicationFeed {
defaultTitle = col.getName(); defaultTitle = col.getName();
feed.setDescription(collectionService.getMetadata(col, "short_description")); feed.setDescription(collectionService.getMetadata(col, "short_description"));
logo = col.getLogo(); logo = col.getLogo();
String cols = ConfigurationManager.getProperty("webui.feed.podcast.collections"); String cols = configurationService.getProperty("webui.feed.podcast.collections");
if (cols != null && cols.length() > 1 && cols.contains(col.getHandle())) { if (cols != null && cols.length() > 1 && cols.contains(col.getHandle())) {
podcastFeed = true; podcastFeed = true;
} }
@@ -217,7 +217,7 @@ public class SyndicationFeed {
defaultTitle = comm.getName(); defaultTitle = comm.getName();
feed.setDescription(communityService.getMetadata(comm, "short_description")); feed.setDescription(communityService.getMetadata(comm, "short_description"));
logo = comm.getLogo(); logo = comm.getLogo();
String comms = ConfigurationManager.getProperty("webui.feed.podcast.communities"); String comms = configurationService.getProperty("webui.feed.podcast.communities");
if (comms != null && comms.length() > 1 && comms.contains(comm.getHandle())) { if (comms != null && comms.length() > 1 && comms.contains(comm.getHandle())) {
podcastFeed = true; podcastFeed = true;
} }
@@ -251,7 +251,7 @@ public class SyndicationFeed {
// add entries for items // add entries for items
if (items != null) { if (items != null) {
List<SyndEntry> entries = new ArrayList<SyndEntry>(); List<SyndEntry> entries = new ArrayList<>();
for (IndexableObject idxObj : items) { for (IndexableObject idxObj : items) {
if (!(idxObj instanceof IndexableItem)) { if (!(idxObj instanceof IndexableItem)) {
continue; continue;
@@ -277,7 +277,7 @@ public class SyndicationFeed {
// date of last change to Item // date of last change to Item
entry.setUpdatedDate(item.getLastModified()); entry.setUpdatedDate(item.getLastModified());
StringBuffer db = new StringBuffer(); StringBuilder db = new StringBuilder();
for (String df : descriptionFields) { for (String df : descriptionFields) {
// Special Case: "(date)" in field name means render as date // Special Case: "(date)" in field name means render as date
boolean isDate = df.indexOf("(date)") > 0; boolean isDate = df.indexOf("(date)") > 0;
@@ -313,7 +313,7 @@ public class SyndicationFeed {
// This gets the authors into an ATOM feed // This gets the authors into an ATOM feed
List<MetadataValue> authors = itemService.getMetadataByMetadataString(item, authorField); List<MetadataValue> authors = itemService.getMetadataByMetadataString(item, authorField);
if (authors.size() > 0) { if (authors.size() > 0) {
List<SyndPerson> creators = new ArrayList<SyndPerson>(); List<SyndPerson> creators = new ArrayList<>();
for (MetadataValue author : authors) { for (MetadataValue author : authors) {
SyndPerson sp = new SyndPersonImpl(); SyndPerson sp = new SyndPersonImpl();
sp.setName(author.getValue()); sp.setName(author.getValue());
@@ -329,7 +329,7 @@ public class SyndicationFeed {
if (dcCreatorField != null) { if (dcCreatorField != null) {
List<MetadataValue> dcAuthors = itemService.getMetadataByMetadataString(item, dcCreatorField); List<MetadataValue> dcAuthors = itemService.getMetadataByMetadataString(item, dcCreatorField);
if (dcAuthors.size() > 0) { if (dcAuthors.size() > 0) {
List<String> creators = new ArrayList<String>(); List<String> creators = new ArrayList<>();
for (MetadataValue author : dcAuthors) { for (MetadataValue author : dcAuthors) {
creators.add(author.getValue()); creators.add(author.getValue());
} }
@@ -345,7 +345,7 @@ public class SyndicationFeed {
if (dcDescriptionField != null) { if (dcDescriptionField != null) {
List<MetadataValue> v = itemService.getMetadataByMetadataString(item, dcDescriptionField); List<MetadataValue> v = itemService.getMetadataByMetadataString(item, dcDescriptionField);
if (v.size() > 0) { if (v.size() > 0) {
StringBuffer descs = new StringBuffer(); StringBuilder descs = new StringBuilder();
for (MetadataValue d : v) { for (MetadataValue d : v) {
if (descs.length() > 0) { if (descs.length() > 0) {
descs.append("\n\n"); descs.append("\n\n");
@@ -374,8 +374,6 @@ public class SyndicationFeed {
enc.setLength(bit.getSizeBytes()); enc.setLength(bit.getSizeBytes());
enc.setUrl(urlOfBitstream(request, bit)); enc.setUrl(urlOfBitstream(request, bit));
enclosures.add(enc); enclosures.add(enc);
} else {
continue;
} }
} }
} }
@@ -395,7 +393,7 @@ public class SyndicationFeed {
} }
} }
} catch (Exception e) { } catch (SQLException e) {
System.out.println(e.getMessage()); System.out.println(e.getMessage());
} }
entry.setEnclosures(enclosures); entry.setEnclosures(enclosures);
@@ -501,7 +499,7 @@ public class SyndicationFeed {
// utility to get config property with default value when not set. // utility to get config property with default value when not set.
protected static String getDefaultedConfiguration(String key, String dfl) { protected static String getDefaultedConfiguration(String key, String dfl) {
String result = ConfigurationManager.getProperty(key); String result = configurationService.getProperty(key);
return (result == null) ? dfl : result; return (result == null) ? dfl : result;
} }
@@ -531,14 +529,14 @@ public class SyndicationFeed {
if (dso == null) { if (dso == null) {
if (baseURL == null) { if (baseURL == null) {
if (request == null) { if (request == null) {
baseURL = ConfigurationManager.getProperty("dspace.ui.url"); baseURL = configurationService.getProperty("dspace.ui.url");
} else { } else {
baseURL = ConfigurationManager.getProperty("dspace.ui.url"); baseURL = configurationService.getProperty("dspace.ui.url");
baseURL += request.getContextPath(); baseURL += request.getContextPath();
} }
} }
return baseURL; return baseURL;
} else if (ConfigurationManager.getBooleanProperty("webui.feed.localresolve")) { } else if (configurationService.getBooleanProperty("webui.feed.localresolve")) {
// return a link to handle in repository // return a link to handle in repository
return resolveURL(request, null) + "/handle/" + dso.getHandle(); return resolveURL(request, null) + "/handle/" + dso.getHandle();
} else { } else {

View File

@@ -33,7 +33,6 @@ import org.apache.logging.log4j.Logger;
import org.dspace.authenticate.factory.AuthenticateServiceFactory; import org.dspace.authenticate.factory.AuthenticateServiceFactory;
import org.dspace.authenticate.service.AuthenticationService; import org.dspace.authenticate.service.AuthenticationService;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
@@ -41,19 +40,28 @@ import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.GroupService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* This combined LDAP authentication method supersedes both the 'LDAPAuthentication' * This combined LDAP authentication method supersedes both the 'LDAPAuthentication'
* and the 'LDAPHierarchicalAuthentication' methods. It's capable of both: * and the 'LDAPHierarchicalAuthentication' methods. It's capable of both:
* - authenticaton against a flat LDAP tree where all users are in the same unit * <ul>
* (if search.user or search.password is not set) * <li>authentication against a flat LDAP tree where all users are in the same unit
* - authentication against structured hierarchical LDAP trees of users. * (if {@code search.user} or {@code search.password} is not set)</li>
* <li>authentication against structured hierarchical LDAP trees of users.</li>
* </ul>
* An initial bind is required using a user name and password in order to * An initial bind is required using a user name and password in order to
* search the tree and find the DN of the user. A second bind is then required to * search the tree and find the DN of the user. A second bind is then required to
* check the credentials of the user by binding directly to their DN. * check the credentials of the user by binding directly to their DN.
* *
* @author Stuart Lewis, Chris Yates, Alex Barbieri, Flavio Botelho, Reuben Pasquini, Samuel Ottenhoff, Ivan Masár * @author Stuart Lewis
* @version $Revision$ * @author Chris Yates
* @author Alex Barbieri
* @author Flavio Botelho
* @author Reuben Pasquini
* @author Samuel Ottenhoff
* @author Ivan Masár
*/ */
public class LDAPAuthentication public class LDAPAuthentication
implements AuthenticationMethod { implements AuthenticationMethod {
@@ -61,13 +69,17 @@ public class LDAPAuthentication
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(LDAPAuthentication.class); private static final Logger log
= org.apache.logging.log4j.LogManager.getLogger(LDAPAuthentication.class);
protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance()
.getAuthenticationService();
protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
protected AuthenticationService authenticationService
= AuthenticateServiceFactory.getInstance().getAuthenticationService();
protected EPersonService ePersonService
= EPersonServiceFactory.getInstance().getEPersonService();
protected GroupService groupService
= EPersonServiceFactory.getInstance().getGroupService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Let a real auth method return true if it wants. * Let a real auth method return true if it wants.
@@ -80,7 +92,7 @@ public class LDAPAuthentication
String username) String username)
throws SQLException { throws SQLException {
// Looks to see if autoregister is set or not // Looks to see if autoregister is set or not
return ConfigurationManager.getBooleanProperty("authentication-ldap", "autoregister"); return configurationService.getBooleanProperty("authentication-ldap.autoregister");
} }
/** /**
@@ -128,7 +140,7 @@ public class LDAPAuthentication
// ensures they are LDAP users // ensures they are LDAP users
try { try {
if (!context.getCurrentUser().getNetid().equals("")) { if (!context.getCurrentUser().getNetid().equals("")) {
String groupName = ConfigurationManager.getProperty("authentication-ldap", "login.specialgroup"); String groupName = configurationService.getProperty("authentication-ldap.login.specialgroup");
if ((groupName != null) && (!groupName.trim().equals(""))) { if ((groupName != null) && (!groupName.trim().equals(""))) {
Group ldapGroup = groupService.findByName(context, groupName); Group ldapGroup = groupService.findByName(context, groupName);
if (ldapGroup == null) { if (ldapGroup == null) {
@@ -142,7 +154,7 @@ public class LDAPAuthentication
} }
} }
} }
} catch (Exception npe) { } catch (SQLException ex) {
// The user is not an LDAP user, so we don't need to worry about them // The user is not an LDAP user, so we don't need to worry about them
} }
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
@@ -205,11 +217,11 @@ public class LDAPAuthentication
SpeakerToLDAP ldap = new SpeakerToLDAP(log); SpeakerToLDAP ldap = new SpeakerToLDAP(log);
// Get the DN of the user // Get the DN of the user
boolean anonymousSearch = ConfigurationManager.getBooleanProperty("authentication-ldap", "search.anonymous"); boolean anonymousSearch = configurationService.getBooleanProperty("authentication-ldap.search.anonymous");
String adminUser = ConfigurationManager.getProperty("authentication-ldap", "search.user"); String adminUser = configurationService.getProperty("authentication-ldap.search.user");
String adminPassword = ConfigurationManager.getProperty("authentication-ldap", "search.password"); String adminPassword = configurationService.getProperty("authentication-ldap.search.password");
String objectContext = ConfigurationManager.getProperty("authentication-ldap", "object_context"); String objectContext = configurationService.getProperty("authentication-ldap.object_context");
String idField = ConfigurationManager.getProperty("authentication-ldap", "id_field"); String idField = configurationService.getProperty("authentication-ldap.id_field");
String dn = ""; String dn = "";
// If adminUser is blank and anonymous search is not allowed, then we can't search so construct the DN // If adminUser is blank and anonymous search is not allowed, then we can't search so construct the DN
@@ -263,9 +275,8 @@ public class LDAPAuthentication
if (StringUtils.isEmpty(email)) { if (StringUtils.isEmpty(email)) {
// If no email, check if we have a "netid_email_domain". If so, append it to the netid to create // If no email, check if we have a "netid_email_domain". If so, append it to the netid to create
// email // email
if (StringUtils if (configurationService.hasProperty("authentication-ldap.netid_email_domain")) {
.isNotEmpty(ConfigurationManager.getProperty("authentication-ldap", "netid_email_domain"))) { email = netid + configurationService.getProperty("authentication-ldap.netid_email_domain");
email = netid + ConfigurationManager.getProperty("authentication-ldap", "netid_email_domain");
} else { } else {
// We don't have a valid email address. We'll default it to 'netid' but log a warning // We don't have a valid email address. We'll default it to 'netid' but log a warning
log.warn(LogManager.getHeader(context, "autoregister", log.warn(LogManager.getHeader(context, "autoregister",
@@ -365,21 +376,34 @@ public class LDAPAuthentication
/** /**
* LDAP settings * LDAP settings
*/ */
String ldap_provider_url = ConfigurationManager.getProperty("authentication-ldap", "provider_url"); final String ldap_provider_url;
String ldap_id_field = ConfigurationManager.getProperty("authentication-ldap", "id_field"); final String ldap_id_field;
String ldap_search_context = ConfigurationManager.getProperty("authentication-ldap", "search_context"); final String ldap_search_context;
String ldap_search_scope = ConfigurationManager.getProperty("authentication-ldap", "search_scope"); final String ldap_search_scope;
String ldap_email_field = ConfigurationManager.getProperty("authentication-ldap", "email_field"); final String ldap_email_field;
String ldap_givenname_field = ConfigurationManager.getProperty("authentication-ldap", "givenname_field"); final String ldap_givenname_field;
String ldap_surname_field = ConfigurationManager.getProperty("authentication-ldap", "surname_field"); final String ldap_surname_field;
String ldap_phone_field = ConfigurationManager.getProperty("authentication-ldap", "phone_field"); final String ldap_phone_field;
String ldap_group_field = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap.attribute"); final String ldap_group_field;
boolean useTLS = ConfigurationManager.getBooleanProperty("authentication-ldap", "starttls", false); final boolean useTLS;
SpeakerToLDAP(Logger thelog) { SpeakerToLDAP(Logger thelog) {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
log = thelog; log = thelog;
ldap_provider_url = configurationService.getProperty("authentication-ldap.provider_url");
ldap_id_field = configurationService.getProperty("authentication-ldap.id_field");
ldap_search_context = configurationService.getProperty("authentication-ldap.search_context");
ldap_search_scope = configurationService.getProperty("authentication-ldap.search_scope");
ldap_email_field = configurationService.getProperty("authentication-ldap.email_field");
ldap_givenname_field = configurationService.getProperty("authentication-ldap.givenname_field");
ldap_surname_field = configurationService.getProperty("authentication-ldap.surname_field");
ldap_phone_field = configurationService.getProperty("authentication-ldap.phone_field");
ldap_group_field = configurationService.getProperty("authentication-ldap.login.groupmap.attribute");
useTLS = configurationService.getBooleanProperty("authentication-ldap.starttls", false);
} }
protected String getDNOfUser(String adminUser, String adminPassword, Context context, String netid) { protected String getDNOfUser(String adminUser, String adminPassword, Context context, String netid) {
@@ -399,7 +423,8 @@ public class LDAPAuthentication
} }
// Set up environment for creating initial context // Set up environment for creating initial context
Hashtable<String, String> env = new Hashtable<String, String>(); @SuppressWarnings("UseOfObsoleteCollectionType")
Hashtable<String, String> env = new Hashtable<>();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url); env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url);
@@ -447,7 +472,7 @@ public class LDAPAuthentication
SearchControls ctrls = new SearchControls(); SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(ldap_search_scope_value); ctrls.setSearchScope(ldap_search_scope_value);
String searchName = ""; String searchName;
if (useTLS) { if (useTLS) {
searchName = ldap_search_context; searchName = ldap_search_context;
} else { } else {
@@ -555,7 +580,8 @@ public class LDAPAuthentication
// Set up environment for creating initial context // Set up environment for creating initial context
Hashtable<String, String> env = new Hashtable<String, String>(); @SuppressWarnings("UseOfObsoleteCollectionType")
Hashtable<String, String> env = new Hashtable<>();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory"); "com.sun.jndi.ldap.LdapCtxFactory");
env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url); env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url);
@@ -652,7 +678,7 @@ public class LDAPAuthentication
if (StringUtils.isNotBlank(dn)) { if (StringUtils.isNotBlank(dn)) {
System.out.println("dn:" + dn); System.out.println("dn:" + dn);
int i = 1; int i = 1;
String groupMap = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap." + i); String groupMap = configurationService.getProperty("authentication-ldap", "login.groupmap." + i);
boolean cmp; boolean cmp;
@@ -692,7 +718,7 @@ public class LDAPAuthentication
} }
} }
groupMap = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap." + ++i); groupMap = configurationService.getProperty("authentication-ldap", "login.groupmap." + ++i);
} }
} }
} }

View File

@@ -12,6 +12,7 @@ import java.net.MalformedURLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery;
@@ -21,7 +22,8 @@ import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
import org.dspace.authority.indexer.AuthorityIndexingService; import org.dspace.authority.indexer.AuthorityIndexingService;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* @author Antoine Snyers (antoine at atmire.com) * @author Antoine Snyers (antoine at atmire.com)
@@ -31,7 +33,7 @@ import org.dspace.core.ConfigurationManager;
*/ */
public class AuthoritySolrServiceImpl implements AuthorityIndexingService, AuthoritySearchService { public class AuthoritySolrServiceImpl implements AuthorityIndexingService, AuthoritySearchService {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(AuthoritySolrServiceImpl.class); private static final Logger log = LogManager.getLogger(AuthoritySolrServiceImpl.class);
protected AuthoritySolrServiceImpl() { protected AuthoritySolrServiceImpl() {
@@ -46,7 +48,9 @@ public class AuthoritySolrServiceImpl implements AuthorityIndexingService, Autho
throws MalformedURLException, SolrServerException, IOException { throws MalformedURLException, SolrServerException, IOException {
if (solr == null) { if (solr == null) {
String solrService = ConfigurationManager.getProperty("solr.authority.server"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String solrService = configurationService.getProperty("solr.authority.server");
log.debug("Solr authority URL: " + solrService); log.debug("Solr authority URL: " + solrService);
@@ -153,7 +157,7 @@ public class AuthoritySolrServiceImpl implements AuthorityIndexingService, Autho
QueryResponse response = getSolr().query(solrQuery); QueryResponse response = getSolr().query(solrQuery);
List<String> results = new ArrayList<String>(); List<String> results = new ArrayList<>();
FacetField facetField = response.getFacetField("field"); FacetField facetField = response.getFacetField("field");
if (facetField != null) { if (facetField != null) {
List<FacetField.Count> values = facetField.getValues(); List<FacetField.Count> values = facetField.getValues();

View File

@@ -8,6 +8,7 @@
package org.dspace.authority; package org.dspace.authority;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
@@ -19,15 +20,18 @@ import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException; import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authority.factory.AuthorityServiceFactory; import org.dspace.authority.factory.AuthorityServiceFactory;
import org.dspace.authority.service.AuthorityValueService; import org.dspace.authority.service.AuthorityValueService;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* @author Antoine Snyers (antoine at atmire.com) * @author Antoine Snyers (antoine at atmire.com)
@@ -40,21 +44,23 @@ public class UpdateAuthorities {
/** /**
* log4j logger * log4j logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(UpdateAuthorities.class); private static final Logger log = LogManager.getLogger(UpdateAuthorities.class);
protected PrintWriter print = null; protected PrintWriter print = null;
private Context context; private final Context context;
private List<String> selectedIDs; private List<String> selectedIDs;
protected final ItemService itemService; protected final ItemService itemService;
protected final AuthorityValueService authorityValueService; protected final AuthorityValueService authorityValueService;
protected final ConfigurationService configurationService;
public UpdateAuthorities(Context context) { public UpdateAuthorities(Context context) {
print = new PrintWriter(System.out); print = new PrintWriter(System.out);
this.context = context; this.context = context;
this.authorityValueService = AuthorityServiceFactory.getInstance().getAuthorityValueService(); this.authorityValueService = AuthorityServiceFactory.getInstance().getAuthorityValueService();
this.itemService = ContentServiceFactory.getInstance().getItemService(); this.itemService = ContentServiceFactory.getInstance().getItemService();
this.configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
} }
public static void main(String[] args) throws ParseException { public static void main(String[] args) throws ParseException {
@@ -102,7 +108,7 @@ public class UpdateAuthorities {
} }
private void setSelectedIDs(String b) { private void setSelectedIDs(String b) {
this.selectedIDs = new ArrayList<String>(); this.selectedIDs = new ArrayList<>();
String[] orcids = b.split(","); String[] orcids = b.split(",");
for (String orcid : orcids) { for (String orcid : orcids) {
this.selectedIDs.add(orcid.trim()); this.selectedIDs.add(orcid.trim());
@@ -125,7 +131,7 @@ public class UpdateAuthorities {
List<AuthorityValue> authorities; List<AuthorityValue> authorities;
if (selectedIDs != null && !selectedIDs.isEmpty()) { if (selectedIDs != null && !selectedIDs.isEmpty()) {
authorities = new ArrayList<AuthorityValue>(); authorities = new ArrayList<>();
for (String selectedID : selectedIDs) { for (String selectedID : selectedIDs) {
AuthorityValue byUID = authorityValueService.findByUID(context, selectedID); AuthorityValue byUID = authorityValueService.findByUID(context, selectedID);
authorities.add(byUID); authorities.add(byUID);
@@ -149,7 +155,7 @@ public class UpdateAuthorities {
protected void followUp(AuthorityValue authority) { protected void followUp(AuthorityValue authority) {
print.println("Updated: " + authority.getValue() + " - " + authority.getId()); print.println("Updated: " + authority.getValue() + " - " + authority.getId());
boolean updateItems = ConfigurationManager.getBooleanProperty("solrauthority", "auto-update-items"); boolean updateItems = configurationService.getBooleanProperty("solrauthority.auto-update-items");
if (updateItems) { if (updateItems) {
updateItems(authority); updateItems(authority);
} }
@@ -169,7 +175,7 @@ public class UpdateAuthorities {
print.println("Updated item with handle " + next.getHandle()); print.println("Updated item with handle " + next.getHandle());
} }
} }
} catch (Exception e) { } catch (SQLException | AuthorizeException e) {
log.error("Error updating item", e); log.error("Error updating item", e);
print.println("Error updating item. " + Arrays.toString(e.getStackTrace())); print.println("Error updating item. " + Arrays.toString(e.getStackTrace()));
} }

View File

@@ -7,8 +7,11 @@
*/ */
package org.dspace.browse; package org.dspace.browse;
import org.dspace.core.ConfigurationManager; import java.lang.reflect.InvocationTargetException;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Factory class to generate DAOs based on the configuration * Factory class to generate DAOs based on the configuration
@@ -33,16 +36,21 @@ public class BrowseDAOFactory {
*/ */
public static BrowseDAO getInstance(Context context) public static BrowseDAO getInstance(Context context)
throws BrowseException { throws BrowseException {
String className = ConfigurationManager.getProperty("browseDAO.class"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String className = configurationService.getProperty("browseDAO.class");
if (className == null) { if (className == null) {
// SOLR implementation is the default since DSpace 4.0 // SOLR implementation is the default since DSpace 4.0
return new SolrBrowseDAO(context); return new SolrBrowseDAO(context);
} }
try { try {
return (BrowseDAO) Class return (BrowseDAO) Class
.forName(ConfigurationManager.getProperty("browseDAO.class")) .forName(configurationService.getProperty("browseDAO.class"))
.getConstructor(Context.class).newInstance(context); .getConstructor(Context.class).newInstance(context);
} catch (Exception e) { } catch (ClassNotFoundException | IllegalAccessException
| IllegalArgumentException | InstantiationException
| NoSuchMethodException | SecurityException |
InvocationTargetException e) {
throw new BrowseException("The configuration for browseDAO is invalid: " + className, e); throw new BrowseException("The configuration for browseDAO is invalid: " + className, e);
} }
} }

View File

@@ -13,7 +13,8 @@ import java.util.StringTokenizer;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.sort.SortException; import org.dspace.sort.SortException;
import org.dspace.sort.SortOption; import org.dspace.sort.SortOption;
@@ -414,6 +415,7 @@ public final class BrowseIndex {
* @return the name of the table * @return the name of the table
* @deprecated 1.5 * @deprecated 1.5
*/ */
@Deprecated
public static String getTableName(int number, boolean isCommunity, boolean isCollection, boolean isDistinct, public static String getTableName(int number, boolean isCommunity, boolean isCollection, boolean isDistinct,
boolean isMap) { boolean isMap) {
return BrowseIndex.getTableName(makeTableBaseName(number), isCommunity, isCollection, isDistinct, isMap); return BrowseIndex.getTableName(makeTableBaseName(number), isCommunity, isCollection, isDistinct, isMap);
@@ -462,6 +464,7 @@ public final class BrowseIndex {
* @return the name of the table * @return the name of the table
* @deprecated 1.5 * @deprecated 1.5
*/ */
@Deprecated
public String getTableName(boolean isCommunity, boolean isCollection, boolean isDistinct, boolean isMap) { public String getTableName(boolean isCommunity, boolean isCollection, boolean isDistinct, boolean isMap) {
if (isDistinct || isMap) { if (isDistinct || isMap) {
return BrowseIndex.getTableName(number, isCommunity, isCollection, isDistinct, isMap); return BrowseIndex.getTableName(number, isCommunity, isCollection, isDistinct, isMap);
@@ -482,6 +485,7 @@ public final class BrowseIndex {
* @return the name of the table * @return the name of the table
* @deprecated 1.5 * @deprecated 1.5
*/ */
@Deprecated
public String getTableName(boolean isCommunity, boolean isCollection) { public String getTableName(boolean isCommunity, boolean isCollection) {
return getTableName(isCommunity, isCollection, false, false); return getTableName(isCommunity, isCollection, false, false);
} }
@@ -514,6 +518,7 @@ public final class BrowseIndex {
* @return table name * @return table name
* @deprecated 1.5 * @deprecated 1.5
*/ */
@Deprecated
public String getTableName(boolean isDistinct, boolean isCommunity, boolean isCollection) { public String getTableName(boolean isDistinct, boolean isCommunity, boolean isCollection) {
return getTableName(isCommunity, isCollection, isDistinct, false); return getTableName(isCommunity, isCollection, isDistinct, false);
} }
@@ -649,6 +654,7 @@ public final class BrowseIndex {
* @throws BrowseException if browse error * @throws BrowseException if browse error
* @deprecated * @deprecated
*/ */
@Deprecated
public static String[] tables() public static String[] tables()
throws BrowseException { throws BrowseException {
BrowseIndex[] bis = getBrowseIndices(); BrowseIndex[] bis = getBrowseIndices();
@@ -670,13 +676,14 @@ public final class BrowseIndex {
throws BrowseException { throws BrowseException {
int idx = 1; int idx = 1;
String definition; String definition;
ArrayList<BrowseIndex> browseIndices = new ArrayList<BrowseIndex>(); ArrayList<BrowseIndex> browseIndices = new ArrayList<>();
while (((definition = ConfigurationManager.getProperty("webui.browse.index." + idx))) != null) { ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
while (((definition = configurationService.getProperty("webui.browse.index." + idx))) != null) {
BrowseIndex bi = new BrowseIndex(definition, idx); BrowseIndex bi = new BrowseIndex(definition, idx);
bi.displayFrequencies = Boolean.valueOf(ConfigurationManager bi.displayFrequencies = configurationService
.getBooleanProperty("webui.browse.metadata.show-freq." .getBooleanProperty("webui.browse.metadata.show-freq." + idx, true);
+ idx, true));
browseIndices.add(bi); browseIndices.add(bi);
idx++; idx++;
@@ -804,8 +811,8 @@ public final class BrowseIndex {
* @return true or false * @return true or false
*/ */
public boolean isTagCloudEnabled() { public boolean isTagCloudEnabled() {
ConfigurationService configurationService
return ConfigurationManager.getBooleanProperty("webui.browse.index.tagcloud." + number); = DSpaceServicesFactory.getInstance().getConfigurationService();
return configurationService.getBooleanProperty("webui.browse.index.tagcloud." + number);
} }
} }

View File

@@ -10,7 +10,8 @@ package org.dspace.browse;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Class to represent the configuration of the cross-linking between browse * Class to represent the configuration of the cross-linking between browse
@@ -23,7 +24,7 @@ public class CrossLinks {
/** /**
* a map of the desired links * a map of the desired links
*/ */
private Map<String, String> links = new HashMap<String, String>(); private Map<String, String> links = new HashMap<>();
/** /**
* Construct a new object which will obtain the configuration for itself. * Construct a new object which will obtain the configuration for itself.
@@ -35,7 +36,9 @@ public class CrossLinks {
int i = 1; int i = 1;
while (true) { while (true) {
String field = "webui.browse.link." + i; String field = "webui.browse.link." + i;
String config = ConfigurationManager.getProperty(field); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String config = configurationService.getProperty(field);
if (config == null) { if (config == null) {
break; break;
} }

View File

@@ -7,8 +7,9 @@
*/ */
package org.dspace.browse; package org.dspace.browse;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Factory class to allow us to load the correct DAO for registering * Factory class to allow us to load the correct DAO for registering
@@ -38,7 +39,9 @@ public class ItemCountDAOFactory {
/** Log4j logger */ /** Log4j logger */
ItemCountDAO dao = null; ItemCountDAO dao = null;
String className = ConfigurationManager.getProperty("ItemCountDAO.class"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String className = configurationService.getProperty("ItemCountDAO.class");
// SOLR implementation is the default since DSpace 4.0 // SOLR implementation is the default since DSpace 4.0
if (className == null) { if (className == null) {
@@ -47,7 +50,8 @@ public class ItemCountDAOFactory {
try { try {
dao = (ItemCountDAO) Class dao = (ItemCountDAO) Class
.forName(className.trim()).newInstance(); .forName(className.trim()).newInstance();
} catch (Exception e) { } catch (ClassNotFoundException | IllegalAccessException
| InstantiationException e) {
throw new ItemCountException("The configuration for ItemCountDAO is invalid: " + className, e); throw new ItemCountException("The configuration for ItemCountDAO is invalid: " + className, e);
} }
} }

View File

@@ -12,8 +12,10 @@ import java.util.Locale;
import com.ibm.icu.text.CollationElementIterator; import com.ibm.icu.text.CollationElementIterator;
import com.ibm.icu.text.Collator; import com.ibm.icu.text.Collator;
import com.ibm.icu.text.RuleBasedCollator; import com.ibm.icu.text.RuleBasedCollator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.text.filter.TextFilter; import org.dspace.text.filter.TextFilter;
/** /**
@@ -32,7 +34,7 @@ import org.dspace.text.filter.TextFilter;
* @author Graham Triggs * @author Graham Triggs
*/ */
public class LocaleOrderingFilter implements TextFilter { public class LocaleOrderingFilter implements TextFilter {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(LocaleOrderingFilter.class); private static final Logger log = LogManager.getLogger(LocaleOrderingFilter.class);
/** /**
* Uses a Locale dependent Collator to generate a sort string * Uses a Locale dependent Collator to generate a sort string
@@ -47,7 +49,7 @@ public class LocaleOrderingFilter implements TextFilter {
// Have we got a collator? // Have we got a collator?
if (collator != null) { if (collator != null) {
int element; int element;
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
// Iterate through the elements of the collator // Iterate through the elements of the collator
CollationElementIterator iter = collator.getCollationElementIterator(str); CollationElementIterator iter = collator.getCollationElementIterator(str);
@@ -107,7 +109,9 @@ public class LocaleOrderingFilter implements TextFilter {
Locale theLocale = null; Locale theLocale = null;
// Get a Locale configuration from the dspace.cfg // Get a Locale configuration from the dspace.cfg
String locale = ConfigurationManager.getProperty("webui.browse.sort.locale"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String locale = configurationService.getProperty("webui.browse.sort.locale");
if (locale != null) { if (locale != null) {
// Attempt to create Locale for the configured value // Attempt to create Locale for the configured value

View File

@@ -21,13 +21,15 @@ import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException; import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.checker.factory.CheckerServiceFactory; import org.dspace.checker.factory.CheckerServiceFactory;
import org.dspace.checker.service.SimpleReporterService; import org.dspace.checker.service.SimpleReporterService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
import org.dspace.core.Utils; import org.dspace.core.Utils;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* <p> * <p>
@@ -44,7 +46,7 @@ public class DailyReportEmailer {
/** /**
* log4j logger. * log4j logger.
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(DailyReportEmailer.class); private static final Logger log = LogManager.getLogger(DailyReportEmailer.class);
/** /**
* Default constructor. * Default constructor.
@@ -63,14 +65,16 @@ public class DailyReportEmailer {
public void sendReport(File attachment, int numberOfBitstreams) public void sendReport(File attachment, int numberOfBitstreams)
throws IOException, javax.mail.MessagingException { throws IOException, javax.mail.MessagingException {
if (numberOfBitstreams > 0) { if (numberOfBitstreams > 0) {
String hostname = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url")); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String hostname = Utils.getHostName(configurationService.getProperty("dspace.ui.url"));
Email email = new Email(); Email email = new Email();
email.setSubject( email.setSubject(String.format(
"Checksum checker Report - " + numberOfBitstreams + " Bitstreams found with POSSIBLE issues on " + "Checksum checker Report - %d Bitstreams found with POSSIBLE issues on %s",
hostname); numberOfBitstreams, hostname));
email.setContent("Checker Report", "report is attached ..."); email.setContent("Checker Report", "report is attached ...");
email.addAttachment(attachment, "checksum_checker_report.txt"); email.addAttachment(attachment, "checksum_checker_report.txt");
email.addRecipient(ConfigurationManager.getProperty("mail.admin")); email.addRecipient(configurationService.getProperty("mail.admin"));
email.send(); email.send();
} }
} }
@@ -164,7 +168,9 @@ public class DailyReportEmailer {
int numBitstreams = 0; int numBitstreams = 0;
// create a temporary file in the log directory // create a temporary file in the log directory
String dirLocation = ConfigurationManager.getProperty("log.report.dir"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String dirLocation = configurationService.getProperty("log.report.dir");
File directory = new File(dirLocation); File directory = new File(dirLocation);
if (directory.exists() && directory.isDirectory()) { if (directory.exists() && directory.isDirectory()) {
@@ -247,7 +253,7 @@ public class DailyReportEmailer {
if (writer != null) { if (writer != null) {
try { try {
writer.close(); writer.close();
} catch (Exception e) { } catch (IOException e) {
log.fatal("Could not close writer", e); log.fatal("Could not close writer", e);
} }
} }

View File

@@ -19,12 +19,14 @@ import java.util.Properties;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.checker.factory.CheckerServiceFactory; import org.dspace.checker.factory.CheckerServiceFactory;
import org.dspace.checker.service.ChecksumHistoryService; import org.dspace.checker.service.ChecksumHistoryService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Utils; import org.dspace.core.Utils;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Manages the deletion of results from the checksum history. It uses the * Manages the deletion of results from the checksum history. It uses the
@@ -40,7 +42,7 @@ public final class ResultsPruner {
/** /**
* Default logger. * Default logger.
*/ */
private static final Logger LOG = org.apache.logging.log4j.LogManager.getLogger(ResultsPruner.class); private static final Logger LOG = LogManager.getLogger(ResultsPruner.class);
/** /**
* Factory method for the default results pruner configuration using * Factory method for the default results pruner configuration using
@@ -51,12 +53,13 @@ public final class ResultsPruner {
*/ */
public static ResultsPruner getDefaultPruner(Context context) { public static ResultsPruner getDefaultPruner(Context context) {
try { try {
return getPruner(context, ConfigurationManager.getProperties()); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
return getPruner(context, configurationService.getProperties());
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new IllegalStateException( throw new IllegalStateException(
"VeryExceptionalException - config file not there! ", e); "VeryExceptionalException - config file not there! ", e);
} }
} }

View File

@@ -36,7 +36,6 @@ import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
@@ -55,6 +54,7 @@ import org.dspace.eperson.service.SubscribeService;
import org.dspace.event.Event; import org.dspace.event.Event;
import org.dspace.harvest.HarvestedCollection; import org.dspace.harvest.HarvestedCollection;
import org.dspace.harvest.service.HarvestedCollectionService; import org.dspace.harvest.service.HarvestedCollectionService;
import org.dspace.services.ConfigurationService;
import org.dspace.workflow.factory.WorkflowServiceFactory; import org.dspace.workflow.factory.WorkflowServiceFactory;
import org.dspace.xmlworkflow.WorkflowConfigurationException; import org.dspace.xmlworkflow.WorkflowConfigurationException;
import org.dspace.xmlworkflow.factory.XmlWorkflowFactory; import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
@@ -111,6 +111,9 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> i
@Autowired(required = true) @Autowired(required = true)
protected SearchService searchService; protected SearchService searchService;
@Autowired(required = true)
protected ConfigurationService configurationService;
protected CollectionServiceImpl() { protected CollectionServiceImpl() {
super(); super();
} }
@@ -189,7 +192,7 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> i
@Override @Override
public List<Collection> findAuthorizedOptimized(Context context, int actionID) throws SQLException { public List<Collection> findAuthorizedOptimized(Context context, int actionID) throws SQLException {
if (!ConfigurationManager if (!configurationService
.getBooleanProperty("org.dspace.content.Collection.findAuthorizedPerformanceOptimize", false)) { .getBooleanProperty("org.dspace.content.Collection.findAuthorizedPerformanceOptimize", false)) {
// Fallback to legacy query if config says so. The rationale could be that a site found a bug. // Fallback to legacy query if config says so. The rationale could be that a site found a bug.
return findAuthorized(context, null, actionID); return findAuthorized(context, null, actionID);
@@ -922,7 +925,7 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> i
public List<Collection> findCollectionsWithSubmit(String q, Context context, Community community, public List<Collection> findCollectionsWithSubmit(String q, Context context, Community community,
int offset, int limit) throws SQLException, SearchServiceException { int offset, int limit) throws SQLException, SearchServiceException {
List<Collection> collections = new ArrayList<Collection>(); List<Collection> collections = new ArrayList<>();
DiscoverQuery discoverQuery = new DiscoverQuery(); DiscoverQuery discoverQuery = new DiscoverQuery();
discoverQuery.setDSpaceObjectFilter(IndexableCollection.TYPE); discoverQuery.setDSpaceObjectFilter(IndexableCollection.TYPE);
discoverQuery.setStart(offset); discoverQuery.setStart(offset);

View File

@@ -14,9 +14,10 @@ import javax.persistence.Transient;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.SiteService; import org.dspace.content.service.SiteService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
/** /**
@@ -56,7 +57,9 @@ public class Site extends DSpaceObject {
} }
public String getURL() { public String getURL() {
return ConfigurationManager.getProperty("dspace.ui.url"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
return configurationService.getProperty("dspace.ui.url");
} }
private SiteService getSiteService() { private SiteService getSiteService() {

View File

@@ -15,7 +15,6 @@ import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService; import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.dao.SiteDAO; import org.dspace.content.dao.SiteDAO;
import org.dspace.content.service.SiteService; import org.dspace.content.service.SiteService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.event.Event; import org.dspace.event.Event;
@@ -94,7 +93,7 @@ public class SiteServiceImpl extends DSpaceObjectServiceImpl<Site> implements Si
@Override @Override
public String getName(Site dso) { public String getName(Site dso) {
return ConfigurationManager.getProperty("dspace.name"); return configurationService.getProperty("dspace.name");
} }
@Override @Override

View File

@@ -9,23 +9,23 @@ package org.dspace.content.authority;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.MetadataField; import org.dspace.content.MetadataField;
import org.dspace.content.authority.service.MetadataAuthorityService; import org.dspace.content.authority.service.MetadataAuthorityService;
import org.dspace.content.service.MetadataFieldService; import org.dspace.content.service.MetadataFieldService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
/** /**
* Broker for metadata authority settings configured for each metadata field. * Broker for metadata authority settings configured for each metadata field.
* *
* Configuration keys, per metadata field (e.g. "dc.contributer.author") * Configuration keys, per metadata field (e.g. "dc.contributor.author")
* *
* {@code * {@code
* # is field authority controlled (i.e. store authority, confidence values)? * # is field authority controlled (i.e. store authority, confidence values)?
@@ -52,13 +52,16 @@ import org.springframework.beans.factory.annotation.Autowired;
* @see Choices * @see Choices
*/ */
public class MetadataAuthorityServiceImpl implements MetadataAuthorityService { public class MetadataAuthorityServiceImpl implements MetadataAuthorityService {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(MetadataAuthorityServiceImpl.class); private static final Logger log = LogManager.getLogger(MetadataAuthorityServiceImpl.class);
@Autowired(required = true) @Autowired(required = true)
protected MetadataFieldService metadataFieldService; protected MetadataFieldService metadataFieldService;
@Autowired(required = true)
protected ConfigurationService configurationService;
// map of field key to authority plugin // map of field key to authority plugin
protected Map<String, Boolean> controlled = new HashMap<String, Boolean>(); protected Map<String, Boolean> controlled = new HashMap<>();
// map of field key to answer of whether field is required to be controlled // map of field key to answer of whether field is required to be controlled
protected Map<String, Boolean> isAuthorityRequired = null; protected Map<String, Boolean> isAuthorityRequired = null;
@@ -67,7 +70,7 @@ public class MetadataAuthorityServiceImpl implements MetadataAuthorityService {
* map of field key to answer of which is the min acceptable confidence * map of field key to answer of which is the min acceptable confidence
* value for a field with authority * value for a field with authority
*/ */
protected Map<String, Integer> minConfidence = new HashMap<String, Integer>(); protected Map<String, Integer> minConfidence = new HashMap<>();
/** /**
* fallback default value unless authority.minconfidence = X is configured. * fallback default value unless authority.minconfidence = X is configured.
@@ -81,13 +84,12 @@ public class MetadataAuthorityServiceImpl implements MetadataAuthorityService {
public void init() { public void init() {
if (isAuthorityRequired == null) { if (isAuthorityRequired == null) {
isAuthorityRequired = new HashMap<String, Boolean>(); isAuthorityRequired = new HashMap<>();
Enumeration pn = ConfigurationManager.propertyNames(); List<String> pn = configurationService.getPropertyKeys();
final String authPrefix = "authority.controlled."; final String authPrefix = "authority.controlled.";
Context context = new Context(); Context context = new Context();
try { try {
while (pn.hasMoreElements()) { for (String key : pn) {
String key = (String) pn.nextElement();
if (key.startsWith(authPrefix)) { if (key.startsWith(authPrefix)) {
// field is expected to be "schema.element.qualifier" // field is expected to be "schema.element.qualifier"
String field = key.substring(authPrefix.length()); String field = key.substring(authPrefix.length());
@@ -115,8 +117,8 @@ public class MetadataAuthorityServiceImpl implements MetadataAuthorityService {
"Error while configuring authority control, metadata field: " + field + " could not " + "Error while configuring authority control, metadata field: " + field + " could not " +
"be found"); "be found");
} }
boolean ctl = ConfigurationManager.getBooleanProperty(key, true); boolean ctl = configurationService.getBooleanProperty(key, true);
boolean req = ConfigurationManager.getBooleanProperty("authority.required." + field, false); boolean req = configurationService.getBooleanProperty("authority.required." + field, false);
controlled.put(metadataField.toString(), ctl); controlled.put(metadataField.toString(), ctl);
isAuthorityRequired.put(metadataField.toString(), req); isAuthorityRequired.put(metadataField.toString(), req);
@@ -143,7 +145,7 @@ public class MetadataAuthorityServiceImpl implements MetadataAuthorityService {
} }
private int readConfidence(String key) { private int readConfidence(String key) {
String mc = ConfigurationManager.getProperty(key); String mc = configurationService.getProperty(key);
if (mc != null) { if (mc != null) {
int mci = Choices.getConfidenceValue(mc.trim(), Choices.CF_UNSET - 1); int mci = Choices.getConfidenceValue(mc.trim(), Choices.CF_UNSET - 1);
if (mci == Choices.CF_UNSET - 1) { if (mci == Choices.CF_UNSET - 1) {

View File

@@ -7,6 +7,7 @@
*/ */
package org.dspace.content.authority; package org.dspace.content.authority;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@@ -14,8 +15,10 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrDocumentList;
@@ -25,7 +28,6 @@ import org.dspace.authority.AuthorityValue;
import org.dspace.authority.SolrAuthorityInterface; import org.dspace.authority.SolrAuthorityInterface;
import org.dspace.authority.factory.AuthorityServiceFactory; import org.dspace.authority.factory.AuthorityServiceFactory;
import org.dspace.authority.service.AuthorityValueService; import org.dspace.authority.service.AuthorityValueService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.NameAwarePlugin; import org.dspace.core.NameAwarePlugin;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
@@ -49,13 +51,16 @@ public class SolrAuthority implements ChoiceAuthority {
DSpaceServicesFactory.getInstance().getServiceManager() DSpaceServicesFactory.getInstance().getServiceManager()
.getServiceByName("AuthoritySource", SolrAuthorityInterface.class); .getServiceByName("AuthoritySource", SolrAuthorityInterface.class);
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SolrAuthority.class); private static final Logger log = LogManager.getLogger(SolrAuthority.class);
protected boolean externalResults = false; protected boolean externalResults = false;
protected final AuthorityValueService authorityValueService = AuthorityServiceFactory.getInstance()
.getAuthorityValueService(); protected final AuthorityValueService authorityValueService
protected final ConfigurationService configurationService = DSpaceServicesFactory.getInstance() = AuthorityServiceFactory.getInstance().getAuthorityValueService();
.getConfigurationService();
protected final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
public Choices getMatches(String text, int start, int limit, String locale, public Choices getMatches(String text, int start, int limit, String locale,
boolean bestMatch) { boolean bestMatch) {
if (limit == 0) { if (limit == 0) {
@@ -91,7 +96,7 @@ public class SolrAuthority implements ChoiceAuthority {
//We add one to our facet limit so that we know if there are more matches //We add one to our facet limit so that we know if there are more matches
int maxNumberOfSolrResults = limit + 1; int maxNumberOfSolrResults = limit + 1;
if (externalResults) { if (externalResults) {
maxNumberOfSolrResults = ConfigurationManager.getIntProperty("xmlui.lookup.select.size", 12); maxNumberOfSolrResults = configurationService.getIntProperty("xmlui.lookup.select.size", 12);
} }
queryArgs.set(CommonParams.ROWS, maxNumberOfSolrResults); queryArgs.set(CommonParams.ROWS, maxNumberOfSolrResults);
@@ -144,7 +149,7 @@ public class SolrAuthority implements ChoiceAuthority {
int confidence; int confidence;
if (choices.size() == 0) { if (choices.isEmpty()) {
confidence = Choices.CF_NOTFOUND; confidence = Choices.CF_NOTFOUND;
} else if (choices.size() == 1) { } else if (choices.size() == 1) {
confidence = Choices.CF_UNCERTAIN; confidence = Choices.CF_UNCERTAIN;
@@ -154,7 +159,7 @@ public class SolrAuthority implements ChoiceAuthority {
result = new Choices(choices.toArray(new Choice[choices.size()]), start, result = new Choices(choices.toArray(new Choice[choices.size()]), start,
hasMore ? max : choices.size() + start, confidence, hasMore); hasMore ? max : choices.size() + start, confidence, hasMore);
} catch (Exception e) { } catch (IOException | SolrServerException e) {
log.error("Error while retrieving authority values {field: " + field + ", prefix:" + text + "}", e); log.error("Error while retrieving authority values {field: " + field + ", prefix:" + text + "}", e);
result = new Choices(true); result = new Choices(true);
} }
@@ -269,7 +274,7 @@ public class SolrAuthority implements ChoiceAuthority {
return label; return label;
} }
} }
} catch (Exception e) { } catch (IOException | SolrServerException e) {
log.error("error occurred while trying to get label for key " + key, e); log.error("error occurred while trying to get label for key " + key, e);
} }

View File

@@ -31,7 +31,6 @@ import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.SiteService; import org.dspace.content.service.SiteService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
@@ -39,6 +38,8 @@ import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
@@ -51,29 +52,34 @@ import org.jdom.Namespace;
* a complete and accurate image of all of the attributes an object * a complete and accurate image of all of the attributes an object
* has in the RDBMS. * has in the RDBMS.
* *
* <p>
* It encodes the following common properties of all archival objects: * It encodes the following common properties of all archival objects:
* <dl>
* <dt>identifier.uri</dt> <dd>persistent identifier of object in URI form (e.g. Handle URN)</dd>
* <dt>relation.isPartOf</dt> <dd>persistent identifier of object's parent in URI form (e.g. Handle URN)</dd>
* <dt>relation.isReferencedBy</dt> <dd>if relevant, persistent identifier of
* other objects that map this one as a child. May repeat.</dd>
* </dl>
* *
* identifier.uri -- persistent identifier of object in URI form (e.g. Handle URN) * <p>
* relation.isPartOf -- persistent identifier of object's parent in URI form (e.g. Handle URN)
* relation.isReferencedBy -- if relevant, persistent identifier of other objects that map this one as a child. May
* repeat.
*
* There may also be other fields, depending on the type of object, * There may also be other fields, depending on the type of object,
* which encode attributes that are not part of the descriptive metadata and * which encode attributes that are not part of the descriptive metadata and
* are not adequately covered by other technical MD formats (i.e. PREMIS). * are not adequately covered by other technical MD formats (i.e. PREMIS).
* *
* <p>
* Configuration entries: * Configuration entries:
* aip.ingest.createEperson -- boolean, create EPerson for Submitter * <dl>
* automatically, on ingest, if it doesn't exist. * <dt>aip.ingest.createEperson</dt> <dd>boolean, create EPerson for Submitter
* automatically, on ingest, if it doesn't exist.</dd>
* </dl>
* *
* @author Larry Stone * @author Larry Stone
* @version $Revision: 1.2 $
*/ */
public class AIPTechMDCrosswalk implements IngestionCrosswalk, DisseminationCrosswalk { public class AIPTechMDCrosswalk implements IngestionCrosswalk, DisseminationCrosswalk {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(AIPTechMDCrosswalk.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(AIPTechMDCrosswalk.class);
protected final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance() protected final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance()
.getBitstreamFormatService(); .getBitstreamFormatService();
protected final SiteService siteService = ContentServiceFactory.getInstance().getSiteService(); protected final SiteService siteService = ContentServiceFactory.getInstance().getSiteService();
@@ -81,6 +87,8 @@ public class AIPTechMDCrosswalk implements IngestionCrosswalk, DisseminationCros
protected final EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); protected final EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); protected final HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Get XML namespaces of the elements this crosswalk may return. * Get XML namespaces of the elements this crosswalk may return.
@@ -391,7 +399,7 @@ public class AIPTechMDCrosswalk implements IngestionCrosswalk, DisseminationCros
String configName = new DSpaceAIPIngester().getConfigurationName(); String configName = new DSpaceAIPIngester().getConfigurationName();
//Create the EPerson if specified and person doesn't already exit //Create the EPerson if specified and person doesn't already exit
if (ConfigurationManager.getBooleanProperty( if (configurationService.getBooleanProperty(
METSManifest.CONFIG_METS_PREFIX + configName + ".ingest.createSubmitter")) { METSManifest.CONFIG_METS_PREFIX + configName + ".ingest.createSubmitter")) {
sub = ePersonService.create(context); sub = ePersonService.create(context);
sub.setEmail(value); sub.setEmail(value);

View File

@@ -21,8 +21,9 @@ import org.dspace.content.NonUniqueMetadataException;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.MetadataFieldService; import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService; import org.dspace.content.service.MetadataSchemaService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
public class CrosswalkMetadataValidator { public class CrosswalkMetadataValidator {
@@ -32,21 +33,23 @@ public class CrosswalkMetadataValidator {
private String schemaChoice; private String schemaChoice;
private String fieldChoice; private String fieldChoice;
private Map<Triple<String, String, String>, MetadataField> validatedMetadataFields; private final Map<Triple<String, String, String>, MetadataField> validatedMetadataFields;
public CrosswalkMetadataValidator() { public CrosswalkMetadataValidator() {
metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService();
metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService();
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
validatedMetadataFields = new HashMap<>(); validatedMetadataFields = new HashMap<>();
// The two options, with three possibilities each: add, ignore, fail // The two options, with three possibilities each: add, ignore, fail
schemaChoice = ConfigurationManager.getProperty("oai", "harvester.unknownSchema"); schemaChoice = configurationService.getProperty("oai.harvester.unknownSchema");
if (schemaChoice == null) { if (schemaChoice == null) {
schemaChoice = "fail"; schemaChoice = "fail";
} }
fieldChoice = ConfigurationManager.getProperty("oai", "harvester.unknownField"); fieldChoice = configurationService.getProperty("oai.harvester.unknownField");
if (fieldChoice == null) { if (fieldChoice == null) {
fieldChoice = "fail"; fieldChoice = "fail";
} }
@@ -123,6 +126,6 @@ public class CrosswalkMetadataValidator {
private ImmutableTriple<String, String, String> createKey(final String schema, final String element, private ImmutableTriple<String, String, String> createKey(final String schema, final String element,
final String qualifier) { final String qualifier) {
return new ImmutableTriple<String, String, String>(schema, element, qualifier); return new ImmutableTriple<>(schema, element, qualifier);
} }
} }

View File

@@ -19,10 +19,11 @@ import org.dspace.content.DSpaceObject;
import org.dspace.content.packager.PackageDisseminator; import org.dspace.content.packager.PackageDisseminator;
import org.dspace.content.packager.PackageException; import org.dspace.content.packager.PackageException;
import org.dspace.content.packager.PackageParameters; import org.dspace.content.packager.PackageParameters;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.factory.CoreServiceFactory; import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.JDOMException; import org.jdom.JDOMException;
@@ -85,7 +86,7 @@ public class METSDisseminationCrosswalk
public List<Element> disseminateList(Context context, DSpaceObject dso) public List<Element> disseminateList(Context context, DSpaceObject dso)
throws CrosswalkException, throws CrosswalkException,
IOException, SQLException, AuthorizeException { IOException, SQLException, AuthorizeException {
List<Element> result = new ArrayList<Element>(1); List<Element> result = new ArrayList<>(1);
result.add(disseminateElement(context, dso)); result.add(disseminateElement(context, dso));
return result; return result;
} }
@@ -114,8 +115,11 @@ public class METSDisseminationCrosswalk
pparams.put("manifestOnly", "true"); pparams.put("manifestOnly", "true");
// Create a temporary file to disseminate into // Create a temporary file to disseminate into
String tempDirectory = (ConfigurationManager.getProperty("upload.temp.dir") != null) ConfigurationService configurationService
? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir"); = DSpaceServicesFactory.getInstance().getConfigurationService();
String tempDirectory = (configurationService.hasProperty("upload.temp.dir"))
? configurationService.getProperty("upload.temp.dir")
: System.getProperty("java.io.tmpdir");
File tempFile = File.createTempFile("METSDissemination" + dso.hashCode(), null, new File(tempDirectory)); File tempFile = File.createTempFile("METSDissemination" + dso.hashCode(), null, new File(tempDirectory));
tempFile.deleteOnExit(); tempFile.deleteOnExit();

View File

@@ -21,6 +21,7 @@ import java.util.Map;
import java.util.Properties; import java.util.Properties;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection; import org.dspace.content.Collection;
@@ -34,12 +35,13 @@ import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.SelfNamedPlugin; import org.dspace.core.SelfNamedPlugin;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Attribute; import org.jdom.Attribute;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
@@ -84,14 +86,13 @@ import org.jdom.xpath.XPath;
* *
* @author Larry Stone * @author Larry Stone
* @author Scott Phillips * @author Scott Phillips
* @version $Revision$
*/ */
public class MODSDisseminationCrosswalk extends SelfNamedPlugin public class MODSDisseminationCrosswalk extends SelfNamedPlugin
implements DisseminationCrosswalk { implements DisseminationCrosswalk {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(MODSDisseminationCrosswalk.class); private static final Logger log = LogManager.getLogger(MODSDisseminationCrosswalk.class);
private static final String CONFIG_PREFIX = "crosswalk.mods.properties."; private static final String CONFIG_PREFIX = "crosswalk.mods.properties.";
@@ -99,6 +100,8 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
protected final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); protected final HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Fill in the plugin alias table from DSpace configuration entries * Fill in the plugin alias table from DSpace configuration entries
@@ -107,10 +110,9 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
private static String aliases[] = null; private static String aliases[] = null;
static { static {
List<String> aliasList = new ArrayList<String>(); List<String> aliasList = new ArrayList<>();
Enumeration<String> pe = (Enumeration<String>) ConfigurationManager.propertyNames(); List<String> pe = configurationService.getPropertyKeys();
while (pe.hasMoreElements()) { for (String key : pe) {
String key = pe.nextElement();
if (key.startsWith(CONFIG_PREFIX)) { if (key.startsWith(CONFIG_PREFIX)) {
aliasList.add(key.substring(CONFIG_PREFIX.length())); aliasList.add(key.substring(CONFIG_PREFIX.length()));
} }
@@ -142,8 +144,8 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
private static final String schemaLocation = private static final String schemaLocation =
MODS_NS.getURI() + " " + MODS_XSD; MODS_NS.getURI() + " " + MODS_XSD;
private static XMLOutputter outputUgly = new XMLOutputter(); private static final XMLOutputter outputUgly = new XMLOutputter();
private static SAXBuilder builder = new SAXBuilder(); private static final SAXBuilder builder = new SAXBuilder();
private Map<String, modsTriple> modsMap = null; private Map<String, modsTriple> modsMap = null;
@@ -176,11 +178,7 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
result.xpath.addNamespace(XLINK_NS); result.xpath.addNamespace(XLINK_NS);
Document d = builder.build(new StringReader(prolog + xml + postlog)); Document d = builder.build(new StringReader(prolog + xml + postlog));
result.xml = (Element) d.getRootElement().getContent(0); result.xml = (Element) d.getRootElement().getContent(0);
} catch (JDOMException je) { } catch (JDOMException | IOException je) {
log.error("Error initializing modsTriple(\"" + qdc + "\",\"" + xml + "\",\"" + xpath + "\"): got " + je
.toString());
return null;
} catch (IOException je) {
log.error("Error initializing modsTriple(\"" + qdc + "\",\"" + xml + "\",\"" + xpath + "\"): got " + je log.error("Error initializing modsTriple(\"" + qdc + "\",\"" + xml + "\",\"" + xpath + "\"): got " + je
.toString()); .toString());
return null; return null;
@@ -226,14 +224,14 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
return; return;
} }
String cmPropName = CONFIG_PREFIX + myAlias; String cmPropName = CONFIG_PREFIX + myAlias;
String propsFilename = ConfigurationManager.getProperty(cmPropName); String propsFilename = configurationService.getProperty(cmPropName);
if (propsFilename == null) { if (propsFilename == null) {
String msg = "MODS crosswalk missing " + String msg = "MODS crosswalk missing " +
"configuration file for crosswalk named \"" + myAlias + "\""; "configuration file for crosswalk named \"" + myAlias + "\"";
log.error(msg); log.error(msg);
throw new CrosswalkInternalException(msg); throw new CrosswalkInternalException(msg);
} else { } else {
String parent = ConfigurationManager.getProperty("dspace.dir") + String parent = configurationService.getProperty("dspace.dir") +
File.separator + "config" + File.separator; File.separator + "config" + File.separator;
File propsFile = new File(parent, propsFilename); File propsFile = new File(parent, propsFilename);
Properties modsConfig = new Properties(); Properties modsConfig = new Properties();
@@ -256,7 +254,7 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
} }
} }
modsMap = new HashMap<String, modsTriple>(); modsMap = new HashMap<>();
Enumeration<String> pe = (Enumeration<String>) modsConfig.propertyNames(); Enumeration<String> pe = (Enumeration<String>) modsConfig.propertyNames();
while (pe.hasMoreElements()) { while (pe.hasMoreElements()) {
String qdc = pe.nextElement(); String qdc = pe.nextElement();
@@ -343,7 +341,7 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
} }
initMap(); initMap();
List<Element> result = new ArrayList<Element>(dcvs.size()); List<Element> result = new ArrayList<>(dcvs.size());
for (MetadataValueDTO dcv : dcvs) { for (MetadataValueDTO dcv : dcvs) {
String qdc = dcv.getSchema() + "." + dcv.getElement(); String qdc = dcv.getSchema() + "." + dcv.getElement();
@@ -579,7 +577,7 @@ public class MODSDisseminationCrosswalk extends SelfNamedPlugin
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Filtering out non-XML characters in string, reason=" + reason); log.debug("Filtering out non-XML characters in string, reason=" + reason);
} }
StringBuffer result = new StringBuffer(value.length()); StringBuilder result = new StringBuilder(value.length());
for (int i = 0; i < value.length(); ++i) { for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i); char c = value.charAt(i);
if (Verifier.isXMLCharacter((int) c)) { if (Verifier.isXMLCharacter((int) c)) {

View File

@@ -15,6 +15,7 @@ import java.util.List;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
@@ -25,9 +26,10 @@ import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
@@ -41,27 +43,29 @@ import org.jdom.Namespace;
* specification for both ingest and dissemination. * specification for both ingest and dissemination.
* *
* @author Larry Stone * @author Larry Stone
* @version $Revision$
*/ */
public class PREMISCrosswalk public class PREMISCrosswalk
implements IngestionCrosswalk, DisseminationCrosswalk { implements IngestionCrosswalk, DisseminationCrosswalk {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(PREMISCrosswalk.class); private static final Logger log = LogManager.getLogger(PREMISCrosswalk.class);
private static final Namespace PREMIS_NS = private static final Namespace PREMIS_NS =
Namespace.getNamespace("premis", "http://www.loc.gov/standards/premis"); Namespace.getNamespace("premis", "http://www.loc.gov/standards/premis");
// XML schemaLocation fragment for this crosswalk, from config. // XML schemaLocation fragment for this crosswalk, from config.
private String schemaLocation = private final String schemaLocation =
PREMIS_NS.getURI() + " http://www.loc.gov/standards/premis/PREMIS-v1-0.xsd"; PREMIS_NS.getURI() + " http://www.loc.gov/standards/premis/PREMIS-v1-0.xsd";
private static final Namespace namespaces[] = {PREMIS_NS}; private static final Namespace namespaces[] = {PREMIS_NS};
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); protected BitstreamService bitstreamService
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance() = ContentServiceFactory.getInstance().getBitstreamService();
.getBitstreamFormatService(); protected BitstreamFormatService bitstreamFormatService
= ContentServiceFactory.getInstance().getBitstreamFormatService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/*----------- Submission functions -------------------*/ /*----------- Submission functions -------------------*/
@@ -219,7 +223,7 @@ public class PREMISCrosswalk
// b. name of bitstream, if any // b. name of bitstream, if any
// c. made-up name based on sequence ID and extension. // c. made-up name based on sequence ID and extension.
String sid = String.valueOf(bitstream.getSequenceID()); String sid = String.valueOf(bitstream.getSequenceID());
String baseUrl = ConfigurationManager.getProperty("dspace.ui.url"); String baseUrl = configurationService.getProperty("dspace.ui.url");
String handle = null; String handle = null;
// get handle of parent Item of this bitstream, if there is one: // get handle of parent Item of this bitstream, if there is one:
List<Bundle> bn = bitstream.getBundles(); List<Bundle> bn = bitstream.getBundles();
@@ -308,7 +312,7 @@ public class PREMISCrosswalk
public List<Element> disseminateList(Context context, DSpaceObject dso) public List<Element> disseminateList(Context context, DSpaceObject dso)
throws CrosswalkException, throws CrosswalkException,
IOException, SQLException, AuthorizeException { IOException, SQLException, AuthorizeException {
List<Element> result = new ArrayList<Element>(1); List<Element> result = new ArrayList<>(1);
result.add(disseminateElement(context, dso)); result.add(disseminateElement(context, dso));
return result; return result;
} }

View File

@@ -20,6 +20,7 @@ import java.util.Map;
import java.util.Properties; import java.util.Properties;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
@@ -30,10 +31,11 @@ import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.SelfNamedPlugin; import org.dspace.core.SelfNamedPlugin;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
@@ -91,20 +93,19 @@ import org.jdom.input.SAXBuilder;
* http://dublincore.org/schemas/xmls/qdc/2003/04/02/qualifieddc.xsd</pre> * http://dublincore.org/schemas/xmls/qdc/2003/04/02/qualifieddc.xsd</pre>
* *
* @author Larry Stone * @author Larry Stone
* @version $Revision$
*/ */
public class QDCCrosswalk extends SelfNamedPlugin public class QDCCrosswalk extends SelfNamedPlugin
implements DisseminationCrosswalk, IngestionCrosswalk { implements DisseminationCrosswalk, IngestionCrosswalk {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(QDCCrosswalk.class); private static final Logger log = LogManager.getLogger(QDCCrosswalk.class);
// map of qdc to JDOM Element // map of qdc to JDOM Element
private Map<String, Element> qdc2element = new HashMap<String, Element>(); private final Map<String, Element> qdc2element = new HashMap<>();
// map of JDOM Element to qdc Metadatum // map of JDOM Element to qdc Metadatum
private Map<String, String> element2qdc = new HashMap<String, String>(); private final Map<String, String> element2qdc = new HashMap<>();
// the XML namespaces from config file for this name. // the XML namespaces from config file for this name.
private Namespace namespaces[] = null; private Namespace namespaces[] = null;
@@ -124,11 +125,14 @@ public class QDCCrosswalk extends SelfNamedPlugin
// XML schemaLocation fragment for this crosswalk, from config. // XML schemaLocation fragment for this crosswalk, from config.
private String schemaLocation = null; private String schemaLocation = null;
private static SAXBuilder builder = new SAXBuilder(); private static final SAXBuilder builder = new SAXBuilder();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
private CrosswalkMetadataValidator metadataValidator = new CrosswalkMetadataValidator(); protected static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
private final CrosswalkMetadataValidator metadataValidator = new CrosswalkMetadataValidator();
/** /**
* Fill in the plugin-name table from DSpace configuration entries * Fill in the plugin-name table from DSpace configuration entries
@@ -137,11 +141,10 @@ public class QDCCrosswalk extends SelfNamedPlugin
private static String aliases[] = null; private static String aliases[] = null;
static { static {
List<String> aliasList = new ArrayList<String>(); List<String> aliasList = new ArrayList<>();
Enumeration<String> pe = (Enumeration<String>) ConfigurationManager.propertyNames(); List<String> configKeys = configurationService.getPropertyKeys();
String propname = CONFIG_PREFIX + ".properties."; String propname = CONFIG_PREFIX + ".properties.";
while (pe.hasMoreElements()) { for (String key : configKeys) {
String key = pe.nextElement();
if (key.startsWith(propname)) { if (key.startsWith(propname)) {
aliasList.add(key.substring(propname.length())); aliasList.add(key.substring(propname.length()));
} }
@@ -218,32 +221,31 @@ public class QDCCrosswalk extends SelfNamedPlugin
} }
// grovel DSpace configuration for namespaces // grovel DSpace configuration for namespaces
List<Namespace> nsList = new ArrayList<Namespace>(); List<Namespace> nsList = new ArrayList<>();
Enumeration<String> pe = (Enumeration<String>) ConfigurationManager.propertyNames(); List<String> configKeys = configurationService.getPropertyKeys();
String propname = CONFIG_PREFIX + ".namespace." + myName + "."; String propname = CONFIG_PREFIX + ".namespace." + myName + ".";
while (pe.hasMoreElements()) { for (String key : configKeys) {
String key = pe.nextElement();
if (key.startsWith(propname)) { if (key.startsWith(propname)) {
nsList.add(Namespace.getNamespace(key.substring(propname.length()), nsList.add(Namespace.getNamespace(key.substring(propname.length()),
ConfigurationManager.getProperty(key))); configurationService.getProperty(key)));
} }
} }
nsList.add(Namespace.XML_NAMESPACE); nsList.add(Namespace.XML_NAMESPACE);
namespaces = (Namespace[]) nsList.toArray(new Namespace[nsList.size()]); namespaces = (Namespace[]) nsList.toArray(new Namespace[nsList.size()]);
// get XML schemaLocation fragment from config // get XML schemaLocation fragment from config
schemaLocation = ConfigurationManager.getProperty(CONFIG_PREFIX + ".schemaLocation." + myName); schemaLocation = configurationService.getProperty(CONFIG_PREFIX + ".schemaLocation." + myName);
// read properties // read properties
String cmPropName = CONFIG_PREFIX + ".properties." + myName; String cmPropName = CONFIG_PREFIX + ".properties." + myName;
String propsFilename = ConfigurationManager.getProperty(cmPropName); String propsFilename = configurationService.getProperty(cmPropName);
if (propsFilename == null) { if (propsFilename == null) {
throw new CrosswalkInternalException("Configuration error: " + throw new CrosswalkInternalException("Configuration error: " +
"No properties file configured for QDC crosswalk named \"" + "No properties file configured for QDC crosswalk named \"" +
myName + "\""); myName + "\"");
} }
String parent = ConfigurationManager.getProperty("dspace.dir") + String parent = configurationService.getProperty("dspace.dir") +
File.separator + "config" + File.separator; File.separator + "config" + File.separator;
File propsFile = new File(parent, propsFilename); File propsFile = new File(parent, propsFilename);
Properties qdcProps = new Properties(); Properties qdcProps = new Properties();
@@ -264,7 +266,7 @@ public class QDCCrosswalk extends SelfNamedPlugin
// grovel properties to initialize qdc->element and element->qdc maps. // grovel properties to initialize qdc->element and element->qdc maps.
// evaluate the XML fragment with a wrapper including namespaces. // evaluate the XML fragment with a wrapper including namespaces.
String postlog = "</wrapper>"; String postlog = "</wrapper>";
StringBuffer prologb = new StringBuffer("<wrapper"); StringBuilder prologb = new StringBuilder("<wrapper");
for (int i = 0; i < namespaces.length; ++i) { for (int i = 0; i < namespaces.length; ++i) {
prologb.append(" xmlns:"); prologb.append(" xmlns:");
prologb.append(namespaces[i].getPrefix()); prologb.append(namespaces[i].getPrefix());
@@ -274,9 +276,9 @@ public class QDCCrosswalk extends SelfNamedPlugin
} }
prologb.append(">"); prologb.append(">");
String prolog = prologb.toString(); String prolog = prologb.toString();
pe = (Enumeration<String>) qdcProps.propertyNames(); Enumeration<String> qdcKeys = (Enumeration<String>) qdcProps.propertyNames();
while (pe.hasMoreElements()) { while (qdcKeys.hasMoreElements()) {
String qdc = pe.nextElement(); String qdc = qdcKeys.nextElement();
String val = qdcProps.getProperty(qdc); String val = qdcProps.getProperty(qdc);
try { try {
Document d = builder.build(new StringReader(prolog + val + postlog)); Document d = builder.build(new StringReader(prolog + val + postlog));
@@ -296,7 +298,7 @@ public class QDCCrosswalk extends SelfNamedPlugin
public Namespace[] getNamespaces() { public Namespace[] getNamespaces() {
try { try {
init(); init();
} catch (Exception e) { } catch (IOException | CrosswalkException e) {
// ignore // ignore
} }
return (Namespace[]) ArrayUtils.clone(namespaces); return (Namespace[]) ArrayUtils.clone(namespaces);
@@ -306,7 +308,7 @@ public class QDCCrosswalk extends SelfNamedPlugin
public String getSchemaLocation() { public String getSchemaLocation() {
try { try {
init(); init();
} catch (Exception e) { } catch (IOException | CrosswalkException e) {
// ignore // ignore
} }
return schemaLocation; return schemaLocation;
@@ -338,7 +340,7 @@ public class QDCCrosswalk extends SelfNamedPlugin
init(); init();
List<MetadataValue> dc = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); List<MetadataValue> dc = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
List<Element> result = new ArrayList<Element>(dc.size()); List<Element> result = new ArrayList<>(dc.size());
for (int i = 0; i < dc.size(); i++) { for (int i = 0; i < dc.size(); i++) {
MetadataValue metadataValue = dc.get(i); MetadataValue metadataValue = dc.get(i);
MetadataField metadataField = metadataValue.getMetadataField(); MetadataField metadataField = metadataValue.getMetadataField();

View File

@@ -20,10 +20,11 @@ import org.dspace.content.packager.PackageException;
import org.dspace.content.packager.PackageIngester; import org.dspace.content.packager.PackageIngester;
import org.dspace.content.packager.PackageParameters; import org.dspace.content.packager.PackageParameters;
import org.dspace.content.packager.RoleDisseminator; import org.dspace.content.packager.RoleDisseminator;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.factory.CoreServiceFactory; import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.workflow.WorkflowException; import org.dspace.workflow.WorkflowException;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
@@ -179,8 +180,11 @@ public class RoleCrosswalk
} }
// Create a temporary file to disseminate into // Create a temporary file to disseminate into
String tempDirectory = (ConfigurationManager.getProperty("upload.temp.dir") != null) ConfigurationService configurationService
? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir"); = DSpaceServicesFactory.getInstance().getConfigurationService();
String tempDirectory = (configurationService.hasProperty("upload.temp.dir"))
? configurationService.getProperty("upload.temp.dir")
: System.getProperty("java.io.tmpdir");
File tempFile = File File tempFile = File
.createTempFile("RoleCrosswalkDisseminate" + dso.hashCode(), null, new File(tempDirectory)); .createTempFile("RoleCrosswalkDisseminate" + dso.hashCode(), null, new File(tempDirectory));
tempFile.deleteOnExit(); tempFile.deleteOnExit();
@@ -292,8 +296,11 @@ public class RoleCrosswalk
} }
// Create a temporary file to ingest from // Create a temporary file to ingest from
String tempDirectory = (ConfigurationManager.getProperty("upload.temp.dir") != null) ConfigurationService configurationService
? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir"); = DSpaceServicesFactory.getInstance().getConfigurationService();
String tempDirectory = (configurationService.hasProperty("upload.temp.dir"))
? configurationService.getProperty("upload.temp.dir")
: System.getProperty("java.io.tmpdir");
File tempFile = File.createTempFile("RoleCrosswalkIngest" + dso.hashCode(), null, new File(tempDirectory)); File tempFile = File.createTempFile("RoleCrosswalkIngest" + dso.hashCode(), null, new File(tempDirectory));
tempFile.deleteOnExit(); tempFile.deleteOnExit();
FileOutputStream fileOutStream = null; FileOutputStream fileOutStream = null;

View File

@@ -29,10 +29,11 @@ import org.dspace.content.MetadataSchema;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.SelfNamedPlugin; import org.dspace.core.SelfNamedPlugin;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
import org.jdom.Verifier; import org.jdom.Verifier;
@@ -59,29 +60,32 @@ import org.jdom.Verifier;
* collections. * collections.
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$
*/ */
public class XHTMLHeadDisseminationCrosswalk extends SelfNamedPlugin implements public class XHTMLHeadDisseminationCrosswalk
DisseminationCrosswalk { extends SelfNamedPlugin
implements DisseminationCrosswalk {
/** /**
* log4j logger * log4j logger
*/ */
private static Logger log = LogManager.getLogger(XHTMLHeadDisseminationCrosswalk.class); private static final Logger log = LogManager.getLogger(XHTMLHeadDisseminationCrosswalk.class);
private static final String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
protected final ItemService itemService
= ContentServiceFactory.getInstance().getItemService();
protected final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Location of config file * Location of configuration file
*/ */
private final String config = ConfigurationManager private final String config = configurationService.getProperty("dspace.dir")
.getProperty("dspace.dir")
+ File.separator + File.separator
+ "config" + "config"
+ File.separator + File.separator
+ "crosswalks" + "crosswalks"
+ File.separator + "xhtml-head-item.properties"; + File.separator + "xhtml-head-item.properties";
private static final String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
/** /**
* Maps DSpace metadata field to name to use in XHTML head element, e.g. * Maps DSpace metadata field to name to use in XHTML head element, e.g.
* dc.creator or dc.description.abstract * dc.creator or dc.description.abstract
@@ -99,9 +103,9 @@ public class XHTMLHeadDisseminationCrosswalk extends SelfNamedPlugin implements
private Map<String, String> schemaURLs; private Map<String, String> schemaURLs;
public XHTMLHeadDisseminationCrosswalk() throws IOException { public XHTMLHeadDisseminationCrosswalk() throws IOException {
names = new HashMap<String, String>(); names = new HashMap<>();
schemes = new HashMap<String, String>(); schemes = new HashMap<>();
schemaURLs = new HashMap<String, String>(); schemaURLs = new HashMap<>();
// Read in configuration // Read in configuration
Properties crosswalkProps = new Properties(); Properties crosswalkProps = new Properties();
@@ -189,7 +193,7 @@ public class XHTMLHeadDisseminationCrosswalk extends SelfNamedPlugin implements
Item item = (Item) dso; Item item = (Item) dso;
String handle = item.getHandle(); String handle = item.getHandle();
List<Element> metas = new ArrayList<Element>(); List<Element> metas = new ArrayList<>();
List<MetadataValue> values = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); List<MetadataValue> values = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
// Add in schema URLs e.g. <link rel="schema.DC" href="...." /> // Add in schema URLs e.g. <link rel="schema.DC" href="...." />

View File

@@ -11,7 +11,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List; import java.util.List;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
@@ -19,8 +18,9 @@ import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.SelfNamedPlugin; import org.dspace.core.SelfNamedPlugin;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Namespace; import org.jdom.Namespace;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -83,7 +83,6 @@ import org.slf4j.LoggerFactory;
* does this automatically. * does this automatically.
* *
* @author Larry Stone * @author Larry Stone
* @version $Revision$
*/ */
public abstract class XSLTCrosswalk extends SelfNamedPlugin { public abstract class XSLTCrosswalk extends SelfNamedPlugin {
/** /**
@@ -98,7 +97,7 @@ public abstract class XSLTCrosswalk extends SelfNamedPlugin {
Namespace.getNamespace("dim", "http://www.dspace.org/xmlns/dspace/dim"); Namespace.getNamespace("dim", "http://www.dspace.org/xmlns/dspace/dim");
/** /**
* Prefix for all lines in the config file for XSLT plugins. * Prefix for all lines in the configuration file for XSLT plugins.
*/ */
protected static final String CONFIG_PREFIX = "crosswalk."; protected static final String CONFIG_PREFIX = "crosswalk.";
@@ -117,11 +116,12 @@ public abstract class XSLTCrosswalk extends SelfNamedPlugin {
String suffix = CONFIG_STYLESHEET; String suffix = CONFIG_STYLESHEET;
List<String> aliasList = new ArrayList<>(); List<String> aliasList = new ArrayList<>();
Enumeration<String> pe = (Enumeration<String>) ConfigurationManager.propertyNames(); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
List<String> configKeys = configurationService.getPropertyKeys();
LOG.debug("XSLTCrosswalk: Looking for config prefix = {}", prefix); LOG.debug("XSLTCrosswalk: Looking for config prefix = {}", prefix);
while (pe.hasMoreElements()) { for (String key : configKeys) {
String key = pe.nextElement();
if (key.startsWith(prefix) && key.endsWith(suffix)) { if (key.startsWith(prefix) && key.endsWith(suffix)) {
LOG.debug("Getting XSLT plugin name from config line: {}", key); LOG.debug("Getting XSLT plugin name from config line: {}", key);
aliasList.add(key.substring(prefix.length(), key.length() - suffix.length())); aliasList.add(key.substring(prefix.length(), key.length() - suffix.length()));
@@ -155,13 +155,15 @@ public abstract class XSLTCrosswalk extends SelfNamedPlugin {
return null; return null;
} }
String cmPropName = CONFIG_PREFIX + direction + "." + myAlias + CONFIG_STYLESHEET; String cmPropName = CONFIG_PREFIX + direction + "." + myAlias + CONFIG_STYLESHEET;
String fname = ConfigurationManager.getProperty(cmPropName); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String fname = configurationService.getProperty(cmPropName);
if (fname == null) { if (fname == null) {
LOG.error("Missing configuration filename for XSLT-based crosswalk: no " + LOG.error("Missing configuration filename for XSLT-based crosswalk: no " +
"value for property = {}", cmPropName); "value for property = {}", cmPropName);
return null; return null;
} else { } else {
String parent = ConfigurationManager.getProperty("dspace.dir") + String parent = configurationService.getProperty("dspace.dir") +
File.separator + "config" + File.separator; File.separator + "config" + File.separator;
transformFile = new File(parent, fname); transformFile = new File(parent, fname);
} }

View File

@@ -15,7 +15,6 @@ import java.io.OutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -36,11 +35,12 @@ import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.factory.CoreServiceFactory; import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
@@ -95,11 +95,14 @@ public class XSLTDisseminationCrosswalk
private static final String DIRECTION = "dissemination"; private static final String DIRECTION = "dissemination";
protected static final CommunityService communityService = ContentServiceFactory.getInstance() protected static final CommunityService communityService
.getCommunityService(); = ContentServiceFactory.getInstance().getCommunityService();
protected static final CollectionService collectionService = ContentServiceFactory.getInstance() protected static final CollectionService collectionService
.getCollectionService(); = ContentServiceFactory.getInstance().getCollectionService();
protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected static final ItemService itemService
= ContentServiceFactory.getInstance().getItemService();
protected static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
private static final String aliases[] = makeAliases(DIRECTION); private static final String aliases[] = makeAliases(DIRECTION);
@@ -133,7 +136,7 @@ public class XSLTDisseminationCrosswalk
// get the schema location string, should already be in the // get the schema location string, should already be in the
// right format for value of "schemaLocation" attribute. // right format for value of "schemaLocation" attribute.
schemaLocation = ConfigurationManager.getProperty(prefix + "schemaLocation"); schemaLocation = configurationService.getProperty(prefix + "schemaLocation");
if (schemaLocation == null) { if (schemaLocation == null) {
LOG.warn("No schemaLocation for crosswalk=" + myAlias + ", key=" + prefix + "schemaLocation"); LOG.warn("No schemaLocation for crosswalk=" + myAlias + ", key=" + prefix + "schemaLocation");
} else if (schemaLocation.length() > 0 && schemaLocation.indexOf(' ') < 0) { } else if (schemaLocation.length() > 0 && schemaLocation.indexOf(' ') < 0) {
@@ -146,18 +149,17 @@ public class XSLTDisseminationCrosswalk
// grovel for namespaces of the form: // grovel for namespaces of the form:
// crosswalk.diss.{PLUGIN_NAME}.namespace.{PREFIX} = {URI} // crosswalk.diss.{PLUGIN_NAME}.namespace.{PREFIX} = {URI}
String nsPrefix = prefix + "namespace."; String nsPrefix = prefix + "namespace.";
Enumeration<String> pe = (Enumeration<String>) ConfigurationManager.propertyNames(); List<String> configKeys = configurationService.getPropertyKeys();
List<Namespace> nsList = new ArrayList<>(); List<Namespace> nsList = new ArrayList<>();
while (pe.hasMoreElements()) { for (String key : configKeys) {
String key = pe.nextElement();
if (key.startsWith(nsPrefix)) { if (key.startsWith(nsPrefix)) {
nsList.add(Namespace.getNamespace(key.substring(nsPrefix.length()), nsList.add(Namespace.getNamespace(key.substring(nsPrefix.length()),
ConfigurationManager.getProperty(key))); configurationService.getProperty(key)));
} }
} }
namespaces = nsList.toArray(new Namespace[nsList.size()]); namespaces = nsList.toArray(new Namespace[nsList.size()]);
preferList = ConfigurationManager.getBooleanProperty(prefix + "preferList", false); preferList = configurationService.getBooleanProperty(prefix + "preferList", false);
} }
/** /**
@@ -463,7 +465,7 @@ public class XSLTDisseminationCrosswalk
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("Filtering out non-XML characters in string, reason=" + reason); LOG.debug("Filtering out non-XML characters in string, reason=" + reason);
} }
StringBuffer result = new StringBuffer(value.length()); StringBuilder result = new StringBuilder(value.length());
for (int i = 0; i < value.length(); ++i) { for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i); char c = value.charAt(i);
if (Verifier.isXMLCharacter((int) c)) { if (Verifier.isXMLCharacter((int) c)) {
@@ -558,7 +560,7 @@ public class XSLTDisseminationCrosswalk
try { try {
XMLOutputter xmlout = new XMLOutputter(Format.getPrettyFormat()); XMLOutputter xmlout = new XMLOutputter(Format.getPrettyFormat());
xmlout.output(new Document(root), out); xmlout.output(new Document(root), out);
} catch (Exception e) { } catch (IOException e) {
// as this script is for testing dissemination crosswalks, we want // as this script is for testing dissemination crosswalks, we want
// verbose information in case of an exception. // verbose information in case of an exception.
System.err.println("An error occurred after processing the dissemination crosswalk."); System.err.println("An error occurred after processing the dissemination crosswalk.");

View File

@@ -41,12 +41,13 @@ import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.workflow.WorkflowException; import org.dspace.workflow.WorkflowException;
import org.dspace.workflow.factory.WorkflowServiceFactory; import org.dspace.workflow.factory.WorkflowServiceFactory;
import org.jdom.Element; import org.jdom.Element;
@@ -100,7 +101,6 @@ import org.jdom.Element;
* *
* @author Larry Stone * @author Larry Stone
* @author Tim Donohue * @author Tim Donohue
* @version $Revision$
* @see org.dspace.content.packager.METSManifest * @see org.dspace.content.packager.METSManifest
* @see AbstractPackageIngester * @see AbstractPackageIngester
* @see PackageIngester * @see PackageIngester
@@ -109,7 +109,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(AbstractMETSIngester.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(AbstractMETSIngester.class);
protected final BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); protected final BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance() protected final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance()
@@ -121,6 +121,8 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester {
protected final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); protected final HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected final WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance() protected final WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance()
.getWorkspaceItemService(); .getWorkspaceItemService();
protected final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* <p> * <p>
@@ -135,7 +137,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester {
protected static final class MdrefManager implements METSManifest.Mdref { protected static final class MdrefManager implements METSManifest.Mdref {
private File packageFile = null; private File packageFile = null;
private PackageParameters params; private final PackageParameters params;
// constructor initializes from package file // constructor initializes from package file
private MdrefManager(File packageFile, PackageParameters params) { private MdrefManager(File packageFile, PackageParameters params) {
@@ -1133,22 +1135,22 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester {
// whether or not to save manifest as a bitstream in METADATA bundle. // whether or not to save manifest as a bitstream in METADATA bundle.
protected boolean preserveManifest() { protected boolean preserveManifest() {
return ConfigurationManager.getBooleanProperty("mets." return configurationService.getBooleanProperty(
+ getConfigurationName() + ".ingest.preserveManifest", "mets." + getConfigurationName() + ".ingest.preserveManifest",
false); false);
} }
// return short name of manifest bitstream format // return short name of manifest bitstream format
protected String getManifestBitstreamFormat() { protected String getManifestBitstreamFormat() {
return ConfigurationManager.getProperty("mets." return configurationService.getProperty(
+ getConfigurationName() + ".ingest.manifestBitstreamFormat"); "mets." + getConfigurationName() + ".ingest.manifestBitstreamFormat");
} }
// whether or not to use Collection Templates when creating a new item // whether or not to use Collection Templates when creating a new item
protected boolean useCollectionTemplate() { protected boolean useCollectionTemplate() {
return ConfigurationManager.getBooleanProperty("mets." return configurationService.getBooleanProperty(
+ getConfigurationName() + ".ingest.useCollectionTemplate", "mets." + getConfigurationName() + ".ingest.useCollectionTemplate",
false); false);
} }
/** /**

View File

@@ -25,7 +25,6 @@ import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bundle; import org.dspace.content.Bundle;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
@@ -45,7 +44,6 @@ import org.dspace.core.Context;
* plugin, and a way to create packages acceptable to the METS SIP importer. * plugin, and a way to create packages acceptable to the METS SIP importer.
* *
* @author Larry Stone * @author Larry Stone
* @version $Revision$
*/ */
public class DSpaceMETSDisseminator public class DSpaceMETSDisseminator
extends AbstractMETSDisseminator { extends AbstractMETSDisseminator {
@@ -115,8 +113,7 @@ public class DSpaceMETSDisseminator
agent.setTYPE(Type.ORGANIZATION); agent.setTYPE(Type.ORGANIZATION);
Name name = new Name(); Name name = new Name();
name.getContent() name.getContent()
.add(new PCData(ConfigurationManager .add(new PCData(configurationService.getProperty("dspace.name")));
.getProperty("dspace.name")));
agent.getContent().add(name); agent.getContent().add(name);
metsHdr.getContent().add(agent); metsHdr.getContent().add(agent);
return metsHdr; return metsHdr;
@@ -198,7 +195,7 @@ public class DSpaceMETSDisseminator
@Override @Override
public String[] getRightsMdTypes(Context context, DSpaceObject dso, PackageParameters params) public String[] getRightsMdTypes(Context context, DSpaceObject dso, PackageParameters params)
throws SQLException, IOException, AuthorizeException { throws SQLException, IOException, AuthorizeException {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<>();
if (dso.getType() == Constants.ITEM) { if (dso.getType() == Constants.ITEM) {
Item item = (Item) dso; Item item = (Item) dso;

View File

@@ -13,11 +13,11 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
@@ -29,10 +29,11 @@ import org.dspace.content.crosswalk.CrosswalkObjectNotSupported;
import org.dspace.content.crosswalk.IngestionCrosswalk; import org.dspace.content.crosswalk.IngestionCrosswalk;
import org.dspace.content.crosswalk.MetadataValidationException; import org.dspace.content.crosswalk.MetadataValidationException;
import org.dspace.content.crosswalk.StreamIngestionCrosswalk; import org.dspace.content.crosswalk.StreamIngestionCrosswalk;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.factory.CoreServiceFactory; import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Content; import org.jdom.Content;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
@@ -117,8 +118,10 @@ public class METSManifest {
/** /**
* log4j category * log4j category
*/ */
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(METSManifest.class); private static final Logger log = LogManager.getLogger(METSManifest.class);
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Canonical filename of METS manifest within a package or as a bitstream. * Canonical filename of METS manifest within a package or as a bitstream.
*/ */
@@ -131,7 +134,7 @@ public class METSManifest {
public static final String CONFIG_METS_PREFIX = "mets."; public static final String CONFIG_METS_PREFIX = "mets.";
/** /**
* prefix of config lines identifying local XML Schema (XSD) files * prefix of configuration lines identifying local XML Schema (XSD) files
*/ */
protected static final String CONFIG_XSD_PREFIX = CONFIG_METS_PREFIX + "xsd."; protected static final String CONFIG_XSD_PREFIX = CONFIG_METS_PREFIX + "xsd.";
@@ -190,21 +193,20 @@ public class METSManifest {
protected static String localSchemas; protected static String localSchemas;
static { static {
String dspace_dir = ConfigurationManager.getProperty("dspace.dir"); String dspace_dir = configurationService.getProperty("dspace.dir");
File xsdPath1 = new File(dspace_dir + "/config/schemas/"); File xsdPath1 = new File(dspace_dir + "/config/schemas/");
File xsdPath2 = new File(dspace_dir + "/config/"); File xsdPath2 = new File(dspace_dir + "/config/");
Enumeration<String> pe = (Enumeration<String>) ConfigurationManager.propertyNames(); List<String> configKeys = configurationService.getPropertyKeys();
StringBuffer result = new StringBuffer(); StringBuilder result = new StringBuilder();
while (pe.hasMoreElements()) { for (String key : configKeys) {
// config lines have the format: // config lines have the format:
// mets.xsd.{identifier} = {namespace} {xsd-URL} // mets.xsd.{identifier} = {namespace} {xsd-URL}
// e.g. // e.g.
// mets.xsd.dc = http://purl.org/dc/elements/1.1/ dc.xsd // mets.xsd.dc = http://purl.org/dc/elements/1.1/ dc.xsd
// (filename is relative to {dspace_dir}/config/schemas/) // (filename is relative to {dspace_dir}/config/schemas/)
String key = pe.nextElement();
if (key.startsWith(CONFIG_XSD_PREFIX)) { if (key.startsWith(CONFIG_XSD_PREFIX)) {
String spec = ConfigurationManager.getProperty(key); String spec = configurationService.getProperty(key);
String val[] = spec.trim().split("\\s+"); String val[] = spec.trim().split("\\s+");
if (val.length == 2) { if (val.length == 2) {
File xsd = new File(xsdPath1, val[1]); File xsd = new File(xsdPath1, val[1]);
@@ -240,7 +242,7 @@ public class METSManifest {
* *
* @param builder XML parser (for parsing mdRef'd files and binData) * @param builder XML parser (for parsing mdRef'd files and binData)
* @param mets parsed METS document * @param mets parsed METS document
* @param configName config name * @param configName configuration name
*/ */
protected METSManifest(SAXBuilder builder, Element mets, String configName) { protected METSManifest(SAXBuilder builder, Element mets, String configName) {
super(); super();
@@ -337,7 +339,7 @@ public class METSManifest {
return bundleFiles; return bundleFiles;
} }
bundleFiles = new ArrayList<Element>(); bundleFiles = new ArrayList<>();
Element fileSec = mets.getChild("fileSec", metsNS); Element fileSec = mets.getChild("fileSec", metsNS);
if (fileSec != null) { if (fileSec != null) {
@@ -356,7 +358,7 @@ public class METSManifest {
return contentFiles; return contentFiles;
} }
contentFiles = new ArrayList<Element>(); contentFiles = new ArrayList<>();
Element fileSec = mets.getChild("fileSec", metsNS); Element fileSec = mets.getChild("fileSec", metsNS);
if (fileSec != null) { if (fileSec != null) {
@@ -637,7 +639,7 @@ public class METSManifest {
// XML parser stupidly includes newlines in prettyprinting // XML parser stupidly includes newlines in prettyprinting
// as text content objects.. // as text content objects..
String id = mdSec.getAttributeValue("ID"); String id = mdSec.getAttributeValue("ID");
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
for (Iterator mi = mdc.iterator(); mi.hasNext(); ) { for (Iterator mi = mdc.iterator(); mi.hasNext(); ) {
sb.append(", ").append(((Content) mi.next()).toString()); sb.append(", ").append(((Content) mi.next()).toString());
} }
@@ -661,12 +663,12 @@ public class METSManifest {
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) { if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
byte value[] = Base64.decodeBase64(bin.getText().getBytes()); byte value[] = Base64.decodeBase64(bin.getText().getBytes());
Document mdd = parser.build(new ByteArrayInputStream(value)); Document mdd = parser.build(new ByteArrayInputStream(value));
List<Element> result = new ArrayList<Element>(1); List<Element> result = new ArrayList<>(1);
result.add(mdd.getRootElement()); result.add(mdd.getRootElement());
return result; return result;
} else { } else {
log.warn("Ignoring binData section because MIMETYPE is not XML, but: " + mimeType); log.warn("Ignoring binData section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0); return new ArrayList<>(0);
} }
} }
} else { } else {
@@ -680,12 +682,12 @@ public class METSManifest {
// This next line triggers a false-positive XXE warning from LGTM, even though we disallow DTD // This next line triggers a false-positive XXE warning from LGTM, even though we disallow DTD
// parsing during initialization of parser in create() // parsing during initialization of parser in create()
Document mdd = parser.build(callback.getInputStream(mdRef)); // lgtm [java/xxe] Document mdd = parser.build(callback.getInputStream(mdRef)); // lgtm [java/xxe]
List<Element> result = new ArrayList<Element>(1); List<Element> result = new ArrayList<>(1);
result.add(mdd.getRootElement()); result.add(mdd.getRootElement());
return result; return result;
} else { } else {
log.warn("Ignoring mdRef section because MIMETYPE is not XML, but: " + mimeType); log.warn("Ignoring mdRef section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0); return new ArrayList<>(0);
} }
} else { } else {
@@ -805,7 +807,7 @@ public class METSManifest {
//get our child object <div>s //get our child object <div>s
List childObjDivs = getChildObjDivs(); List childObjDivs = getChildObjDivs();
List<String> childPathList = new ArrayList<String>(); List<String> childPathList = new ArrayList<>();
if (childObjDivs != null && !childObjDivs.isEmpty()) { if (childObjDivs != null && !childObjDivs.isEmpty()) {
Iterator childIterator = childObjDivs.iterator(); Iterator childIterator = childObjDivs.iterator();
@@ -917,10 +919,10 @@ public class METSManifest {
* then try * then try
* mets.default.ingest.crosswalk.MDNAME = XWALKNAME * mets.default.ingest.crosswalk.MDNAME = XWALKNAME
*/ */
String xwalkName = ConfigurationManager.getProperty( String xwalkName = configurationService.getProperty(
CONFIG_METS_PREFIX + configName + ".ingest.crosswalk." + type); CONFIG_METS_PREFIX + configName + ".ingest.crosswalk." + type);
if (xwalkName == null) { if (xwalkName == null) {
xwalkName = ConfigurationManager.getProperty( xwalkName = configurationService.getProperty(
CONFIG_METS_PREFIX + "default.ingest.crosswalk." + type); CONFIG_METS_PREFIX + "default.ingest.crosswalk." + type);
if (xwalkName == null) { if (xwalkName == null) {
xwalkName = type; xwalkName = type;
@@ -993,7 +995,7 @@ public class METSManifest {
return new Element[0]; return new Element[0];
} }
String amdID[] = amds.split("\\s+"); String amdID[] = amds.split("\\s+");
List<Element> resultList = new ArrayList<Element>(); List<Element> resultList = new ArrayList<>();
for (int i = 0; i < amdID.length; ++i) { for (int i = 0; i < amdID.length; ++i) {
List rmds = getElementByXPath("mets:amdSec[@ID=\"" + amdID[i] + "\"]", false). List rmds = getElementByXPath("mets:amdSec[@ID=\"" + amdID[i] + "\"]", false).
getChildren("rightsMD", getChildren("rightsMD",

View File

@@ -1,340 +0,0 @@
/**
* 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.util.Enumeration;
import java.util.Properties;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.ConfigurationConverter;
import org.apache.logging.log4j.Logger;
import org.dspace.services.factory.DSpaceServicesFactory;
/**
* Class for reading the DSpace system configuration. The main configuration is
* read in as properties from a standard properties file.
* <P>
* To specify a different configuration, the system property
* <code>dspace.dir</code> should be set to the DSpace installation directory.
* <P>
* Other configuration files are read from the <code>config</code> directory
* of the DSpace installation directory.
*
* @author Robert Tansley
* @author Larry Stone - Interpolated values.
* @author Mark Diggory - General Improvements to detection, logging and loading.
* @author Tim Donohue - Refactored to wrap ConfigurationService
* @version $Revision$
* @deprecated Please use org.dspace.services.ConfigurationService. See examples below.
*/
public class ConfigurationManager {
/**
* log4j category
*/
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ConfigurationManager.class);
protected ConfigurationManager() {
}
/**
* Identify if DSpace is properly configured
*
* @return boolean true if configured, false otherwise
*/
public static boolean isConfigured() {
return DSpaceServicesFactory.getInstance().getConfigurationService() != null;
}
/**
* Returns all properties in main configuration
*
* @return properties - all non-modular properties
*/
public static Properties getProperties() {
return DSpaceServicesFactory.getInstance().getConfigurationService().getProperties();
}
/**
* Returns all properties for a given module
*
* @param module the name of the module
* @return properties - all module's properties
*/
public static Properties getProperties(String module) {
// Find subset of Configurations which have been prefixed with the module name
Configuration subset = DSpaceServicesFactory.getInstance().getConfigurationService().getConfiguration()
.subset(module);
// Convert to a Properties object and return it
return ConfigurationConverter.getProperties(subset);
}
/**
* 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.
*/
public static String getProperty(String property) {
return DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(property);
}
/**
* Get a module configuration property value.
*
* @param module the name of the module, or <code>null</code> for regular configuration
* property
* @param property the name (key) of the property
* @return the value of the property, or <code>null</code> if the
* property does not exist
*/
public static String getProperty(String module, String property) {
if (module == null) {
return getProperty(property);
}
// Assume "module" properties are always prefixed with the module name
return getProperty(module + "." + property);
}
/**
* 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>.
*/
public static int getIntProperty(String property) {
return DSpaceServicesFactory.getInstance().getConfigurationService().getIntProperty(property);
}
/**
* 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>.
*/
public static int getIntProperty(String module, String property) {
if (module == null) {
return getIntProperty(property);
}
// Assume "module" properties are always prefixed with the module name
return getIntProperty(module + "." + property);
}
/**
* 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.
* @return the value of the property. <code>default</code> is returned if
* the property does not exist or is not an Integer. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static int getIntProperty(String property, int defaultValue) {
return DSpaceServicesFactory.getInstance().getConfigurationService().getIntProperty(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.
* @return the value of the property. <code>default</code> is returned if
* the property does not exist or is not an Integer. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static int getIntProperty(String module, String property, int defaultValue) {
if (module == null) {
return getIntProperty(property, defaultValue);
}
// Assume "module" properties are always prefixed with the module name
return getIntProperty(module + "." + property, defaultValue);
}
/**
* Get a configuration property as a long
*
* @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>.
*/
public static long getLongProperty(String property) {
return DSpaceServicesFactory.getInstance().getConfigurationService().getLongProperty(property);
}
/**
* Get a module configuration property as a long
*
* @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>.
*/
public static long getLongProperty(String module, String property) {
if (module == null) {
return getLongProperty(property);
}
// Assume "module" properties are always prefixed with the module name
return getLongProperty(module + "." + property);
}
/**
* Get a configuration property as an long, with default
*
* @param property the name of the property
* @param defaultValue value to return if property is not found or is not a Long.
* @return the value of the property. <code>default</code> is returned if
* the property does not exist or is not an Integer. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static long getLongProperty(String property, int defaultValue) {
return DSpaceServicesFactory.getInstance().getConfigurationService().getLongProperty(property, defaultValue);
}
/**
* Get a configuration property as an long, with default
*
* @param module the module, or <code>null</code> for regular property
* @param property the name of the property
* @param defaultValue value to return if property is not found or is not a Long.
* @return the value of the property. <code>default</code> is returned if
* the property does not exist or is not an Integer. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static long getLongProperty(String module, String property, int defaultValue) {
if (module == null) {
return getLongProperty(property, defaultValue);
}
// Assume "module" properties are always prefixed with the module name
return getLongProperty(module + "." + property, defaultValue);
}
/**
* 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
* <code>getProperty</code>.
*/
public static boolean getBooleanProperty(String property) {
return DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty(property);
}
/**
* 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 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
* <code>getProperty</code>.
*/
public static boolean getBooleanProperty(String module, String property) {
if (module == null) {
return getBooleanProperty(property);
}
// Assume "module" properties are always prefixed with the module name
return getBooleanProperty(module + "." + property);
}
/**
* Get a configuration property as a boolean, with default.
* 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
* @param defaultValue value to return if property is not found.
* @return the value of the property. <code>default</code> is returned if
* the property does not exist. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static boolean getBooleanProperty(String property, boolean defaultValue) {
return DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty(property, defaultValue);
}
/**
* Get a module configuration property as a boolean, with default.
* 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 property the name of the property
* @param defaultValue value to return if property is not found.
* @return the value of the property. <code>default</code> is returned if
* the property does not exist. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static boolean getBooleanProperty(String module, String property, boolean defaultValue) {
if (module == null) {
return getBooleanProperty(property, defaultValue);
}
// Assume "module" properties are always prefixed with the module name
return getBooleanProperty(module + "." + property, defaultValue);
}
/**
* Returns an enumeration of all the keys in the DSpace configuration
* <P>
* As ConfigurationManager is now deprecated, older code using this method
* should consider using ConfigurationService.getPropertyKeys() directly.
*
* @return an enumeration of all the keys in the DSpace configuration
*/
public static Enumeration<?> propertyNames() {
// Get a list of all property keys, and convert into an Enumeration
return java.util.Collections
.enumeration(DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyKeys());
}
/**
* Returns an enumeration of all the keys in a module configuration
* <P>
* As ConfigurationManager is now deprecated, older code using this method
* should consider using ConfigurationService.getPropertyKeys(String prefix) directly.
*
* @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.
*/
public static Enumeration<?> propertyNames(String module) {
// Get property keys beginning with this prefix, and convert into an Enumeration
return java.util.Collections
.enumeration(DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyKeys(module));
}
}

View File

@@ -16,8 +16,10 @@ import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* MicrosoftTranslator translates metadata fields using Microsoft Translation API v2 * MicrosoftTranslator translates metadata fields using Microsoft Translation API v2
@@ -36,12 +38,14 @@ public class MicrosoftTranslator extends AbstractTranslator {
protected final String baseUrl = "http://api.microsofttranslator.com/V2/Http.svc/Translate"; protected final String baseUrl = "http://api.microsofttranslator.com/V2/Http.svc/Translate";
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(MicrosoftTranslator.class); private static final Logger log = LogManager.getLogger(MicrosoftTranslator.class);
@Override @Override
protected void initApi() { protected void initApi() {
apiKey = ConfigurationManager.getProperty(PLUGIN_PREFIX, "api.key.microsoft"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
apiKey = configurationService.getProperty(PLUGIN_PREFIX, "api.key.microsoft");
} }
@Override @Override

View File

@@ -28,6 +28,7 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.UUID; import java.util.UUID;
import javax.mail.MessagingException;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MapUtils;
@@ -55,7 +56,6 @@ import org.dspace.content.Community;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
@@ -73,6 +73,7 @@ import org.dspace.discovery.indexobject.factory.IndexObjectFactoryFactory;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.GroupService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -110,6 +111,8 @@ public class SolrServiceImpl implements SearchService, IndexingService {
protected IndexObjectFactoryFactory indexObjectServiceFactory; protected IndexObjectFactoryFactory indexObjectServiceFactory;
@Autowired @Autowired
protected SolrSearchCore solrSearchCore; protected SolrSearchCore solrSearchCore;
@Autowired
protected ConfigurationService configurationService;
protected SolrServiceImpl() { protected SolrServiceImpl() {
@@ -140,7 +143,6 @@ public class SolrServiceImpl implements SearchService, IndexingService {
* @param context Users Context * @param context Users Context
* @param indexableObject The object we want to index * @param indexableObject The object we want to index
* @param force Force update even if not stale. * @param force Force update even if not stale.
* @throws SQLException if error
*/ */
@Override @Override
public void indexContent(Context context, IndexableObject indexableObject, public void indexContent(Context context, IndexableObject indexableObject,
@@ -153,7 +155,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
update(context, indexableObjectFactory, indexableObject); update(context, indexableObjectFactory, indexableObject);
log.info(LogManager.getHeader(context, "indexed_object", indexableObject.getUniqueIndexID())); log.info(LogManager.getHeader(context, "indexed_object", indexableObject.getUniqueIndexID()));
} }
} catch (Exception e) { } catch (IOException | SQLException | SolrServerException | SearchServiceException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }
@@ -200,7 +202,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
if (commit) { if (commit) {
solrSearchCore.getSolr().commit(); solrSearchCore.getSolr().commit();
} }
} catch (Exception exception) { } catch (IOException | SolrServerException exception) {
log.error(exception.getMessage(), exception); log.error(exception.getMessage(), exception);
emailException(exception); emailException(exception);
} }
@@ -223,6 +225,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
* *
* @param context the dspace context * @param context the dspace context
* @param searchUniqueID the search uniqueID of the document to be deleted * @param searchUniqueID the search uniqueID of the document to be deleted
* @param commit commit the update immediately.
* @throws IOException if IO error * @throws IOException if IO error
*/ */
@Override @Override
@@ -246,13 +249,15 @@ public class SolrServiceImpl implements SearchService, IndexingService {
* *
* @param context context object * @param context context object
* @param dso object to re-index * @param dso object to re-index
* @throws java.sql.SQLException passed through.
* @throws java.io.IOException passed through.
*/ */
@Override @Override
public void reIndexContent(Context context, IndexableObject dso) public void reIndexContent(Context context, IndexableObject dso)
throws SQLException, IOException { throws SQLException, IOException {
try { try {
indexContent(context, dso); indexContent(context, dso);
} catch (Exception exception) { } catch (SQLException exception) {
log.error(exception.getMessage(), exception); log.error(exception.getMessage(), exception);
emailException(exception); emailException(exception);
} }
@@ -262,6 +267,8 @@ public class SolrServiceImpl implements SearchService, IndexingService {
* create full index - wiping old index * create full index - wiping old index
* *
* @param c context to use * @param c context to use
* @throws java.sql.SQLException passed through.
* @throws java.io.IOException passed through.
*/ */
@Override @Override
public void createIndex(Context c) throws SQLException, IOException { public void createIndex(Context c) throws SQLException, IOException {
@@ -321,7 +328,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
solrSearchCore.getSolr().commit(); solrSearchCore.getSolr().commit();
} }
} catch (Exception e) { } catch (IOException | SQLException | SolrServerException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }
@@ -391,7 +398,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
start += batch; start += batch;
} }
} }
} catch (Exception e) { } catch (IOException | SQLException | SolrServerException e) {
log.error("Error cleaning discovery index: " + e.getMessage(), e); log.error("Error cleaning discovery index: " + e.getMessage(), e);
} finally { } finally {
context.abort(); context.abort();
@@ -414,10 +421,8 @@ public class SolrServiceImpl implements SearchService, IndexingService {
long finish = System.currentTimeMillis(); long finish = System.currentTimeMillis();
System.out.println("SOLR Search Optimize -- Process Finished:" + finish); System.out.println("SOLR Search Optimize -- Process Finished:" + finish);
System.out.println("SOLR Search Optimize -- Total time taken:" + (finish - start) + " (ms)."); System.out.println("SOLR Search Optimize -- Total time taken:" + (finish - start) + " (ms).");
} catch (SolrServerException sse) { } catch (SolrServerException | IOException sse) {
System.err.println(sse.getMessage()); System.err.println(sse.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
} }
} }
@@ -446,16 +451,14 @@ public class SolrServiceImpl implements SearchService, IndexingService {
protected void emailException(Exception exception) { protected void emailException(Exception exception) {
// Also email an alert, system admin may need to check for stale lock // Also email an alert, system admin may need to check for stale lock
try { try {
String recipient = ConfigurationManager String recipient = configurationService.getProperty("alert.recipient");
.getProperty("alert.recipient");
if (StringUtils.isNotBlank(recipient)) { if (StringUtils.isNotBlank(recipient)) {
Email email = Email Email email = Email
.getEmail(I18nUtil.getEmailFilename( .getEmail(I18nUtil.getEmailFilename(
Locale.getDefault(), "internal_error")); Locale.getDefault(), "internal_error"));
email.addRecipient(recipient); email.addRecipient(recipient);
email.addArgument(ConfigurationManager email.addArgument(configurationService.getProperty("dspace.ui.url"));
.getProperty("dspace.ui.url"));
email.addArgument(new Date()); email.addArgument(new Date());
String stackTrace; String stackTrace;
@@ -473,7 +476,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
email.addArgument(stackTrace); email.addArgument(stackTrace);
email.send(); email.send();
} }
} catch (Exception e) { } catch (IOException | MessagingException e) {
// Not much we can do here! // Not much we can do here!
log.warn("Unable to send email alert", e); log.warn("Unable to send email alert", e);
} }
@@ -718,7 +721,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
QueryResponse queryResponse = solrSearchCore.getSolr().query(solrQuery, SolrRequest.METHOD.POST); QueryResponse queryResponse = solrSearchCore.getSolr().query(solrQuery, SolrRequest.METHOD.POST);
return retrieveResult(context, discoveryQuery, queryResponse); return retrieveResult(context, discoveryQuery, queryResponse);
} catch (Exception e) { } catch (IOException | SQLException | SolrServerException | SearchServiceException e) {
throw new org.dspace.discovery.SearchServiceException(e.getMessage(), e); throw new org.dspace.discovery.SearchServiceException(e.getMessage(), e);
} }
} }
@@ -879,7 +882,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
DiscoverResult.SearchDocument resultDoc = new DiscoverResult.SearchDocument(); DiscoverResult.SearchDocument resultDoc = new DiscoverResult.SearchDocument();
//Add information about our search fields //Add information about our search fields
for (String field : searchFields) { for (String field : searchFields) {
List<String> valuesAsString = new ArrayList<String>(); List<String> valuesAsString = new ArrayList<>();
for (Object o : doc.getFieldValues(field)) { for (Object o : doc.getFieldValues(field)) {
valuesAsString.add(String.valueOf(o)); valuesAsString.add(String.valueOf(o));
} }
@@ -892,10 +895,10 @@ public class SolrServiceImpl implements SearchService, IndexingService {
indexableObject.getUniqueIndexID()); indexableObject.getUniqueIndexID());
if (MapUtils.isNotEmpty(highlightedFields)) { if (MapUtils.isNotEmpty(highlightedFields)) {
//We need to remove all the "_hl" appendix strings from our keys //We need to remove all the "_hl" appendix strings from our keys
Map<String, List<String>> resultMap = new HashMap<String, List<String>>(); Map<String, List<String>> resultMap = new HashMap<>();
for (String key : highlightedFields.keySet()) { for (String key : highlightedFields.keySet()) {
List<String> highlightOriginalValue = highlightedFields.get(key); List<String> highlightOriginalValue = highlightedFields.get(key);
List<String[]> resultHighlightOriginalValue = new ArrayList<String[]>(); List<String[]> resultHighlightOriginalValue = new ArrayList<>();
for (String highlightValue : highlightOriginalValue) { for (String highlightValue : highlightOriginalValue) {
String[] splitted = highlightValue.split("###"); String[] splitted = highlightValue.split("###");
resultHighlightOriginalValue.add(splitted); resultHighlightOriginalValue.add(splitted);
@@ -952,7 +955,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
// just retrieve the facets in the order they where requested! // just retrieve the facets in the order they where requested!
// also for the date we ask it in proper (reverse) order // also for the date we ask it in proper (reverse) order
// At the moment facet queries are only used for dates // At the moment facet queries are only used for dates
LinkedHashMap<String, Integer> sortedFacetQueries = new LinkedHashMap<String, Integer>( LinkedHashMap<String, Integer> sortedFacetQueries = new LinkedHashMap<>(
solrQueryResponse.getFacetQuery()); solrQueryResponse.getFacetQuery());
for (String facetQuery : sortedFacetQueries.keySet()) { 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 //TODO: do not assume this, people may want to use it for other ends, use a regex to make sure
@@ -1046,7 +1049,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
SolrDocumentList docs = rsp.getResults(); SolrDocumentList docs = rsp.getResults();
Iterator iter = docs.iterator(); Iterator iter = docs.iterator();
List<IndexableObject> result = new ArrayList<IndexableObject>(); List<IndexableObject> result = new ArrayList<>();
while (iter.hasNext()) { while (iter.hasNext()) {
SolrDocument doc = (SolrDocument) iter.next(); SolrDocument doc = (SolrDocument) iter.next();
IndexableObject o = findIndexableObject(context, doc); IndexableObject o = findIndexableObject(context, doc);
@@ -1055,7 +1058,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
} }
return result; return result;
} catch (Exception e) { } catch (IOException | SQLException | SolrServerException e) {
// Any acception that we get ignore it. // Any acception that we get ignore it.
// We do NOT want any crashed to shown by the user // We do NOT want any crashed to shown by the user
log.error(LogManager.getHeader(context, "Error while quering solr", "Query: " + query), e); log.error(LogManager.getHeader(context, "Error while quering solr", "Query: " + query), e);
@@ -1158,7 +1161,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
} }
} }
} }
} catch (Exception e) { } catch (IOException | SQLException | SolrServerException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while retrieving related items", "Handle: " LogManager.getHeader(context, "Error while retrieving related items", "Handle: "
+ item.getHandle()), e); + item.getHandle()), e);
@@ -1233,7 +1236,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
//Escape any regex chars //Escape any regex chars
separator = java.util.regex.Pattern.quote(separator); separator = java.util.regex.Pattern.quote(separator);
String[] fqParts = value.split(separator); String[] fqParts = value.split(separator);
StringBuffer valueBuffer = new StringBuffer(); StringBuilder valueBuffer = new StringBuilder();
int start = fqParts.length / 2; int start = fqParts.length / 2;
for (int i = start; i < fqParts.length; i++) { for (int i = start; i < fqParts.length; i++) {
String[] split = fqParts[i].split(SearchUtils.AUTHORITY_SEPARATOR, 2); String[] split = fqParts[i].split(SearchUtils.AUTHORITY_SEPARATOR, 2);
@@ -1265,7 +1268,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
//Escape any regex chars //Escape any regex chars
separator = java.util.regex.Pattern.quote(separator); separator = java.util.regex.Pattern.quote(separator);
String[] fqParts = value.split(separator); String[] fqParts = value.split(separator);
StringBuffer authorityBuffer = new StringBuffer(); StringBuilder authorityBuffer = new StringBuilder();
int start = fqParts.length / 2; int start = fqParts.length / 2;
for (int i = start; i < fqParts.length; i++) { for (int i = start; i < fqParts.length; i++) {
String[] split = fqParts[i].split(SearchUtils.AUTHORITY_SEPARATOR, 2); String[] split = fqParts[i].split(SearchUtils.AUTHORITY_SEPARATOR, 2);
@@ -1297,7 +1300,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
//Escape any regex chars //Escape any regex chars
separator = java.util.regex.Pattern.quote(separator); separator = java.util.regex.Pattern.quote(separator);
String[] fqParts = value.split(separator); String[] fqParts = value.split(separator);
StringBuffer valueBuffer = new StringBuffer(); StringBuilder valueBuffer = new StringBuilder();
int end = fqParts.length / 2; int end = fqParts.length / 2;
for (int i = 0; i < end; i++) { for (int i = 0; i < end; i++) {
valueBuffer.append(fqParts[i]); valueBuffer.append(fqParts[i]);
@@ -1325,7 +1328,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
if (solrSearchCore.getSolr() != null) { if (solrSearchCore.getSolr() != null) {
solrSearchCore.getSolr().commit(); solrSearchCore.getSolr().commit();
} }
} catch (Exception e) { } catch (IOException | SolrServerException e) {
throw new SearchServiceException(e.getMessage(), e); throw new SearchServiceException(e.getMessage(), e);
} }
} }

View File

@@ -13,9 +13,9 @@ import java.util.Locale;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
@@ -44,7 +44,7 @@ public class AccountServiceImpl implements AccountService {
/** /**
* log4j log * log4j log
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(AccountServiceImpl.class); private static final Logger log = LogManager.getLogger(AccountServiceImpl.class);
@Autowired(required = true) @Autowired(required = true)
protected EPersonService ePersonService; protected EPersonService ePersonService;
@Autowired(required = true) @Autowired(required = true)
@@ -58,14 +58,20 @@ public class AccountServiceImpl implements AccountService {
/** /**
* Email registration info to the given email address. * Email registration info to the given email address.
* * Potential error conditions:
* Potential error conditions: Cannot create registration data in database * <ul>
* (throws SQLException) Error sending email (throws MessagingException) * <li>Cannot create registration data in database (throws SQLException).</li>
* Error reading email template (throws IOException) Authorization error * <li>Error sending email (throws MessagingException).</li>
* (throws AuthorizeException) * <li>Error reading email template (throws IOException).</li>
* <li>Authorization error (throws AuthorizeException).</li>
* </ul>
* *
* @param context DSpace context * @param context DSpace context
* @param email Email address to send the registration email to * @param email Email address to send the registration email to
* @throws java.sql.SQLException passed through.
* @throws java.io.IOException passed through.
* @throws javax.mail.MessagingException passed through.
* @throws org.dspace.authorize.AuthorizeException passed through.
*/ */
@Override @Override
public void sendRegistrationInfo(Context context, String email) public void sendRegistrationInfo(Context context, String email)
@@ -79,14 +85,22 @@ public class AccountServiceImpl implements AccountService {
/** /**
* Email forgot password info to the given email address. * Email forgot password info to the given email address.
* Potential error conditions:
* <ul>
* <li>No EPerson with that email (returns null).</li>
* <li>Cannot create registration data in database (throws SQLException).</li>
* <li>Error sending email (throws MessagingException).</li>
* <li>Error reading email template (throws IOException).</li>
* <li>Authorization error (throws AuthorizeException).</li>
* </ul>
* *
* 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 context DSpace context
* @param email Email address to send the forgot-password email to * @param email Email address to send the forgot-password email to
* @throws java.sql.SQLException passed through.
* @throws java.io.IOException passed through.
* @throws javax.mail.MessagingException passed through.
* @throws org.dspace.authorize.AuthorizeException passed through.
*/ */
@Override @Override
public void sendForgotPasswordInfo(Context context, String email) public void sendForgotPasswordInfo(Context context, String email)
@@ -111,6 +125,7 @@ public class AccountServiceImpl implements AccountService {
* @return The EPerson corresponding to token, or null. * @return The EPerson corresponding to token, or null.
* @throws SQLException If the token or eperson cannot be retrieved from the * @throws SQLException If the token or eperson cannot be retrieved from the
* database. * database.
* @throws AuthorizeException passed through.
*/ */
@Override @Override
public EPerson getEPerson(Context context, String token) public EPerson getEPerson(Context context, String token)
@@ -131,6 +146,7 @@ public class AccountServiceImpl implements AccountService {
* @param context DSpace context * @param context DSpace context
* @param token Account token * @param token Account token
* @return The email address corresponding to token, or null. * @return The email address corresponding to token, or null.
* @throws java.sql.SQLException passed through.
*/ */
@Override @Override
public String getEmail(Context context, String token) public String getEmail(Context context, String token)
@@ -243,7 +259,7 @@ public class AccountServiceImpl implements AccountService {
*/ */
protected void sendEmail(Context context, String email, boolean isRegister, RegistrationData rd) protected void sendEmail(Context context, String email, boolean isRegister, RegistrationData rd)
throws MessagingException, IOException, SQLException { throws MessagingException, IOException, SQLException {
String base = ConfigurationManager.getProperty("dspace.ui.url"); String base = configurationService.getProperty("dspace.ui.url");
// Note change from "key=" to "token=" // Note change from "key=" to "token="
String specialLink = new StringBuffer().append(base).append( String specialLink = new StringBuffer().append(base).append(

View File

@@ -12,7 +12,6 @@ import java.util.UUID;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
@@ -22,6 +21,8 @@ import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.event.Consumer; import org.dspace.event.Consumer;
import org.dspace.event.Event; import org.dspace.event.Event;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Class for handling updates to EPersons * Class for handling updates to EPersons
@@ -35,9 +36,12 @@ public class EPersonConsumer implements Consumer {
/** /**
* log4j logger * log4j logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(EPersonConsumer.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(EPersonConsumer.class);
protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); protected EPersonService ePersonService
= EPersonServiceFactory.getInstance().getEPersonService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Initalise the consumer * Initalise the consumer
@@ -69,7 +73,7 @@ public class EPersonConsumer implements Consumer {
case Constants.EPERSON: case Constants.EPERSON:
if (et == Event.CREATE) { if (et == Event.CREATE) {
// Notify of new user registration // Notify of new user registration
String notifyRecipient = ConfigurationManager.getProperty("registration.notify"); String notifyRecipient = configurationService.getProperty("registration.notify");
if (notifyRecipient == null) { if (notifyRecipient == null) {
notifyRecipient = ""; notifyRecipient = "";
} }
@@ -82,8 +86,8 @@ public class EPersonConsumer implements Consumer {
.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "registration_notify")); .getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "registration_notify"));
adminEmail.addRecipient(notifyRecipient); adminEmail.addRecipient(notifyRecipient);
adminEmail.addArgument(ConfigurationManager.getProperty("dspace.name")); adminEmail.addArgument(configurationService.getProperty("dspace.name"));
adminEmail.addArgument(ConfigurationManager.getProperty("dspace.ui.url")); adminEmail.addArgument(configurationService.getProperty("dspace.ui.url"));
adminEmail.addArgument(eperson.getFirstName() + " " + eperson.getLastName()); // Name adminEmail.addArgument(eperson.getFirstName() + " " + eperson.getLastName()); // Name
adminEmail.addArgument(eperson.getEmail()); adminEmail.addArgument(eperson.getEmail());
adminEmail.addArgument(new Date()); adminEmail.addArgument(new Date());

View File

@@ -34,7 +34,6 @@ import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
@@ -45,6 +44,8 @@ import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.search.Harvest; import org.dspace.search.Harvest;
import org.dspace.search.HarvestedItemInfo; import org.dspace.search.HarvestedItemInfo;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* CLI tool used for sending new item e-mail alerts to users * CLI tool used for sending new item e-mail alerts to users
@@ -56,9 +57,14 @@ public class SubscribeCLITool {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SubscribeCLITool.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SubscribeCLITool.class);
private static HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); private static final HandleService handleService
private static ItemService itemService = ContentServiceFactory.getInstance().getItemService(); = HandleServiceFactory.getInstance().getHandleService();
private static SubscribeService subscribeService = EPersonServiceFactory.getInstance().getSubscribeService(); private static final ItemService itemService
= ContentServiceFactory.getInstance().getItemService();
private static final SubscribeService subscribeService
= EPersonServiceFactory.getInstance().getSubscribeService();
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Default constructor * Default constructor
@@ -168,14 +174,14 @@ public class SubscribeCLITool {
// FIXME: text of email should be more configurable from an // FIXME: text of email should be more configurable from an
// i18n viewpoint // i18n viewpoint
StringBuffer emailText = new StringBuffer(); StringBuilder emailText = new StringBuilder();
boolean isFirst = true; boolean isFirst = true;
for (int i = 0; i < collections.size(); i++) { for (int i = 0; i < collections.size(); i++) {
Collection c = collections.get(i); Collection c = collections.get(i);
try { try {
boolean includeAll = ConfigurationManager boolean includeAll = configurationService
.getBooleanProperty("harvest.includerestricted.subscription", true); .getBooleanProperty("harvest.includerestricted.subscription", true);
// we harvest all the changed item from yesterday until now // we harvest all the changed item from yesterday until now
@@ -191,7 +197,7 @@ public class SubscribeCLITool {
false, // Or withdrawals false, // Or withdrawals
includeAll); includeAll);
if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false)) { if (configurationService.getBooleanProperty("eperson.subscription.onlynew", false)) {
// get only the items archived yesterday // get only the items archived yesterday
itemInfos = filterOutModified(itemInfos); itemInfos = filterOutModified(itemInfos);
} else { } else {
@@ -300,7 +306,7 @@ public class SubscribeCLITool {
try { try {
line = new PosixParser().parse(options, argv); line = new PosixParser().parse(options, argv);
} catch (Exception e) { } catch (org.apache.commons.cli.ParseException e) {
// automatically generate the help statement // automatically generate the help statement
formatter.printHelp(usage, e.getMessage(), options, ""); formatter.printHelp(usage, e.getMessage(), options, "");
System.exit(1); System.exit(1);
@@ -320,7 +326,7 @@ public class SubscribeCLITool {
context = new Context(Context.Mode.READ_ONLY); context = new Context(Context.Mode.READ_ONLY);
processDaily(context, test); processDaily(context, test);
context.complete(); context.complete();
} catch (Exception e) { } catch (IOException | SQLException e) {
log.fatal(e); log.fatal(e);
} finally { } finally {
if (context != null && context.isValid()) { if (context != null && context.isValid()) {
@@ -333,7 +339,7 @@ public class SubscribeCLITool {
private static List<HarvestedItemInfo> filterOutToday(List<HarvestedItemInfo> completeList) { private static List<HarvestedItemInfo> filterOutToday(List<HarvestedItemInfo> completeList) {
log.debug("Filtering out all today item to leave new items list size=" log.debug("Filtering out all today item to leave new items list size="
+ completeList.size()); + completeList.size());
List<HarvestedItemInfo> filteredList = new ArrayList<HarvestedItemInfo>(); List<HarvestedItemInfo> filteredList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String today = sdf.format(new Date()); String today = sdf.format(new Date());
@@ -384,7 +390,7 @@ public class SubscribeCLITool {
private static List<HarvestedItemInfo> filterOutModified(List<HarvestedItemInfo> completeList) { private static List<HarvestedItemInfo> filterOutModified(List<HarvestedItemInfo> completeList) {
log.debug("Filtering out all modified to leave new items list size=" + completeList.size()); log.debug("Filtering out all modified to leave new items list size=" + completeList.size());
List<HarvestedItemInfo> filteredList = new ArrayList<HarvestedItemInfo>(); List<HarvestedItemInfo> filteredList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Get the start and end dates for yesterday // Get the start and end dates for yesterday

View File

@@ -10,27 +10,27 @@ package org.dspace.event;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* An instance of this class contains the configuration profile of a specific, * An instance of this class contains the configuration profile of a specific,
* named Consumer, <em>in the context of a specific Dispatcher</em>. This * named Consumer, <em>in the context of a specific Dispatcher</em>. This
* includes the name, the class to instantiate and event filters. Note that all * includes the name, the class to instantiate and event filters. Note that all
* characteristics are "global" and the same for all dispatchers. * characteristics are "global" and the same for all dispatchers.
*
* @version $Revision$
*/ */
public class ConsumerProfile { public class ConsumerProfile {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(ConsumerProfile.class); private static final Logger log = LogManager.getLogger(ConsumerProfile.class);
/** /**
* Name matching the key in DSpace Configuration * Name matching the key in DSpace Configuration
*/ */
private String name; private final String name;
/** /**
* Instance of configured consumer class * Instance of configured consumer class
@@ -82,9 +82,11 @@ public class ConsumerProfile {
private void readConfiguration() private void readConfiguration()
throws IllegalArgumentException, ClassNotFoundException, throws IllegalArgumentException, ClassNotFoundException,
InstantiationException, IllegalAccessException { InstantiationException, IllegalAccessException {
String className = ConfigurationManager.getProperty(CONSUMER_PREFIX ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String className = configurationService.getProperty(CONSUMER_PREFIX
+ name + ".class"); + name + ".class");
String filterString = ConfigurationManager.getProperty(CONSUMER_PREFIX String filterString = configurationService.getProperty(CONSUMER_PREFIX
+ name + ".filters"); + name + ".filters");
if (className == null) { if (className == null) {
@@ -99,7 +101,7 @@ public class ConsumerProfile {
consumer = (Consumer) Class.forName(className.trim()).newInstance(); consumer = (Consumer) Class.forName(className.trim()).newInstance();
// Each "filter" is <objectTypes> + <eventTypes> : ... // Each "filter" is <objectTypes> + <eventTypes> : ...
filters = new ArrayList<int[]>(); filters = new ArrayList<>();
String part[] = filterString.trim().split(":"); String part[] = filterString.trim().split(":");
for (int j = 0; j < part.length; ++j) { for (int j = 0; j < part.length; ++j) {
String fpart[] = part[j].split("\\+"); String fpart[] = part[j].split("\\+");

View File

@@ -12,10 +12,12 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Demonstration and test consumer for the event system. This consumer only * Demonstration and test consumer for the event system. This consumer only
@@ -27,10 +29,13 @@ import org.dspace.eperson.EPerson;
*/ */
public class TestConsumer implements Consumer { public class TestConsumer implements Consumer {
// Log4j logger // Log4j logger
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(TestConsumer.class); private static final Logger log = LogManager.getLogger(TestConsumer.class);
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
// Send diagnostic output here - set to null to turn it off. // Send diagnostic output here - set to null to turn it off.
private static PrintStream out = ConfigurationManager private static final PrintStream out = configurationService
.getBooleanProperty("testConsumer.verbose") ? System.out : null; .getBooleanProperty("testConsumer.verbose") ? System.out : null;
@Override @Override

View File

@@ -15,16 +15,18 @@ import java.util.List;
import java.util.Stack; import java.util.Stack;
import java.util.UUID; import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.harvest.factory.HarvestServiceFactory; import org.dspace.harvest.factory.HarvestServiceFactory;
import org.dspace.harvest.service.HarvestedCollectionService; import org.dspace.harvest.service.HarvestedCollectionService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* The class responsible for scheduling harvesting cycles are regular intervals. * The class responsible for scheduling harvesting cycles are regular intervals.
@@ -32,7 +34,7 @@ import org.dspace.harvest.service.HarvestedCollectionService;
* @author alexey * @author alexey
*/ */
public class HarvestScheduler implements Runnable { public class HarvestScheduler implements Runnable {
protected static Logger log = org.apache.logging.log4j.LogManager.getLogger(HarvestScheduler.class); protected static Logger log = LogManager.getLogger(HarvestScheduler.class);
protected static EPerson harvestAdmin; protected static EPerson harvestAdmin;
@@ -77,10 +79,12 @@ public class HarvestScheduler implements Runnable {
protected static long maxHeartbeat; protected static long maxHeartbeat;
private static final CollectionService collectionService = ContentServiceFactory.getInstance() private static final CollectionService collectionService
.getCollectionService(); = ContentServiceFactory.getInstance().getCollectionService();
private static final HarvestedCollectionService harvestedCollectionService = private static final HarvestedCollectionService harvestedCollectionService
HarvestServiceFactory.getInstance().getHarvestedCollectionService(); = HarvestServiceFactory.getInstance().getHarvestedCollectionService();
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
public static boolean hasStatus(int statusToCheck) { public static boolean hasStatus(int statusToCheck) {
return status == statusToCheck; return status == statusToCheck;
@@ -121,25 +125,25 @@ public class HarvestScheduler implements Runnable {
public HarvestScheduler() throws SQLException, AuthorizeException { public HarvestScheduler() throws SQLException, AuthorizeException {
mainContext = new Context(); mainContext = new Context();
String harvestAdminParam = ConfigurationManager.getProperty("oai", "harvester.eperson"); String harvestAdminParam = configurationService.getProperty("oai.harvester.eperson");
harvestAdmin = null; harvestAdmin = null;
if (harvestAdminParam != null && harvestAdminParam.length() > 0) { if (harvestAdminParam != null && harvestAdminParam.length() > 0) {
harvestAdmin = EPersonServiceFactory.getInstance().getEPersonService() harvestAdmin = EPersonServiceFactory.getInstance().getEPersonService()
.findByEmail(mainContext, harvestAdminParam); .findByEmail(mainContext, harvestAdminParam);
} }
harvestThreads = new Stack<HarvestThread>(); harvestThreads = new Stack<>();
maxActiveThreads = ConfigurationManager.getIntProperty("oai", "harvester.maxThreads"); maxActiveThreads = configurationService.getIntProperty("oai.harvester.maxThreads");
if (maxActiveThreads == 0) { if (maxActiveThreads == 0) {
maxActiveThreads = 3; maxActiveThreads = 3;
} }
minHeartbeat = ConfigurationManager.getIntProperty("oai", "harvester.minHeartbeat"); minHeartbeat = configurationService.getIntProperty("oai.harvester.minHeartbeat");
minHeartbeat = minHeartbeat * 1000; // multiple by 1000 to turn seconds to ms minHeartbeat = minHeartbeat * 1000; // multiple by 1000 to turn seconds to ms
if (minHeartbeat == 0) { if (minHeartbeat == 0) {
minHeartbeat = 30000; minHeartbeat = 30000;
} }
maxHeartbeat = ConfigurationManager.getIntProperty("oai", "harvester.maxHeartbeat"); maxHeartbeat = configurationService.getIntProperty("oai.harvester.maxHeartbeat");
maxHeartbeat = maxHeartbeat * 1000; // multiple by 1000 to turn seconds to ms maxHeartbeat = maxHeartbeat * 1000; // multiple by 1000 to turn seconds to ms
if (maxHeartbeat == 0) { if (maxHeartbeat == 0) {
maxHeartbeat = 3600000; maxHeartbeat = 3600000;
@@ -235,7 +239,7 @@ public class HarvestScheduler implements Runnable {
mainContext.abort(); mainContext.abort();
} }
} catch (Exception e) { } catch (IOException | InterruptedException | SQLException | AuthorizeException e) {
log.error("Exception on iteration: " + i); log.error("Exception on iteration: " + i);
e.printStackTrace(); e.printStackTrace();
} }
@@ -245,7 +249,7 @@ public class HarvestScheduler implements Runnable {
Context tempContext = new Context(); Context tempContext = new Context();
HarvestedCollection hc = harvestedCollectionService.findOldestHarvest(tempContext); HarvestedCollection hc = harvestedCollectionService.findOldestHarvest(tempContext);
int harvestInterval = ConfigurationManager.getIntProperty("oai", "harvester.harvestFrequency"); int harvestInterval = configurationService.getIntProperty("oai.harvester.harvestFrequency");
if (harvestInterval == 0) { if (harvestInterval == 0) {
harvestInterval = 720; harvestInterval = 720;
} }

View File

@@ -12,24 +12,30 @@ import static org.dspace.harvest.OAIHarvester.OAI_DMD_ERROR;
import static org.dspace.harvest.OAIHarvester.OAI_ORE_ERROR; import static org.dspace.harvest.OAIHarvester.OAI_ORE_ERROR;
import static org.dspace.harvest.OAIHarvester.OAI_SET_ERROR; import static org.dspace.harvest.OAIHarvester.OAI_SET_ERROR;
import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import ORG.oclc.oai.harvester2.verb.Identify; import ORG.oclc.oai.harvester2.verb.Identify;
import ORG.oclc.oai.harvester2.verb.ListIdentifiers; import ORG.oclc.oai.harvester2.verb.ListIdentifiers;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.harvest.dao.HarvestedCollectionDAO; import org.dspace.harvest.dao.HarvestedCollectionDAO;
import org.dspace.harvest.service.HarvestedCollectionService; import org.dspace.harvest.service.HarvestedCollectionService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
import org.jdom.input.DOMBuilder; import org.jdom.input.DOMBuilder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.DOMException;
import org.xml.sax.SAXException;
/** /**
* Service implementation for the HarvestedCollection object. * Service implementation for the HarvestedCollection object.
@@ -108,12 +114,14 @@ public class HarvestedCollectionServiceImpl implements HarvestedCollectionServic
@Override @Override
public List<HarvestedCollection> findReady(Context context) throws SQLException { public List<HarvestedCollection> findReady(Context context) throws SQLException {
int harvestInterval = ConfigurationManager.getIntProperty("oai", "harvester.harvestFrequency"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
int harvestInterval = configurationService.getIntProperty("oai.harvester.harvestFrequency");
if (harvestInterval == 0) { if (harvestInterval == 0) {
harvestInterval = 720; harvestInterval = 720;
} }
int expirationInterval = ConfigurationManager.getIntProperty("oai", "harvester.threadTimeout"); int expirationInterval = configurationService.getIntProperty("oai.harvester.threadTimeout");
if (expirationInterval == 0) { if (expirationInterval == 0) {
expirationInterval = 24; expirationInterval = 24;
} }
@@ -182,14 +190,15 @@ public class HarvestedCollectionServiceImpl implements HarvestedCollectionServic
* @param testORE whether the method should also check the PMH provider for ORE support * @param testORE whether the method should also check the PMH provider for ORE support
* @return list of errors encountered during verification. Empty list indicates a "success" condition. * @return list of errors encountered during verification. Empty list indicates a "success" condition.
*/ */
@Override
public List<String> verifyOAIharvester(String oaiSource, public List<String> verifyOAIharvester(String oaiSource,
String oaiSetId, String metaPrefix, boolean testORE) { String oaiSetId, String metaPrefix, boolean testORE) {
List<String> errorSet = new ArrayList<String>(); List<String> errorSet = new ArrayList<>();
// First, see if we can contact the target server at all. // First, see if we can contact the target server at all.
try { try {
new Identify(oaiSource); new Identify(oaiSource);
} catch (Exception ex) { } catch (IOException | ParserConfigurationException | TransformerException | SAXException ex) {
errorSet.add(OAI_ADDRESS_ERROR + ": OAI server could not be reached."); errorSet.add(OAI_ADDRESS_ERROR + ": OAI server could not be reached.");
return errorSet; return errorSet;
} }
@@ -207,7 +216,7 @@ public class HarvestedCollectionServiceImpl implements HarvestedCollectionServic
try { try {
OREOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, OAIHarvester.getORENamespace().getURI()); OREOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, OAIHarvester.getORENamespace().getURI());
DMDOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, DMD_NS.getURI()); DMDOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, DMD_NS.getURI());
} catch (Exception ex) { } catch (IOException | ParserConfigurationException | TransformerException | SAXException ex) {
errorSet.add(OAI_ADDRESS_ERROR errorSet.add(OAI_ADDRESS_ERROR
+ ": OAI did not respond to ListMetadataFormats query (" + ": OAI did not respond to ListMetadataFormats query ("
+ ORE_NS.getPrefix() + ":" + OREOAIPrefix + " ; " + ORE_NS.getPrefix() + ":" + OREOAIPrefix + " ; "
@@ -251,11 +260,11 @@ public class HarvestedCollectionServiceImpl implements HarvestedCollectionServic
} }
} }
} }
} catch (RuntimeException re) { } catch (IOException | ParserConfigurationException | TransformerException | DOMException | SAXException e) {
throw re;
} catch (Exception e) {
errorSet.add(OAI_ADDRESS_ERROR + ": OAI server could not be reached"); errorSet.add(OAI_ADDRESS_ERROR + ": OAI server could not be reached");
return errorSet; return errorSet;
} catch (RuntimeException re) {
throw re;
} }
return errorSet; return errorSet;

View File

@@ -12,7 +12,6 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.dspace.core.ConfigurationManager;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.storage.bitstore.DSBitStoreService; import org.dspace.storage.bitstore.DSBitStoreService;
import org.dspace.utils.DSpace; import org.dspace.utils.DSpace;
@@ -24,9 +23,9 @@ public class InfoCheck extends Check {
@Override @Override
public String run(ReportInfo ri) { public String run(ReportInfo ri) {
StringBuilder sb = new StringBuilder();
ConfigurationService configurationService ConfigurationService configurationService
= new DSpace().getConfigurationService(); = new DSpace().getConfigurationService();
StringBuilder sb = new StringBuilder();
sb.append("Generated: ").append( sb.append("Generated: ").append(
new Date().toString() new Date().toString()
).append("\n"); ).append("\n");
@@ -38,12 +37,13 @@ public class InfoCheck extends Check {
).append("\n"); ).append("\n");
sb.append("Url: ").append( sb.append("Url: ").append(
ConfigurationManager.getProperty("dspace.ui.url") configurationService.getProperty("dspace.ui.url")
).append("\n"); ).append("\n");
sb.append("\n"); sb.append("\n");
DSBitStoreService localStore = new DSpace().getServiceManager().getServicesByType(DSBitStoreService.class) DSBitStoreService localStore = new DSpace().getServiceManager()
.get(0); .getServicesByType(DSBitStoreService.class)
.get(0);
for (String[] ss : new String[][] { for (String[] ss : new String[][] {
new String[] { new String[] {
localStore.getBaseDir().toString(), localStore.getBaseDir().toString(),

View File

@@ -7,6 +7,7 @@
*/ */
package org.dspace.health; package org.dspace.health;
import java.io.IOException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@@ -14,6 +15,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import javax.mail.MessagingException;
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.HelpFormatter;
@@ -21,11 +23,12 @@ import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException; import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Email; import org.dspace.core.Email;
import org.dspace.core.factory.CoreServiceFactory; import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.core.service.PluginService; import org.dspace.core.service.PluginService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
@@ -33,10 +36,10 @@ import org.dspace.services.factory.DSpaceServicesFactory;
*/ */
public class Report { public class Report {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(Report.class); private static final Logger log = LogManager.getLogger(Report.class);
public static final String EMAIL_PATH = "config/emails/healthcheck"; public static final String EMAIL_PATH = "config/emails/healthcheck";
// store the individual check reports // store the individual check reports
private StringBuilder summary_; private final StringBuilder summary_;
// ctor // ctor
// //
@@ -95,6 +98,7 @@ public class Report {
return checks; return checks;
} }
@Override
public String toString() { public String toString() {
return summary_.toString(); return summary_.toString();
} }
@@ -173,10 +177,11 @@ public class Report {
} }
try { try {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
// last n days // last n days
int for_last_n_days = ConfigurationManager.getIntProperty( int for_last_n_days = configurationService.getIntProperty(
"healthcheck", "last_n_days"); "healthcheck.last_n_days");
if (cmdline.hasOption(option_last_n)) { if (cmdline.hasOption(option_last_n)) {
for_last_n_days = Integer.getInteger( for_last_n_days = Integer.getInteger(
cmdline.getOptionValue(option_last_n)); cmdline.getOptionValue(option_last_n));
@@ -195,10 +200,10 @@ public class Report {
if (cmdline.hasOption(option_email)) { if (cmdline.hasOption(option_email)) {
String to = cmdline.getOptionValue(option_email); String to = cmdline.getOptionValue(option_email);
if (!to.contains("@")) { if (!to.contains("@")) {
to = ConfigurationManager.getProperty(to); to = configurationService.getProperty(to);
} }
try { try {
String dspace_dir = ConfigurationManager.getProperty("dspace.dir"); String dspace_dir = configurationService.getProperty("dspace.dir");
String email_path = dspace_dir.endsWith("/") ? dspace_dir String email_path = dspace_dir.endsWith("/") ? dspace_dir
: dspace_dir + "/"; : dspace_dir + "/";
email_path += Report.EMAIL_PATH; email_path += Report.EMAIL_PATH;
@@ -208,7 +213,7 @@ public class Report {
email.addRecipient(to); email.addRecipient(to);
email.addArgument(r.toString()); email.addArgument(r.toString());
email.send(); email.send();
} catch (Exception e) { } catch (IOException | MessagingException e) {
log.fatal("Error sending email:", e); log.fatal("Error sending email:", e);
System.err.println("Error sending email:\n" + e.getMessage()); System.err.println("Error sending email:\n" + e.getMessage());
System.exit(1); System.exit(1);

View File

@@ -18,10 +18,10 @@ import org.dspace.content.Item;
import org.dspace.content.MetadataSchemaEnum; import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -38,7 +38,7 @@ public class HandleIdentifierProvider extends IdentifierProvider {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(HandleIdentifierProvider.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(HandleIdentifierProvider.class);
/** /**
* Prefix registered to no one * Prefix registered to no one
@@ -97,7 +97,7 @@ public class HandleIdentifierProvider extends IdentifierProvider {
} }
return id; return id;
} catch (Exception e) { } catch (IOException | SQLException | AuthorizeException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e);
@@ -112,7 +112,7 @@ public class HandleIdentifierProvider extends IdentifierProvider {
Item item = (Item) dso; Item item = (Item) dso;
populateHandleMetadata(context, item, identifier); populateHandleMetadata(context, item, identifier);
} }
} catch (Exception e) { } catch (IOException | IllegalStateException | SQLException | AuthorizeException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e);
@@ -124,7 +124,7 @@ public class HandleIdentifierProvider extends IdentifierProvider {
public void reserve(Context context, DSpaceObject dso, String identifier) { public void reserve(Context context, DSpaceObject dso, String identifier) {
try { try {
handleService.createHandle(context, dso, identifier); handleService.createHandle(context, dso, identifier);
} catch (Exception e) { } catch (IllegalStateException | SQLException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID());
@@ -147,7 +147,7 @@ public class HandleIdentifierProvider extends IdentifierProvider {
try { try {
return handleService.createHandle(context, dso); return handleService.createHandle(context, dso);
} catch (Exception e) { } catch (SQLException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID());
@@ -159,7 +159,7 @@ public class HandleIdentifierProvider extends IdentifierProvider {
// We can do nothing with this, return null // We can do nothing with this, return null
try { try {
return handleService.resolveToObject(context, identifier); return handleService.resolveToObject(context, identifier);
} catch (Exception e) { } catch (IllegalStateException | SQLException e) {
log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier), log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier),
e); e);
} }
@@ -212,7 +212,9 @@ public class HandleIdentifierProvider extends IdentifierProvider {
* @return configured prefix or "123456789" * @return configured prefix or "123456789"
*/ */
public static String getPrefix() { public static String getPrefix() {
String prefix = ConfigurationManager.getProperty("handle.prefix"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String prefix = configurationService.getProperty("handle.prefix");
if (null == prefix) { if (null == prefix) {
prefix = EXAMPLE_PREFIX; // XXX no good way to exit cleanly prefix = EXAMPLE_PREFIX; // XXX no good way to exit cleanly
log.error("handle.prefix is not configured; using " + prefix); log.error("handle.prefix is not configured; using " + prefix);

View File

@@ -22,11 +22,11 @@ import org.dspace.content.Item;
import org.dspace.content.MetadataSchemaEnum; import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.versioning.Version; import org.dspace.versioning.Version;
import org.dspace.versioning.VersionHistory; import org.dspace.versioning.VersionHistory;
@@ -46,7 +46,8 @@ public class VersionedHandleIdentifierProvider extends IdentifierProvider {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(VersionedHandleIdentifierProvider.class); private static final Logger log
= org.apache.logging.log4j.LogManager.getLogger(VersionedHandleIdentifierProvider.class);
/** /**
* Prefix registered to no one * Prefix registered to no one
@@ -110,7 +111,7 @@ public class VersionedHandleIdentifierProvider extends IdentifierProvider {
if (dso instanceof Item) { if (dso instanceof Item) {
populateHandleMetadata(context, (Item) dso, id); populateHandleMetadata(context, (Item) dso, id);
} }
} catch (Exception e) { } catch (IOException | SQLException | AuthorizeException e) {
log.error(LogManager.getHeader(context, "Error while attempting to create handle", log.error(LogManager.getHeader(context, "Error while attempting to create handle",
"Item id: " + (dso != null ? dso.getID() : "")), e); "Item id: " + (dso != null ? dso.getID() : "")), e);
throw new RuntimeException( throw new RuntimeException(
@@ -261,7 +262,7 @@ public class VersionedHandleIdentifierProvider extends IdentifierProvider {
public void reserve(Context context, DSpaceObject dso, String identifier) { public void reserve(Context context, DSpaceObject dso, String identifier) {
try { try {
handleService.createHandle(context, dso, identifier); handleService.createHandle(context, dso, identifier);
} catch (Exception e) { } catch (IllegalStateException | SQLException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID());
@@ -295,7 +296,7 @@ public class VersionedHandleIdentifierProvider extends IdentifierProvider {
handleId = createNewIdentifier(context, dso, null); handleId = createNewIdentifier(context, dso, null);
} }
return handleId; return handleId;
} catch (Exception e) { } catch (SQLException | AuthorizeException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID());
@@ -307,7 +308,7 @@ public class VersionedHandleIdentifierProvider extends IdentifierProvider {
// We can do nothing with this, return null // We can do nothing with this, return null
try { try {
return handleService.resolveToObject(context, identifier); return handleService.resolveToObject(context, identifier);
} catch (Exception e) { } catch (IllegalStateException | SQLException e) {
log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier), log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier),
e); e);
} }
@@ -356,7 +357,9 @@ public class VersionedHandleIdentifierProvider extends IdentifierProvider {
* @return configured prefix or "123456789" * @return configured prefix or "123456789"
*/ */
public static String getPrefix() { public static String getPrefix() {
String prefix = ConfigurationManager.getProperty("handle.prefix"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String prefix = configurationService.getProperty("handle.prefix");
if (null == prefix) { if (null == prefix) {
prefix = EXAMPLE_PREFIX; // XXX no good way to exit cleanly prefix = EXAMPLE_PREFIX; // XXX no good way to exit cleanly
log.error("handle.prefix is not configured; using " + prefix); log.error("handle.prefix is not configured; using " + prefix);

View File

@@ -20,11 +20,11 @@ import org.dspace.content.Item;
import org.dspace.content.MetadataSchemaEnum; import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.versioning.Version; import org.dspace.versioning.Version;
import org.dspace.versioning.VersionHistory; import org.dspace.versioning.VersionHistory;
@@ -43,7 +43,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident
/** /**
* log4j category * log4j category
*/ */
private static Logger log = private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(VersionedHandleIdentifierProviderWithCanonicalHandles.class); org.apache.logging.log4j.LogManager.getLogger(VersionedHandleIdentifierProviderWithCanonicalHandles.class);
/** /**
@@ -231,7 +231,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident
modifyHandleMetadata(context, item, getCanonical(identifier)); modifyHandleMetadata(context, item, getCanonical(identifier));
} }
} }
} catch (Exception e) { } catch (IOException | SQLException | AuthorizeException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e);
@@ -284,7 +284,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident
public void reserve(Context context, DSpaceObject dso, String identifier) { public void reserve(Context context, DSpaceObject dso, String identifier) {
try { try {
handleService.createHandle(context, dso, identifier); handleService.createHandle(context, dso, identifier);
} catch (Exception e) { } catch (IllegalStateException | SQLException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID());
@@ -318,7 +318,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident
handleId = createNewIdentifier(context, dso, null); handleId = createNewIdentifier(context, dso, null);
} }
return handleId; return handleId;
} catch (Exception e) { } catch (SQLException | AuthorizeException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e);
throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID());
@@ -330,7 +330,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident
// We can do nothing with this, return null // We can do nothing with this, return null
try { try {
return handleService.resolveToObject(context, identifier); return handleService.resolveToObject(context, identifier);
} catch (Exception e) { } catch (IllegalStateException | SQLException e) {
log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier), log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier),
e); e);
} }
@@ -378,7 +378,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident
handleService.modifyHandleDSpaceObject(context, canonical, previous); handleService.modifyHandleDSpaceObject(context, canonical, previous);
} }
} }
} catch (Exception e) { } catch (RuntimeException | SQLException e) {
log.error( log.error(
LogManager.getHeader(context, "Error while attempting to register doi", "Item id: " + dso.getID()), e); LogManager.getHeader(context, "Error while attempting to register doi", "Item id: " + dso.getID()), e);
throw new IdentifierException("Error while moving doi identifier", e); throw new IdentifierException("Error while moving doi identifier", e);
@@ -404,7 +404,9 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident
* @return configured prefix or "123456789" * @return configured prefix or "123456789"
*/ */
public static String getPrefix() { public static String getPrefix() {
String prefix = ConfigurationManager.getProperty("handle.prefix"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String prefix = configurationService.getProperty("handle.prefix");
if (null == prefix) { if (null == prefix) {
prefix = EXAMPLE_PREFIX; // XXX no good way to exit cleanly prefix = EXAMPLE_PREFIX; // XXX no good way to exit cleanly
log.error("handle.prefix is not configured; using " + prefix); log.error("handle.prefix is not configured; using " + prefix);

View File

@@ -17,6 +17,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.UUID; import java.util.UUID;
import javax.mail.MessagingException;
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.CommandLineParser;
@@ -26,11 +27,11 @@ import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException; import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
@@ -42,6 +43,8 @@ import org.dspace.identifier.DOIIdentifierProvider;
import org.dspace.identifier.IdentifierException; import org.dspace.identifier.IdentifierException;
import org.dspace.identifier.factory.IdentifierServiceFactory; import org.dspace.identifier.factory.IdentifierServiceFactory;
import org.dspace.identifier.service.DOIService; import org.dspace.identifier.service.DOIService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.utils.DSpace; import org.dspace.utils.DSpace;
@@ -51,14 +54,15 @@ import org.dspace.utils.DSpace;
*/ */
public class DOIOrganiser { public class DOIOrganiser {
private static final Logger LOG = org.apache.logging.log4j.LogManager.getLogger(DOIOrganiser.class); private static final Logger LOG = LogManager.getLogger(DOIOrganiser.class);
private DOIIdentifierProvider provider; private final DOIIdentifierProvider provider;
private Context context; private final Context context;
private boolean quiet; private boolean quiet;
protected HandleService handleService; protected HandleService handleService;
protected ItemService itemService; protected ItemService itemService;
protected DOIService doiService; protected DOIService doiService;
protected ConfigurationService configurationService;
public DOIOrganiser(Context context, DOIIdentifierProvider provider) { public DOIOrganiser(Context context, DOIIdentifierProvider provider) {
this.context = context; this.context = context;
@@ -67,6 +71,7 @@ public class DOIOrganiser {
this.handleService = HandleServiceFactory.getInstance().getHandleService(); this.handleService = HandleServiceFactory.getInstance().getHandleService();
this.itemService = ContentServiceFactory.getInstance().getItemService(); this.itemService = ContentServiceFactory.getInstance().getItemService();
this.doiService = IdentifierServiceFactory.getInstance().getDOIService(); this.doiService = IdentifierServiceFactory.getInstance().getDOIService();
this.configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
} }
public static void main(String[] args) { public static void main(String[] args) {
@@ -191,7 +196,7 @@ public class DOIOrganiser {
try { try {
List<DOI> dois = doiService List<DOI> dois = doiService
.getDOIsByStatus(context, Arrays.asList(DOIIdentifierProvider.TO_BE_RESERVED)); .getDOIsByStatus(context, Arrays.asList(DOIIdentifierProvider.TO_BE_RESERVED));
if (0 == dois.size()) { if (dois.isEmpty()) {
System.err.println("There are no objects in the database " System.err.println("There are no objects in the database "
+ "that could be reserved."); + "that could be reserved.");
} }
@@ -211,7 +216,7 @@ public class DOIOrganiser {
try { try {
List<DOI> dois = doiService List<DOI> dois = doiService
.getDOIsByStatus(context, Arrays.asList(DOIIdentifierProvider.TO_BE_REGISTERED)); .getDOIsByStatus(context, Arrays.asList(DOIIdentifierProvider.TO_BE_REGISTERED));
if (0 == dois.size()) { if (dois.isEmpty()) {
System.err.println("There are no objects in the database " System.err.println("There are no objects in the database "
+ "that could be registered."); + "that could be registered.");
} }
@@ -232,7 +237,7 @@ public class DOIOrganiser {
DOIIdentifierProvider.UPDATE_BEFORE_REGISTRATION, DOIIdentifierProvider.UPDATE_BEFORE_REGISTRATION,
DOIIdentifierProvider.UPDATE_RESERVED, DOIIdentifierProvider.UPDATE_RESERVED,
DOIIdentifierProvider.UPDATE_REGISTERED)); DOIIdentifierProvider.UPDATE_REGISTERED));
if (0 == dois.size()) { if (dois.isEmpty()) {
System.err.println("There are no objects in the database " System.err.println("There are no objects in the database "
+ "whose metadata needs an update."); + "whose metadata needs an update.");
} }
@@ -252,7 +257,7 @@ public class DOIOrganiser {
try { try {
List<DOI> dois = doiService List<DOI> dois = doiService
.getDOIsByStatus(context, Arrays.asList(DOIIdentifierProvider.TO_BE_DELETED)); .getDOIsByStatus(context, Arrays.asList(DOIIdentifierProvider.TO_BE_DELETED));
if (0 == dois.size()) { if (dois.isEmpty()) {
System.err.println("There are no objects in the database " System.err.println("There are no objects in the database "
+ "that could be deleted."); + "that could be deleted.");
} }
@@ -280,13 +285,7 @@ public class DOIOrganiser {
try { try {
DOI doiRow = organiser.resolveToDOI(identifier); DOI doiRow = organiser.resolveToDOI(identifier);
organiser.reserve(doiRow); organiser.reserve(doiRow);
} catch (SQLException ex) { } catch (SQLException | IllegalArgumentException | IllegalStateException | IdentifierException ex) {
LOG.error(ex);
} catch (IllegalArgumentException ex) {
LOG.error(ex);
} catch (IllegalStateException ex) {
LOG.error(ex);
} catch (IdentifierException ex) {
LOG.error(ex); LOG.error(ex);
} }
} }
@@ -301,13 +300,7 @@ public class DOIOrganiser {
try { try {
DOI doiRow = organiser.resolveToDOI(identifier); DOI doiRow = organiser.resolveToDOI(identifier);
organiser.register(doiRow); organiser.register(doiRow);
} catch (SQLException ex) { } catch (SQLException | IllegalArgumentException | IllegalStateException | IdentifierException ex) {
LOG.error(ex);
} catch (IllegalArgumentException ex) {
LOG.error(ex);
} catch (IllegalStateException ex) {
LOG.error(ex);
} catch (IdentifierException ex) {
LOG.error(ex); LOG.error(ex);
} }
} }
@@ -322,13 +315,7 @@ public class DOIOrganiser {
try { try {
DOI doiRow = organiser.resolveToDOI(identifier); DOI doiRow = organiser.resolveToDOI(identifier);
organiser.update(doiRow); organiser.update(doiRow);
} catch (SQLException ex) { } catch (SQLException | IllegalArgumentException | IllegalStateException | IdentifierException ex) {
LOG.error(ex);
} catch (IllegalArgumentException ex) {
LOG.error(ex);
} catch (IllegalStateException ex) {
LOG.error(ex);
} catch (IdentifierException ex) {
LOG.error(ex); LOG.error(ex);
} }
} }
@@ -342,9 +329,7 @@ public class DOIOrganiser {
} else { } else {
try { try {
organiser.delete(identifier); organiser.delete(identifier);
} catch (SQLException ex) { } catch (SQLException | IllegalArgumentException ex) {
LOG.error(ex);
} catch (IllegalArgumentException ex) {
LOG.error(ex); LOG.error(ex);
} }
} }
@@ -714,7 +699,7 @@ public class DOIOrganiser {
private void sendAlertMail(String action, DSpaceObject dso, String doi, String reason) private void sendAlertMail(String action, DSpaceObject dso, String doi, String reason)
throws IOException { throws IOException {
String recipient = ConfigurationManager.getProperty("alert.recipient"); String recipient = configurationService.getProperty("alert.recipient");
try { try {
if (recipient != null) { if (recipient != null) {
@@ -733,7 +718,7 @@ public class DOIOrganiser {
System.err.println("Email alert is sent."); System.err.println("Email alert is sent.");
} }
} }
} catch (Exception e) { } catch (IOException | MessagingException e) {
LOG.warn("Unable to send email alert", e); LOG.warn("Unable to send email alert", e);
if (!quiet) { if (!quiet) {
System.err.println("Unable to send email alert."); System.err.println("Unable to send email alert.");

View File

@@ -17,8 +17,10 @@ import java.util.regex.Pattern;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Class to mediate with the sort configuration * Class to mediate with the sort configuration
@@ -26,13 +28,13 @@ import org.dspace.core.ConfigurationManager;
* @author Richard Jones * @author Richard Jones
*/ */
public class SortOption { public class SortOption {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SortOption.class); private static final Logger log = LogManager.getLogger(SortOption.class);
public static final String ASCENDING = "ASC"; public static final String ASCENDING = "ASC";
public static final String DESCENDING = "DESC"; public static final String DESCENDING = "DESC";
/** /**
* the number of the sort option as given in the config file * the number of the sort option as given in the configuration file
*/ */
private int number; private int number;
@@ -77,7 +79,9 @@ public class SortOption {
int idx = 1; int idx = 1;
String option; String option;
while (((option = ConfigurationManager.getProperty("webui.itemlist.sort-option." + idx))) != null) { ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
while (((option = configurationService.getProperty("webui.itemlist.sort-option." + idx))) != null) {
SortOption so = new SortOption(idx, option); SortOption so = new SortOption(idx, option);
newSortOptionsSet.add(so); newSortOptionsSet.add(so);
idx++; idx++;

View File

@@ -34,11 +34,12 @@ import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.statistics.Dataset; import org.dspace.statistics.Dataset;
import org.dspace.statistics.ObjectCount; import org.dspace.statistics.ObjectCount;
import org.dspace.statistics.SolrLoggerServiceImpl; import org.dspace.statistics.SolrLoggerServiceImpl;
@@ -78,6 +79,8 @@ public class StatisticsDataVisits extends StatisticsData {
protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); protected final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Construct a completely uninitialized query. * Construct a completely uninitialized query.
@@ -296,7 +299,7 @@ public class StatisticsDataVisits extends StatisticsData {
ObjectCount[] topCounts2 = queryFacetField(secondDataSet, secondDataSet.getQueries().get(0).getQuery(), ObjectCount[] topCounts2 = queryFacetField(secondDataSet, secondDataSet.getQueries().get(0).getQuery(),
filterQuery, facetMinCount); filterQuery, facetMinCount);
// Now that have results for both of them lets do x.y queries // Now that have results for both of them lets do x.y queries
List<String> facetQueries = new ArrayList<String>(); List<String> facetQueries = new ArrayList<>();
for (ObjectCount count2 : topCounts2) { for (ObjectCount count2 : topCounts2) {
String facetQuery = secondDataSet.getFacetField() + ":" + ClientUtils String facetQuery = secondDataSet.getFacetField() + ":" + ClientUtils
.escapeQueryChars(count2.getValue()); .escapeQueryChars(count2.getValue());
@@ -604,7 +607,7 @@ public class StatisticsDataVisits extends StatisticsData {
protected Map<String, String> getAttributes(String value, protected Map<String, String> getAttributes(String value,
DatasetQuery datasetQuery, Context context) throws SQLException { DatasetQuery datasetQuery, Context context) throws SQLException {
HashMap<String, String> attrs = new HashMap<String, String>(); HashMap<String, String> attrs = new HashMap<>();
Query query = datasetQuery.getQueries().get(0); Query query = datasetQuery.getQueries().get(0);
//TODO: CHANGE & THROW AWAY THIS ENTIRE METHOD //TODO: CHANGE & THROW AWAY THIS ENTIRE METHOD
//Check if int //Check if int
@@ -652,7 +655,7 @@ public class StatisticsDataVisits extends StatisticsData {
} }
String url = ConfigurationManager.getProperty("dspace.ui.url") + "/bitstream/" + identifier + "/"; String url = configurationService.getProperty("dspace.ui.url") + "/bitstream/" + identifier + "/";
// If we can put the pretty name of the bitstream on the end of the URL // If we can put the pretty name of the bitstream on the end of the URL
try { try {
@@ -718,10 +721,10 @@ public class StatisticsDataVisits extends StatisticsData {
private String name; private String name;
private int max; private int max;
private String facetField; private String facetField;
private List<Query> queries; private final List<Query> queries;
public DatasetQuery() { public DatasetQuery() {
queries = new ArrayList<Query>(); queries = new ArrayList<>();
} }
public int getMax() { public int getMax() {

View File

@@ -9,7 +9,8 @@ package org.dspace.statistics.util;
import java.io.IOException; import java.io.IOException;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.xbill.DNS.DClass; import org.xbill.DNS.DClass;
import org.xbill.DNS.ExtendedResolver; import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Message; import org.xbill.DNS.Message;
@@ -21,7 +22,7 @@ import org.xbill.DNS.Section;
import org.xbill.DNS.Type; import org.xbill.DNS.Type;
/** /**
* XBill DNS resolver to retrieve hostnames for client IP addresses. * XBill DNS resolver to retrieve host names for client IP addresses.
* TODO: deal with IPv6 addresses. * TODO: deal with IPv6 addresses.
* *
* @author kevinvandevelde at atmire.com * @author kevinvandevelde at atmire.com
@@ -42,10 +43,12 @@ public class DnsLookup {
* @throws IOException from infrastructure. * @throws IOException from infrastructure.
*/ */
public static String reverseDns(String hostIp) throws IOException { public static String reverseDns(String hostIp) throws IOException {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
Resolver res = new ExtendedResolver(); Resolver res = new ExtendedResolver();
// set the timeout, defaults to 200 milliseconds // set the timeout, defaults to 200 milliseconds
int timeout = ConfigurationManager.getIntProperty("usage-statistics", "resolver.timeout", 200); int timeout = configurationService.getIntProperty("usage-statistics.resolver.timeout", 200);
res.setTimeout(0, timeout); res.setTimeout(0, timeout);
Name name = ReverseMap.fromAddress(hostIp); Name name = ReverseMap.fromAddress(hostIp);
@@ -72,9 +75,10 @@ public class DnsLookup {
*/ */
public static String forward(String hostname) public static String forward(String hostname)
throws IOException { throws IOException {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
Resolver res = new ExtendedResolver(); Resolver res = new ExtendedResolver();
int timeout = ConfigurationManager.getIntProperty("usage-statistics", int timeout = configurationService.getIntProperty("usage-statistics.resolver.timeout", 200);
"resolver.timeout", 200);
res.setTimeout(0, timeout); res.setTimeout(0, timeout);
Name name = Name.fromString(hostname, Name.root); Name name = Name.fromString(hostname, Name.root);

View File

@@ -15,8 +15,10 @@ import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.InetAddress; import java.net.InetAddress;
import java.sql.SQLException;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@@ -27,6 +29,7 @@ import java.util.Random;
import java.util.UUID; import java.util.UUID;
import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.model.CityResponse;
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.CommandLineParser;
@@ -34,6 +37,7 @@ import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient;
@@ -49,10 +53,11 @@ import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.DSpaceObjectLegacySupportService; import org.dspace.content.service.DSpaceObjectLegacySupportService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.statistics.SolrLoggerServiceImpl; import org.dspace.statistics.SolrLoggerServiceImpl;
import org.dspace.statistics.factory.StatisticsServiceFactory; import org.dspace.statistics.factory.StatisticsServiceFactory;
import org.dspace.statistics.service.SolrLoggerService; import org.dspace.statistics.service.SolrLoggerService;
@@ -64,7 +69,7 @@ import org.dspace.statistics.service.SolrLoggerService;
* @see ClassicDSpaceLogConverter * @see ClassicDSpaceLogConverter
*/ */
public class StatisticsImporter { public class StatisticsImporter {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(StatisticsImporter.class); private static final Logger log = LogManager.getLogger(StatisticsImporter.class);
/** /**
* Date format (for solr) * Date format (for solr)
@@ -75,7 +80,11 @@ public class StatisticsImporter {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
} }
}; };
protected final SolrLoggerService solrLoggerService = StatisticsServiceFactory.getInstance().getSolrLoggerService();
protected final SolrLoggerService solrLoggerService
= StatisticsServiceFactory.getInstance().getSolrLoggerService();
protected static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Solr server connection * Solr server connection
@@ -176,7 +185,7 @@ public class StatisticsImporter {
} }
System.out.println("Found " + localBitstreams.size()); System.out.println("Found " + localBitstreams.size());
} catch (Exception e) { } catch (SQLException e) {
System.err.println("Error retrieving items from DSpace database:"); System.err.println("Error retrieving items from DSpace database:");
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
@@ -256,7 +265,7 @@ public class StatisticsImporter {
try { try {
dns = DnsLookup.reverseDns(ip); dns = DnsLookup.reverseDns(ip);
dnsCache.put(ip, dns); dnsCache.put(ip, dns);
} catch (Exception e) { } catch (IOException e) {
dns = ""; dns = "";
} }
} }
@@ -297,7 +306,7 @@ public class StatisticsImporter {
} }
continue; continue;
} }
} catch (Exception e) { } catch (GeoIp2Exception | IOException e) {
// No problem - just can't look them up // No problem - just can't look them up
} }
@@ -370,7 +379,7 @@ public class StatisticsImporter {
} catch (RuntimeException re) { } catch (RuntimeException re) {
throw re; throw re;
} catch (Exception e) { } catch (IOException | SQLException | ParseException | SolrServerException e) {
System.err.println(e.getMessage()); System.err.println(e.getMessage());
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
@@ -464,13 +473,13 @@ public class StatisticsImporter {
boolean verbose = line.hasOption('v'); boolean verbose = line.hasOption('v');
// Find our solr server // Find our solr server
String sserver = ConfigurationManager.getProperty("solr-statistics", "server"); String sserver = configurationService.getProperty("solr-statistics", "server");
if (verbose) { if (verbose) {
System.out.println("Writing to solr server at: " + sserver); System.out.println("Writing to solr server at: " + sserver);
} }
solr = new HttpSolrClient.Builder(sserver).build(); solr = new HttpSolrClient.Builder(sserver).build();
String dbPath = ConfigurationManager.getProperty("usage-statistics", "dbfile"); String dbPath = configurationService.getProperty("usage-statistics", "dbfile");
try { try {
File dbFile = new File(dbPath); File dbFile = new File(dbPath);
geoipLookup = new DatabaseReader.Builder(dbFile).build(); geoipLookup = new DatabaseReader.Builder(dbFile).build();

View File

@@ -12,6 +12,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Map; import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region; import com.amazonaws.regions.Region;
@@ -27,10 +28,12 @@ import com.amazonaws.services.s3.model.S3Object;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Utils; import org.dspace.core.Utils;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.annotation.Required;
/** /**
@@ -45,7 +48,7 @@ public class S3BitStoreService implements BitStoreService {
/** /**
* log4j log * log4j log
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(S3BitStoreService.class); private static final Logger log = LogManager.getLogger(S3BitStoreService.class);
/** /**
* Checksum algorithm * Checksum algorithm
@@ -71,6 +74,8 @@ public class S3BitStoreService implements BitStoreService {
*/ */
private AmazonS3 s3Service = null; private AmazonS3 s3Service = null;
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
public S3BitStoreService() { public S3BitStoreService() {
} }
@@ -81,6 +86,7 @@ public class S3BitStoreService implements BitStoreService {
* - secret key * - secret key
* - bucket name * - bucket name
*/ */
@Override
public void init() throws IOException { public void init() throws IOException {
if (StringUtils.isBlank(getAwsAccessKey()) || StringUtils.isBlank(getAwsSecretKey())) { if (StringUtils.isBlank(getAwsAccessKey()) || StringUtils.isBlank(getAwsSecretKey())) {
log.warn("Empty S3 access or secret"); log.warn("Empty S3 access or secret");
@@ -93,7 +99,7 @@ public class S3BitStoreService implements BitStoreService {
// bucket name // bucket name
if (StringUtils.isEmpty(bucketName)) { if (StringUtils.isEmpty(bucketName)) {
// get hostname of DSpace UI to use to name bucket // get hostname of DSpace UI to use to name bucket
String hostname = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url")); String hostname = Utils.getHostName(configurationService.getProperty("dspace.ui.url"));
bucketName = "dspace-asset-" + hostname; bucketName = "dspace-asset-" + hostname;
log.warn("S3 BucketName is not configured, setting default: " + bucketName); log.warn("S3 BucketName is not configured, setting default: " + bucketName);
} }
@@ -103,7 +109,7 @@ public class S3BitStoreService implements BitStoreService {
s3Service.createBucket(bucketName); s3Service.createBucket(bucketName);
log.info("Creating new S3 Bucket: " + bucketName); log.info("Creating new S3 Bucket: " + bucketName);
} }
} catch (Exception e) { } catch (AmazonClientException e) {
log.error(e); log.error(e);
throw new IOException(e); throw new IOException(e);
} }
@@ -129,6 +135,7 @@ public class S3BitStoreService implements BitStoreService {
* *
* @return a unique ID * @return a unique ID
*/ */
@Override
public String generateId() { public String generateId() {
return Utils.generateKey(); return Utils.generateKey();
} }
@@ -141,12 +148,13 @@ public class S3BitStoreService implements BitStoreService {
* @return The stream of bits, or null * @return The stream of bits, or null
* @throws java.io.IOException If a problem occurs while retrieving the bits * @throws java.io.IOException If a problem occurs while retrieving the bits
*/ */
@Override
public InputStream get(Bitstream bitstream) throws IOException { public InputStream get(Bitstream bitstream) throws IOException {
String key = getFullKey(bitstream.getInternalId()); String key = getFullKey(bitstream.getInternalId());
try { try {
S3Object object = s3Service.getObject(new GetObjectRequest(bucketName, key)); S3Object object = s3Service.getObject(new GetObjectRequest(bucketName, key));
return (object != null) ? object.getObjectContent() : null; return (object != null) ? object.getObjectContent() : null;
} catch (Exception e) { } catch (AmazonClientException e) {
log.error("get(" + key + ")", e); log.error("get(" + key + ")", e);
throw new IOException(e); throw new IOException(e);
} }
@@ -163,6 +171,7 @@ public class S3BitStoreService implements BitStoreService {
* @param in The stream of bits to store * @param in The stream of bits to store
* @throws java.io.IOException If a problem occurs while storing the bits * @throws java.io.IOException If a problem occurs while storing the bits
*/ */
@Override
public void put(Bitstream bitstream, InputStream in) throws IOException { public void put(Bitstream bitstream, InputStream in) throws IOException {
String key = getFullKey(bitstream.getInternalId()); String key = getFullKey(bitstream.getInternalId());
//Copy istream to temp file, and send the file, with some metadata //Copy istream to temp file, and send the file, with some metadata
@@ -180,7 +189,7 @@ public class S3BitStoreService implements BitStoreService {
scratchFile.delete(); scratchFile.delete();
} catch (Exception e) { } catch (AmazonClientException | IOException e) {
log.error("put(" + bitstream.getInternalId() + ", is)", e); log.error("put(" + bitstream.getInternalId() + ", is)", e);
throw new IOException(e); throw new IOException(e);
} finally { } finally {
@@ -203,6 +212,7 @@ public class S3BitStoreService implements BitStoreService {
* If file not found, then return null * If file not found, then return null
* @throws java.io.IOException If a problem occurs while obtaining metadata * @throws java.io.IOException If a problem occurs while obtaining metadata
*/ */
@Override
public Map about(Bitstream bitstream, Map attrs) throws IOException { public Map about(Bitstream bitstream, Map attrs) throws IOException {
String key = getFullKey(bitstream.getInternalId()); String key = getFullKey(bitstream.getInternalId());
try { try {
@@ -225,7 +235,7 @@ public class S3BitStoreService implements BitStoreService {
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
return null; return null;
} }
} catch (Exception e) { } catch (AmazonClientException e) {
log.error("about(" + key + ", attrs)", e); log.error("about(" + key + ", attrs)", e);
throw new IOException(e); throw new IOException(e);
} }
@@ -238,11 +248,12 @@ public class S3BitStoreService implements BitStoreService {
* @param bitstream The asset to delete * @param bitstream The asset to delete
* @throws java.io.IOException If a problem occurs while removing the asset * @throws java.io.IOException If a problem occurs while removing the asset
*/ */
@Override
public void remove(Bitstream bitstream) throws IOException { public void remove(Bitstream bitstream) throws IOException {
String key = getFullKey(bitstream.getInternalId()); String key = getFullKey(bitstream.getInternalId());
try { try {
s3Service.deleteObject(bucketName, key); s3Service.deleteObject(bucketName, key);
} catch (Exception e) { } catch (AmazonClientException e) {
log.error("remove(" + key + ")", e); log.error("remove(" + key + ")", e);
throw new IOException(e); throw new IOException(e);
} }
@@ -345,7 +356,7 @@ public class S3BitStoreService implements BitStoreService {
store.s3Service.setRegion(usEast1); store.s3Service.setRegion(usEast1);
// get hostname of DSpace UI to use to name bucket // get hostname of DSpace UI to use to name bucket
String hostname = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url")); String hostname = Utils.getHostName(configurationService.getProperty("dspace.ui.url"));
//Bucketname should be lowercase //Bucketname should be lowercase
store.bucketName = "dspace-asset-" + hostname + ".s3test"; store.bucketName = "dspace-asset-" + hostname + ".s3test";
store.s3Service.createBucket(store.bucketName); store.s3Service.createBucket(store.bucketName);

View File

@@ -8,12 +8,14 @@
package org.dspace.submit.lookup; package org.dspace.submit.lookup;
import java.io.File; import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import gr.ekt.bte.core.Record; import gr.ekt.bte.core.Record;
import gr.ekt.bte.core.Value; import gr.ekt.bte.core.Value;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.MetadataSchema; import org.dspace.content.MetadataSchema;
@@ -21,8 +23,9 @@ import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.MetadataSchemaService; import org.dspace.content.service.MetadataSchemaService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* @author Andrea Bollini * @author Andrea Bollini
@@ -31,17 +34,19 @@ import org.dspace.core.Context;
* @author Panagiotis Koutsourakis * @author Panagiotis Koutsourakis
*/ */
public class SubmissionLookupUtils { public class SubmissionLookupUtils {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(SubmissionLookupUtils.class); private static final Logger log = LogManager.getLogger(SubmissionLookupUtils.class);
/** /**
* Default constructor * Default constructor
*/ */
private SubmissionLookupUtils() { } private SubmissionLookupUtils() { }
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Location of config file * Location of config file
*/ */
private static final String configFilePath = ConfigurationManager private static final String configFilePath = configurationService
.getProperty("dspace.dir") .getProperty("dspace.dir")
+ File.separator + File.separator
+ "config" + "config"
@@ -69,7 +74,7 @@ public class SubmissionLookupUtils {
SubmissionLookupService.SL_NAMESPACE_PREFIX)) { SubmissionLookupService.SL_NAMESPACE_PREFIX)) {
List<MetadataValue> slCache = itemService.getMetadata(item, schema.getName(), List<MetadataValue> slCache = itemService.getMetadata(item, schema.getName(),
dcElement, dcQualifier, Item.ANY); dcElement, dcQualifier, Item.ANY);
if (slCache.size() == 0) { if (slCache.isEmpty()) {
continue; continue;
} }
@@ -95,7 +100,7 @@ public class SubmissionLookupUtils {
} }
} }
return check; return check;
} catch (Exception e) { } catch (SQLException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e);
} }
@@ -121,7 +126,7 @@ public class SubmissionLookupUtils {
} }
public static List<String> getValues(Record rec, String field) { public static List<String> getValues(Record rec, String field) {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<>();
List<Value> values = rec.getValues(field); List<Value> values = rec.getValues(field);
if (values != null && values.size() > 0) { if (values != null && values.size() > 0) {
for (Value value : values) { for (Value value : values) {
@@ -137,10 +142,10 @@ public class SubmissionLookupUtils {
result.append("\nPublication {\n"); result.append("\nPublication {\n");
for (String field : record.getFields()) { for (String field : record.getFields()) {
result.append("--" + field + ":\n"); result.append("--").append(field).append(":\n");
List<Value> values = record.getValues(field); List<Value> values = record.getValues(field);
for (Value value : values) { for (Value value : values) {
result.append("\t" + value.getAsString() + "\n"); result.append("\t").append(value.getAsString()).append("\n");
} }
} }

View File

@@ -28,6 +28,7 @@ import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.PosixParser;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.SolrServerException;
@@ -43,7 +44,8 @@ import org.apache.solr.client.solrj.response.RangeFacet;
import org.apache.solr.common.luke.FieldFlag; import org.apache.solr.common.luke.FieldFlag;
import org.apache.solr.common.params.CoreAdminParams; import org.apache.solr.common.params.CoreAdminParams;
import org.apache.solr.common.params.FacetParams; import org.apache.solr.common.params.FacetParams;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Utility class to export, clear and import Solr indexes. * Utility class to export, clear and import Solr indexes.
@@ -95,7 +97,9 @@ public class SolrImportExport {
private static final String MULTIPLE_VALUES_SPLITTER = ","; private static final String MULTIPLE_VALUES_SPLITTER = ",";
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SolrImportExport.class); private static final Logger log = LogManager.getLogger(SolrImportExport.class);
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Default constructor * Default constructor
@@ -248,8 +252,8 @@ public class SolrImportExport {
//The configuration details for the statistics shards reside within the "statistics" folder //The configuration details for the statistics shards reside within the "statistics" folder
String instanceIndexName = indexName.startsWith("statistics-") ? "statistics" : indexName; String instanceIndexName = indexName.startsWith("statistics-") ? "statistics" : indexName;
String solrInstanceDir = ConfigurationManager String solrInstanceDir = configurationService.getProperty("dspace.dir")
.getProperty("dspace.dir") + File.separator + "solr" + File.separator + instanceIndexName; + File.separator + "solr" + File.separator + instanceIndexName;
// the [dspace]/solr/[indexName]/conf directory needs to be available on the local machine for this to work // the [dspace]/solr/[indexName]/conf directory needs to be available on the local machine for this to work
// -- we need access to the schema.xml and solrconfig.xml file, plus files referenced from there // -- we need access to the schema.xml and solrconfig.xml file, plus files referenced from there
// if this directory can't be found, output an error message and skip this index // if this directory can't be found, output an error message and skip this index
@@ -294,7 +298,7 @@ public class SolrImportExport {
} }
// Create a temp directory to store temporary core data // Create a temp directory to store temporary core data
File tempDataDir = new File(ConfigurationManager.getProperty( File tempDataDir = new File(configurationService.getProperty(
"dspace.dir") + File.separator + "temp" + File.separator + "solr-data"); "dspace.dir") + File.separator + "temp" + File.separator + "solr-data");
boolean createdTempDataDir = tempDataDir.mkdirs(); boolean createdTempDataDir = tempDataDir.mkdirs();
if (!createdTempDataDir && !tempDataDir.exists()) { if (!createdTempDataDir && !tempDataDir.exists()) {
@@ -334,7 +338,7 @@ public class SolrImportExport {
// clear actual core (temp core name, clearing actual data dir) & import // clear actual core (temp core name, clearing actual data dir) & import
importIndex(indexName, exportDir, tempSolrUrl, true); importIndex(indexName, exportDir, tempSolrUrl, true);
} catch (Exception e) { } catch (IOException | SolrServerException | SolrImportExportException e) {
// we ran into some problems with the export/import -- keep going to try and restore the solr cores // we ran into some problems with the export/import -- keep going to try and restore the solr cores
System.err.println( System.err.println(
"Encountered problem during reindex: " + e.getMessage() + ", will attempt to restore Solr cores"); "Encountered problem during reindex: " + e.getMessage() + ", will attempt to restore Solr cores");
@@ -406,7 +410,6 @@ public class SolrImportExport {
* and ends with .csv (to match what is generated by #makeExportFilename). * and ends with .csv (to match what is generated by #makeExportFilename).
* @param solrUrl The solr URL for the index to export. Must not be null. * @param solrUrl The solr URL for the index to export. Must not be null.
* @param clear if true, clear the index before importing. * @param clear if true, clear the index before importing.
* @param overwrite if true, skip _version_ field on import to disable Solr's optimistic concurrency functionality
* @throws IOException if there is a problem reading the files or communicating with Solr. * @throws IOException if there is a problem reading the files or communicating with Solr.
* @throws SolrServerException if there is a problem reading the files or communicating with Solr. * @throws SolrServerException if there is a problem reading the files or communicating with Solr.
* @throws SolrImportExportException if there is a problem communicating with Solr. * @throws SolrImportExportException if there is a problem communicating with Solr.
@@ -659,7 +662,8 @@ public class SolrImportExport {
if (StringUtils.isNotBlank(directoryValue)) { if (StringUtils.isNotBlank(directoryValue)) {
return directoryValue; return directoryValue;
} }
return ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr-export" + File.separator; return configurationService.getProperty("dspace.dir")
+ File.separator + "solr-export" + File.separator;
} }
/** /**
@@ -695,10 +699,10 @@ public class SolrImportExport {
private static String makeSolrUrl(String indexName) { private static String makeSolrUrl(String indexName) {
if (indexName.startsWith("statistics")) { if (indexName.startsWith("statistics")) {
// TODO account for year shards properly? // TODO account for year shards properly?
return ConfigurationManager.getProperty("solr-statistics", "server") + indexName return configurationService.getProperty("solr-statistics.server") + indexName
.replaceFirst("statistics", ""); .replaceFirst("statistics", "");
} else if ("authority".equals(indexName)) { } else if ("authority".equals(indexName)) {
return ConfigurationManager.getProperty("solr.authority.server"); return configurationService.getProperty("solr.authority.server");
} }
return "http://localhost:8080/solr/" + indexName; // TODO better default? return "http://localhost:8080/solr/" + indexName; // TODO better default?
} }

View File

@@ -17,7 +17,8 @@ import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import org.apache.xpath.XPathAPI; import org.apache.xpath.XPathAPI;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
@@ -57,8 +58,12 @@ public class ControlledVocabulary {
public static ControlledVocabulary loadVocabulary(String fileName) public static ControlledVocabulary loadVocabulary(String fileName)
throws IOException, SAXException, ParserConfigurationException, TransformerException { throws IOException, SAXException, ParserConfigurationException, TransformerException {
StringBuilder filePath = new StringBuilder(); StringBuilder filePath = new StringBuilder();
filePath.append(ConfigurationManager.getProperty("dspace.dir")).append(File.separatorChar).append("config") ConfigurationService configurationService
.append(File.separatorChar).append("controlled-vocabularies").append(File.separator).append(fileName) = DSpaceServicesFactory.getInstance().getConfigurationService();
filePath.append(configurationService.getProperty("dspace.dir"))
.append(File.separatorChar).append("config")
.append(File.separatorChar).append("controlled-vocabularies")
.append(File.separator).append(fileName)
.append(".xml"); .append(".xml");
File controlledVocFile = new File(filePath.toString()); File controlledVocFile = new File(filePath.toString());
@@ -99,7 +104,7 @@ public class ControlledVocabulary {
} }
NodeList subNodes = XPathAPI.selectNodeList(node, "isComposedBy/node"); NodeList subNodes = XPathAPI.selectNodeList(node, "isComposedBy/node");
List<ControlledVocabulary> subVocabularies = new ArrayList<ControlledVocabulary>(subNodes.getLength()); List<ControlledVocabulary> subVocabularies = new ArrayList<>(subNodes.getLength());
for (int i = 0; i < subNodes.getLength(); i++) { for (int i = 0; i < subNodes.getLength(); i++) {
subVocabularies.add(loadVocabularyNode(subNodes.item(i), value)); subVocabularies.add(loadVocabularyNode(subNodes.item(i), value));
} }

View File

@@ -15,20 +15,23 @@ import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.util.Util; import org.dspace.app.util.Util;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.GroupService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.xmlworkflow.factory.XmlWorkflowFactory; import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
import org.dspace.xmlworkflow.factory.XmlWorkflowServiceFactory; import org.dspace.xmlworkflow.factory.XmlWorkflowServiceFactory;
import org.dspace.xmlworkflow.state.Workflow; import org.dspace.xmlworkflow.state.Workflow;
@@ -47,13 +50,15 @@ public class WorkflowUtils extends Util {
/** /**
* log4j category * log4j category
*/ */
public static Logger log = org.apache.logging.log4j.LogManager.getLogger(WorkflowUtils.class); public static Logger log = LogManager.getLogger(WorkflowUtils.class);
protected static final CollectionRoleService collectionRoleService = protected static final CollectionRoleService collectionRoleService =
XmlWorkflowServiceFactory.getInstance().getCollectionRoleService(); XmlWorkflowServiceFactory.getInstance().getCollectionRoleService();
protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
protected static final XmlWorkflowFactory xmlWorkflowFactory = XmlWorkflowServiceFactory.getInstance() protected static final XmlWorkflowFactory xmlWorkflowFactory = XmlWorkflowServiceFactory.getInstance()
.getWorkflowFactory(); .getWorkflowFactory();
protected static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Default constructor * Default constructor
@@ -153,15 +158,13 @@ public class WorkflowUtils extends Util {
Context c = (Context) request.getAttribute("dspace.context"); Context c = (Context) request.getAttribute("dspace.context");
try { try {
String recipient = ConfigurationManager String recipient = configurationService.getProperty("alert.recipient");
.getProperty("alert.recipient");
if (StringUtils.isNotBlank(recipient)) { if (StringUtils.isNotBlank(recipient)) {
Email email = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), "internal_error")); Email email = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), "internal_error"));
email.addRecipient(recipient); email.addRecipient(recipient);
email.addArgument(ConfigurationManager email.addArgument(configurationService.getProperty("dspace.ui.url"));
.getProperty("dspace.ui.url"));
email.addArgument(new Date()); email.addArgument(new Date());
email.addArgument(request.getSession().getId()); email.addArgument(request.getSession().getId());
email.addArgument(logInfo); email.addArgument(logInfo);
@@ -181,7 +184,7 @@ public class WorkflowUtils extends Util {
email.addArgument(stackTrace); email.addArgument(stackTrace);
email.send(); email.send();
} }
} catch (Exception e) { } catch (IOException | MessagingException e) {
// Not much we can do here! // Not much we can do here!
log.warn("Unable to send email alert", e); log.warn("Unable to send email alert", e);
} }
@@ -239,7 +242,7 @@ public class WorkflowUtils extends Util {
public static Map<String, Role> getCollectionRoles(Collection thisCollection) public static Map<String, Role> getCollectionRoles(Collection thisCollection)
throws IOException, WorkflowConfigurationException, SQLException { throws IOException, WorkflowConfigurationException, SQLException {
Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection); Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection);
LinkedHashMap<String, Role> result = new LinkedHashMap<String, Role>(); LinkedHashMap<String, Role> result = new LinkedHashMap<>();
if (workflow != null) { if (workflow != null) {
//Make sure we find one //Make sure we find one
Map<String, Role> allRoles = workflow.getRoles(); Map<String, Role> allRoles = workflow.getRoles();
@@ -260,7 +263,7 @@ public class WorkflowUtils extends Util {
public static Map<String, Role> getCollectionAndRepositoryRoles(Collection thisCollection) public static Map<String, Role> getCollectionAndRepositoryRoles(Collection thisCollection)
throws IOException, WorkflowConfigurationException, SQLException { throws IOException, WorkflowConfigurationException, SQLException {
Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection); Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection);
LinkedHashMap<String, Role> result = new LinkedHashMap<String, Role>(); LinkedHashMap<String, Role> result = new LinkedHashMap<>();
if (workflow != null) { if (workflow != null) {
//Make sure we find one //Make sure we find one
Map<String, Role> allRoles = workflow.getRoles(); Map<String, Role> allRoles = workflow.getRoles();
@@ -282,7 +285,7 @@ public class WorkflowUtils extends Util {
public static Map<String, Role> getAllExternalRoles(Collection thisCollection) public static Map<String, Role> getAllExternalRoles(Collection thisCollection)
throws IOException, WorkflowConfigurationException, SQLException { throws IOException, WorkflowConfigurationException, SQLException {
Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection); Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection);
LinkedHashMap<String, Role> result = new LinkedHashMap<String, Role>(); LinkedHashMap<String, Role> result = new LinkedHashMap<>();
if (workflow != null) { if (workflow != null) {
//Make sure we find one //Make sure we find one
Map<String, Role> allRoles = workflow.getRoles(); Map<String, Role> allRoles = workflow.getRoles();

View File

@@ -40,7 +40,6 @@ import org.dspace.content.service.BundleService;
import org.dspace.content.service.InstallItemService; import org.dspace.content.service.InstallItemService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
@@ -51,6 +50,7 @@ import org.dspace.eperson.Group;
import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.GroupService;
import org.dspace.event.Event; import org.dspace.event.Event;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.usage.UsageWorkflowEvent; import org.dspace.usage.UsageWorkflowEvent;
import org.dspace.workflow.WorkflowException; import org.dspace.workflow.WorkflowException;
@@ -88,7 +88,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
/* support for 'no notification' */ /* support for 'no notification' */
protected Map<UUID, Boolean> noEMail = new HashMap<>(); protected Map<UUID, Boolean> noEMail = new HashMap<>();
private Logger log = org.apache.logging.log4j.LogManager.getLogger(XmlWorkflowServiceImpl.class); private final Logger log = org.apache.logging.log4j.LogManager.getLogger(XmlWorkflowServiceImpl.class);
@Autowired(required = true) @Autowired(required = true)
protected AuthorizeService authorizeService; protected AuthorizeService authorizeService;
@@ -122,6 +122,8 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
protected BitstreamFormatService bitstreamFormatService; protected BitstreamFormatService bitstreamFormatService;
@Autowired(required = true) @Autowired(required = true)
protected BitstreamService bitstreamService; protected BitstreamService bitstreamService;
@Autowired(required = true)
protected ConfigurationService configurationService;
protected XmlWorkflowServiceImpl() { protected XmlWorkflowServiceImpl() {
@@ -137,7 +139,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
@Override @Override
public List<String> getEPersonDeleteConstraints(Context context, EPerson ePerson) throws SQLException { public List<String> getEPersonDeleteConstraints(Context context, EPerson ePerson) throws SQLException {
List<String> constraints = new ArrayList<String>(); List<String> constraints = new ArrayList<>();
if (CollectionUtils.isNotEmpty(claimedTaskService.findByEperson(context, ePerson))) { if (CollectionUtils.isNotEmpty(claimedTaskService.findByEperson(context, ePerson))) {
constraints.add("cwf_claimtask"); constraints.add("cwf_claimtask");
} }
@@ -237,7 +239,9 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
/** /**
* startWithoutNotify() starts the workflow normally, but disables * startWithoutNotify() starts the workflow normally, but disables
* notifications (useful for large imports,) for the first workflow step - * notifications (useful for large imports,) for the first workflow step -
* subsequent notifications happen normally * subsequent notifications happen normally.
* @param context the current DSpace session.
* @param wsi the submitted Item entering workflow.
*/ */
@Override @Override
public XmlWorkflowItem startWithoutNotify(Context context, WorkspaceItem wsi) public XmlWorkflowItem startWithoutNotify(Context context, WorkspaceItem wsi)
@@ -436,7 +440,8 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
return null; return null;
} }
} }
} catch (Exception e) { } catch (IOException | SQLException | AuthorizeException
| WorkflowException | WorkflowConfigurationException e) {
log.error("error while processing workflow outcome", e); log.error("error while processing workflow outcome", e);
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
@@ -463,8 +468,8 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
Collection myCollection = wfi.getCollection(); Collection myCollection = wfi.getCollection();
String workflowStepString = null; String workflowStepString = null;
List<EPerson> currentEpersonOwners = new ArrayList<EPerson>(); List<EPerson> currentEpersonOwners = new ArrayList<>();
List<Group> currentGroupOwners = new ArrayList<Group>(); List<Group> currentGroupOwners = new ArrayList<>();
//These are only null if our item is sent back to the submission //These are only null if our item is sent back to the submission
if (newStep != null && newActionConfig != null) { if (newStep != null && newActionConfig != null) {
workflowStepString = workflowId + "." + newStep.getId() + "." + newActionConfig.getId(); workflowStepString = workflowId + "." + newStep.getId() + "." + newActionConfig.getId();
@@ -497,7 +502,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
usageWorkflowEvent.setGroupOwners(currentGroupOwners.toArray(new Group[currentGroupOwners.size()])); usageWorkflowEvent.setGroupOwners(currentGroupOwners.toArray(new Group[currentGroupOwners.size()]));
DSpaceServicesFactory.getInstance().getEventService().fireEvent(usageWorkflowEvent); DSpaceServicesFactory.getInstance().getEventService().fireEvent(usageWorkflowEvent);
} catch (Exception e) { } catch (SQLException e) {
//Catch all errors we do not want our workflow to crash because the logging threw an exception //Catch all errors we do not want our workflow to crash because the logging threw an exception
log.error(LogManager.getHeader(c, "Error while logging workflow event", "Workflow Item: " + wfi.getID()), log.error(LogManager.getHeader(c, "Error while logging workflow event", "Workflow Item: " + wfi.getID()),
e); e);
@@ -736,11 +741,12 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
grantUserAllItemPolicies(context, wi.getItem(), e, ResourcePolicy.TYPE_WORKFLOW); grantUserAllItemPolicies(context, wi.getItem(), e, ResourcePolicy.TYPE_WORKFLOW);
} }
@Override
public void grantUserAllItemPolicies(Context context, Item item, EPerson epa, String policyType) public void grantUserAllItemPolicies(Context context, Item item, EPerson epa, String policyType)
throws AuthorizeException, SQLException { throws AuthorizeException, SQLException {
if (epa != null) { if (epa != null) {
//A list of policies the user has for this item //A list of policies the user has for this item
List<Integer> userHasPolicies = new ArrayList<Integer>(); List<Integer> userHasPolicies = new ArrayList<>();
List<ResourcePolicy> itempols = authorizeService.getPolicies(context, item); List<ResourcePolicy> itempols = authorizeService.getPolicies(context, item);
for (ResourcePolicy resourcePolicy : itempols) { for (ResourcePolicy resourcePolicy : itempols) {
if (epa.equals(resourcePolicy.getEPerson())) { if (epa.equals(resourcePolicy.getEPerson())) {
@@ -772,7 +778,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
throws AuthorizeException, SQLException { throws AuthorizeException, SQLException {
if (group != null) { if (group != null) {
//A list of policies the user has for this item //A list of policies the user has for this item
List<Integer> groupHasPolicies = new ArrayList<Integer>(); List<Integer> groupHasPolicies = new ArrayList<>();
List<ResourcePolicy> itempols = authorizeService.getPolicies(context, item); List<ResourcePolicy> itempols = authorizeService.getPolicies(context, item);
for (ResourcePolicy resourcePolicy : itempols) { for (ResourcePolicy resourcePolicy : itempols) {
if (group.equals(resourcePolicy.getGroup())) { if (group.equals(resourcePolicy.getGroup())) {
@@ -829,6 +835,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
} }
} }
@Override
public void removeUserItemPolicies(Context context, Item item, EPerson e) throws SQLException, AuthorizeException { public void removeUserItemPolicies(Context context, Item item, EPerson e) throws SQLException, AuthorizeException {
if (e != null && item.getSubmitter() != null) { if (e != null && item.getSubmitter() != null) {
//Also remove any lingering authorizations from this user //Also remove any lingering authorizations from this user
@@ -1088,13 +1095,13 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
email.addArgument(coll.getName()); email.addArgument(coll.getName());
email.addArgument(rejector); email.addArgument(rejector);
email.addArgument(reason); email.addArgument(reason);
email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/mydspace"); email.addArgument(configurationService.getProperty("dspace.ui.url") + "/mydspace");
email.send(); email.send();
} else { } else {
// DO nothing // DO nothing
} }
} catch (Exception ex) { } catch (IOException | MessagingException ex) {
// log this email error // log this email error
log.warn(LogManager.getHeader(c, "notify_of_reject", log.warn(LogManager.getHeader(c, "notify_of_reject",
"cannot email user" + " eperson_id" + e.getID() "cannot email user" + " eperson_id" + e.getID()
@@ -1105,7 +1112,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
@Override @Override
public String getMyDSpaceLink() { public String getMyDSpaceLink() {
return ConfigurationManager.getProperty("dspace.ui.url") + "/mydspace"; return configurationService.getProperty("dspace.ui.url") + "/mydspace";
} }
protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException { protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException {

View File

@@ -15,10 +15,11 @@ import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.xmlworkflow.Role; import org.dspace.xmlworkflow.Role;
import org.dspace.xmlworkflow.RoleMembers; import org.dspace.xmlworkflow.RoleMembers;
import org.dspace.xmlworkflow.WorkflowConfigurationException; import org.dspace.xmlworkflow.WorkflowConfigurationException;
@@ -38,6 +39,8 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
* @author Mark Diggory (markd at atmire dot com) * @author Mark Diggory (markd at atmire dot com)
*/ */
public class ClaimAction extends UserSelectionAction { public class ClaimAction extends UserSelectionAction {
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
@Override @Override
public void activate(Context context, XmlWorkflowItem wfItem) throws SQLException, IOException, AuthorizeException { public void activate(Context context, XmlWorkflowItem wfItem) throws SQLException, IOException, AuthorizeException {
@@ -105,7 +108,7 @@ public class ClaimAction extends UserSelectionAction {
//Create task for the users left //Create task for the users left
XmlWorkflowServiceFactory.getInstance().getXmlWorkflowService() XmlWorkflowServiceFactory.getInstance().getXmlWorkflowService()
.createPoolTasks(c, wfi, roleMembers, getParent().getStep(), getParent()); .createPoolTasks(c, wfi, roleMembers, getParent().getStep(), getParent());
if (ConfigurationManager.getBooleanProperty("workflow", "notify.returned.tasks", true)) { if (configurationService.getBooleanProperty("workflow.notify.returned.tasks", true)) {
alertUsersOnActivation(c, wfi, roleMembers); alertUsersOnActivation(c, wfi, roleMembers);
} }
@@ -135,7 +138,7 @@ public class ClaimAction extends UserSelectionAction {
RoleMembers roleMembers = role.getMembers(context, wfi); RoleMembers roleMembers = role.getMembers(context, wfi);
ArrayList<EPerson> epersons = roleMembers.getAllUniqueMembers(context); ArrayList<EPerson> epersons = roleMembers.getAllUniqueMembers(context);
return !(epersons.size() == 0 || step.getRequiredUsers() > epersons.size()); return !(epersons.isEmpty() || step.getRequiredUsers() > epersons.size());
} else { } else {
// We don't have a role and do have a UI so throw a workflow exception // We don't have a role and do have a UI so throw a workflow exception
throw new WorkflowConfigurationException( throw new WorkflowConfigurationException(

View File

@@ -17,13 +17,15 @@ import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.SiteService; import org.dspace.content.service.SiteService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -38,14 +40,17 @@ public class SiteTest extends AbstractUnitTest {
/** /**
* log4j category * log4j category
*/ */
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SiteTest.class); private static final Logger log = LogManager.getLogger(SiteTest.class);
/** /**
* Site instance for the tests * Site instance for the tests
*/ */
private Site s; private Site s;
private SiteService siteService = ContentServiceFactory.getInstance().getSiteService(); private final SiteService siteService
= ContentServiceFactory.getInstance().getSiteService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
@@ -105,8 +110,8 @@ public class SiteTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testGetHandle() { public void testGetHandle() {
assertThat("testGetHandle 0", s.getHandle(), equalTo(ConfigurationManager.getProperty("handle.prefix") assertThat("testGetHandle 0", s.getHandle(),
+ "/0")); equalTo(configurationService.getProperty("handle.prefix") + "/0"));
} }
/** /**
@@ -114,12 +119,13 @@ public class SiteTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testGetSiteHandle() { public void testGetSiteHandle() {
assertThat("testGetSiteHandle 0", s.getHandle(), equalTo(ConfigurationManager.getProperty("handle.prefix") assertThat("testGetSiteHandle 0", s.getHandle(),
+ "/0")); equalTo(configurationService.getProperty("handle.prefix") + "/0"));
} }
/** /**
* Test of find method, of class Site. * Test of find method, of class Site.
* @throws java.lang.Exception passed through.
*/ */
@Test @Test
public void testSiteFind() throws Exception { public void testSiteFind() throws Exception {
@@ -133,17 +139,19 @@ public class SiteTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testGetName() { public void testGetName() {
assertThat("testGetName 0", s.getName(), equalTo(ConfigurationManager.getProperty("dspace.name"))); assertThat("testGetName 0", s.getName(),
assertThat("testGetName 1", siteService.getName(s), equalTo(ConfigurationManager.getProperty("dspace.name"))); equalTo(configurationService.getProperty("dspace.name")));
assertThat("testGetName 1", siteService.getName(s),
equalTo(configurationService.getProperty("dspace.name")));
} }
/** /**
* Test of getURL method, of class Site. * Test of getURL method, of class Site.
*/ */
@Test @Test
public void testGetURL() { public void testGetURL() {
assertThat("testGetURL 0", s.getURL(), equalTo(ConfigurationManager.getProperty("dspace.ui.url"))); assertThat("testGetURL 0", s.getURL(),
equalTo(configurationService.getProperty("dspace.ui.url")));
} }
@Test @Test

View File

@@ -18,7 +18,8 @@ import com.lyncode.xoai.dataprovider.data.About;
import com.lyncode.xoai.dataprovider.data.Item; import com.lyncode.xoai.dataprovider.data.Item;
import com.lyncode.xoai.dataprovider.xml.xoai.Element; import com.lyncode.xoai.dataprovider.xml.xoai.Element;
import com.lyncode.xoai.dataprovider.xml.xoai.Element.Field; import com.lyncode.xoai.dataprovider.xml.xoai.Element.Field;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
@@ -29,7 +30,7 @@ public abstract class DSpaceItem implements Item {
} }
private static List<Element> flat(List<Element> input) { private static List<Element> flat(List<Element> input) {
List<Element> elems = new ArrayList<Element>(); List<Element> elems = new ArrayList<>();
for (Element e : input) { for (Element e : input) {
if (e.getElement() != null) { if (e.getElement() != null) {
elems.addAll(e.getElement()); elems.addAll(e.getElement());
@@ -39,7 +40,7 @@ public abstract class DSpaceItem implements Item {
} }
private static List<String> values(List<Element> input) { private static List<String> values(List<Element> input) {
List<String> elems = new ArrayList<String>(); List<String> elems = new ArrayList<>();
for (Element e : input) { for (Element e : input) {
if (e.getElement() != null && !e.getElement().isEmpty() && e.getElement().get(0).getField() != null) { if (e.getElement() != null && !e.getElement().isEmpty() && e.getElement().get(0).getField() != null) {
for (Field f : e.getElement().get(0).getField()) { for (Field f : e.getElement().get(0).getField()) {
@@ -68,8 +69,9 @@ public abstract class DSpaceItem implements Item {
public static String buildIdentifier(String handle) { public static String buildIdentifier(String handle) {
if (_prefix == null) { if (_prefix == null) {
_prefix = ConfigurationManager.getProperty("oai", ConfigurationService configurationService
"identifier.prefix"); = DSpaceServicesFactory.getInstance().getConfigurationService();
_prefix = configurationService.getProperty("oai.identifier.prefix");
} }
return "oai:" + _prefix + ":" + handle; return "oai:" + _prefix + ":" + handle;
} }
@@ -90,13 +92,13 @@ public abstract class DSpaceItem implements Item {
} else if (parts.length == 3) { } else if (parts.length == 3) {
return this.getMetadata(parts[0], parts[1], parts[2]); return this.getMetadata(parts[0], parts[1], parts[2]);
} else { } else {
return new ArrayList<String>(); return new ArrayList<>();
} }
} }
@Override @Override
public List<About> getAbout() { public List<About> getAbout() {
return new ArrayList<About>(); return new ArrayList<>();
} }
protected abstract String getHandle(); protected abstract String getHandle();
@@ -107,7 +109,7 @@ public abstract class DSpaceItem implements Item {
} }
private static class MetadataNamePredicate implements Predicate<Element> { private static class MetadataNamePredicate implements Predicate<Element> {
private String name; private final String name;
public MetadataNamePredicate(String n) { public MetadataNamePredicate(String n) {
name = n; name = n;

View File

@@ -27,9 +27,8 @@ import com.lyncode.xoai.dataprovider.xml.XmlOutputContext;
import com.lyncode.xoai.dataprovider.xml.oaipmh.OAIPMH; import com.lyncode.xoai.dataprovider.xml.oaipmh.OAIPMH;
import com.lyncode.xoai.util.Base64Utils; import com.lyncode.xoai.util.Base64Utils;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.xoai.services.api.cache.XOAICacheService; import org.dspace.xoai.services.api.cache.XOAICacheService;
import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.util.DateUtils; import org.dspace.xoai.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -39,9 +38,12 @@ public class DSpaceXOAICacheService implements XOAICacheService {
private static String baseDir; private static String baseDir;
private static String staticHead; private static String staticHead;
private static String getBaseDir() { @Autowired
ConfigurationService configurationService;
private String getBaseDir() {
if (baseDir == null) { if (baseDir == null) {
String dir = ConfigurationManager.getProperty("oai", "cache.dir") + REQUEST_DIR; String dir = configurationService.getProperty("oai.cache.dir") + REQUEST_DIR;
baseDir = dir; baseDir = dir;
} }
return baseDir; return baseDir;
@@ -61,10 +63,7 @@ public class DSpaceXOAICacheService implements XOAICacheService {
return staticHead + "<responseDate>" + DateUtils.format(date) + "</responseDate>"; return staticHead + "<responseDate>" + DateUtils.format(date) + "</responseDate>";
} }
@Autowired private final XOAIManager manager;
ConfigurationService configurationService;
private XOAIManager manager;
public DSpaceXOAICacheService(XOAIManager manager) { public DSpaceXOAICacheService(XOAIManager manager) {
this.manager = manager; this.manager = manager;
@@ -82,7 +81,7 @@ public class DSpaceXOAICacheService implements XOAICacheService {
@Override @Override
public boolean isActive() { public boolean isActive() {
return configurationService.getBooleanProperty("oai", "cache", true); return configurationService.getBooleanProperty("oai.cache", true);
} }
@Override @Override

View File

@@ -15,8 +15,9 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.xoai.services.api.cache.XOAILastCompilationCacheService; import org.dspace.xoai.services.api.cache.XOAILastCompilationCacheService;
import org.springframework.beans.factory.annotation.Autowired;
public class DSpaceXOAILastCompilationCacheService implements XOAILastCompilationCacheService { public class DSpaceXOAILastCompilationCacheService implements XOAILastCompilationCacheService {
@@ -31,9 +32,12 @@ public class DSpaceXOAILastCompilationCacheService implements XOAILastCompilatio
private static File file = null; private static File file = null;
private static File getFile() { @Autowired(required = true)
ConfigurationService configurationService;
private File getFile() {
if (file == null) { if (file == null) {
String dir = ConfigurationManager.getProperty("oai", "cache.dir") + DATEFILE; String dir = configurationService.getProperty("oai.cache.dir") + DATEFILE;
file = new File(dir); file = new File(dir);
} }
return file; return file;

View File

@@ -18,14 +18,20 @@ import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver; import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
public class DSpaceResourceResolver implements ResourceResolver { public class DSpaceResourceResolver implements ResourceResolver {
private static final TransformerFactory transformerFactory = TransformerFactory private static final TransformerFactory transformerFactory = TransformerFactory
.newInstance("net.sf.saxon.TransformerFactoryImpl", null); .newInstance("net.sf.saxon.TransformerFactoryImpl", null);
private final String basePath = ConfigurationManager.getProperty("oai", private final String basePath;
"config.dir");
public DSpaceResourceResolver() {
ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
basePath = configurationService.getProperty("oai.config.dir");
}
@Override @Override
public InputStream getResource(String path) throws IOException { public InputStream getResource(String path) throws IOException {

View File

@@ -13,7 +13,8 @@ import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
@@ -30,7 +31,9 @@ public class DSpaceSolrServer {
public static SolrClient getServer() throws SolrServerException { public static SolrClient getServer() throws SolrServerException {
if (_server == null) { if (_server == null) {
String serverUrl = ConfigurationManager.getProperty("oai.solr.url"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String serverUrl = configurationService.getProperty("oai.solr.url");
try { try {
_server = new HttpSolrClient.Builder(serverUrl).build(); _server = new HttpSolrClient.Builder(serverUrl).build();
log.debug("OAI Solr Server Initialized"); log.debug("OAI Solr Server Initialized");

View File

@@ -31,10 +31,11 @@ import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.RelationshipService; import org.dspace.content.service.RelationshipService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Utils; import org.dspace.core.Utils;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.xoai.data.DSpaceItem; import org.dspace.xoai.data.DSpaceItem;
/** /**
@@ -56,6 +57,8 @@ public class ItemUtils {
private static final BitstreamService bitstreamService private static final BitstreamService bitstreamService
= ContentServiceFactory.getInstance().getBitstreamService(); = ContentServiceFactory.getInstance().getBitstreamService();
private static final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Default constructor * Default constructor
*/ */
@@ -105,7 +108,7 @@ public class ItemUtils {
String url = ""; String url = "";
String bsName = bit.getName(); String bsName = bit.getName();
String sid = String.valueOf(bit.getSequenceID()); String sid = String.valueOf(bit.getSequenceID());
String baseUrl = ConfigurationManager.getProperty("oai", "bitstream.baseUrl"); String baseUrl = configurationService.getProperty("oai", "bitstream.baseUrl");
String handle = null; String handle = null;
// get handle of parent Item of this bitstream, if there // get handle of parent Item of this bitstream, if there
// is one: // is one:
@@ -284,9 +287,9 @@ public class ItemUtils {
// Repository Info // Repository Info
Element repository = create("repository"); Element repository = create("repository");
repository.getField().add(createValue("url", ConfigurationManager.getProperty("dspace.ui.url"))); repository.getField().add(createValue("url", configurationService.getProperty("dspace.ui.url")));
repository.getField().add(createValue("name", ConfigurationManager.getProperty("dspace.name"))); repository.getField().add(createValue("name", configurationService.getProperty("dspace.name")));
repository.getField().add(createValue("mail", ConfigurationManager.getProperty("mail.admin"))); repository.getField().add(createValue("mail", configurationService.getProperty("mail.admin")));
metadata.getElement().add(repository); metadata.getElement().add(repository);
// Licensing info // Licensing info

View File

@@ -71,10 +71,10 @@ import org.dspace.content.BitstreamFormat;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.DSpaceObjectService; import org.dspace.content.service.DSpaceObjectService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.services.RequestService; import org.dspace.services.RequestService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.util.UUIDUtils; import org.dspace.util.UUIDUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -134,7 +134,7 @@ public class Utils {
private ConfigurationService configurationService; private ConfigurationService configurationService;
/** Cache to support fast lookups of LinkRest method annotation information. */ /** Cache to support fast lookups of LinkRest method annotation information. */
private Map<Method, Optional<LinkRest>> linkAnnotationForMethod = new HashMap<>(); private final Map<Method, Optional<LinkRest>> linkAnnotationForMethod = new HashMap<>();
public <T> Page<T> getPage(List<T> fullContents, @Nullable Pageable optionalPageable) { public <T> Page<T> getPage(List<T> fullContents, @Nullable Pageable optionalPageable) {
Pageable pageable = getPageable(optionalPageable); Pageable pageable = getPageable(optionalPageable);
@@ -149,7 +149,7 @@ public class Utils {
pageContent = fullContents.subList(Math.toIntExact(pageable.getOffset()), pageContent = fullContents.subList(Math.toIntExact(pageable.getOffset()),
Math.toIntExact(pageable.getOffset()) + pageable.getPageSize()); Math.toIntExact(pageable.getOffset()) + pageable.getPageSize());
} }
return new PageImpl<T>(pageContent, pageable, total); return new PageImpl<>(pageContent, pageable, total);
} }
} }
@@ -304,11 +304,12 @@ public class Utils {
} }
/** /**
* Build the canonical representation of a metadata key in DSpace. ie * Build the canonical representation of a metadata key in DSpace. I.e.
* <schema>.<element>[.<qualifier>] * <schema>.<element>[.<qualifier>]
* *
* @param schema * @param schema
* @param element * @param element
* @param qualifier
* @return * @return
*/ */
public String getMetadataKey(String schema, String element, String qualifier) { public String getMetadataKey(String schema, String element, String qualifier) {
@@ -320,11 +321,11 @@ public class Utils {
* *
* @param multipartFile * @param multipartFile
* the multipartFile representing the uploaded file. Please note that it is a complex object including * the multipartFile representing the uploaded file. Please note that it is a complex object including
* additional information other than the binary like the orginal file name and the mimetype * additional information other than the binary like the original file name and the MIME type
* @param prefixTempName * @param prefixTempName
* the prefix to use to generate the filename of the temporary file * the prefix to use to generate the filename of the temporary file
* @param suffixTempName * @param suffixTempName
* the suffic to use to generate the filename of the temporary file * the suffix to use to generate the filename of the temporary file
* @return the temporary file on the server * @return the temporary file on the server
* @throws IOException * @throws IOException
* @throws FileNotFoundException * @throws FileNotFoundException
@@ -332,8 +333,10 @@ public class Utils {
public static File getFile(MultipartFile multipartFile, String prefixTempName, String suffixTempName) public static File getFile(MultipartFile multipartFile, String prefixTempName, String suffixTempName)
throws IOException, FileNotFoundException { throws IOException, FileNotFoundException {
// TODO after change item-submission into // TODO after change item-submission into
String tempDir = (ConfigurationManager.getProperty("upload.temp.dir") != null) ConfigurationService configurationService
? ConfigurationManager.getProperty("upload.temp.dir") = DSpaceServicesFactory.getInstance().getConfigurationService();
String tempDir = (configurationService.hasProperty("upload.temp.dir"))
? configurationService.getProperty("upload.temp.dir")
: System.getProperty("java.io.tmpdir"); : System.getProperty("java.io.tmpdir");
File uploadDir = new File(tempDir); File uploadDir = new File(tempDir);
if (!uploadDir.exists()) { if (!uploadDir.exists()) {
@@ -349,7 +352,7 @@ public class Utils {
} }
/** /**
* Return the filename part from a multipartFile upload that could eventually contains the fullpath on the client * Return the filename part from a multipartFile upload that could eventually contains the full path on the client
* *
* @param multipartFile * @param multipartFile

View File

@@ -10,13 +10,15 @@ package org.dspace.sword;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat; import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle; import org.dspace.content.Bundle;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.atom.Content; import org.purl.sword.atom.Content;
import org.purl.sword.atom.ContentType; import org.purl.sword.atom.ContentType;
import org.purl.sword.atom.InvalidMediaTypeException; import org.purl.sword.atom.InvalidMediaTypeException;
@@ -33,7 +35,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
/** /**
* logger * logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(BitstreamEntryGenerator.class); private static final Logger log = LogManager.getLogger(BitstreamEntryGenerator.class);
/** /**
* Create a new ATOM Entry generator which can provide a SWORD Entry for * Create a new ATOM Entry generator which can provide a SWORD Entry for
@@ -50,6 +52,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
* Add all the subject classifications from the bibliographic * Add all the subject classifications from the bibliographic
* metadata. * metadata.
*/ */
@Override
protected void addCategories() { protected void addCategories() {
// do nothing // do nothing
} }
@@ -57,6 +60,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
/** /**
* Set the content type that DSpace received. * Set the content type that DSpace received.
*/ */
@Override
protected void addContentElement() protected void addContentElement()
throws DSpaceSWORDException { throws DSpaceSWORDException {
try { try {
@@ -100,13 +104,16 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
* they can be used to access the resource over http (i.e. * they can be used to access the resource over http (i.e.
* a real URL). * a real URL).
*/ */
@Override
protected void addIdentifier() protected void addIdentifier()
throws DSpaceSWORDException { throws DSpaceSWORDException {
// if this is a deposit which is no op we can't do anything here // if this is a deposit which is no op we can't do anything here
if (this.deposit != null && this.deposit.isNoOp()) { if (this.deposit != null && this.deposit.isNoOp()) {
// just use the dspace url as the // just use the dspace url as the
// property // property
String cfg = ConfigurationManager.getProperty("dspace.ui.url"); ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
String cfg = configurationService.getProperty("dspace.ui.url");
entry.setId(cfg); entry.setId(cfg);
return; return;
@@ -119,7 +126,6 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
String bsurl = urlManager.getBitstreamUrl(this.bitstream); String bsurl = urlManager.getBitstreamUrl(this.bitstream);
entry.setId(bsurl); entry.setId(bsurl);
log.debug("Added identifier for bitstream with url=" + bsurl); log.debug("Added identifier for bitstream with url=" + bsurl);
return;
// FIXME: later on we will maybe have a workflow page supplied // FIXME: later on we will maybe have a workflow page supplied
// by the sword interface? // by the sword interface?
@@ -128,6 +134,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add links associated with this item. * Add links associated with this item.
*/ */
@Override
protected void addLinks() protected void addLinks()
throws DSpaceSWORDException { throws DSpaceSWORDException {
// if this is a deposit which is no op we can't do anything here // if this is a deposit which is no op we can't do anything here
@@ -163,14 +170,16 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the date of publication from the bibliographic metadata * Add the date of publication from the bibliographic metadata
*/ */
@Override
protected void addPublishDate() { protected void addPublishDate() {
// do nothing // do nothing
} }
/** /**
* Add rights information. This attaches an href to the URL * Add rights information. This attaches an href to the URL
* of the item's licence file * of the item's license file
*/ */
@Override
protected void addRights() protected void addRights()
throws DSpaceSWORDException { throws DSpaceSWORDException {
try { try {
@@ -219,6 +228,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the summary/abstract from the bibliographic metadata * Add the summary/abstract from the bibliographic metadata
*/ */
@Override
protected void addSummary() { protected void addSummary() {
// do nothing // do nothing
} }
@@ -226,6 +236,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the title from the bibliographic metadata * Add the title from the bibliographic metadata
*/ */
@Override
protected void addTitle() { protected void addTitle() {
Title title = new Title(); Title title = new Title();
title.setContent(this.bitstream.getName()); title.setContent(this.bitstream.getName());
@@ -237,6 +248,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the date that this item was last updated * Add the date that this item was last updated
*/ */
@Override
protected void addLastUpdatedDate() { protected void addLastUpdatedDate() {
// do nothing // do nothing
} }

View File

@@ -10,11 +10,13 @@ package org.dspace.sword;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.base.Collection; import org.purl.sword.base.Collection;
/** /**
@@ -25,12 +27,15 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator {
/** /**
* logger * logger
*/ */
private static Logger log = private static final Logger log =
org.apache.logging.log4j.LogManager.getLogger(CollectionCollectionGenerator.class); LogManager.getLogger(CollectionCollectionGenerator.class);
protected CollectionService collectionService = protected CollectionService collectionService =
ContentServiceFactory.getInstance().getCollectionService(); ContentServiceFactory.getInstance().getCollectionService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Construct an object taking the SWORD service instance an argument * Construct an object taking the SWORD service instance an argument
* *
@@ -48,6 +53,7 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator {
* @param dso target DSpace object * @param dso target DSpace object
* @throws DSpaceSWORDException can be thrown by the internals of the DSpace SWORD implementation * @throws DSpaceSWORDException can be thrown by the internals of the DSpace SWORD implementation
*/ */
@Override
public Collection buildCollection(DSpaceObject dso) public Collection buildCollection(DSpaceObject dso)
throws DSpaceSWORDException { throws DSpaceSWORDException {
if (!(dso instanceof org.dspace.content.Collection)) { if (!(dso instanceof org.dspace.content.Collection)) {
@@ -122,8 +128,8 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator {
// should we offer the items in the collection up as deposit // should we offer the items in the collection up as deposit
// targets? // targets?
boolean itemService = ConfigurationManager boolean itemService = configurationService
.getBooleanProperty("sword-server", "expose-items"); .getBooleanProperty("sword-server.expose-items");
if (itemService) { if (itemService) {
String subService = urlManager.constructSubServiceUrl(col); String subService = urlManager.constructSubServiceUrl(col);
scol.setService(subService); scol.setService(subService);

View File

@@ -12,6 +12,7 @@ import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
@@ -25,8 +26,9 @@ import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.BundleService; import org.dspace.content.service.BundleService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.base.Deposit; import org.purl.sword.base.Deposit;
import org.purl.sword.base.ErrorCodes; import org.purl.sword.base.ErrorCodes;
import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDErrorException;
@@ -40,7 +42,7 @@ public class CollectionDepositor extends Depositor {
/** /**
* logger * logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(CollectionDepositor.class); private static final Logger log = LogManager.getLogger(CollectionDepositor.class);
protected ItemService itemService = protected ItemService itemService =
ContentServiceFactory.getInstance().getItemService(); ContentServiceFactory.getInstance().getItemService();
@@ -54,6 +56,8 @@ public class CollectionDepositor extends Depositor {
protected BitstreamFormatService bitstreamFormatService = protected BitstreamFormatService bitstreamFormatService =
ContentServiceFactory.getInstance().getBitstreamFormatService(); ContentServiceFactory.getInstance().getBitstreamFormatService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* The DSpace Collection we are depositing into * The DSpace Collection we are depositing into
*/ */
@@ -90,6 +94,7 @@ public class CollectionDepositor extends Depositor {
* @throws SWORDErrorException on generic SWORD exception * @throws SWORDErrorException on generic SWORD exception
* @throws DSpaceSWORDException can be thrown by the internals of the DSpace SWORD implementation * @throws DSpaceSWORDException can be thrown by the internals of the DSpace SWORD implementation
*/ */
@Override
public DepositResult doDeposit(Deposit deposit) public DepositResult doDeposit(Deposit deposit)
throws SWORDErrorException, DSpaceSWORDException { throws SWORDErrorException, DSpaceSWORDException {
// get the things out of the service that we need // get the things out of the service that we need
@@ -145,7 +150,7 @@ public class CollectionDepositor extends Depositor {
// for a moment // for a moment
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
String bundleName = ConfigurationManager.getProperty( String bundleName = configurationService.getProperty(
"sword-server", "bundle.name"); "sword-server", "bundle.name");
if (bundleName == null || "".equals(bundleName)) { if (bundleName == null || "".equals(bundleName)) {
bundleName = "SWORD"; bundleName = "SWORD";
@@ -215,13 +220,14 @@ public class CollectionDepositor extends Depositor {
/** /**
* Reverse any changes which may have resulted as the consequence of a deposit. * Reverse any changes which may have resulted as the consequence of a deposit.
* *
* This is inteded for use during no-op deposits, and should be called at the * This is intended for use during no-op deposits, and should be called at the
* end of such a deposit process in order to remove any temporary files and * end of such a deposit process in order to remove any temporary files and
* to abort the database connection, so no changes are written. * to abort the database connection, so no changes are written.
* *
* @param result deposit result to undo * @param result deposit result to undo
* @throws DSpaceSWORDException can be thrown by the internals of the DSpace SWORD implementation * @throws DSpaceSWORDException can be thrown by the internals of the DSpace SWORD implementation
*/ */
@Override
public void undoDeposit(DepositResult result) throws DSpaceSWORDException { public void undoDeposit(DepositResult result) throws DSpaceSWORDException {
SWORDContext sc = swordService.getSwordContext(); SWORDContext sc = swordService.getSwordContext();

View File

@@ -11,13 +11,15 @@ import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.sql.SQLException; import java.sql.SQLException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* This class provides a single point of contact for * This class provides a single point of contact for
@@ -30,10 +32,12 @@ public class CollectionLocation {
/** /**
* Log4j logger * Log4j logger
*/ */
public static final Logger log = org.apache.logging.log4j.LogManager.getLogger(CollectionLocation.class); public static final Logger log = LogManager.getLogger(CollectionLocation.class);
protected HandleService handleService = HandleServiceFactory.getInstance() protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService(); .getHandleService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Obtain the deposit URL for the given collection. These URLs * Obtain the deposit URL for the given collection. These URLs
@@ -106,10 +110,10 @@ public class CollectionLocation {
*/ */
private String getBaseUrl() private String getBaseUrl()
throws DSpaceSWORDException { throws DSpaceSWORDException {
String depositUrl = ConfigurationManager.getProperty( String depositUrl = configurationService.getProperty(
"sword-server", "deposit.url"); "sword-server.deposit.url");
if (depositUrl == null || "".equals(depositUrl)) { if (depositUrl == null || "".equals(depositUrl)) {
String dspaceUrl = ConfigurationManager String dspaceUrl = configurationService
.getProperty("dspace.server.url"); .getProperty("dspace.server.url");
if (dspaceUrl == null || "".equals(dspaceUrl)) { if (dspaceUrl == null || "".equals(dspaceUrl)) {
throw new DSpaceSWORDException( throw new DSpaceSWORDException(

View File

@@ -10,7 +10,8 @@ package org.dspace.sword;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.atom.Author; import org.purl.sword.atom.Author;
import org.purl.sword.atom.Contributor; import org.purl.sword.atom.Contributor;
import org.purl.sword.atom.Generator; import org.purl.sword.atom.Generator;
@@ -196,8 +197,10 @@ public abstract class DSpaceATOMEntry {
* add the generator field content * add the generator field content
*/ */
protected void addGenerator() { protected void addGenerator() {
boolean identify = ConfigurationManager.getBooleanProperty( ConfigurationService configurationService
"sword-server", "identify-version"); = DSpaceServicesFactory.getInstance().getConfigurationService();
boolean identify = configurationService.getBooleanProperty(
"sword-server.identify-version");
SWORDUrlManager urlManager = swordService.getUrlManager(); SWORDUrlManager urlManager = swordService.getUrlManager();
String softwareUri = urlManager.getGeneratorUrl(); String softwareUri = urlManager.getGeneratorUrl();
if (identify) { if (identify) {

View File

@@ -25,8 +25,9 @@ import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.BundleService; import org.dspace.content.service.BundleService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.base.Deposit; import org.purl.sword.base.Deposit;
import org.purl.sword.base.ErrorCodes; import org.purl.sword.base.ErrorCodes;
import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDErrorException;
@@ -44,6 +45,9 @@ public class ItemDepositor extends Depositor {
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService(); .getInstance().getBitstreamFormatService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
private Item item; private Item item;
public ItemDepositor(SWORDService swordService, DSpaceObject dso) public ItemDepositor(SWORDService swordService, DSpaceObject dso)
@@ -59,6 +63,7 @@ public class ItemDepositor extends Depositor {
this.item = (Item) dso; this.item = (Item) dso;
} }
@Override
public DepositResult doDeposit(Deposit deposit) public DepositResult doDeposit(Deposit deposit)
throws SWORDErrorException, DSpaceSWORDException { throws SWORDErrorException, DSpaceSWORDException {
// get the things out of the service that we need // get the things out of the service that we need
@@ -108,8 +113,8 @@ public class ItemDepositor extends Depositor {
// for a moment // for a moment
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
String bundleName = ConfigurationManager String bundleName = configurationService
.getProperty("sword-server", "bundle.name"); .getProperty("sword-server.bundle.name");
if (StringUtils.isBlank(bundleName)) { if (StringUtils.isBlank(bundleName)) {
bundleName = "SWORD"; bundleName = "SWORD";
} }
@@ -175,6 +180,7 @@ public class ItemDepositor extends Depositor {
return result; return result;
} }
@Override
public void undoDeposit(DepositResult result) throws DSpaceSWORDException { public void undoDeposit(DepositResult result) throws DSpaceSWORDException {
try { try {
SWORDContext sc = swordService.getSwordContext(); SWORDContext sc = swordService.getSwordContext();

View File

@@ -11,6 +11,7 @@ import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat; import org.dspace.content.BitstreamFormat;
@@ -19,10 +20,11 @@ import org.dspace.content.DCDate;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.atom.Content; import org.purl.sword.atom.Content;
import org.purl.sword.atom.ContentType; import org.purl.sword.atom.ContentType;
import org.purl.sword.atom.InvalidMediaTypeException; import org.purl.sword.atom.InvalidMediaTypeException;
@@ -40,13 +42,15 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
/** /**
* logger * logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(ItemEntryGenerator.class); private static final Logger log = LogManager.getLogger(ItemEntryGenerator.class);
protected HandleService handleService = HandleServiceFactory.getInstance() protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService(); .getHandleService();
protected ItemService itemService = ContentServiceFactory.getInstance() protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService(); .getItemService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
protected ItemEntryGenerator(SWORDService service) { protected ItemEntryGenerator(SWORDService service) {
super(service); super(service);
@@ -56,6 +60,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
* Add all the subject classifications from the bibliographic * Add all the subject classifications from the bibliographic
* metadata. * metadata.
*/ */
@Override
protected void addCategories() { protected void addCategories() {
List<MetadataValue> dcv = itemService List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.subject.*"); .getMetadataByMetadataString(item, "dc.subject.*");
@@ -70,6 +75,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
* Set the content type that DSpace received. This is just * Set the content type that DSpace received. This is just
* "application/zip" in this default implementation. * "application/zip" in this default implementation.
*/ */
@Override
protected void addContentElement() protected void addContentElement()
throws DSpaceSWORDException { throws DSpaceSWORDException {
// get the things we need out of the service // get the things we need out of the service
@@ -83,11 +89,10 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
} }
if (StringUtils.isNotBlank(handle)) { if (StringUtils.isNotBlank(handle)) {
boolean keepOriginal = ConfigurationManager boolean keepOriginal = configurationService
.getBooleanProperty("sword-server", .getBooleanProperty("sword-server.keep-original-package");
"keep-original-package"); String swordBundle = configurationService
String swordBundle = ConfigurationManager .getProperty("sword-server.bundle.name");
.getProperty("sword-server", "bundle.name");
if (StringUtils.isBlank(swordBundle)) { if (StringUtils.isBlank(swordBundle)) {
swordBundle = "SWORD"; swordBundle = "SWORD";
} }
@@ -146,6 +151,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
* they can be used to access the resource over http (i.e. * they can be used to access the resource over http (i.e.
* a real URL). * a real URL).
*/ */
@Override
protected void addIdentifier() { protected void addIdentifier() {
// it's possible that the item hasn't been assigned a handle yet // it's possible that the item hasn't been assigned a handle yet
if (!this.deposit.isNoOp()) { if (!this.deposit.isNoOp()) {
@@ -162,7 +168,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
// if we get this far, then we just use the dspace url as the // if we get this far, then we just use the dspace url as the
// property // property
String cfg = ConfigurationManager.getProperty("dspace.ui.url"); String cfg = configurationService.getProperty("dspace.ui.url");
entry.setId(cfg); entry.setId(cfg);
// FIXME: later on we will maybe have a workflow page supplied // FIXME: later on we will maybe have a workflow page supplied
@@ -172,6 +178,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add links associated with this item. * Add links associated with this item.
*/ */
@Override
protected void addLinks() protected void addLinks()
throws DSpaceSWORDException { throws DSpaceSWORDException {
SWORDUrlManager urlManager = swordService.getUrlManager(); SWORDUrlManager urlManager = swordService.getUrlManager();
@@ -223,6 +230,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the date of publication from the bibliographic metadata * Add the date of publication from the bibliographic metadata
*/ */
@Override
protected void addPublishDate() { protected void addPublishDate() {
List<MetadataValue> dcv = itemService List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.date.issued"); .getMetadataByMetadataString(item, "dc.date.issued");
@@ -233,8 +241,9 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add rights information. This attaches an href to the URL * Add rights information. This attaches an href to the URL
* of the item's licence file * of the item's license file
*/ */
@Override
protected void addRights() protected void addRights()
throws DSpaceSWORDException { throws DSpaceSWORDException {
SWORDUrlManager urlManager = swordService.getUrlManager(); SWORDUrlManager urlManager = swordService.getUrlManager();
@@ -246,7 +255,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
return; return;
} }
String base = ConfigurationManager.getProperty("dspace.ui.url"); String base = configurationService.getProperty("dspace.ui.url");
// if there's no base URL, we are stuck // if there's no base URL, we are stuck
if (base == null) { if (base == null) {
@@ -275,6 +284,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the summary/abstract from the bibliographic metadata * Add the summary/abstract from the bibliographic metadata
*/ */
@Override
protected void addSummary() { protected void addSummary() {
List<MetadataValue> dcv = itemService List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.description.abstract"); .getMetadataByMetadataString(item, "dc.description.abstract");
@@ -291,6 +301,7 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the title from the bibliographic metadata * Add the title from the bibliographic metadata
*/ */
@Override
protected void addTitle() { protected void addTitle() {
List<MetadataValue> dcv = itemService List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.title"); .getMetadataByMetadataString(item, "dc.title");
@@ -307,9 +318,10 @@ public class ItemEntryGenerator extends DSpaceATOMEntry {
/** /**
* Add the date that this item was last updated * Add the date that this item was last updated
*/ */
@Override
protected void addLastUpdatedDate() { protected void addLastUpdatedDate() {
String config = ConfigurationManager String config = configurationService
.getProperty("sword-server", "updated.field"); .getProperty("sword-server.updated.field");
List<MetadataValue> dcv = itemService List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, config); .getMetadataByMetadataString(item, config);
if (dcv != null && dcv.size() == 1) { if (dcv != null && dcv.size() == 1) {

View File

@@ -27,7 +27,6 @@ import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
@@ -35,6 +34,8 @@ import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.base.AtomDocumentRequest; import org.purl.sword.base.AtomDocumentRequest;
import org.purl.sword.base.Deposit; import org.purl.sword.base.Deposit;
import org.purl.sword.base.ErrorCodes; import org.purl.sword.base.ErrorCodes;
@@ -53,7 +54,7 @@ public class SWORDAuthenticator {
/** /**
* logger * logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(SWORDAuthenticator.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SWORDAuthenticator.class);
protected AuthenticationService authenticationService = protected AuthenticationService authenticationService =
AuthenticateServiceFactory.getInstance().getAuthenticationService(); AuthenticateServiceFactory.getInstance().getAuthenticationService();
@@ -73,6 +74,9 @@ public class SWORDAuthenticator {
protected ItemService itemService = protected ItemService itemService =
ContentServiceFactory.getInstance().getItemService(); ContentServiceFactory.getInstance().getItemService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Does the given username and password authenticate for the * Does the given username and password authenticate for the
* given DSpace Context? * given DSpace Context?
@@ -263,8 +267,8 @@ public class SWORDAuthenticator {
} }
// first find out if we support on-behalf-of deposit // first find out if we support on-behalf-of deposit
boolean mediated = ConfigurationManager.getBooleanProperty( boolean mediated = configurationService.getBooleanProperty(
"sword-server", "on-behalf-of.enable"); "sword-server.on-behalf-of.enable");
if (!mediated && obo != null) { if (!mediated && obo != null) {
// user is trying to do a mediated deposit on a repository which does not support it // user is trying to do a mediated deposit on a repository which does not support it
log.error( log.error(

View File

@@ -12,6 +12,7 @@ import java.sql.SQLException;
import java.util.Date; import java.util.Date;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.DCDate; import org.dspace.content.DCDate;
@@ -21,11 +22,12 @@ import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.packager.PackageIngester; import org.dspace.content.packager.PackageIngester;
import org.dspace.content.packager.PackageParameters; import org.dspace.content.packager.PackageParameters;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.factory.CoreServiceFactory; import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.base.Deposit; import org.purl.sword.base.Deposit;
import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDErrorException;
@@ -34,15 +36,18 @@ public class SWORDMETSIngester implements SWORDIngester {
protected ItemService itemService = ContentServiceFactory.getInstance() protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService(); .getItemService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Log4j logger * Log4j logger
*/ */
public static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SWORDMETSIngester.class); public static final Logger log = LogManager.getLogger(SWORDMETSIngester.class);
/* (non-Javadoc) /* (non-Javadoc)
* @see org.dspace.sword.SWORDIngester#ingest(org.dspace.core.Context, org.purl.sword.base.Deposit) * @see org.dspace.sword.SWORDIngester#ingest(org.dspace.core.Context, org.purl.sword.base.Deposit)
*/ */
@Override
public DepositResult ingest(SWORDService service, Deposit deposit, public DepositResult ingest(SWORDService service, Deposit deposit,
DSpaceObject dso) DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException { throws DSpaceSWORDException, SWORDErrorException {
@@ -64,8 +69,7 @@ public class SWORDMETSIngester implements SWORDIngester {
File depositFile = deposit.getFile(); File depositFile = deposit.getFile();
// load the plugin manager for the required configuration // load the plugin manager for the required configuration
String cfg = ConfigurationManager.getProperty("sword-server", String cfg = configurationService.getProperty("sword-server.mets-ingester.package-ingester");
"mets-ingester.package-ingester");
if (cfg == null || "".equals(cfg)) { if (cfg == null || "".equals(cfg)) {
cfg = "METS"; // default to METS cfg = "METS"; // default to METS
} }
@@ -87,14 +91,14 @@ public class SWORDMETSIngester implements SWORDIngester {
params.setWorkflowEnabled(true); params.setWorkflowEnabled(true);
// Should restore mode be enabled, i.e. keep existing handle? // Should restore mode be enabled, i.e. keep existing handle?
if (ConfigurationManager if (configurationService
.getBooleanProperty("sword-server", "restore-mode.enable", .getBooleanProperty("sword-server.restore-mode.enable",
false)) { false)) {
params.setRestoreModeEnabled(true); params.setRestoreModeEnabled(true);
} }
// Whether or not to use the collection template // Whether or not to use the collection template
params.setUseCollectionTemplate(ConfigurationManager params.setUseCollectionTemplate(configurationService
.getBooleanProperty( .getBooleanProperty(
"mets.default.ingest.useCollectionTemplate", "mets.default.ingest.useCollectionTemplate",
false)); false));
@@ -181,8 +185,8 @@ public class SWORDMETSIngester implements SWORDIngester {
*/ */
private void setUpdatedDate(Context context, Item item) private void setUpdatedDate(Context context, Item item)
throws DSpaceSWORDException { throws DSpaceSWORDException {
String field = ConfigurationManager String field = configurationService
.getProperty("sword-server", "updated.field"); .getProperty("sword-server.updated.field");
if (field == null || "".equals(field)) { if (field == null || "".equals(field)) {
throw new DSpaceSWORDException( throw new DSpaceSWORDException(
"No configuration, or configuration is invalid for: sword.updated.field"); "No configuration, or configuration is invalid for: sword.updated.field");
@@ -221,8 +225,8 @@ public class SWORDMETSIngester implements SWORDIngester {
return; return;
} }
String field = ConfigurationManager String field = configurationService
.getProperty("sword-server", "slug.field"); .getProperty("sword-server.slug.field");
if (field == null || "".equals(field)) { if (field == null || "".equals(field)) {
throw new DSpaceSWORDException( throw new DSpaceSWORDException(
"No configuration, or configuration is invalid for: sword.slug.field"); "No configuration, or configuration is invalid for: sword.slug.field");

View File

@@ -21,10 +21,11 @@ import org.dspace.content.DSpaceObject;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDErrorException;
/** /**
@@ -37,12 +38,12 @@ public class SWORDUrlManager {
/** /**
* the SWORD configuration * the SWORD configuration
*/ */
private SWORDConfiguration config; private final SWORDConfiguration config;
/** /**
* the active DSpace context * the active DSpace context
*/ */
private Context context; private final Context context;
protected HandleService handleService = protected HandleService handleService =
HandleServiceFactory.getInstance().getHandleService(); HandleServiceFactory.getInstance().getHandleService();
@@ -50,6 +51,9 @@ public class SWORDUrlManager {
protected BitstreamService bitstreamService = protected BitstreamService bitstreamService =
ContentServiceFactory.getInstance().getBitstreamService(); ContentServiceFactory.getInstance().getBitstreamService();
private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
public SWORDUrlManager(SWORDConfiguration config, Context context) { public SWORDUrlManager(SWORDConfiguration config, Context context) {
this.config = config; this.config = config;
this.context = context; this.context = context;
@@ -62,8 +66,8 @@ public class SWORDUrlManager {
* @return the generator URL for ATOM entry documents * @return the generator URL for ATOM entry documents
*/ */
public String getGeneratorUrl() { public String getGeneratorUrl() {
String cfg = ConfigurationManager.getProperty( String cfg = configurationService.getProperty(
"sword-server", "generator.url"); "sword-server.generator.url");
if (cfg == null || "".equals(cfg)) { if (cfg == null || "".equals(cfg)) {
return SWORDProperties.SOFTWARE_URI; return SWORDProperties.SOFTWARE_URI;
} }
@@ -300,10 +304,10 @@ public class SWORDUrlManager {
*/ */
public String getBaseServiceDocumentUrl() public String getBaseServiceDocumentUrl()
throws DSpaceSWORDException { throws DSpaceSWORDException {
String depositUrl = ConfigurationManager.getProperty( String depositUrl = configurationService.getProperty(
"sword-server", "servicedocument.url"); "sword-server.servicedocument.url");
if (depositUrl == null || "".equals(depositUrl)) { if (depositUrl == null || "".equals(depositUrl)) {
String dspaceUrl = ConfigurationManager.getProperty( String dspaceUrl = configurationService.getProperty(
"dspace.server.url"); "dspace.server.url");
if (dspaceUrl == null || "".equals(dspaceUrl)) { if (dspaceUrl == null || "".equals(dspaceUrl)) {
throw new DSpaceSWORDException( throw new DSpaceSWORDException(
@@ -343,10 +347,10 @@ public class SWORDUrlManager {
*/ */
public String getBaseDepositUrl() public String getBaseDepositUrl()
throws DSpaceSWORDException { throws DSpaceSWORDException {
String depositUrl = ConfigurationManager.getProperty( String depositUrl = configurationService.getProperty(
"sword-server", "deposit.url"); "sword-server.deposit.url");
if (depositUrl == null || "".equals(depositUrl)) { if (depositUrl == null || "".equals(depositUrl)) {
String dspaceUrl = ConfigurationManager.getProperty( String dspaceUrl = configurationService.getProperty(
"dspace.server.url"); "dspace.server.url");
if (dspaceUrl == null || "".equals(dspaceUrl)) { if (dspaceUrl == null || "".equals(dspaceUrl)) {
throw new DSpaceSWORDException( throw new DSpaceSWORDException(
@@ -421,7 +425,7 @@ public class SWORDUrlManager {
} }
String handle = item.getHandle(); String handle = item.getHandle();
String bsLink = ConfigurationManager.getProperty("dspace.ui.url"); String bsLink = configurationService.getProperty("dspace.ui.url");
if (handle != null && !"".equals(handle)) { if (handle != null && !"".equals(handle)) {
bsLink = bsLink + "/bitstream/" + handle + "/" + bsLink = bsLink + "/bitstream/" + handle + "/" +
@@ -447,10 +451,10 @@ public class SWORDUrlManager {
*/ */
public String getBaseMediaLinkUrl() public String getBaseMediaLinkUrl()
throws DSpaceSWORDException { throws DSpaceSWORDException {
String mlUrl = ConfigurationManager.getProperty( String mlUrl = configurationService.getProperty(
"sword-server", "media-link.url"); "sword-server", "media-link.url");
if (StringUtils.isBlank(mlUrl)) { if (StringUtils.isBlank(mlUrl)) {
String dspaceUrl = ConfigurationManager.getProperty( String dspaceUrl = configurationService.getProperty(
"dspace.server.url"); "dspace.server.url");
if (dspaceUrl == null || "".equals(dspaceUrl)) { if (dspaceUrl == null || "".equals(dspaceUrl)) {
throw new DSpaceSWORDException( throw new DSpaceSWORDException(

View File

@@ -16,8 +16,9 @@ import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.purl.sword.atom.Generator; import org.purl.sword.atom.Generator;
import org.purl.sword.base.SWORDErrorException; import org.purl.sword.base.SWORDErrorException;
import org.purl.sword.base.Service; import org.purl.sword.base.Service;
@@ -31,9 +32,12 @@ public class ServiceDocumentManager {
protected CommunityService communityService = ContentServiceFactory protected CommunityService communityService = ContentServiceFactory
.getInstance().getCommunityService(); .getInstance().getCommunityService();
private SWORDService swordService; private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
private SWORDAuthenticator swordAuth; private final SWORDService swordService;
private final SWORDAuthenticator swordAuth;
public ServiceDocumentManager(SWORDService service) { public ServiceDocumentManager(SWORDService service) {
this.swordService = service; this.swordService = service;
@@ -97,13 +101,13 @@ public class ServiceDocumentManager {
// we are dealing with the default service document // we are dealing with the default service document
// set the title of the workspace as per the name of the DSpace installation // set the title of the workspace as per the name of the DSpace installation
String ws = ConfigurationManager.getProperty("dspace.name"); String ws = configurationService.getProperty("dspace.name");
Workspace workspace = new Workspace(); Workspace workspace = new Workspace();
workspace.setTitle(ws); workspace.setTitle(ws);
// next thing to do is determine whether the default is communities or collections // next thing to do is determine whether the default is communities or collections
boolean swordCommunities = ConfigurationManager.getBooleanProperty( boolean swordCommunities = configurationService.getBooleanProperty(
"sword-server", "expose-communities"); "sword-server.expose-communities");
if (swordCommunities) { if (swordCommunities) {
List<Community> comms = swordAuth.getAllowedCommunities( List<Community> comms = swordAuth.getAllowedCommunities(
@@ -178,8 +182,8 @@ public class ServiceDocumentManager {
* @param service The service document to add the generator to * @param service The service document to add the generator to
*/ */
private void addGenerator(Service service) { private void addGenerator(Service service) {
boolean identify = ConfigurationManager.getBooleanProperty( boolean identify = configurationService.getBooleanProperty(
"sword-server", "identify-version", false); "sword-server.identify-version", false);
SWORDUrlManager urlManager = swordService.getUrlManager(); SWORDUrlManager urlManager = swordService.getUrlManager();
String softwareUri = urlManager.getGeneratorUrl(); String softwareUri = urlManager.getGeneratorUrl();
if (identify) { if (identify) {

View File

@@ -17,7 +17,8 @@ import org.dspace.content.MetadataField;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
public class AbstractSimpleDC { public class AbstractSimpleDC {
protected HashMap<String, String> dcMap = null; protected HashMap<String, String> dcMap = null;
@@ -27,16 +28,18 @@ public class AbstractSimpleDC {
protected ItemService itemService = ContentServiceFactory.getInstance() protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService(); .getItemService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
protected void loadMetadataMaps() { protected void loadMetadataMaps() {
if (this.dcMap == null) { if (this.dcMap == null) {
// we should load our DC map from configuration // we should load our DC map from configuration
this.dcMap = new HashMap<>(); this.dcMap = new HashMap<>();
Properties props = ConfigurationManager Properties props = configurationService.getProperties();
.getProperties("swordv2-server");
for (Object key : props.keySet()) { for (Object key : props.keySet()) {
String keyString = (String) key; String keyString = (String) key;
if (keyString.startsWith("simpledc.")) { if (keyString.startsWith("swordv2-server.simpledc.")) {
String k = keyString.substring("simpledc.".length()); String k = keyString.substring("swordv2-server.simpledc.".length());
String v = (String) props.get(key); String v = (String) props.get(key);
this.dcMap.put(k, v); this.dcMap.put(k, v);
} }
@@ -45,12 +48,11 @@ public class AbstractSimpleDC {
if (this.atomMap == null) { if (this.atomMap == null) {
this.atomMap = new HashMap<>(); this.atomMap = new HashMap<>();
Properties props = ConfigurationManager Properties props = configurationService.getProperties();
.getProperties("swordv2-server");
for (Object key : props.keySet()) { for (Object key : props.keySet()) {
String keyString = (String) key; String keyString = (String) key;
if (keyString.startsWith("atom.")) { if (keyString.startsWith("swordv2-server.atom.")) {
String k = keyString.substring("atom.".length()); String k = keyString.substring("swordv2-server.atom.".length());
String v = (String) props.get(key); String v = (String) props.get(key);
this.atomMap.put(k, v); this.atomMap.put(k, v);
} }

View File

@@ -12,6 +12,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.BitstreamFormat; import org.dspace.content.BitstreamFormat;
import org.dspace.content.Collection; import org.dspace.content.Collection;
@@ -21,8 +22,9 @@ import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.swordapp.server.Deposit; import org.swordapp.server.Deposit;
import org.swordapp.server.SwordAuthException; import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordError; import org.swordapp.server.SwordError;
@@ -30,7 +32,7 @@ import org.swordapp.server.SwordServerException;
public abstract class AbstractSwordContentIngester public abstract class AbstractSwordContentIngester
implements SwordContentIngester { implements SwordContentIngester {
public static final Logger log = org.apache.logging.log4j.LogManager.getLogger( public static final Logger log = LogManager.getLogger(
AbstractSwordContentIngester.class); AbstractSwordContentIngester.class);
protected BitstreamFormatService bitstreamFormatService = protected BitstreamFormatService bitstreamFormatService =
@@ -39,6 +41,10 @@ public abstract class AbstractSwordContentIngester
protected ItemService itemService = protected ItemService itemService =
ContentServiceFactory.getInstance().getItemService(); ContentServiceFactory.getInstance().getItemService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
@Override
public DepositResult ingest(Context context, Deposit deposit, public DepositResult ingest(Context context, Deposit deposit,
DSpaceObject dso, VerboseDescription verboseDescription) DSpaceObject dso, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException, throws DSpaceSwordException, SwordError, SwordAuthException,
@@ -46,6 +52,7 @@ public abstract class AbstractSwordContentIngester
return this.ingest(context, deposit, dso, verboseDescription, null); return this.ingest(context, deposit, dso, verboseDescription, null);
} }
@Override
public DepositResult ingest(Context context, Deposit deposit, public DepositResult ingest(Context context, Deposit deposit,
DSpaceObject dso, VerboseDescription verboseDescription, DSpaceObject dso, VerboseDescription verboseDescription,
DepositResult result) DepositResult result)
@@ -110,8 +117,8 @@ public abstract class AbstractSwordContentIngester
protected void setUpdatedDate(Context context, Item item, protected void setUpdatedDate(Context context, Item item,
VerboseDescription verboseDescription) VerboseDescription verboseDescription)
throws DSpaceSwordException { throws DSpaceSwordException {
String field = ConfigurationManager String field = configurationService
.getProperty("swordv2-server", "updated.field"); .getProperty("swordv2-server.updated.field");
if (field == null || "".equals(field)) { if (field == null || "".equals(field)) {
throw new DSpaceSwordException( throw new DSpaceSwordException(
"No configuration, or configuration is invalid for: sword.updated.field"); "No configuration, or configuration is invalid for: sword.updated.field");
@@ -153,8 +160,8 @@ public abstract class AbstractSwordContentIngester
return; return;
} }
String field = ConfigurationManager String field = configurationService
.getProperty("swordv2-server", "slug.field"); .getProperty("swordv2-server.slug.field");
if (field == null || "".equals(field)) { if (field == null || "".equals(field)) {
throw new DSpaceSwordException( throw new DSpaceSwordException(
"No configuration, or configuration is invalid for: sword.slug.field"); "No configuration, or configuration is invalid for: sword.slug.field");

View File

@@ -13,8 +13,9 @@ import org.dspace.content.Item;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.swordapp.server.AtomStatement; import org.swordapp.server.AtomStatement;
import org.swordapp.server.Statement; import org.swordapp.server.Statement;
import org.swordapp.server.SwordError; import org.swordapp.server.SwordError;
@@ -24,19 +25,22 @@ public class AtomStatementDisseminator extends GenericStatementDisseminator
implements SwordStatementDisseminator { implements SwordStatementDisseminator {
protected ItemService itemService = ContentServiceFactory.getInstance() protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService(); .getItemService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
@Override
public Statement disseminate(Context context, Item item) public Statement disseminate(Context context, Item item)
throws DSpaceSwordException, SwordError, SwordServerException { throws DSpaceSwordException, SwordError, SwordServerException {
SwordUrlManager urlManager = new SwordUrlManager( SwordUrlManager urlManager = new SwordUrlManager(
new SwordConfigurationDSpace(), context); new SwordConfigurationDSpace(), context);
String feedUri = urlManager.getAtomStatementUri(item); String feedUri = urlManager.getAtomStatementUri(item);
String authorField = ConfigurationManager String authorField = configurationService
.getProperty("swordv2-server", "author.field"); .getProperty("swordv2-server.author.field");
String titleField = ConfigurationManager String titleField = configurationService
.getProperty("swordv2-server", "title.field"); .getProperty("swordv2-server.title.field");
String updatedField = ConfigurationManager String updatedField = configurationService
.getProperty("swordv2-server", "updated.field"); .getProperty("swordv2-server.updated.field");
String author = this.stringMetadata(item, authorField); String author = this.stringMetadata(item, authorField);
String title = this.stringMetadata(item, titleField); String title = this.stringMetadata(item, titleField);

View File

@@ -11,14 +11,16 @@ import java.util.List;
import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRI;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.swordapp.server.SwordCollection; import org.swordapp.server.SwordCollection;
/** /**
@@ -26,12 +28,15 @@ import org.swordapp.server.SwordCollection;
* DSpace Collections * DSpace Collections
*/ */
public class CollectionCollectionGenerator implements AtomCollectionGenerator { public class CollectionCollectionGenerator implements AtomCollectionGenerator {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger( private static final Logger log = LogManager.getLogger(
CommunityCollectionGenerator.class); CommunityCollectionGenerator.class);
protected CollectionService collectionService = protected CollectionService collectionService =
ContentServiceFactory.getInstance().getCollectionService(); ContentServiceFactory.getInstance().getCollectionService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
/** /**
* Build the collection for the given DSpaceObject. In this implementation, * Build the collection for the given DSpaceObject. In this implementation,
* if the object is not a DSpace Collection, it will throw DSpaceSwordException * if the object is not a DSpace Collection, it will throw DSpaceSwordException
@@ -41,6 +46,7 @@ public class CollectionCollectionGenerator implements AtomCollectionGenerator {
* @return the SWORD ATOM collection * @return the SWORD ATOM collection
* @throws DSpaceSwordException can be thrown by the internals of the DSpace SWORD implementation * @throws DSpaceSwordException can be thrown by the internals of the DSpace SWORD implementation
*/ */
@Override
public SwordCollection buildCollection(Context context, DSpaceObject dso, public SwordCollection buildCollection(Context context, DSpaceObject dso,
SwordConfigurationDSpace swordConfig) SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException { throws DSpaceSwordException {
@@ -118,7 +124,7 @@ public class CollectionCollectionGenerator implements AtomCollectionGenerator {
// should we offer the items in the collection up as deposit // should we offer the items in the collection up as deposit
// targets? // targets?
boolean itemService = ConfigurationManager.getBooleanProperty( boolean itemService = configurationService.getBooleanProperty(
"sword.expose-items"); "sword.expose-items");
if (itemService) { if (itemService) {
String subService = urlManager.constructSubServiceUrl(col); String subService = urlManager.constructSubServiceUrl(col);

View File

@@ -22,7 +22,6 @@ import org.dspace.content.MetadataValue;
import org.dspace.content.WorkspaceItem; import org.dspace.content.WorkspaceItem;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowItem;
@@ -43,6 +42,7 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI
protected WorkflowItemService workflowItemService = WorkflowServiceFactory protected WorkflowItemService workflowItemService = WorkflowServiceFactory
.getInstance().getWorkflowItemService(); .getInstance().getWorkflowItemService();
@Override
public Feed listCollectionContents(IRI colIRI, public Feed listCollectionContents(IRI colIRI,
AuthCredentials authCredentials, SwordConfiguration swordConfig) AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordServerException, SwordError, SwordAuthException { throws SwordServerException, SwordError, SwordAuthException {
@@ -84,8 +84,8 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI
for (Item item : items) { for (Item item : items) {
Entry entry = feed.addEntry(); Entry entry = feed.addEntry();
entry.setId(urlManager.getEditIRI(item).toString()); entry.setId(urlManager.getEditIRI(item).toString());
String title = this.stringMetadata(item, ConfigurationManager String title = this.stringMetadata(item, configurationService
.getProperty("swordv2-server", "title.field")); .getProperty("swordv2-server.title.field"));
title = title == null ? "Untitled" : title; title = title == null ? "Untitled" : title;
entry.setTitle(title); entry.setTitle(title);
entry.addLink( entry.addLink(

View File

@@ -39,10 +39,11 @@ import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.BundleService; import org.dspace.content.service.BundleService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.core.Utils; import org.dspace.core.Utils;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.swordapp.server.AuthCredentials; import org.swordapp.server.AuthCredentials;
import org.swordapp.server.Deposit; import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt; import org.swordapp.server.DepositReceipt;
@@ -52,7 +53,7 @@ import org.swordapp.server.SwordServerException;
import org.swordapp.server.UriRegistry; import org.swordapp.server.UriRegistry;
public class DSpaceSwordAPI { public class DSpaceSwordAPI {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(DSpaceSwordAPI.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(DSpaceSwordAPI.class);
protected ItemService itemService = protected ItemService itemService =
ContentServiceFactory.getInstance().getItemService(); ContentServiceFactory.getInstance().getItemService();
@@ -66,6 +67,9 @@ public class DSpaceSwordAPI {
protected BitstreamFormatService bitstreamFormatService = protected BitstreamFormatService bitstreamFormatService =
ContentServiceFactory.getInstance().getBitstreamFormatService(); ContentServiceFactory.getInstance().getBitstreamFormatService();
protected ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
public SwordContext noAuthContext() public SwordContext noAuthContext()
throws DSpaceSwordException { throws DSpaceSwordException {
SwordContext sc = new SwordContext(); SwordContext sc = new SwordContext();
@@ -115,7 +119,7 @@ public class DSpaceSwordAPI {
String[] parts = acceptHeader.split(","); String[] parts = acceptHeader.split(",");
List<Object[]> unsorted = new ArrayList<Object[]>(); List<Object[]> unsorted = new ArrayList<>();
float highest_q = 0; float highest_q = 0;
int counter = 0; int counter = 0;
for (String part : parts) { for (String part : parts) {
@@ -174,7 +178,7 @@ public class DSpaceSwordAPI {
// set up a dictionary to hold our sorted results. The dictionary will be keyed with the q value, and the // set up a dictionary to hold our sorted results. The dictionary will be keyed with the q value, and the
// value of each key will be a list of content type strings (in no particular order) // value of each key will be a list of content type strings (in no particular order)
TreeMap<Float, List<String>> sorted = new TreeMap<Float, List<String>>(); TreeMap<Float, List<String>> sorted = new TreeMap<>();
// go through the unsorted list // go through the unsorted list
for (Object[] oa : unsorted) { for (Object[] oa : unsorted) {
@@ -192,7 +196,7 @@ public class DSpaceSwordAPI {
if (sorted.containsKey(qv)) { if (sorted.containsKey(qv)) {
sorted.get(qv).add(contentType); sorted.get(qv).add(contentType);
} else { } else {
List<String> cts = new ArrayList<String>(); List<String> cts = new ArrayList<>();
cts.add(contentType); cts.add(contentType);
sorted.put(qv, cts); sorted.put(qv, cts);
} }
@@ -205,7 +209,7 @@ public class DSpaceSwordAPI {
if (sorted.containsKey(nq)) { if (sorted.containsKey(nq)) {
sorted.get(nq).add(contentType); sorted.get(nq).add(contentType);
} else { } else {
List<String> cts = new ArrayList<String>(); List<String> cts = new ArrayList<>();
cts.add(contentType); cts.add(contentType);
sorted.put(nq, cts); sorted.put(nq, cts);
} }
@@ -255,8 +259,8 @@ public class DSpaceSwordAPI {
// for a moment // for a moment
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
String bundleName = ConfigurationManager.getProperty( String bundleName = configurationService.getProperty(
"swordv2-server", "bundle.name"); "swordv2-server.bundle.name");
if (bundleName == null || "".equals(bundleName)) { if (bundleName == null || "".equals(bundleName)) {
bundleName = "SWORD"; bundleName = "SWORD";
} }
@@ -496,9 +500,8 @@ public class DSpaceSwordAPI {
protected void addVerboseDescription(DepositReceipt receipt, protected void addVerboseDescription(DepositReceipt receipt,
VerboseDescription verboseDescription) { VerboseDescription verboseDescription) {
boolean includeVerbose = ConfigurationManager boolean includeVerbose = configurationService
.getBooleanProperty("swordv2-server", .getBooleanProperty("swordv2-server.verbose-description.receipt.enable");
"verbose-description.receipt.enable");
if (includeVerbose) { if (includeVerbose) {
receipt.setVerboseDescription(verboseDescription.toString()); receipt.setVerboseDescription(verboseDescription.toString());
} }

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