Merge branch 'main' into CST-4509-assignAnEntityTypeToCollection

This commit is contained in:
Mykhaylo
2021-09-26 10:47:03 +02:00
129 changed files with 934 additions and 740 deletions

View File

@@ -81,7 +81,7 @@ public class MetadataImporter {
* @throws SQLException if database error * @throws SQLException if database error
* @throws IOException if IO error * @throws IOException if IO error
* @throws TransformerException if transformer error * @throws TransformerException if transformer error
* @throws ParserConfigurationException if config error * @throws ParserConfigurationException if configuration error
* @throws AuthorizeException if authorization error * @throws AuthorizeException if authorization error
* @throws SAXException if parser error * @throws SAXException if parser error
* @throws NonUniqueMetadataException if duplicate metadata * @throws NonUniqueMetadataException if duplicate metadata
@@ -91,7 +91,6 @@ public class MetadataImporter {
throws ParseException, SQLException, IOException, TransformerException, throws ParseException, SQLException, IOException, TransformerException,
ParserConfigurationException, AuthorizeException, SAXException, ParserConfigurationException, AuthorizeException, SAXException,
NonUniqueMetadataException, RegistryImportException { NonUniqueMetadataException, RegistryImportException {
boolean forceUpdate = false;
// create an options object and populate it // create an options object and populate it
CommandLineParser parser = new DefaultParser(); CommandLineParser parser = new DefaultParser();
@@ -100,16 +99,14 @@ public class MetadataImporter {
options.addOption("u", "update", false, "update an existing schema"); options.addOption("u", "update", false, "update an existing schema");
CommandLine line = parser.parse(options, args); CommandLine line = parser.parse(options, args);
String file = null;
if (line.hasOption('f')) { if (line.hasOption('f')) {
file = line.getOptionValue('f'); String file = line.getOptionValue('f');
boolean forceUpdate = line.hasOption('u');
loadRegistry(file, forceUpdate);
} else { } else {
usage(); usage();
System.exit(0); System.exit(1);
} }
forceUpdate = line.hasOption('u');
loadRegistry(file, forceUpdate);
} }
/** /**
@@ -120,7 +117,7 @@ public class MetadataImporter {
* @throws SQLException if database error * @throws SQLException if database error
* @throws IOException if IO error * @throws IOException if IO error
* @throws TransformerException if transformer error * @throws TransformerException if transformer error
* @throws ParserConfigurationException if config error * @throws ParserConfigurationException if configuration error
* @throws AuthorizeException if authorization error * @throws AuthorizeException if authorization error
* @throws SAXException if parser error * @throws SAXException if parser error
* @throws NonUniqueMetadataException if duplicate metadata * @throws NonUniqueMetadataException if duplicate metadata
@@ -227,7 +224,7 @@ public class MetadataImporter {
/** /**
* Process a node in the metadata registry XML file. The node must * Process a node in the metadata registry XML file. The node must
* be a "dc-type" node. If the type already exists, then it * be a "dc-type" node. If the type already exists, then it
* will not be reimported * will not be re-imported.
* *
* @param context DSpace context object * @param context DSpace context object
* @param node the node in the DOM tree * @param node the node in the DOM tree

View File

@@ -138,7 +138,7 @@ public class DSpaceCSV implements Serializable {
/** /**
* Create a new instance, reading the lines in from file * Create a new instance, reading the lines in from file
* *
* @param inputStream the inputstream to read from * @param inputStream the input stream to read from
* @param c The DSpace Context * @param c The DSpace Context
* @throws Exception thrown if there is an error reading or processing the file * @throws Exception thrown if there is an error reading or processing the file
*/ */
@@ -159,7 +159,7 @@ public class DSpaceCSV implements Serializable {
columnCounter++; columnCounter++;
// Remove surrounding quotes if there are any // Remove surrounding quotes if there are any
if ((element.startsWith("\"")) && (element.endsWith("\""))) { if (element.startsWith("\"") && element.endsWith("\"")) {
element = element.substring(1, element.length() - 1); element = element.substring(1, element.length() - 1);
} }
@@ -337,15 +337,15 @@ public class DSpaceCSV implements Serializable {
/** /**
* Set the value separator for multiple values stored in one csv value. * Set the value separator for multiple values stored in one csv value.
* *
* Is set in bulkedit.cfg as valueseparator * Is set in {@code bulkedit.cfg} as {@code valueseparator}.
* *
* If not set, defaults to double pipe '||' * If not set, defaults to double pipe '||'.
*/ */
private void setValueSeparator() { private void setValueSeparator() {
// Get the value separator // Get the value separator
valueSeparator = DSpaceServicesFactory.getInstance().getConfigurationService() valueSeparator = DSpaceServicesFactory.getInstance().getConfigurationService()
.getProperty("bulkedit.valueseparator"); .getProperty("bulkedit.valueseparator");
if ((valueSeparator != null) && (!"".equals(valueSeparator.trim()))) { if ((valueSeparator != null) && !valueSeparator.trim().isEmpty()) {
valueSeparator = valueSeparator.trim(); valueSeparator = valueSeparator.trim();
} else { } else {
valueSeparator = "||"; valueSeparator = "||";
@@ -360,7 +360,7 @@ public class DSpaceCSV implements Serializable {
/** /**
* Set the field separator use to separate fields in the csv. * Set the field separator use to separate fields in the csv.
* *
* Is set in bulkedit.cfg as fieldseparator * Is set in {@code bulkedit.cfg} as {@code fieldseparator}.
* *
* If not set, defaults to comma ','. * If not set, defaults to comma ','.
* *
@@ -371,7 +371,7 @@ public class DSpaceCSV implements Serializable {
// Get the value separator // Get the value separator
fieldSeparator = DSpaceServicesFactory.getInstance().getConfigurationService() fieldSeparator = DSpaceServicesFactory.getInstance().getConfigurationService()
.getProperty("bulkedit.fieldseparator"); .getProperty("bulkedit.fieldseparator");
if ((fieldSeparator != null) && (!"".equals(fieldSeparator.trim()))) { if ((fieldSeparator != null) && !fieldSeparator.trim().isEmpty()) {
fieldSeparator = fieldSeparator.trim(); fieldSeparator = fieldSeparator.trim();
if ("tab".equals(fieldSeparator)) { if ("tab".equals(fieldSeparator)) {
fieldSeparator = "\t"; fieldSeparator = "\t";
@@ -395,15 +395,15 @@ public class DSpaceCSV implements Serializable {
/** /**
* Set the authority separator for value with authority data. * Set the authority separator for value with authority data.
* *
* Is set in dspace.cfg as bulkedit.authorityseparator * Is set in {@code dspace.cfg} as {@code bulkedit.authorityseparator}.
* *
* If not set, defaults to double colon '::' * If not set, defaults to double colon '::'.
*/ */
private void setAuthoritySeparator() { private void setAuthoritySeparator() {
// Get the value separator // Get the value separator
authoritySeparator = DSpaceServicesFactory.getInstance().getConfigurationService() authoritySeparator = DSpaceServicesFactory.getInstance().getConfigurationService()
.getProperty("bulkedit.authorityseparator"); .getProperty("bulkedit.authorityseparator");
if ((authoritySeparator != null) && (!"".equals(authoritySeparator.trim()))) { if ((authoritySeparator != null) && !authoritySeparator.trim().isEmpty()) {
authoritySeparator = authoritySeparator.trim(); authoritySeparator = authoritySeparator.trim();
} else { } else {
authoritySeparator = "::"; authoritySeparator = "::";
@@ -508,7 +508,7 @@ public class DSpaceCSV implements Serializable {
int i = 0; int i = 0;
for (String part : bits) { for (String part : bits) {
int bitcounter = part.length() - part.replaceAll("\"", "").length(); int bitcounter = part.length() - part.replaceAll("\"", "").length();
if ((part.startsWith("\"")) && ((!part.endsWith("\"")) || ((bitcounter & 1) == 1))) { if (part.startsWith("\"") && (!part.endsWith("\"") || ((bitcounter & 1) == 1))) {
found = true; found = true;
String add = bits.get(i) + fieldSeparator + bits.get(i + 1); String add = bits.get(i) + fieldSeparator + bits.get(i + 1);
bits.remove(i); bits.remove(i);
@@ -524,7 +524,7 @@ public class DSpaceCSV implements Serializable {
// Deal with quotes around the elements // Deal with quotes around the elements
int i = 0; int i = 0;
for (String part : bits) { for (String part : bits) {
if ((part.startsWith("\"")) && (part.endsWith("\""))) { if (part.startsWith("\"") && part.endsWith("\"")) {
part = part.substring(1, part.length() - 1); part = part.substring(1, part.length() - 1);
bits.set(i, part); bits.set(i, part);
} }
@@ -564,7 +564,7 @@ public class DSpaceCSV implements Serializable {
for (String part : bits) { for (String part : bits) {
if (i > 0) { if (i > 0) {
// Is this a last empty item? // Is this a last empty item?
if ((last) && (i == headings.size())) { if (last && (i == headings.size())) {
part = ""; part = "";
} }
@@ -577,7 +577,7 @@ public class DSpaceCSV implements Serializable {
csvLine.add(headings.get(i - 1), null); csvLine.add(headings.get(i - 1), null);
String[] elements = part.split(escapedValueSeparator); String[] elements = part.split(escapedValueSeparator);
for (String element : elements) { for (String element : elements) {
if ((element != null) && (!"".equals(element))) { if ((element != null) && !element.isEmpty()) {
csvLine.add(headings.get(i - 1), element); csvLine.add(headings.get(i - 1), element);
} }
} }
@@ -629,18 +629,18 @@ public class DSpaceCSV implements Serializable {
public InputStream getInputStream() { public InputStream getInputStream() {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
for (String csvLine : getCSVLinesAsStringArray()) { for (String csvLine : getCSVLinesAsStringArray()) {
stringBuilder.append(csvLine + "\n"); stringBuilder.append(csvLine).append("\n");
} }
return IOUtils.toInputStream(stringBuilder.toString(), StandardCharsets.UTF_8); return IOUtils.toInputStream(stringBuilder.toString(), StandardCharsets.UTF_8);
} }
/** /**
* Is it Ok to export this value? When exportAll is set to false, we don't export * Is it okay to export this value? When exportAll is set to false, we don't export
* some of the metadata elements. * some of the metadata elements.
* *
* The list can be configured via the key ignore-on-export in bulkedit.cfg * The list can be configured via the key ignore-on-export in {@code bulkedit.cfg}.
* *
* @param md The Metadatum to examine * @param md The MetadataField to examine
* @return Whether or not it is OK to export this element * @return Whether or not it is OK to export this element
*/ */
protected boolean okToExport(MetadataField md) { protected boolean okToExport(MetadataField md) {
@@ -649,12 +649,8 @@ public class DSpaceCSV implements Serializable {
if (md.getQualifier() != null) { if (md.getQualifier() != null) {
key += "." + md.getQualifier(); key += "." + md.getQualifier();
} }
if (ignore.get(key) != null) {
return false;
}
// Must be OK, so don't ignore // Must be OK, so don't ignore
return true; return ignore.get(key) == null;
} }
/** /**

View File

@@ -16,6 +16,7 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@@ -129,7 +130,7 @@ public class ItemExportServiceImpl implements ItemExportService {
while (i.hasNext()) { while (i.hasNext()) {
if (SUBDIR_LIMIT > 0 && ++counter == SUBDIR_LIMIT) { if (SUBDIR_LIMIT > 0 && ++counter == SUBDIR_LIMIT) {
subdir = Integer.valueOf(subDirSuffix++).toString(); subdir = Integer.toString(subDirSuffix++);
fullPath = destDirName + File.separatorChar + subdir; fullPath = destDirName + File.separatorChar + subdir;
counter = 0; counter = 0;
@@ -191,7 +192,7 @@ public class ItemExportServiceImpl implements ItemExportService {
*/ */
protected void writeMetadata(Context c, Item i, File destDir, boolean migrate) protected void writeMetadata(Context c, Item i, File destDir, boolean migrate)
throws Exception { throws Exception {
Set<String> schemas = new HashSet<String>(); Set<String> schemas = new HashSet<>();
List<MetadataValue> dcValues = itemService.getMetadata(i, Item.ANY, Item.ANY, Item.ANY, Item.ANY); List<MetadataValue> dcValues = itemService.getMetadata(i, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (MetadataValue metadataValue : dcValues) { for (MetadataValue metadataValue : dcValues) {
schemas.add(metadataValue.getMetadataField().getMetadataSchema().getName()); schemas.add(metadataValue.getMetadataField().getMetadataSchema().getName());
@@ -267,7 +268,7 @@ public class ItemExportServiceImpl implements ItemExportService {
+ Utils.addEntities(dcv.getValue()) + "</dcvalue>\n") + Utils.addEntities(dcv.getValue()) + "</dcvalue>\n")
.getBytes("UTF-8"); .getBytes("UTF-8");
if ((!migrate) || if (!migrate ||
(migrate && !( (migrate && !(
("date".equals(metadataField.getElement()) && "issued".equals(qualifier)) || ("date".equals(metadataField.getElement()) && "issued".equals(qualifier)) ||
("date".equals(metadataField.getElement()) && "accessioned".equals(qualifier)) || ("date".equals(metadataField.getElement()) && "accessioned".equals(qualifier)) ||
@@ -292,10 +293,10 @@ public class ItemExportServiceImpl implements ItemExportService {
} }
// When migrating, only keep date.issued if it is different to date.accessioned // When migrating, only keep date.issued if it is different to date.accessioned
if ((migrate) && if (migrate &&
(dateIssued != null) && (dateIssued != null) &&
(dateAccessioned != null) && (dateAccessioned != null) &&
(!dateIssued.equals(dateAccessioned))) { !dateIssued.equals(dateAccessioned)) {
utf8 = (" <dcvalue element=\"date\" " utf8 = (" <dcvalue element=\"date\" "
+ "qualifier=\"issued\">" + "qualifier=\"issued\">"
+ Utils.addEntities(dateIssued) + "</dcvalue>\n") + Utils.addEntities(dateIssued) + "</dcvalue>\n")
@@ -330,7 +331,7 @@ public class ItemExportServiceImpl implements ItemExportService {
File outFile = new File(destDir, filename); File outFile = new File(destDir, filename);
if (outFile.createNewFile()) { if (outFile.createNewFile()) {
PrintWriter out = new PrintWriter(new FileWriter(outFile)); PrintWriter out = new PrintWriter(new FileWriter(outFile, StandardCharsets.UTF_8));
out.println(i.getHandle()); out.println(i.getHandle());
@@ -360,7 +361,7 @@ public class ItemExportServiceImpl implements ItemExportService {
File outFile = new File(destDir, "contents"); File outFile = new File(destDir, "contents");
if (outFile.createNewFile()) { if (outFile.createNewFile()) {
PrintWriter out = new PrintWriter(new FileWriter(outFile)); PrintWriter out = new PrintWriter(new FileWriter(outFile, StandardCharsets.UTF_8));
List<Bundle> bundles = i.getBundles(); List<Bundle> bundles = i.getBundles();
@@ -474,7 +475,7 @@ public class ItemExportServiceImpl implements ItemExportService {
public void createDownloadableExport(DSpaceObject dso, public void createDownloadableExport(DSpaceObject dso,
Context context, boolean migrate) throws Exception { Context context, boolean migrate) throws Exception {
EPerson eperson = context.getCurrentUser(); EPerson eperson = context.getCurrentUser();
ArrayList<DSpaceObject> list = new ArrayList<DSpaceObject>(1); ArrayList<DSpaceObject> list = new ArrayList<>(1);
list.add(dso); list.add(dso);
processDownloadableExport(list, context, eperson == null ? null processDownloadableExport(list, context, eperson == null ? null
: eperson.getEmail(), migrate); : eperson.getEmail(), migrate);
@@ -491,7 +492,7 @@ public class ItemExportServiceImpl implements ItemExportService {
@Override @Override
public void createDownloadableExport(DSpaceObject dso, public void createDownloadableExport(DSpaceObject dso,
Context context, String additionalEmail, boolean migrate) throws Exception { Context context, String additionalEmail, boolean migrate) throws Exception {
ArrayList<DSpaceObject> list = new ArrayList<DSpaceObject>(1); ArrayList<DSpaceObject> list = new ArrayList<>(1);
list.add(dso); list.add(dso);
processDownloadableExport(list, context, additionalEmail, migrate); processDownloadableExport(list, context, additionalEmail, migrate);
} }
@@ -652,7 +653,7 @@ public class ItemExportServiceImpl implements ItemExportService {
while (iter.hasNext()) { while (iter.hasNext()) {
String keyName = iter.next(); String keyName = iter.next();
List<UUID> uuids = itemsMap.get(keyName); List<UUID> uuids = itemsMap.get(keyName);
List<Item> items = new ArrayList<Item>(); List<Item> items = new ArrayList<>();
for (UUID uuid : uuids) { for (UUID uuid : uuids) {
items.add(itemService.find(context, uuid)); items.add(itemService.find(context, uuid));
} }
@@ -876,7 +877,7 @@ public class ItemExportServiceImpl implements ItemExportService {
.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());
now.add(Calendar.HOUR, (-hours)); now.add(Calendar.HOUR, -hours);
File downloadDir = new File(getExportDownloadDirectory(eperson)); File downloadDir = new File(getExportDownloadDirectory(eperson));
if (downloadDir.exists()) { if (downloadDir.exists()) {
File[] files = downloadDir.listFiles(); File[] files = downloadDir.listFiles();
@@ -896,7 +897,7 @@ public class ItemExportServiceImpl implements ItemExportService {
int hours = configurationService.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(configurationService.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.

View File

@@ -11,6 +11,8 @@ import java.io.UnsupportedEncodingException;
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.dspace.app.util.Util; import org.dspace.app.util.Util;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.Bundle; import org.dspace.content.Bundle;
@@ -34,8 +36,9 @@ public class ItemMarkingAvailabilityBitstreamStrategy implements ItemMarkingExtr
@Autowired(required = true) @Autowired(required = true)
protected ItemService itemService; protected ItemService itemService;
public ItemMarkingAvailabilityBitstreamStrategy() { private static final Logger LOG = LogManager.getLogger();
public ItemMarkingAvailabilityBitstreamStrategy() {
} }
@Override @Override
@@ -43,14 +46,14 @@ public class ItemMarkingAvailabilityBitstreamStrategy implements ItemMarkingExtr
throws SQLException { throws SQLException {
List<Bundle> bundles = itemService.getBundles(item, "ORIGINAL"); List<Bundle> bundles = itemService.getBundles(item, "ORIGINAL");
if (bundles.size() == 0) { if (bundles.isEmpty()) {
ItemMarkingInfo markInfo = new ItemMarkingInfo(); ItemMarkingInfo markInfo = new ItemMarkingInfo();
markInfo.setImageName(nonAvailableImageName); markInfo.setImageName(nonAvailableImageName);
return markInfo; return markInfo;
} else { } else {
Bundle originalBundle = bundles.iterator().next(); Bundle originalBundle = bundles.iterator().next();
if (originalBundle.getBitstreams().size() == 0) { if (originalBundle.getBitstreams().isEmpty()) {
ItemMarkingInfo markInfo = new ItemMarkingInfo(); ItemMarkingInfo markInfo = new ItemMarkingInfo();
markInfo.setImageName(nonAvailableImageName); markInfo.setImageName(nonAvailableImageName);
@@ -72,8 +75,7 @@ public class ItemMarkingAvailabilityBitstreamStrategy implements ItemMarkingExtr
try { try {
bsLink = bsLink + Util.encodeBitstreamName(bitstream.getName(), Constants.DEFAULT_ENCODING); bsLink = bsLink + Util.encodeBitstreamName(bitstream.getName(), Constants.DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
LOG.warn("DSpace uses an unsupported encoding", e);
e.printStackTrace();
} }
signInfo.setLink(bsLink); signInfo.setLink(bsLink);

View File

@@ -105,6 +105,7 @@ public class ContentsEntry {
return new ContentsEntry(arp[0], arp[1], actionId, groupName, arp[3]); return new ContentsEntry(arp[0], arp[1], actionId, groupName, arp[3]);
} }
@Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(filename); StringBuilder sb = new StringBuilder(filename);
if (bundlename != null) { if (bundlename != null) {

View File

@@ -120,6 +120,7 @@ class DtoMetadata {
return true; return true;
} }
@Override
public String toString() { public String toString() {
String s = "\tSchema: " + schema + " Element: " + element; String s = "\tSchema: " + schema + " Element: " + element;
if (qualifier != null) { if (qualifier != null) {

View File

@@ -17,6 +17,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
@@ -55,7 +56,7 @@ public class ItemArchive {
protected Transformer transformer = null; protected Transformer transformer = null;
protected List<DtoMetadata> dtomList = null; protected List<DtoMetadata> dtomList = null;
protected List<DtoMetadata> undoDtomList = new ArrayList<DtoMetadata>(); protected List<DtoMetadata> undoDtomList = new ArrayList<>();
protected List<UUID> undoAddContents = new ArrayList<>(); // for undo of add protected List<UUID> undoAddContents = new ArrayList<>(); // for undo of add
@@ -325,7 +326,7 @@ public class ItemArchive {
PrintWriter pw = null; PrintWriter pw = null;
try { try {
File f = new File(dir, ItemUpdate.DELETE_CONTENTS_FILE); File f = new File(dir, ItemUpdate.DELETE_CONTENTS_FILE);
pw = new PrintWriter(new BufferedWriter(new FileWriter(f))); pw = new PrintWriter(new BufferedWriter(new FileWriter(f, StandardCharsets.UTF_8)));
for (UUID i : undoAddContents) { for (UUID i : undoAddContents) {
pw.println(i); pw.println(i);
} }

View File

@@ -9,6 +9,7 @@ package org.dspace.app.mediafilter;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import javax.swing.text.Document; import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.HTMLEditorKit;
@@ -36,7 +37,7 @@ public class HTMLFilter extends MediaFilter {
} }
/** /**
* @return String bitstreamformat * @return String bitstream format
*/ */
@Override @Override
public String getFormatString() { public String getFormatString() {
@@ -73,9 +74,9 @@ public class HTMLFilter extends MediaFilter {
String extractedText = doc.getText(0, doc.getLength()); String extractedText = doc.getText(0, doc.getLength());
// generate an input stream with the extracted text // generate an input stream with the extracted text
byte[] textBytes = extractedText.getBytes(); byte[] textBytes = extractedText.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream bais = new ByteArrayInputStream(textBytes); ByteArrayInputStream bais = new ByteArrayInputStream(textBytes);
return bais; // will this work? or will the byte array be out of scope? return bais;
} }
} }

View File

@@ -10,6 +10,7 @@ package org.dspace.app.mediafilter;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.POITextExtractor; import org.apache.poi.POITextExtractor;
import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.ExtractorFactory;
@@ -66,6 +67,6 @@ public class PoiWordFilter
} }
// return the extracted text as a stream. // return the extracted text as a stream.
return new ByteArrayInputStream(text.getBytes()); return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
} }
} }

View File

@@ -73,6 +73,7 @@ public class SHERPAService {
/** /**
* Complete initialization of the Bean. * Complete initialization of the Bean.
*/ */
@SuppressWarnings("unused")
@PostConstruct @PostConstruct
private void init() { private void init() {
// Get endoint and API key from configuration // Get endoint and API key from configuration

View File

@@ -13,15 +13,18 @@ import java.util.List;
* Plain java representation of a SHERPA Permitted Version object, based on SHERPA API v2 responses. * Plain java representation of a SHERPA Permitted Version object, based on SHERPA API v2 responses.
* *
* In a SHERPA search for journal deposit policies, this data is contained within a publisher policy. * In a SHERPA search for journal deposit policies, this data is contained within a publisher policy.
* Each permitted version is for a particular article version (eg. submitted, accepted, published) and contains * Each permitted version is for a particular article version (e.g. submitted, accepted, published) and contains:
* *
* A list of general conditions / terms for deposit of this version of work * <ul>
* A list of allowed locations (eg. institutional repository, personal homepage, non-commercial repository) * <li>A list of general conditions / terms for deposit of this version of work</li>
* A list of prerequisite conditions for deposit (eg. attribution, linking to published version) * <li>A list of allowed locations (e.g. institutional repository, personal homepage, non-commercial repository)</li>
* A list of required licences for the deposited work (eg. CC-BY-NC) * <li>A list of prerequisite conditions for deposit (e.g. attribution, linking to published version)</li>
* Embargo requirements, if any * <li>A list of required licenses for the deposited work (e.g. CC-BY-NC)</li>
* <li>Embargo requirements, if any</li>
* </ul>
* *
* This class also has some helper data for labels, which can be used with i18n when displaying policy information * This class also has some helper data for labels, which can be used with i18n
* when displaying policy information.
* *
* @see SHERPAPublisherPolicy * @see SHERPAPublisherPolicy
*/ */
@@ -44,7 +47,7 @@ public class SHERPAPermittedVersion {
// Embargo // Embargo
private SHERPAEmbargo embargo; private SHERPAEmbargo embargo;
protected class SHERPAEmbargo { protected static class SHERPAEmbargo {
String units; String units;
int amount; int amount;
} }

View File

@@ -10,7 +10,8 @@ package org.dspace.app.sherpa.v2;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.LinkedList; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@@ -74,7 +75,7 @@ public class SHERPAPublisherResponse {
* @param jsonData - the JSON input stream from the API result response body * @param jsonData - the JSON input stream from the API result response body
*/ */
private void parseJSON(InputStream jsonData) throws IOException { private void parseJSON(InputStream jsonData) throws IOException {
InputStreamReader streamReader = new InputStreamReader(jsonData); InputStreamReader streamReader = new InputStreamReader(jsonData, StandardCharsets.UTF_8);
JSONTokener jsonTokener = new JSONTokener(streamReader); JSONTokener jsonTokener = new JSONTokener(streamReader);
JSONObject httpResponse; JSONObject httpResponse;
try { try {
@@ -86,7 +87,7 @@ public class SHERPAPublisherResponse {
// parsing the full journal / policy responses // parsing the full journal / policy responses
if (items.length() > 0) { if (items.length() > 0) {
metadata = new SHERPASystemMetadata(); metadata = new SHERPASystemMetadata();
this.publishers = new LinkedList<>(); this.publishers = new ArrayList<>();
// Iterate search result items // Iterate search result items
for (int itemIndex = 0; itemIndex < items.length(); itemIndex++) { for (int itemIndex = 0; itemIndex < items.length(); itemIndex++) {
SHERPAPublisher sherpaPublisher = new SHERPAPublisher(); SHERPAPublisher sherpaPublisher = new SHERPAPublisher();

View File

@@ -10,8 +10,8 @@ package org.dspace.app.sherpa.v2;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
@@ -78,7 +78,7 @@ public class SHERPAResponse {
* @param jsonData - the JSON input stream from the API result response body * @param jsonData - the JSON input stream from the API result response body
*/ */
private void parseJSON(InputStream jsonData) throws IOException { private void parseJSON(InputStream jsonData) throws IOException {
InputStreamReader streamReader = new InputStreamReader(jsonData); InputStreamReader streamReader = new InputStreamReader(jsonData, StandardCharsets.UTF_8);
JSONTokener jsonTokener = new JSONTokener(streamReader); JSONTokener jsonTokener = new JSONTokener(streamReader);
JSONObject httpResponse; JSONObject httpResponse;
try { try {
@@ -90,10 +90,10 @@ public class SHERPAResponse {
// - however, we only ever want one result since we're passing an "equals ISSN" query // - however, we only ever want one result since we're passing an "equals ISSN" query
if (items.length() > 0) { if (items.length() > 0) {
metadata = new SHERPASystemMetadata(); metadata = new SHERPASystemMetadata();
this.journals = new LinkedList<>(); this.journals = new ArrayList<>();
// Iterate search result items // Iterate search result items
for (int itemIndex = 0; itemIndex < items.length(); itemIndex++) { for (int itemIndex = 0; itemIndex < items.length(); itemIndex++) {
List<SHERPAPublisher> sherpaPublishers = new LinkedList<>(); List<SHERPAPublisher> sherpaPublishers = new ArrayList<>();
List<SHERPAPublisherPolicy> policies = new ArrayList<>(); List<SHERPAPublisherPolicy> policies = new ArrayList<>();
SHERPAPublisher sherpaPublisher = new SHERPAPublisher(); SHERPAPublisher sherpaPublisher = new SHERPAPublisher();
SHERPAJournal sherpaJournal = new SHERPAJournal(); SHERPAJournal sherpaJournal = new SHERPAJournal();
@@ -289,7 +289,7 @@ public class SHERPAResponse {
// Is the item in DOAJ? // Is the item in DOAJ?
if (item.has("listed_in_doaj")) { if (item.has("listed_in_doaj")) {
sherpaJournal.setInDOAJ(("yes".equals(item.getString("listed_in_doaj")))); sherpaJournal.setInDOAJ("yes".equals(item.getString("listed_in_doaj")));
} }
return sherpaJournal; return sherpaJournal;
@@ -403,7 +403,6 @@ public class SHERPAResponse {
// published = pdfversion // published = pdfversion
// These strings can be used to construct i18n messages. // These strings can be used to construct i18n messages.
String articleVersion = "unknown"; String articleVersion = "unknown";
String versionLabel = "Unknown";
// Each 'permitted OA' can actually refer to multiple versions // Each 'permitted OA' can actually refer to multiple versions
if (permitted.has("article_version")) { if (permitted.has("article_version")) {

View File

@@ -86,7 +86,7 @@ public class SitemapsOrgGenerator extends AbstractGenerator {
@Override @Override
public String getURLText(String url, Date lastMod) { public String getURLText(String url, Date lastMod) {
StringBuffer urlText = new StringBuffer(); StringBuilder urlText = new StringBuilder();
urlText.append("<url><loc>").append(url).append("</loc>"); urlText.append("<url><loc>").append(url).append("</loc>");
if (lastMod != null) { if (lastMod != null) {

View File

@@ -64,10 +64,6 @@ public class CreateStatReport {
*/ */
private static Context context; private static Context context;
/**
* the config file from which to configure the analyser
*/
/** /**
* Default constructor * Default constructor
*/ */
@@ -170,22 +166,19 @@ public class CreateStatReport {
String myLogDir = null; String myLogDir = null;
String myFileTemplate = null; String myFileTemplate = null;
String myConfigFile = null; String myConfigFile = null;
StringBuffer myOutFile = null;
Date myStartDate = null;
Date myEndDate = null;
boolean myLookUp = false; boolean myLookUp = false;
Calendar start = new GregorianCalendar(calendar.get(Calendar.YEAR), Calendar start = new GregorianCalendar(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.MONTH),
calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
myStartDate = start.getTime(); Date myStartDate = start.getTime();
Calendar end = new GregorianCalendar(calendar.get(Calendar.YEAR), Calendar end = new GregorianCalendar(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.MONTH),
calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
myEndDate = end.getTime(); Date myEndDate = end.getTime();
myOutFile = new StringBuffer(outputLogDirectory); StringBuilder myOutFile = new StringBuilder(outputLogDirectory);
myOutFile.append(outputPrefix); myOutFile.append(outputPrefix);
myOutFile.append(calendar.get(Calendar.YEAR)); myOutFile.append(calendar.get(Calendar.YEAR));
myOutFile.append("-"); myOutFile.append("-");
@@ -211,12 +204,11 @@ public class CreateStatReport {
String myLogDir = null; String myLogDir = null;
String myFileTemplate = null; String myFileTemplate = null;
String myConfigFile = null; String myConfigFile = null;
StringBuffer myOutFile = null;
Date myStartDate = null; Date myStartDate = null;
Date myEndDate = null; Date myEndDate = null;
boolean myLookUp = false; boolean myLookUp = false;
myOutFile = new StringBuffer(outputLogDirectory); StringBuilder myOutFile = new StringBuilder(outputLogDirectory);
myOutFile.append(outputPrefix); myOutFile.append(outputPrefix);
myOutFile.append(calendar.get(Calendar.YEAR)); myOutFile.append(calendar.get(Calendar.YEAR));
myOutFile.append("-"); myOutFile.append("-");
@@ -245,9 +237,6 @@ public class CreateStatReport {
String myLogDir = null; String myLogDir = null;
String myFileTemplate = null; String myFileTemplate = null;
String myConfigFile = null; String myConfigFile = null;
StringBuffer myOutFile = null;
Date myStartDate = null;
Date myEndDate = null;
boolean myLookUp = false; boolean myLookUp = false;
Calendar reportEndDate = new GregorianCalendar(calendar.get(Calendar.YEAR), Calendar reportEndDate = new GregorianCalendar(calendar.get(Calendar.YEAR),
@@ -260,14 +249,14 @@ public class CreateStatReport {
Calendar start = new GregorianCalendar(currentMonth.get(Calendar.YEAR), Calendar start = new GregorianCalendar(currentMonth.get(Calendar.YEAR),
currentMonth.get(Calendar.MONTH), currentMonth.get(Calendar.MONTH),
currentMonth.getActualMinimum(Calendar.DAY_OF_MONTH)); currentMonth.getActualMinimum(Calendar.DAY_OF_MONTH));
myStartDate = start.getTime(); Date myStartDate = start.getTime();
Calendar end = new GregorianCalendar(currentMonth.get(Calendar.YEAR), Calendar end = new GregorianCalendar(currentMonth.get(Calendar.YEAR),
currentMonth.get(Calendar.MONTH), currentMonth.get(Calendar.MONTH),
currentMonth.getActualMaximum(Calendar.DAY_OF_MONTH)); currentMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
myEndDate = end.getTime(); Date myEndDate = end.getTime();
myOutFile = new StringBuffer(outputLogDirectory); StringBuilder myOutFile = new StringBuilder(outputLogDirectory);
myOutFile.append(outputPrefix); myOutFile.append(outputPrefix);
myOutFile.append(currentMonth.get(Calendar.YEAR)); myOutFile.append(currentMonth.get(Calendar.YEAR));
myOutFile.append("-"); myOutFile.append("-");
@@ -293,11 +282,9 @@ public class CreateStatReport {
String outputPrefix = "report-general-"; String outputPrefix = "report-general-";
String myFormat = "html"; String myFormat = "html";
StringBuffer myInput = null;
StringBuffer myOutput = null;
String myMap = null; String myMap = null;
myInput = new StringBuffer(outputLogDirectory); StringBuilder myInput = new StringBuilder(outputLogDirectory);
myInput.append(inputPrefix); myInput.append(inputPrefix);
myInput.append(calendar.get(Calendar.YEAR)); myInput.append(calendar.get(Calendar.YEAR));
myInput.append("-"); myInput.append("-");
@@ -306,7 +293,7 @@ public class CreateStatReport {
myInput.append(calendar.get(Calendar.DAY_OF_MONTH)); myInput.append(calendar.get(Calendar.DAY_OF_MONTH));
myInput.append(outputSuffix); myInput.append(outputSuffix);
myOutput = new StringBuffer(outputReportDirectory); StringBuilder myOutput = new StringBuilder(outputReportDirectory);
myOutput.append(outputPrefix); myOutput.append(outputPrefix);
myOutput.append(calendar.get(Calendar.YEAR)); myOutput.append(calendar.get(Calendar.YEAR));
myOutput.append("-"); myOutput.append("-");
@@ -332,8 +319,6 @@ public class CreateStatReport {
String outputPrefix = "report-"; String outputPrefix = "report-";
String myFormat = "html"; String myFormat = "html";
StringBuffer myInput = null;
StringBuffer myOutput = null;
String myMap = null; String myMap = null;
Calendar reportEndDate = new GregorianCalendar(calendar.get(Calendar.YEAR), Calendar reportEndDate = new GregorianCalendar(calendar.get(Calendar.YEAR),
@@ -344,14 +329,14 @@ public class CreateStatReport {
while (currentMonth.before(reportEndDate)) { while (currentMonth.before(reportEndDate)) {
myInput = new StringBuffer(outputLogDirectory); StringBuilder myInput = new StringBuilder(outputLogDirectory);
myInput.append(inputPrefix); myInput.append(inputPrefix);
myInput.append(currentMonth.get(Calendar.YEAR)); myInput.append(currentMonth.get(Calendar.YEAR));
myInput.append("-"); myInput.append("-");
myInput.append(currentMonth.get(Calendar.MONTH) + 1); myInput.append(currentMonth.get(Calendar.MONTH) + 1);
myInput.append(outputSuffix); myInput.append(outputSuffix);
myOutput = new StringBuffer(outputReportDirectory); StringBuilder myOutput = new StringBuilder(outputReportDirectory);
myOutput.append(outputPrefix); myOutput.append(outputPrefix);
myOutput.append(currentMonth.get(Calendar.YEAR)); myOutput.append(currentMonth.get(Calendar.YEAR));
myOutput.append("-"); myOutput.append("-");
@@ -376,18 +361,16 @@ public class CreateStatReport {
String outputPrefix = "report-"; String outputPrefix = "report-";
String myFormat = "html"; String myFormat = "html";
StringBuffer myInput = null;
StringBuffer myOutput = null;
String myMap = null; String myMap = null;
myInput = new StringBuffer(outputLogDirectory); StringBuilder myInput = new StringBuilder(outputLogDirectory);
myInput.append(inputPrefix); myInput.append(inputPrefix);
myInput.append(calendar.get(Calendar.YEAR)); myInput.append(calendar.get(Calendar.YEAR));
myInput.append("-"); myInput.append("-");
myInput.append(calendar.get(Calendar.MONTH) + 1); myInput.append(calendar.get(Calendar.MONTH) + 1);
myInput.append(outputSuffix); myInput.append(outputSuffix);
myOutput = new StringBuffer(outputReportDirectory); StringBuilder myOutput = new StringBuilder(outputReportDirectory);
myOutput.append(outputPrefix); myOutput.append(outputPrefix);
myOutput.append(calendar.get(Calendar.YEAR)); myOutput.append(calendar.get(Calendar.YEAR));
myOutput.append("-"); myOutput.append("-");

View File

@@ -10,8 +10,6 @@ package org.dspace.app.util;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
@@ -30,7 +28,6 @@ import org.dspace.content.EntityType;
import org.dspace.content.RelationshipType; import org.dspace.content.RelationshipType;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.EntityTypeService; import org.dspace.content.service.EntityTypeService;
import org.dspace.content.service.RelationshipService;
import org.dspace.content.service.RelationshipTypeService; import org.dspace.content.service.RelationshipTypeService;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@@ -40,22 +37,20 @@ import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
/** /**
* This script is used to initialize the database with a set of relationshiptypes that are written * This script is used to initialize the database with a set of relationship types that are written
* in an xml file that is given to this script. * in an xml file that is given to this script.
* This XML file needs to have a proper XML structure and needs to define the variables of the RelationshipType object * This XML file needs to have a proper XML structure and needs to define the variables of the RelationshipType object.
*/ */
public class InitializeEntities { public class InitializeEntities {
private final static Logger log = LogManager.getLogger(); private final static Logger log = LogManager.getLogger();
private final RelationshipTypeService relationshipTypeService; private final RelationshipTypeService relationshipTypeService;
private final RelationshipService relationshipService;
private final EntityTypeService entityTypeService; private final EntityTypeService entityTypeService;
private InitializeEntities() { private InitializeEntities() {
relationshipTypeService = ContentServiceFactory.getInstance().getRelationshipTypeService(); relationshipTypeService = ContentServiceFactory.getInstance().getRelationshipTypeService();
relationshipService = ContentServiceFactory.getInstance().getRelationshipService();
entityTypeService = ContentServiceFactory.getInstance().getEntityTypeService(); entityTypeService = ContentServiceFactory.getInstance().getEntityTypeService();
} }
@@ -111,14 +106,12 @@ public class InitializeEntities {
try { try {
File fXmlFile = new File(fileLocation); File fXmlFile = new File(fileLocation);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null; DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile); Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize(); doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("type"); NodeList nList = doc.getElementsByTagName("type");
List<RelationshipType> relationshipTypes = new LinkedList<>();
for (int i = 0; i < nList.getLength(); i++) { for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i); Node nNode = nList.item(i);

View File

@@ -38,13 +38,12 @@ import org.dspace.core.Utils;
* *
* @author Robert Tansley * @author Robert Tansley
* @author Mark Diggory * @author Mark Diggory
* @version $Revision$
*/ */
public class Util { public class Util {
// cache for source version result // cache for source version result
private static String sourceVersion = null; private static String sourceVersion = null;
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(Util.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger();
/** /**
* Default constructor. Must be protected as org.dspace.xmlworkflow.WorkflowUtils extends it * Default constructor. Must be protected as org.dspace.xmlworkflow.WorkflowUtils extends it
@@ -60,7 +59,7 @@ public class Util {
* spaces * spaces
*/ */
public static String nonBreakSpace(String s) { public static String nonBreakSpace(String s) {
StringBuffer newString = new StringBuffer(); StringBuilder newString = new StringBuilder();
for (int i = 0; i < s.length(); i++) { for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i); char ch = s.charAt(i);
@@ -99,7 +98,7 @@ public class Util {
return ""; return "";
} }
StringBuffer out = new StringBuffer(); StringBuilder out = new StringBuilder();
final String[] pctEncoding = {"%00", "%01", "%02", "%03", "%04", final String[] pctEncoding = {"%00", "%01", "%02", "%03", "%04",
"%05", "%06", "%07", "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%05", "%06", "%07", "%08", "%09", "%0a", "%0b", "%0c", "%0d",
@@ -263,7 +262,7 @@ public class Util {
return null; return null;
} }
List<UUID> return_values = new ArrayList<UUID>(request_values.length); List<UUID> return_values = new ArrayList<>(request_values.length);
for (String s : request_values) { for (String s : request_values) {
try { try {
@@ -402,7 +401,7 @@ public class Util {
Item item, List<MetadataValue> values, String schema, String element, Item item, List<MetadataValue> values, String schema, String element,
String qualifier, Locale locale) throws SQLException, String qualifier, Locale locale) throws SQLException,
DCInputsReaderException { DCInputsReaderException {
List<String> toReturn = new ArrayList<String>(); List<String> toReturn = new ArrayList<>();
DCInput myInputs = null; DCInput myInputs = null;
boolean myInputsFound = false; boolean myInputsFound = false;
String formFileName = I18nUtil.getInputFormsFileName(locale); String formFileName = I18nUtil.getInputFormsFileName(locale);
@@ -478,8 +477,9 @@ public class Util {
} }
/** /**
* Split a list in an array of i sub-lists uniformly sized * Split a list in an array of i sub-lists uniformly sized.
* *
* @param <T> type of objects in the list.
* @param idsList the list to split * @param idsList the list to split
* @param i the number of sublists to return * @param i the number of sublists to return
* *

View File

@@ -58,6 +58,7 @@ public class WebApp implements ReloadableEntity<Integer> {
} }
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }

View File

@@ -8,7 +8,6 @@
package org.dspace.app.util; package org.dspace.app.util;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -29,13 +28,13 @@ public class XMLUtils {
/** /**
* @param dataRoot the starting node * @param dataRoot the starting node
* @param name the name of the subelement to find * @param name the tag name of the child element to find.
* @return the list of all DOM Element with the provided name direct child * @return the list of all DOM Element with the provided name direct child
* of the starting node * of the starting node
*/ */
public static List<Element> getElementList(Element dataRoot, String name) { public static List<Element> getElementList(Element dataRoot, String name) {
NodeList list = dataRoot.getElementsByTagName(name); NodeList list = dataRoot.getElementsByTagName(name);
List<Element> listElements = new ArrayList<Element>(); List<Element> listElements = new ArrayList<>();
for (int i = 0; i < list.getLength(); i++) { for (int i = 0; i < list.getLength(); i++) {
Element item = (Element) list.item(i); Element item = (Element) list.item(i);
if (item.getParentNode().equals(dataRoot)) { if (item.getParentNode().equals(dataRoot)) {
@@ -105,7 +104,7 @@ public class XMLUtils {
/** /**
* @param rootElement the starting node * @param rootElement the starting node
* @param subElementName the name of the subelement to find * @param subElementName the tag name of the child element to find.
* @return a list of string including all the text contents of the sub * @return a list of string including all the text contents of the sub
* element with the specified name. If there are not sub element * element with the specified name. If there are not sub element
* with the supplied name the method will return null * with the supplied name the method will return null
@@ -121,7 +120,7 @@ public class XMLUtils {
return null; return null;
} }
List<String> result = new LinkedList<String>(); List<String> result = new ArrayList<>();
for (Element el : subElements) { for (Element el : subElements) {
if (StringUtils.isNotBlank(el.getTextContent())) { if (StringUtils.isNotBlank(el.getTextContent())) {
result.add(el.getTextContent().trim()); result.add(el.getTextContent().trim());
@@ -152,7 +151,7 @@ public class XMLUtils {
return null; return null;
} }
List<String[]> result = new LinkedList<String[]>(); List<String[]> result = new ArrayList<>();
for (Element el : subElements) { for (Element el : subElements) {
String[] tmp = new String[fieldsName.length]; String[] tmp = new String[fieldsName.length];
for (int idx = 0; idx < fieldsName.length; idx++) { for (int idx = 0; idx < fieldsName.length; idx++) {

View File

@@ -15,6 +15,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
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.Context; import org.dspace.core.Context;
import org.dspace.core.LogHelper; import org.dspace.core.LogHelper;
@@ -41,7 +42,6 @@ import org.dspace.services.factory.DSpaceServicesFactory;
* Basic Auth username and password to the <code>AuthenticationManager</code>. * Basic Auth username and password to the <code>AuthenticationManager</code>.
* *
* @author Larry Stone * @author Larry Stone
* @version $Revision$
*/ */
public class PasswordAuthentication public class PasswordAuthentication
implements AuthenticationMethod { implements AuthenticationMethod {
@@ -49,7 +49,7 @@ public class PasswordAuthentication
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(PasswordAuthentication.class); private static final Logger log = LogManager.getLogger();
/** /**
@@ -142,7 +142,7 @@ public class PasswordAuthentication
.toString())) { .toString())) {
String groupName = DSpaceServicesFactory.getInstance().getConfigurationService() String groupName = DSpaceServicesFactory.getInstance().getConfigurationService()
.getProperty("authentication-password.login.specialgroup"); .getProperty("authentication-password.login.specialgroup");
if ((groupName != null) && (!groupName.trim().equals(""))) { if ((groupName != null) && !groupName.trim().isEmpty()) {
Group specialGroup = EPersonServiceFactory.getInstance().getGroupService() Group specialGroup = EPersonServiceFactory.getInstance().getGroupService()
.findByName(context, groupName); .findByName(context, groupName);
if (specialGroup == null) { if (specialGroup == null) {
@@ -181,7 +181,7 @@ public class PasswordAuthentication
* SUCCESS, BAD_CREDENTIALS, CERT_REQUIRED, NO_SUCH_USER, BAD_ARGS * SUCCESS, BAD_CREDENTIALS, CERT_REQUIRED, NO_SUCH_USER, BAD_ARGS
* <p>Meaning: * <p>Meaning:
* <br>SUCCESS - authenticated OK. * <br>SUCCESS - authenticated OK.
* <br>BAD_CREDENTIALS - user exists, but assword doesn't match * <br>BAD_CREDENTIALS - user exists, but password doesn't match
* <br>CERT_REQUIRED - not allowed to login this way without X.509 cert. * <br>CERT_REQUIRED - not allowed to login this way without X.509 cert.
* <br>NO_SUCH_USER - no EPerson with matching email address. * <br>NO_SUCH_USER - no EPerson with matching email address.
* <br>BAD_ARGS - missing username, or user matched but cannot login. * <br>BAD_ARGS - missing username, or user matched but cannot login.

View File

@@ -11,7 +11,6 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -62,7 +61,7 @@ import org.springframework.beans.factory.annotation.Autowired;
*/ */
public class AuthorizeServiceImpl implements AuthorizeService { public class AuthorizeServiceImpl implements AuthorizeService {
private static Logger log = LogManager.getLogger(AuthorizeServiceImpl.class); private static final Logger log = LogManager.getLogger();
@Autowired(required = true) @Autowired(required = true)
protected BitstreamService bitstreamService; protected BitstreamService bitstreamService;
@@ -243,7 +242,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
// If authorization was given before and cached // If authorization was given before and cached
Boolean cachedResult = c.getCachedAuthorizationResult(o, action, e); Boolean cachedResult = c.getCachedAuthorizationResult(o, action, e);
if (cachedResult != null) { if (cachedResult != null) {
return cachedResult.booleanValue(); return cachedResult;
} }
// is eperson set? if not, userToCheck = null (anonymous) // is eperson set? if not, userToCheck = null (anonymous)
@@ -308,7 +307,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
} }
if ((rp.getGroup() != null) if ((rp.getGroup() != null)
&& (groupService.isMember(c, e, rp.getGroup()))) { && groupService.isMember(c, e, rp.getGroup())) {
// group was set, and eperson is a member // group was set, and eperson is a member
// of that group // of that group
c.cacheAuthorizedAction(o, action, e, true, rp); c.cacheAuthorizedAction(o, action, e, true, rp);
@@ -366,7 +365,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
Boolean cachedResult = c.getCachedAuthorizationResult(o, Constants.ADMIN, e); Boolean cachedResult = c.getCachedAuthorizationResult(o, Constants.ADMIN, e);
if (cachedResult != null) { if (cachedResult != null) {
return cachedResult.booleanValue(); return cachedResult;
} }
// //
@@ -383,7 +382,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
} }
if ((rp.getGroup() != null) if ((rp.getGroup() != null)
&& (groupService.isMember(c, e, rp.getGroup()))) { && groupService.isMember(c, e, rp.getGroup())) {
// group was set, and eperson is a member // group was set, and eperson is a member
// of that group // of that group
c.cacheAuthorizedAction(o, Constants.ADMIN, e, true, rp); c.cacheAuthorizedAction(o, Constants.ADMIN, e, true, rp);
@@ -502,7 +501,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
List<ResourcePolicy> policies = getPolicies(c, src); List<ResourcePolicy> policies = getPolicies(c, src);
//Only inherit non-ADMIN policies (since ADMIN policies are automatically inherited) //Only inherit non-ADMIN policies (since ADMIN policies are automatically inherited)
List<ResourcePolicy> nonAdminPolicies = new ArrayList<ResourcePolicy>(); List<ResourcePolicy> nonAdminPolicies = new ArrayList<>();
for (ResourcePolicy rp : policies) { for (ResourcePolicy rp : policies) {
if (rp.getAction() != Constants.ADMIN) { if (rp.getAction() != Constants.ADMIN) {
nonAdminPolicies.add(rp); nonAdminPolicies.add(rp);
@@ -525,7 +524,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest)
throws SQLException, AuthorizeException { throws SQLException, AuthorizeException {
// now add them to the destination object // now add them to the destination object
List<ResourcePolicy> newPolicies = new LinkedList<>(); List<ResourcePolicy> newPolicies = new ArrayList<>(policies.size());
for (ResourcePolicy srp : policies) { for (ResourcePolicy srp : policies) {
ResourcePolicy rp = resourcePolicyService.create(c); ResourcePolicy rp = resourcePolicyService.create(c);
@@ -600,7 +599,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
int actionID) throws java.sql.SQLException { int actionID) throws java.sql.SQLException {
List<ResourcePolicy> policies = getPoliciesActionFilter(c, o, actionID); List<ResourcePolicy> policies = getPoliciesActionFilter(c, o, actionID);
List<Group> groups = new ArrayList<Group>(); List<Group> groups = new ArrayList<>();
for (ResourcePolicy resourcePolicy : policies) { for (ResourcePolicy resourcePolicy : policies) {
if (resourcePolicy.getGroup() != null && resourcePolicyService.isDateValid(resourcePolicy)) { if (resourcePolicy.getGroup() != null && resourcePolicyService.isDateValid(resourcePolicy)) {
groups.add(resourcePolicy.getGroup()); groups.add(resourcePolicy.getGroup());
@@ -768,6 +767,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
* @param context context with the current user * @param context context with the current user
* @return true if the current user is a community admin in the site * @return true if the current user is a community admin in the site
* false when this is not the case, or an exception occurred * false when this is not the case, or an exception occurred
* @throws java.sql.SQLException passed through.
*/ */
@Override @Override
public boolean isCommunityAdmin(Context context) throws SQLException { public boolean isCommunityAdmin(Context context) throws SQLException {
@@ -780,6 +780,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
* @param context context with the current user * @param context context with the current user
* @return true if the current user is a collection admin in the site * @return true if the current user is a collection admin in the site
* false when this is not the case, or an exception occurred * false when this is not the case, or an exception occurred
* @throws java.sql.SQLException passed through.
*/ */
@Override @Override
public boolean isCollectionAdmin(Context context) throws SQLException { public boolean isCollectionAdmin(Context context) throws SQLException {
@@ -792,6 +793,7 @@ public class AuthorizeServiceImpl implements AuthorizeService {
* @param context context with the current user * @param context context with the current user
* @return true if the current user is a community or collection admin in the site * @return true if the current user is a community or collection admin in the site
* false when this is not the case, or an exception occurred * false when this is not the case, or an exception occurred
* @throws java.sql.SQLException passed through.
*/ */
@Override @Override
public boolean isComColAdmin(Context context) throws SQLException { public boolean isComColAdmin(Context context) throws SQLException {

View File

@@ -169,6 +169,7 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
* *
* @return the internal identifier * @return the internal identifier
*/ */
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }

View File

@@ -170,7 +170,7 @@ public class MostRecentChecksum implements Serializable {
return true; return true;
} }
if (o == null || getClass() != o.getClass()) { if (o == null || !(o instanceof MostRecentChecksum)) {
return false; return false;
} }

View File

@@ -109,7 +109,7 @@ public class ResultsLogger implements ChecksumResultsCollector {
"unknown")); "unknown"));
LOG.info(msg("new-checksum") + ": " + info.getCurrentChecksum()); LOG.info(msg("new-checksum") + ": " + info.getCurrentChecksum());
LOG.info(msg("checksum-comparison-result") + ": " LOG.info(msg("checksum-comparison-result") + ": "
+ (info.getChecksumResult().getResultCode())); + info.getChecksumResult().getResultCode());
LOG.info("\n\n"); LOG.info("\n\n");
} }
} }

View File

@@ -77,7 +77,7 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
osw.write(applyDateFormatShort(endDate)); osw.write(applyDateFormatShort(endDate));
osw.write("\n\n\n"); osw.write("\n\n\n");
if (recentChecksums.size() == 0) { if (recentChecksums.isEmpty()) {
osw.write("\n\n"); osw.write("\n\n");
osw.write(msg("no-bitstreams-to-delete")); osw.write(msg("no-bitstreams-to-delete"));
osw.write("\n"); osw.write("\n");
@@ -119,7 +119,7 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
osw.write(applyDateFormatShort(endDate)); osw.write(applyDateFormatShort(endDate));
osw.write("\n\n\n"); osw.write("\n\n\n");
if (history.size() == 0) { if (history.isEmpty()) {
osw.write("\n\n"); osw.write("\n\n");
osw.write(msg("no-changed-bitstreams")); osw.write(msg("no-changed-bitstreams"));
osw.write("\n"); osw.write("\n");
@@ -159,7 +159,7 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
osw.write(applyDateFormatShort(endDate)); osw.write(applyDateFormatShort(endDate));
osw.write("\n\n\n"); osw.write("\n\n\n");
if (history.size() == 0) { if (history.isEmpty()) {
osw.write("\n\n"); osw.write("\n\n");
osw.write(msg("no-bitstreams-changed")); osw.write(msg("no-bitstreams-changed"));
osw.write("\n"); osw.write("\n");
@@ -201,7 +201,7 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
osw.write(applyDateFormatShort(endDate)); osw.write(applyDateFormatShort(endDate));
osw.write("\n\n\n"); osw.write("\n\n\n");
if (mostRecentChecksums.size() == 0) { if (mostRecentChecksums.isEmpty()) {
osw.write("\n\n"); osw.write("\n\n");
osw.write(msg("no-bitstreams-to-no-longer-be-processed")); osw.write(msg("no-bitstreams-to-no-longer-be-processed"));
osw.write("\n"); osw.write("\n");
@@ -233,7 +233,7 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
osw.write(applyDateFormatShort(new Date())); osw.write(applyDateFormatShort(new Date()));
osw.write("\n\n\n"); osw.write("\n\n\n");
if (bitstreams.size() == 0) { if (bitstreams.isEmpty()) {
osw.write("\n\n"); osw.write("\n\n");
osw.write(msg("no-unchecked-bitstreams")); osw.write(msg("no-unchecked-bitstreams"));
osw.write("\n"); osw.write("\n");
@@ -257,7 +257,7 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
protected void printHistoryRecords(List<MostRecentChecksum> mostRecentChecksums, OutputStreamWriter osw) protected void printHistoryRecords(List<MostRecentChecksum> mostRecentChecksums, OutputStreamWriter osw)
throws IOException { throws IOException {
for (MostRecentChecksum mostRecentChecksum : mostRecentChecksums) { for (MostRecentChecksum mostRecentChecksum : mostRecentChecksums) {
StringBuffer buf = new StringBuffer(1000); StringBuilder buf = new StringBuilder(1000);
buf.append("------------------------------------------------ \n"); buf.append("------------------------------------------------ \n");
buf.append(msg("bitstream-id")).append(" = ").append( buf.append(msg("bitstream-id")).append(" = ").append(
mostRecentChecksum.getBitstream().getID()).append("\n"); mostRecentChecksum.getBitstream().getID()).append("\n");
@@ -292,7 +292,7 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
throws IOException, SQLException { throws IOException, SQLException {
for (Bitstream info : bitstreams) { for (Bitstream info : bitstreams) {
StringBuffer buf = new StringBuffer(1000); StringBuilder buf = new StringBuilder(1000);
buf.append("------------------------------------------------ \n"); buf.append("------------------------------------------------ \n");
buf.append(msg("format-id")).append(" = ").append( buf.append(msg("format-id")).append(" = ").append(
info.getFormat(context).getID()).append("\n"); info.getFormat(context).getID()).append("\n");

View File

@@ -21,8 +21,6 @@ import javax.persistence.OneToOne;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.Transient; import javax.persistence.Transient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.Constants; import org.dspace.core.Constants;
@@ -37,17 +35,10 @@ import org.hibernate.proxy.HibernateProxyHelper;
* the contents of a bitstream; you need to create a new bitstream. * the contents of a bitstream; you need to create a new bitstream.
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$
*/ */
@Entity @Entity
@Table(name = "bitstream") @Table(name = "bitstream")
public class Bitstream extends DSpaceObject implements DSpaceObjectLegacySupport { public class Bitstream extends DSpaceObject implements DSpaceObjectLegacySupport {
/**
* log4j logger
*/
private static final Logger log = LogManager.getLogger();
@Column(name = "bitstream_id", insertable = false, updatable = false) @Column(name = "bitstream_id", insertable = false, updatable = false)
private Integer legacyId; private Integer legacyId;
@@ -412,7 +403,7 @@ public class Bitstream extends DSpaceObject implements DSpaceObjectLegacySupport
*/ */
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (other == null) { if (!(other instanceof Bitstream)) {
return false; return false;
} }
Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(other); Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(other);
@@ -420,11 +411,7 @@ public class Bitstream extends DSpaceObject implements DSpaceObjectLegacySupport
return false; return false;
} }
final Bitstream otherBitstream = (Bitstream) other; final Bitstream otherBitstream = (Bitstream) other;
if (!this.getID().equals(otherBitstream.getID())) { return this.getID().equals(otherBitstream.getID());
return false;
}
return true;
} }
@Override @Override

View File

@@ -9,7 +9,7 @@ package org.dspace.content;
import java.io.Serializable; import java.io.Serializable;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.persistence.CollectionTable; import javax.persistence.CollectionTable;
import javax.persistence.Column; import javax.persistence.Column;
@@ -40,7 +40,6 @@ import org.hibernate.proxy.HibernateProxyHelper;
* when <code>update</code> is called. * when <code>update</code> is called.
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$
*/ */
@Entity @Entity
@Table(name = "bitstreamformatregistry") @Table(name = "bitstreamformatregistry")
@@ -112,7 +111,7 @@ public class BitstreamFormat implements Serializable, ReloadableEntity<Integer>
* {@link org.dspace.content.service.BitstreamFormatService#create(Context)} * {@link org.dspace.content.service.BitstreamFormatService#create(Context)}
*/ */
protected BitstreamFormat() { protected BitstreamFormat() {
fileExtensions = new LinkedList<>(); fileExtensions = new ArrayList<>();
} }
/** /**
@@ -120,6 +119,7 @@ public class BitstreamFormat implements Serializable, ReloadableEntity<Integer>
* *
* @return the internal identifier * @return the internal identifier
*/ */
@Override
public final Integer getID() { public final Integer getID() {
return id; return id;
} }
@@ -267,7 +267,7 @@ public class BitstreamFormat implements Serializable, ReloadableEntity<Integer>
*/ */
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (other == null) { if (!(other instanceof BitstreamFormat)) {
return false; return false;
} }
Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(other); Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(other);
@@ -275,11 +275,7 @@ public class BitstreamFormat implements Serializable, ReloadableEntity<Integer>
return false; return false;
} }
final BitstreamFormat otherBitstreamFormat = (BitstreamFormat) other; final BitstreamFormat otherBitstreamFormat = (BitstreamFormat) other;
if (!this.getID().equals(otherBitstreamFormat.getID())) { return this.getID().equals(otherBitstreamFormat.getID());
return false;
}
return true;
} }
@Override @Override

View File

@@ -45,7 +45,8 @@ public class BitstreamServiceImpl extends DSpaceObjectServiceImpl<Bitstream> imp
/** /**
* log4j logger * log4j logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(BitstreamServiceImpl.class); private static final Logger log
= org.apache.logging.log4j.LogManager.getLogger();
@Autowired(required = true) @Autowired(required = true)
@@ -350,7 +351,8 @@ public class BitstreamServiceImpl extends DSpaceObjectServiceImpl<Bitstream> imp
public void expunge(Context context, Bitstream bitstream) throws SQLException, AuthorizeException { public void expunge(Context context, Bitstream bitstream) throws SQLException, AuthorizeException {
authorizeService.authorizeAction(context, bitstream, Constants.DELETE); authorizeService.authorizeAction(context, bitstream, Constants.DELETE);
if (!bitstream.isDeleted()) { if (!bitstream.isDeleted()) {
throw new IllegalStateException("Bitstream must be deleted before it can be removed from the database"); throw new IllegalStateException("Bitstream " + bitstream.getID().toString()
+ " must be deleted before it can be removed from the database.");
} }
bitstreamDAO.delete(context, bitstream); bitstreamDAO.delete(context, bitstream);
} }

View File

@@ -9,7 +9,6 @@ package org.dspace.content;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@@ -138,7 +137,7 @@ public class Bundle extends DSpaceObject implements DSpaceObjectLegacySupport {
* @return the bitstreams * @return the bitstreams
*/ */
public List<Bitstream> getBitstreams() { public List<Bitstream> getBitstreams() {
List<Bitstream> bitstreamList = new LinkedList<>(this.bitstreams); List<Bitstream> bitstreamList = new ArrayList<>(this.bitstreams);
return bitstreamList; return bitstreamList;
} }
@@ -191,7 +190,7 @@ public class Bundle extends DSpaceObject implements DSpaceObjectLegacySupport {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null) { if (obj == null || !(obj instanceof Bundle)) {
return false; return false;
} }
Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj); Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
@@ -202,10 +201,7 @@ public class Bundle extends DSpaceObject implements DSpaceObjectLegacySupport {
if (this.getType() != other.getType()) { if (this.getType() != other.getType()) {
return false; return false;
} }
if (!this.getID().equals(other.getID())) { return this.getID().equals(other.getID());
return false;
}
return true;
} }
@Override @Override

View File

@@ -318,7 +318,7 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> i
* whitespace. * whitespace.
*/ */
if (value == null) { if (value == null) {
clearMetadata(context, collection, field.SCHEMA, field.ELEMENT, field.QUALIFIER, Item.ANY); clearMetadata(context, collection, field.schema, field.element, field.qualifier, Item.ANY);
collection.setMetadataModified(); collection.setMetadataModified();
} else { } else {
super.setMetadataSingleValue(context, collection, field, null, value); super.setMetadataSingleValue(context, collection, field, null, value);

View File

@@ -24,7 +24,6 @@ import javax.persistence.Table;
import javax.persistence.Transient; import javax.persistence.Transient;
import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.logging.log4j.Logger;
import org.dspace.content.comparator.NameAscendingComparator; import org.dspace.content.comparator.NameAscendingComparator;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
@@ -42,18 +41,12 @@ import org.hibernate.proxy.HibernateProxyHelper;
* <code>update</code> is called. * <code>update</code> is called.
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$
*/ */
@Entity @Entity
@Table(name = "community") @Table(name = "community")
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, include = "non-lazy") @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, include = "non-lazy")
public class Community extends DSpaceObject implements DSpaceObjectLegacySupport { public class Community extends DSpaceObject implements DSpaceObjectLegacySupport {
/**
* log4j category
*/
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(Community.class);
@Column(name = "community_id", insertable = false, updatable = false) @Column(name = "community_id", insertable = false, updatable = false)
private Integer legacyId; private Integer legacyId;
@@ -215,7 +208,7 @@ public class Community extends DSpaceObject implements DSpaceObjectLegacySupport
*/ */
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (other == null) { if (!(other instanceof Community)) {
return false; return false;
} }
Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(other); Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(other);
@@ -223,11 +216,7 @@ public class Community extends DSpaceObject implements DSpaceObjectLegacySupport
return false; return false;
} }
final Community otherCommunity = (Community) other; final Community otherCommunity = (Community) other;
if (!this.getID().equals(otherCommunity.getID())) { return this.getID().equals(otherCommunity.getID());
return false;
}
return true;
} }
@Override @Override

View File

@@ -195,7 +195,7 @@ public class CommunityServiceImpl extends DSpaceObjectServiceImpl<Community> imp
* whitespace. * whitespace.
*/ */
if (value == null) { if (value == null) {
clearMetadata(context, community, field.SCHEMA, field.ELEMENT, field.QUALIFIER, Item.ANY); clearMetadata(context, community, field.schema, field.element, field.qualifier, Item.ANY);
community.setMetadataModified(); community.setMetadataModified();
} else { } else {
super.setMetadataSingleValue(context, community, field, null, value); super.setMetadataSingleValue(context, community, field, null, value);

View File

@@ -34,12 +34,11 @@ import org.apache.logging.log4j.Logger;
* There are four levels of granularity, depending on how much date information * There are four levels of granularity, depending on how much date information
* is available: year, month, day, time. * is available: year, month, day, time.
* <P> * <P>
* Examples: <code>1994-05-03T15:30:24</code>,<code>1995-10-04</code>, * Examples: {@code 1994-05-03T15:30:24}, {@code 1995-10-04},
* <code>2001-10</code>,<code>1975</code> * {@code 2001-10}, {@code 1975}
* *
* @author Robert Tansley * @author Robert Tansley
* @author Larry Stone * @author Larry Stone
* @version $Revision$
*/ */
public class DCDate { public class DCDate {
/** /**
@@ -262,7 +261,7 @@ public class DCDate {
* @return the year * @return the year
*/ */
public int getYear() { public int getYear() {
return (!withinGranularity(DateGran.YEAR)) ? -1 : localCalendar.get(Calendar.YEAR); return !withinGranularity(DateGran.YEAR) ? -1 : localCalendar.get(Calendar.YEAR);
} }
/** /**
@@ -271,7 +270,7 @@ public class DCDate {
* @return the month * @return the month
*/ */
public int getMonth() { public int getMonth() {
return (!withinGranularity(DateGran.MONTH)) ? -1 : localCalendar.get(Calendar.MONTH) + 1; return !withinGranularity(DateGran.MONTH) ? -1 : localCalendar.get(Calendar.MONTH) + 1;
} }
/** /**
@@ -280,7 +279,7 @@ public class DCDate {
* @return the day * @return the day
*/ */
public int getDay() { public int getDay() {
return (!withinGranularity(DateGran.DAY)) ? -1 : localCalendar.get(Calendar.DAY_OF_MONTH); return !withinGranularity(DateGran.DAY) ? -1 : localCalendar.get(Calendar.DAY_OF_MONTH);
} }
/** /**
@@ -289,7 +288,7 @@ public class DCDate {
* @return the hour * @return the hour
*/ */
public int getHour() { public int getHour() {
return (!withinGranularity(DateGran.TIME)) ? -1 : localCalendar.get(Calendar.HOUR_OF_DAY); return !withinGranularity(DateGran.TIME) ? -1 : localCalendar.get(Calendar.HOUR_OF_DAY);
} }
/** /**
@@ -298,7 +297,7 @@ public class DCDate {
* @return the minute * @return the minute
*/ */
public int getMinute() { public int getMinute() {
return (!withinGranularity(DateGran.TIME)) ? -1 : localCalendar.get(Calendar.MINUTE); return !withinGranularity(DateGran.TIME) ? -1 : localCalendar.get(Calendar.MINUTE);
} }
/** /**
@@ -307,7 +306,7 @@ public class DCDate {
* @return the second * @return the second
*/ */
public int getSecond() { public int getSecond() {
return (!withinGranularity(DateGran.TIME)) ? -1 : localCalendar.get(Calendar.SECOND); return !withinGranularity(DateGran.TIME) ? -1 : localCalendar.get(Calendar.SECOND);
} }
/** /**
@@ -316,7 +315,7 @@ public class DCDate {
* @return the year * @return the year
*/ */
public int getYearUTC() { public int getYearUTC() {
return (!withinGranularity(DateGran.YEAR)) ? -1 : calendar.get(Calendar.YEAR); return !withinGranularity(DateGran.YEAR) ? -1 : calendar.get(Calendar.YEAR);
} }
/** /**
@@ -325,7 +324,7 @@ public class DCDate {
* @return the month * @return the month
*/ */
public int getMonthUTC() { public int getMonthUTC() {
return (!withinGranularity(DateGran.MONTH)) ? -1 : calendar.get(Calendar.MONTH) + 1; return !withinGranularity(DateGran.MONTH) ? -1 : calendar.get(Calendar.MONTH) + 1;
} }
/** /**
@@ -334,7 +333,7 @@ public class DCDate {
* @return the day * @return the day
*/ */
public int getDayUTC() { public int getDayUTC() {
return (!withinGranularity(DateGran.DAY)) ? -1 : calendar.get(Calendar.DAY_OF_MONTH); return !withinGranularity(DateGran.DAY) ? -1 : calendar.get(Calendar.DAY_OF_MONTH);
} }
/** /**
@@ -343,7 +342,7 @@ public class DCDate {
* @return the hour * @return the hour
*/ */
public int getHourUTC() { public int getHourUTC() {
return (!withinGranularity(DateGran.TIME)) ? -1 : calendar.get(Calendar.HOUR_OF_DAY); return !withinGranularity(DateGran.TIME) ? -1 : calendar.get(Calendar.HOUR_OF_DAY);
} }
/** /**
@@ -352,7 +351,7 @@ public class DCDate {
* @return the minute * @return the minute
*/ */
public int getMinuteUTC() { public int getMinuteUTC() {
return (!withinGranularity(DateGran.TIME)) ? -1 : calendar.get(Calendar.MINUTE); return !withinGranularity(DateGran.TIME) ? -1 : calendar.get(Calendar.MINUTE);
} }
/** /**
@@ -361,15 +360,15 @@ public class DCDate {
* @return the second * @return the second
*/ */
public int getSecondUTC() { public int getSecondUTC() {
return (!withinGranularity(DateGran.TIME)) ? -1 : calendar.get(Calendar.SECOND); return !withinGranularity(DateGran.TIME) ? -1 : calendar.get(Calendar.SECOND);
} }
/** /**
* Get the date as a string to put back in the Dublin Core. Use the UTC/GMT calendar version. * Get the date as a string to put back in the Dublin Core. Use the UTC/GMT calendar version.
* *
* @return The date as a string. * @return The date as a string.
*/ */
@Override
public String toString() { public String toString() {
if (calendar == null) { if (calendar == null) {
return "null"; return "null";

View File

@@ -18,7 +18,6 @@ package org.dspace.content;
* <em>FIXME: No policy for dealing with "van"/"van der" and "Jr."</em> * <em>FIXME: No policy for dealing with "van"/"van der" and "Jr."</em>
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$
*/ */
public class DCPersonName { public class DCPersonName {
/** /**
@@ -89,8 +88,9 @@ public class DCPersonName {
* *
* @return the name, suitable for putting in the database * @return the name, suitable for putting in the database
*/ */
@Override
public String toString() { public String toString() {
StringBuffer out = new StringBuffer(); StringBuilder out = new StringBuilder();
if (lastName != null) { if (lastName != null) {
out.append(lastName); out.append(lastName);

View File

@@ -8,10 +8,9 @@
package org.dspace.content; package org.dspace.content;
/** /**
* Series and report number, as stored in relation.ispartofseries * Series and report number, as stored in {@code relation.ispartofseries}.
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Id$
*/ */
public class DCSeriesNumber { public class DCSeriesNumber {
/** /**
@@ -70,6 +69,7 @@ public class DCSeriesNumber {
* *
* @return the series and number as they should be stored in the DB * @return the series and number as they should be stored in the DB
*/ */
@Override
public String toString() { public String toString() {
if (series == null) { if (series == null) {
return (null); return (null);

View File

@@ -61,7 +61,7 @@ public abstract class DSpaceObject implements Serializable, ReloadableEntity<jav
private List<Handle> handles = new ArrayList<>(); private List<Handle> handles = new ArrayList<>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "dSpaceObject", cascade = CascadeType.ALL) @OneToMany(fetch = FetchType.LAZY, mappedBy = "dSpaceObject", cascade = CascadeType.ALL)
private List<ResourcePolicy> resourcePolicies = new ArrayList<>(); private final List<ResourcePolicy> resourcePolicies = new ArrayList<>();
/** /**
* True if anything else was changed since last update() * True if anything else was changed since last update()

View File

@@ -13,11 +13,11 @@ import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.NotImplementedException;
@@ -435,7 +435,7 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
@Override @Override
public String getMetadataFirstValue(T dso, MetadataFieldName field, String language) { public String getMetadataFirstValue(T dso, MetadataFieldName field, String language) {
List<MetadataValue> metadataValues List<MetadataValue> metadataValues
= getMetadata(dso, field.SCHEMA, field.ELEMENT, field.QUALIFIER, language); = getMetadata(dso, field.schema, field.element, field.qualifier, language);
if (CollectionUtils.isNotEmpty(metadataValues)) { if (CollectionUtils.isNotEmpty(metadataValues)) {
return metadataValues.get(0).getValue(); return metadataValues.get(0).getValue();
} }
@@ -462,11 +462,11 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
String language, String value) String language, String value)
throws SQLException { throws SQLException {
if (value != null) { if (value != null) {
clearMetadata(context, dso, field.SCHEMA, field.ELEMENT, field.QUALIFIER, clearMetadata(context, dso, field.schema, field.element, field.qualifier,
language); language);
String newValueLanguage = (Item.ANY.equals(language)) ? null : language; String newValueLanguage = Item.ANY.equals(language) ? null : language;
addMetadata(context, dso, field.SCHEMA, field.ELEMENT, field.QUALIFIER, addMetadata(context, dso, field.schema, field.element, field.qualifier,
newValueLanguage, value); newValueLanguage, value);
dso.setMetadataModified(); dso.setMetadataModified();
} }
@@ -610,7 +610,7 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
*/ */
// A map created to store the latest place for each metadata field // A map created to store the latest place for each metadata field
Map<MetadataField, Integer> fieldToLastPlace = new HashMap<>(); Map<MetadataField, Integer> fieldToLastPlace = new HashMap<>();
List<MetadataValue> metadataValues = new LinkedList<>(); List<MetadataValue> metadataValues;
if (dso.getType() == Constants.ITEM) { if (dso.getType() == Constants.ITEM) {
metadataValues = getMetadata(dso, Item.ANY, Item.ANY, Item.ANY, Item.ANY); metadataValues = getMetadata(dso, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
} else { } else {
@@ -643,7 +643,7 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
String authority = metadataValue.getAuthority(); String authority = metadataValue.getAuthority();
String relationshipId = StringUtils.split(authority, "::")[1]; String relationshipId = StringUtils.split(authority, "::")[1];
Relationship relationship = relationshipService.find(context, Integer.parseInt(relationshipId)); Relationship relationship = relationshipService.find(context, Integer.parseInt(relationshipId));
if (relationship.getLeftItem() == (Item) dso) { if (relationship.getLeftItem().equals((Item) dso)) {
relationship.setLeftPlace(mvPlace); relationship.setLeftPlace(mvPlace);
} else { } else {
relationship.setRightPlace(mvPlace); relationship.setRightPlace(mvPlace);
@@ -742,12 +742,15 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
@Override @Override
public void moveMetadata(Context context, T dso, String schema, String element, String qualifier, int from, int to) public void moveMetadata(Context context, T dso, String schema, String element, String qualifier, int from, int to)
throws SQLException, IllegalArgumentException { throws SQLException, IllegalArgumentException {
if (from == to) { if (from == to) {
throw new IllegalArgumentException("The \"from\" location MUST be different from \"to\" location"); throw new IllegalArgumentException("The \"from\" location MUST be different from \"to\" location");
} }
List<MetadataValue> list = getMetadata(dso, schema, element, qualifier); List<MetadataValue> list =
getMetadata(dso, schema, element, qualifier).stream()
.sorted(Comparator.comparing(MetadataValue::getPlace))
.collect(Collectors.toList());
if (from >= list.size() || to >= list.size() || to < 0 || from < 0) { if (from >= list.size() || to >= list.size() || to < 0 || from < 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@@ -78,6 +78,7 @@ public class EntityType implements ReloadableEntity<Integer> {
* *
* @return The ID for this EntityType * @return The ID for this EntityType
*/ */
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }
@@ -87,6 +88,7 @@ public class EntityType implements ReloadableEntity<Integer> {
* @param obj object to be compared * @param obj object to be compared
* @return * @return
*/ */
@Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof EntityType)) { if (!(obj instanceof EntityType)) {
return false; return false;
@@ -97,10 +99,7 @@ public class EntityType implements ReloadableEntity<Integer> {
return false; return false;
} }
if (!StringUtils.equals(this.getLabel(), entityType.getLabel())) { return StringUtils.equals(this.getLabel(), entityType.getLabel());
return false;
}
return true;
} }
/** /**

View File

@@ -17,7 +17,6 @@ import org.dspace.eperson.EPerson;
* which stage of submission they are (in workspace or workflow system) * which stage of submission they are (in workspace or workflow system)
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$
*/ */
public interface InProgressSubmission extends ReloadableEntity<Integer> { public interface InProgressSubmission extends ReloadableEntity<Integer> {
/** /**
@@ -25,6 +24,7 @@ public interface InProgressSubmission extends ReloadableEntity<Integer> {
* *
* @return the internal identifier * @return the internal identifier
*/ */
@Override
Integer getID(); Integer getID();
/** /**

View File

@@ -27,8 +27,6 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; import javax.persistence.Transient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dspace.content.comparator.NameAscendingComparator; import org.dspace.content.comparator.NameAscendingComparator;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
@@ -49,17 +47,10 @@ import org.hibernate.proxy.HibernateProxyHelper;
* *
* @author Robert Tansley * @author Robert Tansley
* @author Martin Hald * @author Martin Hald
* @version $Revision$
*/ */
@Entity @Entity
@Table(name = "item") @Table(name = "item")
public class Item extends DSpaceObject implements DSpaceObjectLegacySupport { public class Item extends DSpaceObject implements DSpaceObjectLegacySupport {
/**
* log4j logger
*/
private static final Logger log = LogManager.getLogger();
/** /**
* Wild card for Dublin Core metadata qualifiers/languages * Wild card for Dublin Core metadata qualifiers/languages
*/ */
@@ -297,7 +288,7 @@ public class Item extends DSpaceObject implements DSpaceObjectLegacySupport {
* @return the bundles in an unordered array * @return the bundles in an unordered array
*/ */
public List<Bundle> getBundles(String name) { public List<Bundle> getBundles(String name) {
List<Bundle> matchingBundles = new ArrayList<Bundle>(); List<Bundle> matchingBundles = new ArrayList<>();
// now only keep bundles with matching names // now only keep bundles with matching names
List<Bundle> bunds = getBundles(); List<Bundle> bunds = getBundles();
for (Bundle bundle : bunds) { for (Bundle bundle : bunds) {
@@ -328,7 +319,7 @@ public class Item extends DSpaceObject implements DSpaceObjectLegacySupport {
/** /**
* Return <code>true</code> if <code>other</code> is the same Item as * Return <code>true</code> if <code>other</code> is the same Item as
* this object, <code>false</code> otherwise * this object, <code>false</code> otherwise.
* *
* @param obj object to compare to * @param obj object to compare to
* @return <code>true</code> if object passed in represents the same item * @return <code>true</code> if object passed in represents the same item
@@ -336,7 +327,7 @@ public class Item extends DSpaceObject implements DSpaceObjectLegacySupport {
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null) { if (!(obj instanceof Item)) {
return false; return false;
} }
Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj); Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
@@ -344,10 +335,7 @@ public class Item extends DSpaceObject implements DSpaceObjectLegacySupport {
return false; return false;
} }
final Item otherItem = (Item) obj; final Item otherItem = (Item) obj;
if (!this.getID().equals(otherItem.getID())) { return this.getID().equals(otherItem.getID());
return false;
}
return true;
} }
@Override @Override

View File

@@ -32,7 +32,6 @@ import org.hibernate.proxy.HibernateProxyHelper;
* metadata element belongs in a field. * metadata element belongs in a field.
* *
* @author Martin Hald * @author Martin Hald
* @version $Revision$
* @see org.dspace.content.MetadataValue * @see org.dspace.content.MetadataValue
* @see org.dspace.content.MetadataSchema * @see org.dspace.content.MetadataSchema
*/ */
@@ -77,6 +76,7 @@ public class MetadataField implements ReloadableEntity<Integer> {
* *
* @return metadata field id * @return metadata field id
*/ */
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }
@@ -164,7 +164,7 @@ public class MetadataField implements ReloadableEntity<Integer> {
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null) { if (!(obj instanceof MetadataField)) {
return false; return false;
} }
Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj); Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
@@ -175,10 +175,7 @@ public class MetadataField implements ReloadableEntity<Integer> {
if (!this.getID().equals(other.getID())) { if (!this.getID().equals(other.getID())) {
return false; return false;
} }
if (!getMetadataSchema().equals(other.getMetadataSchema())) { return getMetadataSchema().equals(other.getMetadataSchema());
return false;
}
return true;
} }
@Override @Override

View File

@@ -17,13 +17,13 @@ import javax.annotation.Nonnull;
*/ */
public class MetadataFieldName { public class MetadataFieldName {
/** Name of the metadata schema which defines this field. Never null. */ /** Name of the metadata schema which defines this field. Never null. */
public final String SCHEMA; public final String schema;
/** Element name of this field. Never null. */ /** Element name of this field. Never null. */
public final String ELEMENT; public final String element;
/** Qualifier name of this field. May be {@code null}. */ /** Qualifier name of this field. May be {@code null}. */
public final String QUALIFIER; public final String qualifier;
/** /**
* Initialize a tuple of (schema, element, qualifier) to name a metadata field. * Initialize a tuple of (schema, element, qualifier) to name a metadata field.
@@ -40,9 +40,9 @@ public class MetadataFieldName {
throw new NullPointerException("Element must not be null."); throw new NullPointerException("Element must not be null.");
} }
SCHEMA = schema; this.schema = schema;
ELEMENT = element; this.element = element;
QUALIFIER = qualifier; this.qualifier = qualifier;
} }
/** /**
@@ -59,9 +59,9 @@ public class MetadataFieldName {
throw new NullPointerException("Element must not be null."); throw new NullPointerException("Element must not be null.");
} }
SCHEMA = schema; this.schema = schema;
ELEMENT = element; this.element = element;
QUALIFIER = null; qualifier = null;
} }
/** /**
@@ -79,9 +79,9 @@ public class MetadataFieldName {
throw new IllegalArgumentException("Element must not be null."); throw new IllegalArgumentException("Element must not be null.");
} }
SCHEMA = schema.getName(); this.schema = schema.getName();
ELEMENT = element; this.element = element;
QUALIFIER = qualifier; this.qualifier = qualifier;
} }
/** /**
@@ -98,9 +98,9 @@ public class MetadataFieldName {
throw new IllegalArgumentException("Element must not be null."); throw new IllegalArgumentException("Element must not be null.");
} }
SCHEMA = schema.getName(); this.schema = schema.getName();
ELEMENT = element; this.element = element;
QUALIFIER = null; qualifier = null;
} }
/** /**
@@ -110,9 +110,9 @@ public class MetadataFieldName {
*/ */
public MetadataFieldName(@Nonnull String name) { public MetadataFieldName(@Nonnull String name) {
String[] elements = parse(name); String[] elements = parse(name);
SCHEMA = elements[0]; schema = elements[0];
ELEMENT = elements[1]; element = elements[1];
QUALIFIER = elements[2]; qualifier = elements[2];
} }
/** /**
@@ -138,17 +138,17 @@ public class MetadataFieldName {
/** /**
* Format a dotted-atoms representation of this field name. * Format a dotted-atoms representation of this field name.
* @return SCHEMA.ELEMENT.QUALIFIER * @return schema.element.qualifier
*/ */
@Override @Override
public String toString() { public String toString() {
StringBuilder buffer = new StringBuilder(32); StringBuilder buffer = new StringBuilder(32);
buffer.append(SCHEMA) buffer.append(schema)
.append('.') .append('.')
.append(ELEMENT); .append(element);
if (null != QUALIFIER) { if (null != qualifier) {
buffer.append('.') buffer.append('.')
.append(QUALIFIER); .append(qualifier);
} }
return buffer.toString(); return buffer.toString();
} }

View File

@@ -30,7 +30,6 @@ import org.hibernate.proxy.HibernateProxyHelper;
* </p> * </p>
* *
* @author Martin Hald * @author Martin Hald
* @version $Revision$
* @see org.dspace.content.MetadataValue * @see org.dspace.content.MetadataValue
* @see org.dspace.content.MetadataField * @see org.dspace.content.MetadataField
*/ */
@@ -129,6 +128,7 @@ public class MetadataSchema implements ReloadableEntity<Integer> {
* *
* @return schema record key * @return schema record key
*/ */
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }

View File

@@ -46,7 +46,7 @@ public class MetadataValue implements ReloadableEntity<Integer> {
@Column(name = "metadata_value_id") @Column(name = "metadata_value_id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "metadatavalue_seq") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "metadatavalue_seq")
@SequenceGenerator(name = "metadatavalue_seq", sequenceName = "metadatavalue_seq", allocationSize = 1) @SequenceGenerator(name = "metadatavalue_seq", sequenceName = "metadatavalue_seq", allocationSize = 1)
private Integer id; private final Integer id;
/** /**
* The primary key for the metadata value * The primary key for the metadata value
@@ -104,6 +104,7 @@ public class MetadataValue implements ReloadableEntity<Integer> {
* *
* @return metadata value ID * @return metadata value ID
*/ */
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }
@@ -249,10 +250,7 @@ public class MetadataValue implements ReloadableEntity<Integer> {
if (!this.getID().equals(other.getID())) { if (!this.getID().equals(other.getID())) {
return false; return false;
} }
if (!this.getDSpaceObject().getID().equals(other.getDSpaceObject().getID())) { return this.getDSpaceObject().getID().equals(other.getDSpaceObject().getID());
return false;
}
return true;
} }
@Override @Override

View File

@@ -220,6 +220,7 @@ public class Relationship implements ReloadableEntity<Integer> {
* Standard getter for the ID for this Relationship * Standard getter for the ID for this Relationship
* @return The ID of this relationship * @return The ID of this relationship
*/ */
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }

View File

@@ -8,9 +8,9 @@
package org.dspace.content; package org.dspace.content;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
@@ -250,7 +250,7 @@ public class RelationshipServiceImpl implements RelationshipService {
} }
List<Relationship> rightRelationships = findByItemAndRelationshipType(context, itemToProcess, relationshipType, List<Relationship> rightRelationships = findByItemAndRelationshipType(context, itemToProcess, relationshipType,
isLeft); isLeft);
if (maxCardinality != null && rightRelationships.size() >= maxCardinality) { if (rightRelationships.size() >= maxCardinality) {
return false; return false;
} }
return true; return true;
@@ -266,6 +266,7 @@ public class RelationshipServiceImpl implements RelationshipService {
return StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel()); return StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel());
} }
@Override
public Relationship find(Context context, int id) throws SQLException { public Relationship find(Context context, int id) throws SQLException {
Relationship relationship = relationshipDAO.findByID(context, Relationship.class, id); Relationship relationship = relationshipDAO.findByID(context, Relationship.class, id);
return relationship; return relationship;
@@ -407,7 +408,7 @@ public class RelationshipServiceImpl implements RelationshipService {
// Set a limit on the total depth of relationships to traverse during a relationship change // Set a limit on the total depth of relationships to traverse during a relationship change
int maxDepth = configurationService.getIntProperty("relationship.update.relateditems.maxdepth", 5); int maxDepth = configurationService.getIntProperty("relationship.update.relateditems.maxdepth", 5);
// This is the list containing all items which will have changes to their virtual metadata // This is the list containing all items which will have changes to their virtual metadata
List<Item> itemsToUpdate = new LinkedList<>(); List<Item> itemsToUpdate = new ArrayList<>();
itemsToUpdate.add(relationship.getLeftItem()); itemsToUpdate.add(relationship.getLeftItem());
itemsToUpdate.add(relationship.getRightItem()); itemsToUpdate.add(relationship.getRightItem());

View File

@@ -208,7 +208,7 @@ public class RelationshipType implements ReloadableEntity<Integer> {
/** /**
* Standard setter for the leftMinCardinality Integer for this RelationshipType * Standard setter for the leftMinCardinality Integer for this RelationshipType
* @param leftMinCardinality The leftMinCardinality Integer that this RelationshipType should recieve * @param leftMinCardinality The leftMinCardinality Integer that this RelationshipType should receive
*/ */
public void setLeftMinCardinality(Integer leftMinCardinality) { public void setLeftMinCardinality(Integer leftMinCardinality) {
this.leftMinCardinality = leftMinCardinality; this.leftMinCardinality = leftMinCardinality;
@@ -224,7 +224,7 @@ public class RelationshipType implements ReloadableEntity<Integer> {
/** /**
* Standard setter for the leftMaxCardinality Integer for this RelationshipType * Standard setter for the leftMaxCardinality Integer for this RelationshipType
* @param leftMaxCardinality The leftMaxCardinality Integer that this RelationshipType should recieve * @param leftMaxCardinality The leftMaxCardinality Integer that this RelationshipType should receive
*/ */
public void setLeftMaxCardinality(Integer leftMaxCardinality) { public void setLeftMaxCardinality(Integer leftMaxCardinality) {
this.leftMaxCardinality = leftMaxCardinality; this.leftMaxCardinality = leftMaxCardinality;
@@ -240,7 +240,7 @@ public class RelationshipType implements ReloadableEntity<Integer> {
/** /**
* Standard setter for the rightMinCardinality Integer for this RelationshipType * Standard setter for the rightMinCardinality Integer for this RelationshipType
* @param rightMinCardinality The rightMinCardinality Integer that this RelationshipType should recieve * @param rightMinCardinality The rightMinCardinality Integer that this RelationshipType should receive
*/ */
public void setRightMinCardinality(Integer rightMinCardinality) { public void setRightMinCardinality(Integer rightMinCardinality) {
this.rightMinCardinality = rightMinCardinality; this.rightMinCardinality = rightMinCardinality;
@@ -256,7 +256,7 @@ public class RelationshipType implements ReloadableEntity<Integer> {
/** /**
* Standard setter for the rightMaxCardinality Integer for this RelationshipType * Standard setter for the rightMaxCardinality Integer for this RelationshipType
* @param rightMaxCardinality The rightMaxCardinality Integer that this RelationshipType should recieve * @param rightMaxCardinality The rightMaxCardinality Integer that this RelationshipType should receive
*/ */
public void setRightMaxCardinality(Integer rightMaxCardinality) { public void setRightMaxCardinality(Integer rightMaxCardinality) {
this.rightMaxCardinality = rightMaxCardinality; this.rightMaxCardinality = rightMaxCardinality;
@@ -318,6 +318,7 @@ public class RelationshipType implements ReloadableEntity<Integer> {
* Standard getter for the ID of this RelationshipType * Standard getter for the ID of this RelationshipType
* @return The ID of this RelationshipType * @return The ID of this RelationshipType
*/ */
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }

View File

@@ -44,17 +44,16 @@ import org.jdom.xpath.XPath;
/** /**
* ORE ingestion crosswalk * ORE ingestion crosswalk
* <p> * <p>
* Processes an Atom-encoded ORE resource map and attemps to interpret it as a DSpace item * Processes an Atom-encoded ORE resource map and attempts to interpret it as a DSpace item.
* *
* @author Alexey Maslov * @author Alexey Maslov
* @version $Revision: 1 $
*/ */
public class OREIngestionCrosswalk public class OREIngestionCrosswalk
implements IngestionCrosswalk { implements IngestionCrosswalk {
/** /**
* log4j category * log4j category
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(OREDisseminationCrosswalk.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger();
/* Namespaces */ /* Namespaces */
public static final Namespace ATOM_NS = public static final Namespace ATOM_NS =
@@ -149,7 +148,7 @@ public class OREIngestionCrosswalk
xpathDesc.addNamespace(RDF_NS); xpathDesc.addNamespace(RDF_NS);
desc = (Element) xpathDesc.selectSingleNode(doc); desc = (Element) xpathDesc.selectSingleNode(doc);
} catch (JDOMException e) { } catch (JDOMException e) {
e.printStackTrace(); log.warn("Could not find description for {}", href, e);
} }
if (desc != null && desc.getChild("type", RDF_NS).getAttributeValue("resource", RDF_NS) if (desc != null && desc.getChild("type", RDF_NS).getAttributeValue("resource", RDF_NS)

View File

@@ -9,7 +9,7 @@ package org.dspace.content.dao.impl;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.persistence.Query; import javax.persistence.Query;
@@ -119,7 +119,7 @@ public class CollectionDAOImpl extends AbstractHibernateDSODAO<Collection> imple
CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, Collection.class); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, Collection.class);
Root<Collection> collectionRoot = criteriaQuery.from(Collection.class); Root<Collection> collectionRoot = criteriaQuery.from(Collection.class);
Join<Collection, ResourcePolicy> join = collectionRoot.join("resourcePolicies"); Join<Collection, ResourcePolicy> join = collectionRoot.join("resourcePolicies");
List<Predicate> orPredicates = new LinkedList<>(); List<Predicate> orPredicates = new ArrayList<>(actions.size());
for (Integer action : actions) { for (Integer action : actions) {
orPredicates.add(criteriaBuilder.equal(join.get(ResourcePolicy_.actionId), action)); orPredicates.add(criteriaBuilder.equal(join.get(ResourcePolicy_.actionId), action));
} }
@@ -176,7 +176,7 @@ public class CollectionDAOImpl extends AbstractHibernateDSODAO<Collection> imple
Query query = createQuery(context, q); Query query = createQuery(context, q);
List<Object[]> list = query.getResultList(); List<Object[]> list = query.getResultList();
List<Map.Entry<Collection, Long>> returnList = new LinkedList<>(); List<Map.Entry<Collection, Long>> returnList = new ArrayList<>(list.size());
for (Object[] o : list) { for (Object[] o : list) {
returnList.add(new AbstractMap.SimpleEntry<>((Collection) o[0], (Long) o[1])); returnList.add(new AbstractMap.SimpleEntry<>((Collection) o[0], (Long) o[1]));
} }

View File

@@ -8,7 +8,7 @@
package org.dspace.content.dao.impl; package org.dspace.content.dao.impl;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.persistence.Query; import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
@@ -63,7 +63,7 @@ public class MetadataSchemaDAOImpl extends AbstractHibernateDAO<MetadataSchema>
Root<MetadataSchema> metadataSchemaRoot = criteriaQuery.from(MetadataSchema.class); Root<MetadataSchema> metadataSchemaRoot = criteriaQuery.from(MetadataSchema.class);
criteriaQuery.select(metadataSchemaRoot); criteriaQuery.select(metadataSchemaRoot);
List<javax.persistence.criteria.Order> orderList = new LinkedList<>(); List<javax.persistence.criteria.Order> orderList = new ArrayList<>();
orderList.add(criteriaBuilder.asc(metadataSchemaRoot.get(MetadataSchema_.id))); orderList.add(criteriaBuilder.asc(metadataSchemaRoot.get(MetadataSchema_.id)));
criteriaQuery.orderBy(orderList); criteriaQuery.orderBy(orderList);

View File

@@ -20,7 +20,6 @@ import org.dspace.core.Context;
* logical statement that shouldn't be use as root element. A filter may contain only one substatement. * logical statement that shouldn't be use as root element. A filter may contain only one substatement.
* *
* @author Kim Shepherd * @author Kim Shepherd
* @version $Revision$
* @see org.dspace.content.logic.DefaultFilter * @see org.dspace.content.logic.DefaultFilter
*/ */
public interface Filter extends LogicalStatement { public interface Filter extends LogicalStatement {
@@ -31,5 +30,6 @@ public interface Filter extends LogicalStatement {
* @return boolean * @return boolean
* @throws LogicalStatementException * @throws LogicalStatementException
*/ */
@Override
boolean getResult(Context context, Item item) throws LogicalStatementException; boolean getResult(Context context, Item item) throws LogicalStatementException;
} }

View File

@@ -45,9 +45,10 @@ public interface Condition extends LogicalStatement {
* Get the result of logical evaluation for an item * Get the result of logical evaluation for an item
* @param context DSpace context * @param context DSpace context
* @param item Item to evaluate * @param item Item to evaluate
* @return boolean * @return result
* @throws LogicalStatementException * @throws LogicalStatementException
*/ */
@Override
boolean getResult(Context context, Item item) throws LogicalStatementException; boolean getResult(Context context, Item item) throws LogicalStatementException;
public void setItemService(ItemService itemService); public void setItemService(ItemService itemService);

View File

@@ -15,10 +15,9 @@ import org.dspace.content.logic.LogicalStatementException;
import org.dspace.core.Context; import org.dspace.core.Context;
/** /**
* An operator that implements NIR by negating an OR operation * An operator that implements NOR by negating an OR operation.
* *
* @author Kim Shepherd * @author Kim Shepherd
* @version $Revision$
*/ */
public class Nor extends AbstractOperator { public class Nor extends AbstractOperator {

View File

@@ -11,6 +11,7 @@ import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
@@ -656,7 +657,7 @@ public class METSManifest {
String mimeType = mdWrap.getAttributeValue("MIMETYPE"); String mimeType = mdWrap.getAttributeValue("MIMETYPE");
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(StandardCharsets.UTF_8));
Document mdd = parser.build(new ByteArrayInputStream(value)); Document mdd = parser.build(new ByteArrayInputStream(value));
List<Element> result = new ArrayList<>(1); List<Element> result = new ArrayList<>(1);
result.add(mdd.getRootElement()); result.add(mdd.getRootElement());
@@ -724,13 +725,13 @@ public class METSManifest {
throw new MetadataValidationException( throw new MetadataValidationException(
"Invalid METS Manifest: mdWrap element with neither xmlData nor binData child."); "Invalid METS Manifest: mdWrap element with neither xmlData nor binData child.");
} else { } else {
byte value[] = Base64.decodeBase64(bin.getText().getBytes()); byte value[] = Base64.decodeBase64(bin.getText().getBytes(StandardCharsets.UTF_8));
return new ByteArrayInputStream(value); return new ByteArrayInputStream(value);
} }
} else { } else {
XMLOutputter outputPretty = new XMLOutputter(Format.getPrettyFormat()); XMLOutputter outputPretty = new XMLOutputter(Format.getPrettyFormat());
return new ByteArrayInputStream( return new ByteArrayInputStream(
outputPretty.outputString(xmlData.getChildren()).getBytes()); outputPretty.outputString(xmlData.getChildren()).getBytes(StandardCharsets.UTF_8));
} }
} else { } else {
mdRef = mdSec.getChild("mdRef", metsNS); mdRef = mdSec.getChild("mdRef", metsNS);
@@ -1176,7 +1177,7 @@ public class METSManifest {
"Invalid METS Manifest: mdWrap element for streaming crosswalk without binData " + "Invalid METS Manifest: mdWrap element for streaming crosswalk without binData " +
"child."); "child.");
} else { } else {
byte value[] = Base64.decodeBase64(bin.getText().getBytes()); byte value[] = Base64.decodeBase64(bin.getText().getBytes(StandardCharsets.UTF_8));
sxwalk.ingest(context, dso, sxwalk.ingest(context, dso,
new ByteArrayInputStream(value), new ByteArrayInputStream(value),
mdWrap.getAttributeValue("MIMETYPE")); mdWrap.getAttributeValue("MIMETYPE"));
@@ -1302,6 +1303,6 @@ public class METSManifest {
XMLOutputter outputPretty = new XMLOutputter(Format.getPrettyFormat()); XMLOutputter outputPretty = new XMLOutputter(Format.getPrettyFormat());
return new ByteArrayInputStream( return new ByteArrayInputStream(
outputPretty.outputString(mets).getBytes()); outputPretty.outputString(mets).getBytes(StandardCharsets.UTF_8));
} }
} }

View File

@@ -19,7 +19,6 @@ import org.apache.logging.log4j.Logger;
* exceptions. This class is intended for declarations and catch clauses. * exceptions. This class is intended for declarations and catch clauses.
* *
* @author Larry Stone * @author Larry Stone
* @version $Revision$
*/ */
public class PackageException extends Exception { public class PackageException extends Exception {
/** /**
@@ -76,10 +75,4 @@ public class PackageException extends Exception {
log.error(sw.toString()); log.error(sw.toString());
} }
} }
public String toString() {
String base = getClass().getName() + ": " + getMessage();
return (getCause() == null) ? base :
base + ", Reason: " + getCause().toString();
}
} }

View File

@@ -57,7 +57,7 @@ public class PackageParameters extends Properties {
} else if (v.length == 1) { } else if (v.length == 1) {
result.setProperty(name, v[0]); result.setProperty(name, v[0]);
} else { } else {
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < v.length; ++i) { for (int i = 0; i < v.length; ++i) {
if (i > 0) { if (i > 0) {
sb.append(SEPARATOR); sb.append(SEPARATOR);

View File

@@ -33,6 +33,7 @@ import org.dspace.core.Context;
*/ */
public interface BitstreamService extends DSpaceObjectService<Bitstream>, DSpaceObjectLegacySupportService<Bitstream> { public interface BitstreamService extends DSpaceObjectService<Bitstream>, DSpaceObjectLegacySupportService<Bitstream> {
@Override
public Bitstream find(Context context, UUID id) throws SQLException; public Bitstream find(Context context, UUID id) throws SQLException;
public List<Bitstream> findAll(Context context) throws SQLException; public List<Bitstream> findAll(Context context) throws SQLException;

View File

@@ -8,7 +8,6 @@
package org.dspace.content.virtual; package org.dspace.content.virtual;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.dspace.content.Item; import org.dspace.content.Item;
@@ -24,9 +23,7 @@ public class UUIDValue implements VirtualMetadataConfiguration {
@Override @Override
public List<String> getValues(Context context, Item item) throws SQLException { public List<String> getValues(Context context, Item item) throws SQLException {
List<String> list = new LinkedList<>(); return List.of(String.valueOf(item.getID()));
list.add(String.valueOf(item.getID()));
return list;
} }
@Override @Override

View File

@@ -9,13 +9,14 @@ package org.dspace.core;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.EmptyStackException; import java.util.Deque;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.Stack;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@@ -46,8 +47,6 @@ import org.springframework.util.CollectionUtils;
* changes and free up the resources. * changes and free up the resources.
* <P> * <P>
* The context object is also used as a cache for CM API objects. * The context object is also used as a cache for CM API objects.
*
* @version $Revision$
*/ */
public class Context implements AutoCloseable { public class Context implements AutoCloseable {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(Context.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(Context.class);
@@ -81,13 +80,13 @@ public class Context implements AutoCloseable {
/** /**
* A stack with the history of authorisation system check modify * A stack with the history of authorisation system check modify
*/ */
private Stack<Boolean> authStateChangeHistory; private Deque<Boolean> authStateChangeHistory;
/** /**
* A stack with the name of the caller class that modify authorisation * A stack with the name of the caller class that modify authorisation
* system check * system check
*/ */
private Stack<String> authStateClassCallHistory; private Deque<String> authStateClassCallHistory;
/** /**
* Group IDs of special groups user is a member of * Group IDs of special groups user is a member of
@@ -117,7 +116,7 @@ public class Context implements AutoCloseable {
/** /**
* Cache that is only used the context is in READ_ONLY mode * Cache that is only used the context is in READ_ONLY mode
*/ */
private ContextReadOnlyCache readOnlyCache = new ContextReadOnlyCache(); private final ContextReadOnlyCache readOnlyCache = new ContextReadOnlyCache();
protected EventService eventService; protected EventService eventService;
@@ -159,8 +158,6 @@ public class Context implements AutoCloseable {
/** /**
* Initializes a new context object. * Initializes a new context object.
*
* @throws SQLException if there was an error obtaining a database connection
*/ */
protected void init() { protected void init() {
updateDatabase(); updateDatabase();
@@ -185,8 +182,8 @@ public class Context implements AutoCloseable {
specialGroups = new ArrayList<>(); specialGroups = new ArrayList<>();
authStateChangeHistory = new Stack<>(); authStateChangeHistory = new ConcurrentLinkedDeque<>();
authStateClassCallHistory = new Stack<>(); authStateClassCallHistory = new ConcurrentLinkedDeque<>();
setMode(this.mode); setMode(this.mode);
} }
@@ -312,10 +309,10 @@ public class Context implements AutoCloseable {
Boolean previousState; Boolean previousState;
try { try {
previousState = authStateChangeHistory.pop(); previousState = authStateChangeHistory.pop();
} catch (EmptyStackException ex) { } catch (NoSuchElementException ex) {
log.warn(LogHelper.getHeader(this, "restore_auth_sys_state", log.warn(LogHelper.getHeader(this, "restore_auth_sys_state",
"not previous state info available " "not previous state info available: {}"),
+ ex.getLocalizedMessage())); ex::getLocalizedMessage);
previousState = Boolean.FALSE; previousState = Boolean.FALSE;
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@@ -323,13 +320,19 @@ public class Context implements AutoCloseable {
StackTraceElement[] stackTrace = currThread.getStackTrace(); StackTraceElement[] stackTrace = currThread.getStackTrace();
String caller = stackTrace[stackTrace.length - 1].getClassName(); String caller = stackTrace[stackTrace.length - 1].getClassName();
String previousCaller = (String) authStateClassCallHistory.pop(); String previousCaller;
try {
previousCaller = (String) authStateClassCallHistory.pop();
} catch (NoSuchElementException ex) {
previousCaller = "none";
log.warn(LogHelper.getHeader(this, "restore_auth_sys_state",
"no previous caller info available: {}"),
ex::getLocalizedMessage);
}
// if previousCaller is not the current caller *only* log a warning // if previousCaller is not the current caller *only* log a warning
if (!previousCaller.equals(caller)) { if (!previousCaller.equals(caller)) {
log log.warn(LogHelper.getHeader(
.warn(LogHelper
.getHeader(
this, this,
"restore_auth_sys_state", "restore_auth_sys_state",
"Class: " "Class: "
@@ -338,7 +341,7 @@ public class Context implements AutoCloseable {
+ previousCaller)); + previousCaller));
} }
} }
ignoreAuth = previousState.booleanValue(); ignoreAuth = previousState;
} }
/** /**
@@ -490,7 +493,7 @@ public class Context implements AutoCloseable {
throw new IllegalStateException("Attempt to mutate object in read-only context"); throw new IllegalStateException("Attempt to mutate object in read-only context");
} }
if (events == null) { if (events == null) {
events = new LinkedList<Event>(); events = new LinkedList<>();
} }
events.add(event); events.add(event);
@@ -628,11 +631,7 @@ public class Context implements AutoCloseable {
* @return true if member * @return true if member
*/ */
public boolean inSpecialGroup(UUID groupID) { public boolean inSpecialGroup(UUID groupID) {
if (specialGroups.contains(groupID)) { return specialGroups.contains(groupID);
return true;
}
return false;
} }
/** /**
@@ -642,7 +641,7 @@ public class Context implements AutoCloseable {
* @throws SQLException if database error * @throws SQLException if database error
*/ */
public List<Group> getSpecialGroups() throws SQLException { public List<Group> getSpecialGroups() throws SQLException {
List<Group> myGroups = new ArrayList<Group>(); List<Group> myGroups = new ArrayList<>();
for (UUID groupId : specialGroups) { for (UUID groupId : specialGroups) {
myGroups.add(EPersonServiceFactory.getInstance().getGroupService().find(this, groupId)); myGroups.add(EPersonServiceFactory.getInstance().getGroupService().find(this, groupId));
} }
@@ -667,7 +666,7 @@ public class Context implements AutoCloseable {
currentUserPreviousState = currentUser; currentUserPreviousState = currentUser;
specialGroupsPreviousState = specialGroups; specialGroupsPreviousState = specialGroups;
specialGroups = new ArrayList<UUID>(); specialGroups = new ArrayList<>();
currentUser = newUser; currentUser = newUser;
} }
@@ -709,11 +708,13 @@ public class Context implements AutoCloseable {
/** /**
* Returns the size of the cache of all object that have been read from the database so far. A larger number * Returns the size of the cache of all object that have been read from the
* means that more memory is consumed by the cache. This also has a negative impact on the query performance. In * database so far. A larger number means that more memory is consumed by
* that case you should consider uncaching entities when they are no longer needed (see * the cache. This also has a negative impact on the query performance. In
* {@link Context#uncacheEntity(ReloadableEntity)} () uncacheEntity}). * that case you should consider uncaching entities when they are no longer
* needed (see {@link Context#uncacheEntity(ReloadableEntity)} () uncacheEntity}).
* *
* @return cache size.
* @throws SQLException When connecting to the active cache fails. * @throws SQLException When connecting to the active cache fails.
*/ */
public long getCacheSize() throws SQLException { public long getCacheSize() throws SQLException {
@@ -749,7 +750,7 @@ public class Context implements AutoCloseable {
dbConnection.setConnectionMode(false, false); dbConnection.setConnectionMode(false, false);
break; break;
default: default:
log.warn("New context mode detected that has nog been configured."); log.warn("New context mode detected that has not been configured.");
break; break;
} }
} catch (SQLException ex) { } catch (SQLException ex) {
@@ -811,7 +812,7 @@ public class Context implements AutoCloseable {
* entity. This means changes to the entity will be tracked and persisted to the database. * entity. This means changes to the entity will be tracked and persisted to the database.
* *
* @param entity The entity to reload * @param entity The entity to reload
* @param <E> The class of the enity. The entity must implement the {@link ReloadableEntity} interface. * @param <E> The class of the entity. The entity must implement the {@link ReloadableEntity} interface.
* @return A (possibly) <b>NEW</b> reference to the entity that should be used for further processing. * @return A (possibly) <b>NEW</b> reference to the entity that should be used for further processing.
* @throws SQLException When reloading the entity from the database fails. * @throws SQLException When reloading the entity from the database fails.
*/ */
@@ -824,7 +825,7 @@ public class Context implements AutoCloseable {
* Remove an entity from the cache. This is necessary when batch processing a large number of items. * Remove an entity from the cache. This is necessary when batch processing a large number of items.
* *
* @param entity The entity to reload * @param entity The entity to reload
* @param <E> The class of the enity. The entity must implement the {@link ReloadableEntity} interface. * @param <E> The class of the entity. The entity must implement the {@link ReloadableEntity} interface.
* @throws SQLException When reloading the entity from the database fails. * @throws SQLException When reloading the entity from the database fails.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@@ -571,7 +571,7 @@ public class Email {
/** /**
* @author arnaldo * @author arnaldo
*/ */
public class InputStreamDataSource implements DataSource { public static class InputStreamDataSource implements DataSource {
private final String name; private final String name;
private final String contentType; private final String contentType;
private final ByteArrayOutputStream baos; private final ByteArrayOutputStream baos;
@@ -612,7 +612,7 @@ public class Email {
* Wrap ConfigurationService to prevent templates from modifying * Wrap ConfigurationService to prevent templates from modifying
* the configuration. * the configuration.
*/ */
public class UnmodifiableConfigurationService { public static class UnmodifiableConfigurationService {
private final ConfigurationService configurationService; private final ConfigurationService configurationService;
/** /**

View File

@@ -217,12 +217,11 @@ public class I18nUtil {
*/ */
public static String getInputFormsFileName(Locale locale) { public static String getInputFormsFileName(Locale locale) {
/** Name of the form definition XML file */ /** Name of the form definition XML file */
String fileName = "";
final String FORM_DEF_FILE = "submission-forms"; final String FORM_DEF_FILE = "submission-forms";
final String FILE_TYPE = ".xml"; final String FILE_TYPE = ".xml";
String defsFilename = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir") String defsFilename = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir")
+ File.separator + "config" + File.separator + FORM_DEF_FILE; + File.separator + "config" + File.separator + FORM_DEF_FILE;
fileName = getFilename(locale, defsFilename, FILE_TYPE); String fileName = getFilename(locale, defsFilename, FILE_TYPE);
return fileName; return fileName;
} }
@@ -286,14 +285,13 @@ public class I18nUtil {
*/ */
public static String getDefaultLicense(Context context) { public static String getDefaultLicense(Context context) {
Locale locale = context.getCurrentLocale(); Locale locale = context.getCurrentLocale();
String fileName = "";
/** Name of the default license */ /** Name of the default license */
final String DEF_LIC_FILE = "default"; final String DEF_LIC_FILE = "default";
final String FILE_TYPE = ".license"; final String FILE_TYPE = ".license";
String defsFilename = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir") String defsFilename = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir")
+ File.separator + "config" + File.separator + DEF_LIC_FILE; + File.separator + "config" + File.separator + DEF_LIC_FILE;
fileName = getFilename(locale, defsFilename, FILE_TYPE); String fileName = getFilename(locale, defsFilename, FILE_TYPE);
return fileName; return fileName;
} }
@@ -316,18 +314,17 @@ public class I18nUtil {
// with Language, Country // with Language, Country
String fileNameLC = null; String fileNameLC = null;
// with Language // with Language
String fileNameL = null; String fileNameL = fileName + "_" + locale.getLanguage();
fileNameL = fileName + "_" + locale.getLanguage();
if (fileType == null) { if (fileType == null) {
fileType = ""; fileType = "";
} }
if (!("".equals(locale.getCountry()))) { if (!locale.getCountry().isEmpty()) {
fileNameLC = fileName + "_" + locale.getLanguage() + "_" fileNameLC = fileName + "_" + locale.getLanguage() + "_"
+ locale.getCountry(); + locale.getCountry();
if (!("".equals(locale.getVariant()))) { if (!locale.getVariant().isEmpty()) {
fileNameLCV = fileName + "_" + locale.getLanguage() + "_" fileNameLCV = fileName + "_" + locale.getLanguage() + "_"
+ locale.getCountry() + "_" + locale.getVariant(); + locale.getCountry() + "_" + locale.getVariant();
} }
@@ -372,12 +369,11 @@ public class I18nUtil {
* String - localized filename of an email template * String - localized filename of an email template
*/ */
public static String getEmailFilename(Locale locale, String name) { public static String getEmailFilename(Locale locale, String name) {
String templateName = "";
String templateFile = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir") String templateFile = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "emails" + File.separator + "config" + File.separator + "emails"
+ File.separator + name; + File.separator + name;
templateName = getFilename(locale, templateFile, ""); String templateName = getFilename(locale, templateFile, "");
return templateName; return templateName;
} }
@@ -389,7 +385,7 @@ public class I18nUtil {
* @return array of locale results, possibly empty * @return array of locale results, possibly empty
*/ */
public static Locale[] parseLocales(String[] locales) { public static Locale[] parseLocales(String[] locales) {
List<Locale> resultList = new ArrayList<Locale>(); List<Locale> resultList = new ArrayList<>();
for (String ls : locales) { for (String ls : locales) {
Locale lc = makeLocale(ls); Locale lc = makeLocale(ls);
if (lc != null) { if (lc != null) {

View File

@@ -20,6 +20,7 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.rmi.dgc.VMID; import java.rmi.dgc.VMID;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@@ -38,6 +39,7 @@ import java.util.regex.Pattern;
import com.coverity.security.Escape; import com.coverity.security.Escape;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor; import org.apache.commons.text.StringSubstitutor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
@@ -46,13 +48,12 @@ import org.dspace.services.factory.DSpaceServicesFactory;
* Utility functions for DSpace. * Utility functions for DSpace.
* *
* @author Peter Breton * @author Peter Breton
* @version $Revision$
*/ */
public final class Utils { public final class Utils {
/** /**
* log4j logger * log4j logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(Utils.class); private static final Logger log = LogManager.getLogger(Utils.class);
private static final Pattern DURATION_PATTERN = Pattern private static final Pattern DURATION_PATTERN = Pattern
.compile("(\\d+)([smhdwy])"); .compile("(\\d+)([smhdwy])");
@@ -71,12 +72,12 @@ public final class Utils {
private static int counter = 0; private static int counter = 0;
private static Random random = new Random(); private static final Random random = new Random();
private static VMID vmid = new VMID(); private static final VMID vmid = new VMID();
// for parseISO8601Date // for parseISO8601Date
private static SimpleDateFormat parseFmt[] = { private static final SimpleDateFormat parseFmt[] = {
// first try at parsing, has milliseconds (note General time zone) // first try at parsing, has milliseconds (note General time zone)
new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSz"), new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSz"),
@@ -91,12 +92,14 @@ public final class Utils {
// for formatISO8601Date // for formatISO8601Date
// output canonical format (note RFC22 time zone, easier to hack) // output canonical format (note RFC22 time zone, easier to hack)
private static SimpleDateFormat outFmtSecond = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"); private static final SimpleDateFormat outFmtSecond
= new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ");
// output format with millsecond precision // output format with millsecond precision
private static SimpleDateFormat outFmtMillisec = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZ"); private static final SimpleDateFormat outFmtMillisec
= new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZ");
private static Calendar outCal = GregorianCalendar.getInstance(); private static final Calendar outCal = GregorianCalendar.getInstance();
/** /**
* Private constructor * Private constructor
@@ -110,7 +113,7 @@ public final class Utils {
* @return MD5 checksum for the data in hex format. * @return MD5 checksum for the data in hex format.
*/ */
public static String getMD5(String data) { public static String getMD5(String data) {
return getMD5(data.getBytes()); return getMD5(data.getBytes(StandardCharsets.UTF_8));
} }
/** /**
@@ -153,7 +156,7 @@ public final class Utils {
return null; return null;
} }
StringBuffer result = new StringBuffer(); StringBuilder result = new StringBuilder();
// This is far from the most efficient way to do things... // This is far from the most efficient way to do things...
for (int i = 0; i < data.length; i++) { for (int i = 0; i < data.length; i++) {
@@ -197,10 +200,14 @@ public final class Utils {
random.nextBytes(junk); random.nextBytes(junk);
String input = new StringBuffer().append(vmid).append( String input = new StringBuilder()
new java.util.Date()).append(Arrays.toString(junk)).append(counter++).toString(); .append(vmid)
.append(new java.util.Date())
.append(Arrays.toString(junk))
.append(counter++)
.toString();
return getMD5Bytes(input.getBytes()); return getMD5Bytes(input.getBytes(StandardCharsets.UTF_8));
} }
// The following two methods are taken from the Jakarta IOUtil class. // The following two methods are taken from the Jakarta IOUtil class.

View File

@@ -13,7 +13,6 @@ import java.util.Iterator;
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.Logger;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
@@ -39,8 +38,6 @@ public abstract class AbstractCurationTask implements CurationTask {
protected Curator curator = null; protected Curator curator = null;
// curator-assigned taskId // curator-assigned taskId
protected String taskId = null; protected String taskId = null;
// logger
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(AbstractCurationTask.class);
protected CommunityService communityService; protected CommunityService communityService;
protected ItemService itemService; protected ItemService itemService;
protected HandleService handleService; protected HandleService handleService;

View File

@@ -19,7 +19,6 @@ import org.apache.commons.lang3.tuple.Pair;
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;
import org.dspace.content.BitstreamFormat;
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;
@@ -46,7 +45,7 @@ public class CitationPage extends AbstractCurationTask {
/** /**
* Class Logger * Class Logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(CitationPage.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(CitationPage.class);
protected int status = Curator.CURATE_UNSET; protected int status = Curator.CURATE_UNSET;
protected String result = null; protected String result = null;
@@ -97,7 +96,7 @@ public class CitationPage extends AbstractCurationTask {
//Determine if the DISPLAY bundle exits. If not, create it. //Determine if the DISPLAY bundle exits. If not, create it.
List<Bundle> dBundles = itemService.getBundles(item, CitationPage.DISPLAY_BUNDLE_NAME); List<Bundle> dBundles = itemService.getBundles(item, CitationPage.DISPLAY_BUNDLE_NAME);
Bundle dBundle = null; Bundle dBundle = null;
if (dBundles == null || dBundles.size() == 0) { if (dBundles == null || dBundles.isEmpty()) {
try { try {
dBundle = bundleService.create(Curator.curationContext(), item, CitationPage.DISPLAY_BUNDLE_NAME); dBundle = bundleService.create(Curator.curationContext(), item, CitationPage.DISPLAY_BUNDLE_NAME);
} catch (AuthorizeException e) { } catch (AuthorizeException e) {
@@ -110,7 +109,7 @@ public class CitationPage extends AbstractCurationTask {
//Create a map of the bitstreams in the displayBundle. This is used to //Create a map of the bitstreams in the displayBundle. This is used to
//check if the bundle being cited is already in the display bundle. //check if the bundle being cited is already in the display bundle.
Map<String, Bitstream> displayMap = new HashMap<String, Bitstream>(); Map<String, Bitstream> displayMap = new HashMap<>();
for (Bitstream bs : dBundle.getBitstreams()) { for (Bitstream bs : dBundle.getBitstreams()) {
displayMap.put(bs.getName(), bs); displayMap.put(bs.getName(), bs);
} }
@@ -143,15 +142,16 @@ public class CitationPage extends AbstractCurationTask {
// Loop through each file and generate a cover page for documents // Loop through each file and generate a cover page for documents
// that are PDFs. // that are PDFs.
for (Bitstream bitstream : bitstreams) { for (Bitstream bitstream : bitstreams) {
BitstreamFormat format = bitstream.getFormat(Curator.curationContext());
//If bitstream is a PDF document then it is citable. //If bitstream is a PDF document then it is citable.
CitationDocumentService citationDocument = DisseminateServiceFactory.getInstance() CitationDocumentService citationDocument = DisseminateServiceFactory.getInstance()
.getCitationDocumentService(); .getCitationDocumentService();
if (citationDocument.canGenerateCitationVersion(Curator.curationContext(), bitstream)) { if (citationDocument.canGenerateCitationVersion(Curator.curationContext(), bitstream)) {
this.resBuilder.append(item.getHandle() + " - " this.resBuilder.append(item.getHandle())
+ bitstream.getName() + " is citable."); .append(" - ")
.append(bitstream.getName())
.append(" is citable.");
try { try {
//Create the cited document //Create the cited document
Pair<InputStream, Long> citedDocument = Pair<InputStream, Long> citedDocument =
@@ -168,7 +168,9 @@ public class CitationPage extends AbstractCurationTask {
StringBuilder stack = new StringBuilder(); StringBuilder stack = new StringBuilder();
int numLines = Math.min(stackTrace.length, 12); int numLines = Math.min(stackTrace.length, 12);
for (int j = 0; j < numLines; j++) { for (int j = 0; j < numLines; j++) {
stack.append("\t" + stackTrace[j].toString() + "\n"); stack.append("\t")
.append(stackTrace[j].toString())
.append("\n");
} }
if (stackTrace.length > numLines) { if (stackTrace.length > numLines) {
stack.append("\t. . .\n"); stack.append("\t. . .\n");
@@ -180,8 +182,10 @@ public class CitationPage extends AbstractCurationTask {
} }
} else { } else {
//bitstream is not a document //bitstream is not a document
this.resBuilder.append(item.getHandle() + " - " this.resBuilder.append(item.getHandle())
+ bitstream.getName() + " is not citable.\n"); .append(" - ")
.append(bitstream.getName())
.append(" is not citable.\n");
this.status = Curator.CURATE_SUCCESS; this.status = Curator.CURATE_SUCCESS;
} }
} }
@@ -211,11 +215,11 @@ public class CitationPage extends AbstractCurationTask {
//If we are modifying a file that is not in the //If we are modifying a file that is not in the
//preservation bundle then we have to move it there. //preservation bundle then we have to move it there.
Context context = Curator.curationContext(); Context context = Curator.curationContext();
if (bundle.getID() != pBundle.getID()) { if (!bundle.getID().equals(pBundle.getID())) {
bundleService.addBitstream(context, pBundle, bitstream); bundleService.addBitstream(context, pBundle, bitstream);
bundleService.removeBitstream(context, bundle, bitstream); bundleService.removeBitstream(context, bundle, bitstream);
List<Bitstream> bitstreams = bundle.getBitstreams(); List<Bitstream> bitstreams = bundle.getBitstreams();
if (bitstreams == null || bitstreams.size() == 0) { if (bitstreams == null || bitstreams.isEmpty()) {
itemService.removeBundle(context, item, bundle); itemService.removeBundle(context, item, bundle);
} }
} }
@@ -235,9 +239,11 @@ public class CitationPage extends AbstractCurationTask {
bitstreamService.setFormat(context, citedBitstream, bitstream.getFormat(Curator.curationContext())); bitstreamService.setFormat(context, citedBitstream, bitstream.getFormat(Curator.curationContext()));
citedBitstream.setDescription(context, bitstream.getDescription()); citedBitstream.setDescription(context, bitstream.getDescription());
this.resBuilder.append(" Added " this.resBuilder.append(" Added ")
+ citedBitstream.getName() .append(citedBitstream.getName())
+ " to the " + CitationPage.DISPLAY_BUNDLE_NAME + " bundle.\n"); .append(" to the ")
.append(CitationPage.DISPLAY_BUNDLE_NAME)
.append(" bundle.\n");
//Run update to propagate changes to the //Run update to propagate changes to the
//database. //database.

View File

@@ -13,16 +13,17 @@ import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* FileTaskQueue provides a TaskQueue implementation based on flat files * FileTaskQueue provides a TaskQueue implementation based on flat files
* for the queues and semaphores. * for the queues and semaphores.
@@ -30,14 +31,16 @@ import org.dspace.services.factory.DSpaceServicesFactory;
* @author richardrodgers * @author richardrodgers
*/ */
public class FileTaskQueue implements TaskQueue { public class FileTaskQueue implements TaskQueue {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(TaskQueue.class); private static final Logger log = LogManager.getLogger(TaskQueue.class);
// base directory for curation task queues // base directory for curation task queues
protected String tqDir; protected String tqDir;
// ticket for queue readers // ticket for queue readers
protected long readTicket = -1L; protected long readTicket = -1L;
// list of queues owned by reader // list of queues owned by reader
protected List<Integer> readList = new ArrayList<Integer>(); protected List<Integer> readList = new ArrayList<>();
public FileTaskQueue() { public FileTaskQueue() {
tqDir = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.taskqueue.dir"); tqDir = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.taskqueue.dir");
@@ -72,7 +75,7 @@ public class FileTaskQueue implements TaskQueue {
BufferedWriter writer = null; BufferedWriter writer = null;
try { try {
File queue = new File(qDir, "queue" + Integer.toString(queueIdx)); File queue = new File(qDir, "queue" + Integer.toString(queueIdx));
writer = new BufferedWriter(new FileWriter(queue, true)); writer = new BufferedWriter(new FileWriter(queue, StandardCharsets.UTF_8, true));
Iterator<TaskQueueEntry> iter = entrySet.iterator(); Iterator<TaskQueueEntry> iter = entrySet.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
writer.write(iter.next().toString()); writer.write(iter.next().toString());
@@ -96,7 +99,7 @@ public class FileTaskQueue implements TaskQueue {
@Override @Override
public synchronized Set<TaskQueueEntry> dequeue(String queueName, long ticket) public synchronized Set<TaskQueueEntry> dequeue(String queueName, long ticket)
throws IOException { throws IOException {
Set<TaskQueueEntry> entrySet = new HashSet<TaskQueueEntry>(); Set<TaskQueueEntry> entrySet = new HashSet<>();
if (readTicket == -1L) { if (readTicket == -1L) {
// hold the ticket & copy all Ids available, locking queues // hold the ticket & copy all Ids available, locking queues
// stop when no more queues or one found locked // stop when no more queues or one found locked
@@ -113,8 +116,8 @@ public class FileTaskQueue implements TaskQueue {
// read contents from file // read contents from file
BufferedReader reader = null; BufferedReader reader = null;
try { try {
reader = new BufferedReader(new FileReader(queue)); reader = new BufferedReader(new FileReader(queue, StandardCharsets.UTF_8));
String entryStr = null; String entryStr;
while ((entryStr = reader.readLine()) != null) { while ((entryStr = reader.readLine()) != null) {
entryStr = entryStr.trim(); entryStr = entryStr.trim();
if (entryStr.length() > 0) { if (entryStr.length() > 0) {

View File

@@ -24,7 +24,7 @@ public class ResolvedTask {
private CurationTask cTask; private CurationTask cTask;
private ScriptedTask sTask; private ScriptedTask sTask;
// local name of task // local name of task
private String taskName; private final String taskName;
// annotation data // annotation data
private boolean distributive = false; private boolean distributive = false;
private boolean mutative = false; private boolean mutative = false;
@@ -76,7 +76,7 @@ public class ResolvedTask {
* @throws IOException if error * @throws IOException if error
*/ */
public int perform(DSpaceObject dso) throws IOException { public int perform(DSpaceObject dso) throws IOException {
return (unscripted()) ? cTask.perform(dso) : sTask.performDso(dso); return unscripted() ? cTask.perform(dso) : sTask.performDso(dso);
} }
/** /**
@@ -88,7 +88,7 @@ public class ResolvedTask {
* @throws IOException if error * @throws IOException if error
*/ */
public int perform(Context ctx, String id) throws IOException { public int perform(Context ctx, String id) throws IOException {
return (unscripted()) ? cTask.perform(ctx, id) : sTask.performId(ctx, id); return unscripted() ? cTask.perform(ctx, id) : sTask.performId(ctx, id);
} }
/** /**

View File

@@ -15,11 +15,13 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Properties; import java.util.Properties;
import javax.script.ScriptEngine; import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager; import javax.script.ScriptEngineManager;
import javax.script.ScriptException; import javax.script.ScriptException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.core.factory.CoreServiceFactory; import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
@@ -64,7 +66,7 @@ import org.dspace.services.factory.DSpaceServicesFactory;
public class TaskResolver { public class TaskResolver {
// logging service // logging service
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(TaskResolver.class); private static final Logger log = LogManager.getLogger(TaskResolver.class);
// base directory of task scripts & catalog name // base directory of task scripts & catalog name
protected static final String CATALOG = "task.catalog"; protected static final String CATALOG = "task.catalog";
@@ -94,7 +96,7 @@ public class TaskResolver {
if (script.exists()) { if (script.exists()) {
BufferedReader reader = null; BufferedReader reader = null;
try { try {
reader = new BufferedReader(new FileReader(script)); reader = new BufferedReader(new FileReader(script, StandardCharsets.UTF_8));
String line = null; String line = null;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
if (line.startsWith("#") && line.indexOf("$td=") > 0) { if (line.startsWith("#") && line.indexOf("$td=") > 0) {
@@ -136,7 +138,7 @@ public class TaskResolver {
catalog.put(taskName, descriptor); catalog.put(taskName, descriptor);
Writer writer = null; Writer writer = null;
try { try {
writer = new FileWriter(new File(scriptDir, CATALOG)); writer = new FileWriter(new File(scriptDir, CATALOG), StandardCharsets.UTF_8);
catalog.store(writer, "do not edit"); catalog.store(writer, "do not edit");
} catch (IOException ioE) { } catch (IOException ioE) {
log.error("Error saving scripted task catalog: " + CATALOG); log.error("Error saving scripted task catalog: " + CATALOG);
@@ -179,7 +181,7 @@ public class TaskResolver {
File script = new File(scriptDir, tokens[1]); File script = new File(scriptDir, tokens[1]);
if (script.exists()) { if (script.exists()) {
try { try {
Reader reader = new FileReader(script); Reader reader = new FileReader(script, StandardCharsets.UTF_8);
engine.eval(reader); engine.eval(reader);
reader.close(); reader.close();
// third token is the constructor expression for the class // third token is the constructor expression for the class
@@ -212,7 +214,7 @@ public class TaskResolver {
File catalogFile = new File(scriptDir, CATALOG); File catalogFile = new File(scriptDir, CATALOG);
if (catalogFile.exists()) { if (catalogFile.exists()) {
try { try {
Reader reader = new FileReader(catalogFile); Reader reader = new FileReader(catalogFile, StandardCharsets.UTF_8);
catalog.load(reader); catalog.load(reader);
reader.close(); reader.close();
} catch (IOException ioE) { } catch (IOException ioE) {

View File

@@ -15,7 +15,6 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -23,7 +22,7 @@ import org.apache.commons.collections4.CollectionUtils;
import org.dspace.discovery.configuration.DiscoverySearchFilterFacet; import org.dspace.discovery.configuration.DiscoverySearchFilterFacet;
/** /**
* This class represents a query which the discovery backend can use * This class represents a query which the discovery back-end can use.
* *
* @author Kevin Van de Velde (kevin at atmire dot com) * @author Kevin Van de Velde (kevin at atmire dot com)
*/ */
@@ -33,9 +32,9 @@ public class DiscoverQuery {
* Main attributes for the discovery query * Main attributes for the discovery query
**/ **/
private String query; private String query;
private List<String> filterQueries; private final List<String> filterQueries;
private List<String> dspaceObjectFilters = new ArrayList<>(); private List<String> dspaceObjectFilters = new ArrayList<>();
private List<String> fieldPresentQueries; private final List<String> fieldPresentQueries;
private boolean spellCheck; private boolean spellCheck;
private int start = 0; private int start = 0;
@@ -55,36 +54,35 @@ public class DiscoverQuery {
/** /**
* Attributes required for the faceting of values * Attributes required for the faceting of values
**/ **/
private List<DiscoverFacetField> facetFields; private final List<DiscoverFacetField> facetFields;
private List<String> facetQueries; private final List<String> facetQueries;
private int facetLimit = -1;
private int facetMinCount = -1; private int facetMinCount = -1;
private int facetOffset = 0; private int facetOffset = 0;
private Map<String, DiscoverHitHighlightingField> hitHighlighting; private final Map<String, DiscoverHitHighlightingField> hitHighlighting;
/** /**
* Used when you want to search for a specific field value * Used when you want to search for a specific field value
**/ **/
private List<String> searchFields; private final List<String> searchFields;
/** /**
* Misc attributes can be implementation dependent * Misc attributes can be implementation dependent
**/ **/
private Map<String, List<String>> properties; private final Map<String, List<String>> properties;
private String discoveryConfigurationName; private String discoveryConfigurationName;
public DiscoverQuery() { public DiscoverQuery() {
//Initialize all our lists //Initialize all our lists
this.filterQueries = new ArrayList<String>(); this.filterQueries = new ArrayList<>();
this.fieldPresentQueries = new ArrayList<String>(); this.fieldPresentQueries = new ArrayList<>();
this.facetFields = new ArrayList<DiscoverFacetField>(); this.facetFields = new ArrayList<>();
this.facetQueries = new ArrayList<String>(); this.facetQueries = new ArrayList<>();
this.searchFields = new ArrayList<String>(); this.searchFields = new ArrayList<>();
this.hitHighlighting = new HashMap<String, DiscoverHitHighlightingField>(); this.hitHighlighting = new HashMap<>();
//Use a linked hashmap since sometimes insertion order might matter //Use a linked hashmap since sometimes insertion order might matter
this.properties = new LinkedHashMap<String, List<String>>(); this.properties = new LinkedHashMap<>();
} }
@@ -274,7 +272,7 @@ public class DiscoverQuery {
/** /**
* Sets the fields which you want Discovery to return in the search results. * Sets the fields which you want Discovery to return in the search results.
* It is HIGHLY recommended to limit the fields returned, as by default * It is HIGHLY recommended to limit the fields returned, as by default
* some backends (like Solr) will return everything. * some back-ends (like Solr) will return everything.
* *
* @param field field to add to the list of fields returned * @param field field to add to the list of fields returned
*/ */
@@ -309,7 +307,7 @@ public class DiscoverQuery {
public void addProperty(String property, String value) { public void addProperty(String property, String value) {
List<String> toAddList = properties.get(property); List<String> toAddList = properties.get(property);
if (toAddList == null) { if (toAddList == null) {
toAddList = new ArrayList<String>(); toAddList = new ArrayList<>();
} }
toAddList.add(value); toAddList.add(value);
@@ -322,7 +320,7 @@ public class DiscoverQuery {
} }
public List<DiscoverHitHighlightingField> getHitHighlightingFields() { public List<DiscoverHitHighlightingField> getHitHighlightingFields() {
return new ArrayList<DiscoverHitHighlightingField>(hitHighlighting.values()); return new ArrayList<>(hitHighlighting.values());
} }
public void addHitHighlightingField(DiscoverHitHighlightingField hitHighlighting) { public void addHitHighlightingField(DiscoverHitHighlightingField hitHighlighting) {
@@ -368,7 +366,7 @@ public class DiscoverQuery {
private List<String> buildFacetQueriesWithGap(int newestYear, int oldestYear, String dateFacet, int gap, private List<String> buildFacetQueriesWithGap(int newestYear, int oldestYear, String dateFacet, int gap,
int topYear, int facetLimit) { int topYear, int facetLimit) {
List<String> facetQueries = new LinkedList<>(); List<String> facetQueries = new ArrayList<>();
for (int year = topYear; year > oldestYear && (facetQueries.size() < facetLimit); year -= gap) { for (int year = topYear; year > oldestYear && (facetQueries.size() < facetLimit); year -= gap) {
//Add a filter to remove the last year only if we aren't the last year //Add a filter to remove the last year only if we aren't the last year
int bottomYear = year - gap; int bottomYear = year - gap;
@@ -392,7 +390,7 @@ public class DiscoverQuery {
} }
private int getTopYear(int newestYear, int gap) { private int getTopYear(int newestYear, int gap) {
return (int) (Math.ceil((float) (newestYear) / gap) * gap); return (int) (Math.ceil((float) newestYear / gap) * gap);
} }
/** /**

View File

@@ -16,9 +16,9 @@ import java.io.Reader;
import java.io.SequenceInputStream; import java.io.SequenceInputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@@ -55,7 +55,7 @@ public class FullTextContentStreams extends ContentStreamBase {
} }
protected void init(Item parentItem) { protected void init(Item parentItem) {
fullTextStreams = new LinkedList<>(); fullTextStreams = new ArrayList<>();
if (parentItem != null) { if (parentItem != null) {
sourceInfo = parentItem.getHandle(); sourceInfo = parentItem.getHandle();
@@ -149,8 +149,8 @@ public class FullTextContentStreams extends ContentStreamBase {
} }
private class FullTextBitstream { private class FullTextBitstream {
private String itemHandle; private final String itemHandle;
private Bitstream bitstream; private final Bitstream bitstream;
public FullTextBitstream(final String parentHandle, final Bitstream file) { public FullTextBitstream(final String parentHandle, final Bitstream file) {
this.itemHandle = parentHandle; this.itemHandle = parentHandle;
@@ -179,18 +179,25 @@ public class FullTextContentStreams extends ContentStreamBase {
} }
} }
private class FullTextEnumeration implements Enumeration<InputStream> { /**
* {@link Enumeration} is implemented because instances of this class are
* passed to a JDK class that requires this obsolete type.
*/
@SuppressWarnings("JdkObsolete")
private static class FullTextEnumeration implements Enumeration<InputStream> {
private final Iterator<FullTextBitstream> fulltextIterator; private final Iterator<FullTextBitstream> fulltextIterator;
public FullTextEnumeration(final Iterator<FullTextBitstream> fulltextStreams) { public FullTextEnumeration(final Iterator<FullTextBitstream> fulltextIterator) {
this.fulltextIterator = fulltextStreams; this.fulltextIterator = fulltextIterator;
} }
@Override
public boolean hasMoreElements() { public boolean hasMoreElements() {
return fulltextIterator.hasNext(); return fulltextIterator.hasNext();
} }
@Override
public InputStream nextElement() { public InputStream nextElement() {
InputStream inputStream = null; InputStream inputStream = null;
FullTextBitstream bitstream = null; FullTextBitstream bitstream = null;

View File

@@ -55,7 +55,7 @@ public class SolrServiceFileInfoPlugin implements SolrServiceIndexPlugin {
document.addField(SOLR_FIELD_NAME_FOR_FILENAMES, bitstream.getName()); document.addField(SOLR_FIELD_NAME_FOR_FILENAMES, bitstream.getName());
String description = bitstream.getDescription(); String description = bitstream.getDescription();
if ((description != null) && (!description.isEmpty())) { if ((description != null) && !description.isEmpty()) {
document.addField(SOLR_FIELD_NAME_FOR_DESCRIPTIONS, description); document.addField(SOLR_FIELD_NAME_FOR_DESCRIPTIONS, description);
} }
} }

View File

@@ -14,10 +14,13 @@ import org.dspace.discovery.IndexableObject;
/** /**
* This class exists in order to provide a default implementation for the equals and hashCode methods. * This class exists in order to provide a default implementation for the equals and hashCode methods.
* Since IndexableObjects can be made multiple times for the same underlying object, we needed a more finetuned * Since IndexableObjects can be made multiple times for the same underlying
* equals and hashcode methods. We're simply checking that the underlying objects are equal and generating the hashcode * object, we needed more finely-tuned {@link equals} and {@link hashCode} methods.
* for the underlying object. This way, we'll always get a proper result when calling equals or hashcode on an * We're simply checking that the underlying objects are equal and returning the
* IndexableObject because it'll depend on the underlying object * hash-code for the underlying object. This way, we'll always get a proper
* result when calling {@link equals} or {@link hashCode} on an IndexableObject
* because it'll depend on the underlying object.
*
* @param <T> Refers to the underlying entity that is linked to this object * @param <T> Refers to the underlying entity that is linked to this object
* @param <PK> The type of ID that this entity uses * @param <PK> The type of ID that this entity uses
*/ */

View File

@@ -11,6 +11,7 @@ import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@@ -108,7 +109,7 @@ public class LoadLastLogin {
final SimpleDateFormat dateEncoder = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final SimpleDateFormat dateEncoder = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (String logName : args) { for (String logName : args) {
BufferedReader logReader = new BufferedReader(new FileReader(logName)); BufferedReader logReader = new BufferedReader(new FileReader(logName, StandardCharsets.UTF_8));
while (true) { while (true) {
String line = logReader.readLine(); String line = logReader.readLine();
// End of file? // End of file?

View File

@@ -53,6 +53,7 @@ public class Subscription implements ReloadableEntity<Integer> {
} }
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }

View File

@@ -8,7 +8,7 @@
package org.dspace.eperson.dao.impl; package org.dspace.eperson.dao.impl;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.persistence.Query; import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
@@ -97,7 +97,7 @@ public class SubscriptionDAOImpl extends AbstractHibernateDAO<Subscription> impl
Root<Subscription> subscriptionRoot = criteriaQuery.from(Subscription.class); Root<Subscription> subscriptionRoot = criteriaQuery.from(Subscription.class);
criteriaQuery.select(subscriptionRoot); criteriaQuery.select(subscriptionRoot);
List<javax.persistence.criteria.Order> orderList = new LinkedList<>(); List<javax.persistence.criteria.Order> orderList = new ArrayList<>(1);
orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.ePerson))); orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.ePerson)));
criteriaQuery.orderBy(orderList); criteriaQuery.orderBy(orderList);

View File

@@ -104,7 +104,9 @@ public class ConsumerProfile {
"No filters configured for consumer named: " + name); "No filters configured for consumer named: " + name);
} }
consumer = (Consumer) Class.forName(className.trim()).getDeclaredConstructor().newInstance(); consumer = Class.forName(className.trim())
.asSubclass(Consumer.class)
.getDeclaredConstructor().newInstance();
// Each "filter" is <objectTypes> + <eventTypes> : ... // Each "filter" is <objectTypes> + <eventTypes> : ...
filters = new ArrayList<>(); filters = new ArrayList<>();

View File

@@ -48,8 +48,6 @@ import org.dspace.event.factory.EventServiceFactory;
* significance varies by the combination of action and subject type.</li> * significance varies by the combination of action and subject type.</li>
* <li> - timestamp -- exact millisecond timestamp at which event was logged.</li> * <li> - timestamp -- exact millisecond timestamp at which event was logged.</li>
* </ul> * </ul>
*
* @version $Revision$
*/ */
public class Event implements Serializable { public class Event implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@@ -308,6 +306,7 @@ public class Event implements Serializable {
* @param other the event to compare this one to * @param other the event to compare this one to
* @return true if events are "equal", false otherwise. * @return true if events are "equal", false otherwise.
*/ */
@Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (other instanceof Event) { if (other instanceof Event) {
Event otherEvent = (Event) other; Event otherEvent = (Event) other;
@@ -315,14 +314,15 @@ public class Event implements Serializable {
.equals(otherEvent.detail)) .equals(otherEvent.detail))
&& this.eventType == otherEvent.eventType && this.eventType == otherEvent.eventType
&& this.subjectType == otherEvent.subjectType && this.subjectType == otherEvent.subjectType
&& this.subjectID == otherEvent.subjectID && this.subjectID.equals(otherEvent.subjectID)
&& this.objectType == otherEvent.objectType && this.objectType == otherEvent.objectType
&& this.objectID == otherEvent.objectID; && this.objectID.equals(otherEvent.objectID);
} }
return false; return false;
} }
@Override
public int hashCode() { public int hashCode() {
return new HashCodeBuilder().append(this.detail) return new HashCodeBuilder().append(this.detail)
.append(eventType) .append(eventType)
@@ -634,6 +634,7 @@ public class Event implements Serializable {
* @return Detailed string representation of contents of this event, to * @return Detailed string representation of contents of this event, to
* help in logging and debugging. * help in logging and debugging.
*/ */
@Override
public String toString() { public String toString() {
return "org.dspace.event.Event(eventType=" return "org.dspace.event.Event(eventType="
+ this.getEventTypeAsString() + this.getEventTypeAsString()

View File

@@ -8,6 +8,7 @@
package org.dspace.external; package org.dspace.external;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner; import java.util.Scanner;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -15,6 +16,7 @@ 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.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;
/** /**
@@ -28,9 +30,9 @@ public class OrcidRestConnector {
/** /**
* log4j logger * log4j logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(OrcidRestConnector.class); private static final Logger log = LogManager.getLogger(OrcidRestConnector.class);
private String url; private final String url;
public OrcidRestConnector(String url) { public OrcidRestConnector(String url) {
this.url = url; this.url = url;
@@ -74,7 +76,7 @@ public class OrcidRestConnector {
} }
public static String convertStreamToString(InputStream is) { public static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A"); Scanner s = new Scanner(is, StandardCharsets.UTF_8).useDelimiter("\\A");
return s.hasNext() ? s.next() : ""; return s.hasNext() ? s.next() : "";
} }
} }

View File

@@ -7,7 +7,7 @@
*/ */
package org.dspace.external.model; package org.dspace.external.model;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.dspace.content.dto.MetadataValueDTO; import org.dspace.content.dto.MetadataValueDTO;
@@ -32,7 +32,7 @@ public class ExternalDataObject {
/** /**
* The list of Metadata values. These our MetadataValueDTO because they won't exist in the DB * The list of Metadata values. These our MetadataValueDTO because they won't exist in the DB
*/ */
private List<MetadataValueDTO> metadata = new LinkedList<>(); private List<MetadataValueDTO> metadata = new ArrayList<>();
/** /**
* The display value of the ExternalDataObject * The display value of the ExternalDataObject
*/ */
@@ -87,11 +87,11 @@ public class ExternalDataObject {
/** /**
* This method will add a Metadata value to the list of metadata values * This method will add a Metadata value to the list of metadata values
* @param metadataValueDTO The metadatavalue to be added * @param metadataValueDTO The metadata value to be added.
*/ */
public void addMetadata(MetadataValueDTO metadataValueDTO) { public void addMetadata(MetadataValueDTO metadataValueDTO) {
if (metadata == null) { if (metadata == null) {
metadata = new LinkedList<>(); metadata = new ArrayList<>();
} }
metadata.add(metadataValueDTO); metadata.add(metadataValueDTO);
} }

View File

@@ -13,7 +13,6 @@ import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import org.apache.logging.log4j.Logger;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
/** /**
@@ -25,11 +24,6 @@ import org.xml.sax.SAXException;
*/ */
public abstract class Converter<T> { public abstract class Converter<T> {
/**
* log4j logger
*/
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(Converter.class);
public abstract T convert(InputStream document); public abstract T convert(InputStream document);
protected Object unmarshall(InputStream input, Class<?> type) throws SAXException, URISyntaxException { protected Object unmarshall(InputStream input, Class<?> type) throws SAXException, URISyntaxException {

View File

@@ -105,7 +105,7 @@ public class Handle implements ReloadableEntity<Integer> {
return true; return true;
} }
if (o == null || getClass() != o.getClass()) { if (!(o instanceof Handle)) {
return false; return false;
} }

View File

@@ -56,6 +56,7 @@ public class HarvestedItem implements ReloadableEntity<Integer> {
protected HarvestedItem() { protected HarvestedItem() {
} }
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }
@@ -89,7 +90,6 @@ public class HarvestedItem implements ReloadableEntity<Integer> {
*/ */
public void setOaiID(String itemOaiID) { public void setOaiID(String itemOaiID) {
this.oaiId = itemOaiID; this.oaiId = itemOaiID;
return;
} }

View File

@@ -62,6 +62,7 @@ public class DOI
protected DOI() { protected DOI() {
} }
@Override
public Integer getID() { public Integer getID() {
return id; return id;
} }

View File

@@ -158,6 +158,7 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* Spring will use this setter to set the filter from the configured property in identifier-services.xml * Spring will use this setter to set the filter from the configured property in identifier-services.xml
* @param filterService - an object implementing the org.dspace.content.logic.Filter interface * @param filterService - an object implementing the org.dspace.content.logic.Filter interface
*/ */
@Override
public void setFilterService(Filter filterService) { public void setFilterService(Filter filterService) {
this.filterService = filterService; this.filterService = filterService;
} }
@@ -319,7 +320,6 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* @param skipFilter - boolean indicating whether to skip any filtering of items before performing reservation * @param skipFilter - boolean indicating whether to skip any filtering of items before performing reservation
* @throws IdentifierException * @throws IdentifierException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws SQLException
*/ */
@Override @Override
public void reserve(Context context, DSpaceObject dso, String identifier, boolean skipFilter) public void reserve(Context context, DSpaceObject dso, String identifier, boolean skipFilter)
@@ -367,6 +367,7 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* @param context - DSpace context * @param context - DSpace context
* @param dso - DSpaceObject identified by this DOI * @param dso - DSpaceObject identified by this DOI
* @param identifier - String containing the DOI to reserve * @param identifier - String containing the DOI to reserve
* @param skipFilter - skip the filters for {@link checkMintable(Context, DSpaceObject)}
* @throws IdentifierException * @throws IdentifierException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws SQLException * @throws SQLException
@@ -410,6 +411,7 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* @param context - DSpace context * @param context - DSpace context
* @param dso - DSpaceObject identified by this DOI * @param dso - DSpaceObject identified by this DOI
* @param identifier - String containing the DOI to register * @param identifier - String containing the DOI to register
* @param skipFilter - skip filters for {@link checkMintable(Context, DSpaceObject)}
* @throws IdentifierException * @throws IdentifierException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws SQLException * @throws SQLException
@@ -785,7 +787,7 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* Delete a specific DOI in the registration agency records via the DOI Connector * Delete a specific DOI in the registration agency records via the DOI Connector
* @param context - DSpace context * @param context - DSpace context
* @param identifier - String containing identifier to delete * @param identifier - String containing identifier to delete
* @throws IdentifierException * @throws DOIIdentifierException
*/ */
public void deleteOnline(Context context, String identifier) throws DOIIdentifierException { public void deleteOnline(Context context, String identifier) throws DOIIdentifierException {
String doi = doiService.formatIdentifier(identifier); String doi = doiService.formatIdentifier(identifier);
@@ -826,7 +828,7 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* {@link org.dspace.identifier.service.DOIService#formatIdentifier(String)}. * {@link org.dspace.identifier.service.DOIService#formatIdentifier(String)}.
* @return Null if the DOI couldn't be found or the associated DSpaceObject. * @return Null if the DOI couldn't be found or the associated DSpaceObject.
* @throws SQLException if database error * @throws SQLException if database error
* @throws IdentifierException If {@code identifier} is null or an empty string. * @throws DOIIdentifierException If {@code identifier} is null or an empty string.
* @throws IllegalArgumentException If the identifier couldn't be recognized as DOI. * @throws IllegalArgumentException If the identifier couldn't be recognized as DOI.
*/ */
public DSpaceObject getObjectByDOI(Context context, String identifier) public DSpaceObject getObjectByDOI(Context context, String identifier)
@@ -876,10 +878,10 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
} }
/** /**
* Load a DOI from the database or creates it if it does not exist. This * Load a DOI from the database or creates it if it does not exist.
* method can be used to ensure that a DOI exists in the database and to * This method can be used to ensure that a DOI exists in the database and
* load the appropriate TableRow. As protected method we don't check if the * to load the appropriate TableRow. As protected method we don't check if
* DOI is in a decent format, use DOI.formatIdentifier(String) if necessary. * the DOI is in a decent format, use DOI.formatIdentifier(String) if necessary.
* *
* @param context The relevant DSpace Context. * @param context The relevant DSpace Context.
* @param dso The DSpaceObject the DOI should be loaded or created for. * @param dso The DSpaceObject the DOI should be loaded or created for.
@@ -889,6 +891,7 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* @throws SQLException In case of an error using the database. * @throws SQLException In case of an error using the database.
* @throws DOIIdentifierException If {@code doi} is not part of our prefix or * @throws DOIIdentifierException If {@code doi} is not part of our prefix or
* DOI is registered for another object already. * DOI is registered for another object already.
* @throws IdentifierNotApplicableException passed through.
*/ */
protected DOI loadOrCreateDOI(Context context, DSpaceObject dso, String doiIdentifier) protected DOI loadOrCreateDOI(Context context, DSpaceObject dso, String doiIdentifier)
throws SQLException, DOIIdentifierException, IdentifierNotApplicableException { throws SQLException, DOIIdentifierException, IdentifierNotApplicableException {
@@ -896,11 +899,13 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
} }
/** /**
* Load DOI from database, or create one if it doesn't yet exist * Load DOI from database, or create one if it doesn't yet exist.
* We need to distinguish several cases. LoadOrCreate can be called with a specifid identifier to load or create. * We need to distinguish several cases.LoadOrCreate can be called with a
* It can also be used to create a new unspecified identifier. In the latter case doiIdentifier is set null. * specified identifier to load or create. It can also be used to create a
* If doiIdentifier is set, we know which doi we should try to load or create, but even in sucha situation * new unspecified identifier. In the latter case doiIdentifier is set null.
* we might be able to find it in the database or might have to create it. * If doiIdentifier is set, we know which doi we should try to load or
* create, but even in such a situation we might be able to find it in the
* database or might have to create it.
* *
* @param context - DSpace context * @param context - DSpace context
* @param dso - DSpaceObject to identify * @param dso - DSpaceObject to identify
@@ -909,6 +914,7 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
* @return * @return
* @throws SQLException * @throws SQLException
* @throws DOIIdentifierException * @throws DOIIdentifierException
* @throws org.dspace.identifier.IdentifierNotApplicableException passed through.
*/ */
protected DOI loadOrCreateDOI(Context context, DSpaceObject dso, String doiIdentifier, boolean skipFilter) protected DOI loadOrCreateDOI(Context context, DSpaceObject dso, String doiIdentifier, boolean skipFilter)
throws SQLException, DOIIdentifierException, IdentifierNotApplicableException { throws SQLException, DOIIdentifierException, IdentifierNotApplicableException {
@@ -929,11 +935,11 @@ public class DOIIdentifierProvider extends FilteredIdentifierProvider {
&& doi.getResourceTypeId() != dso.getType()) { && doi.getResourceTypeId() != dso.getType()) {
// doi was assigned to another resource type. Don't // doi was assigned to another resource type. Don't
// reactivate it // reactivate it
throw new DOIIdentifierException("Cannot reassing " throw new DOIIdentifierException("Cannot reassign"
+ "previously deleted DOI " + doiIdentifier + " previously deleted DOI " + doiIdentifier
+ " as the resource types of the object it was " + " as the resource types of the object it was"
+ "previously assigned to and the object it " + " previously assigned to and the object it"
+ "shall be assigned to now divert (was: " + " shall be assigned to now differ (was: "
+ Constants.typeText[doi.getResourceTypeId()] + Constants.typeText[doi.getResourceTypeId()]
+ ", trying to assign to " + ", trying to assign to "
+ Constants.typeText[dso.getType()] + ").", + Constants.typeText[dso.getType()] + ").",

View File

@@ -8,7 +8,7 @@
package org.dspace.identifier.dao.impl; package org.dspace.identifier.dao.impl;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
@@ -52,7 +52,7 @@ public class DOIDAOImpl extends AbstractHibernateDAO<DOI> implements DOIDAO {
Root<DOI> doiRoot = criteriaQuery.from(DOI.class); Root<DOI> doiRoot = criteriaQuery.from(DOI.class);
criteriaQuery.select(doiRoot); criteriaQuery.select(doiRoot);
List<Predicate> listToIncludeInOrPredicate = new LinkedList<>(); List<Predicate> listToIncludeInOrPredicate = new ArrayList<>(statusToExclude.size() + 1);
for (Integer status : statusToExclude) { for (Integer status : statusToExclude) {
listToIncludeInOrPredicate.add(criteriaBuilder.notEqual(doiRoot.get(DOI_.status), status)); listToIncludeInOrPredicate.add(criteriaBuilder.notEqual(doiRoot.get(DOI_.status), status));
@@ -75,7 +75,7 @@ public class DOIDAOImpl extends AbstractHibernateDAO<DOI> implements DOIDAO {
CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, DOI.class); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, DOI.class);
Root<DOI> doiRoot = criteriaQuery.from(DOI.class); Root<DOI> doiRoot = criteriaQuery.from(DOI.class);
criteriaQuery.select(doiRoot); criteriaQuery.select(doiRoot);
List<Predicate> orPredicates = new LinkedList<>(); List<Predicate> orPredicates = new ArrayList<>(statuses.size());
for (Integer status : statuses) { for (Integer status : statuses) {
orPredicates.add(criteriaBuilder.equal(doiRoot.get(DOI_.status), status)); orPredicates.add(criteriaBuilder.equal(doiRoot.get(DOI_.status), status));
} }
@@ -92,13 +92,13 @@ public class DOIDAOImpl extends AbstractHibernateDAO<DOI> implements DOIDAO {
Root<DOI> doiRoot = criteriaQuery.from(DOI.class); Root<DOI> doiRoot = criteriaQuery.from(DOI.class);
criteriaQuery.select(doiRoot); criteriaQuery.select(doiRoot);
List<Predicate> listToIncludeInOrPredicate = new LinkedList<>(); List<Predicate> listToIncludeInOrPredicate = new ArrayList<>(excludedStatuses.size());
for (Integer status : excludedStatuses) { for (Integer status : excludedStatuses) {
listToIncludeInOrPredicate.add(criteriaBuilder.notEqual(doiRoot.get(DOI_.status), status)); listToIncludeInOrPredicate.add(criteriaBuilder.notEqual(doiRoot.get(DOI_.status), status));
} }
List<Predicate> listToIncludeInAndPredicate = new LinkedList<>(); List<Predicate> listToIncludeInAndPredicate = new ArrayList<>();
listToIncludeInAndPredicate.add(criteriaBuilder.like(doiRoot.get(DOI_.doi), doi)); listToIncludeInAndPredicate.add(criteriaBuilder.like(doiRoot.get(DOI_.doi), doi));
listToIncludeInAndPredicate.add(criteriaBuilder.or(listToIncludeInOrPredicate.toArray(new Predicate[] {}))); listToIncludeInAndPredicate.add(criteriaBuilder.or(listToIncludeInOrPredicate.toArray(new Predicate[] {})));
@@ -107,8 +107,6 @@ public class DOIDAOImpl extends AbstractHibernateDAO<DOI> implements DOIDAO {
} }
criteriaQuery.where(listToIncludeInAndPredicate.toArray(new Predicate[] {})); criteriaQuery.where(listToIncludeInAndPredicate.toArray(new Predicate[] {}));
return list(context, criteriaQuery, false, DOI.class, -1, -1); return list(context, criteriaQuery, false, DOI.class, -1, -1);
} }
@Override @Override

View File

@@ -7,9 +7,9 @@
*/ */
package org.dspace.importer.external.datamodel; package org.dspace.importer.external.datamodel;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.dspace.importer.external.metadatamapping.MetadatumDTO; import org.dspace.importer.external.metadatamapping.MetadatumDTO;
@@ -38,7 +38,7 @@ public class ImportRecord {
*/ */
public ImportRecord(List<MetadatumDTO> valueList) { public ImportRecord(List<MetadatumDTO> valueList) {
//don't want to alter the original list. Also now I can control the type of list //don't want to alter the original list. Also now I can control the type of list
this.valueList = new LinkedList<>(valueList); this.valueList = new ArrayList<>(valueList);
} }
/** /**
@@ -81,7 +81,7 @@ public class ImportRecord {
* @return the MetadatumDTO's that are related to a given schema/element/qualifier pair/triplet * @return the MetadatumDTO's that are related to a given schema/element/qualifier pair/triplet
*/ */
public Collection<MetadatumDTO> getValue(String schema, String element, String qualifier) { public Collection<MetadatumDTO> getValue(String schema, String element, String qualifier) {
List<MetadatumDTO> values = new LinkedList<MetadatumDTO>(); List<MetadatumDTO> values = new ArrayList<MetadatumDTO>();
for (MetadatumDTO value : valueList) { for (MetadatumDTO value : valueList) {
if (value.getSchema().equals(schema) && value.getElement().equals(element)) { if (value.getSchema().equals(schema) && value.getElement().equals(element)) {
if (qualifier == null && value.getQualifier() == null) { if (qualifier == null && value.getQualifier() == null) {

View File

@@ -7,18 +7,19 @@
*/ */
package org.dspace.importer.external.metadatamapping; package org.dspace.importer.external.metadatamapping;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.LinkedList;
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.importer.external.metadatamapping.contributor.MetadataContributor; import org.dspace.importer.external.metadatamapping.contributor.MetadataContributor;
import org.dspace.importer.external.metadatamapping.transform.MetadataProcessorService; import org.dspace.importer.external.metadatamapping.transform.MetadataProcessorService;
/** /**
* Abstract class that implements {@link MetadataFieldMapping} * Abstract class that implements {@link MetadataFieldMapping}.
* This class adds a default implementation for the MetadataFieldMapping methods * This class adds a default implementation for the MetadataFieldMapping methods.
* *
* @author Roeland Dillen (roeland at atmire dot com) * @author Roeland Dillen (roeland at atmire dot com)
*/ */
@@ -30,7 +31,7 @@ public abstract class AbstractMetadataFieldMapping<RecordType>
/** /**
* log4j logger * log4j logger
*/ */
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(AbstractMetadataFieldMapping.class); private static final Logger log = LogManager.getLogger(AbstractMetadataFieldMapping.class);
/* A map containing what processing has to be done on a given metadataFieldConfig. /* A map containing what processing has to be done on a given metadataFieldConfig.
* The processing of a value is used to determine the actual value that will be returned used. * The processing of a value is used to determine the actual value that will be returned used.
@@ -66,6 +67,7 @@ public abstract class AbstractMetadataFieldMapping<RecordType>
* @param value The value to map to a MetadatumDTO * @param value The value to map to a MetadatumDTO
* @return A metadatumDTO created from the field and value * @return A metadatumDTO created from the field and value
*/ */
@Override
public MetadatumDTO toDCValue(MetadataFieldConfig field, String value) { public MetadatumDTO toDCValue(MetadataFieldConfig field, String value) {
MetadatumDTO dcValue = new MetadatumDTO(); MetadatumDTO dcValue = new MetadatumDTO();
@@ -108,14 +110,15 @@ public abstract class AbstractMetadataFieldMapping<RecordType>
} }
/** /**
* Loop over the MetadataContributors and return their concatenated retrieved metadatumDTO objects * Loop over the MetadataContributors and return their concatenated
* retrieved metadatumDTO objects.
* *
* @param record Used to retrieve the MetadatumDTO * @param record Used to retrieve the MetadatumDTO
* @return Lit of metadatumDTO * @return Lit of metadatumDTO
*/ */
@Override @Override
public Collection<MetadatumDTO> resultToDCValueMapping(RecordType record) { public Collection<MetadatumDTO> resultToDCValueMapping(RecordType record) {
List<MetadatumDTO> values = new LinkedList<MetadatumDTO>(); List<MetadatumDTO> values = new ArrayList<>();
for (MetadataContributor<RecordType> query : getMetadataFieldMap().values()) { for (MetadataContributor<RecordType> query : getMetadataFieldMap().values()) {
try { try {

View File

@@ -8,7 +8,7 @@
package org.dspace.importer.external.metadatamapping; package org.dspace.importer.external.metadatamapping;
/** /**
* A generalised configuration for metadatafields. * A generalised configuration for metadata fields.
* This is used to make the link between values and the actual MetadatumDTO object. * This is used to make the link between values and the actual MetadatumDTO object.
* *
* @author Roeland Dillen (roeland at atmire dot com) * @author Roeland Dillen (roeland at atmire dot com)
@@ -31,7 +31,7 @@ public class MetadataFieldConfig {
if (this == o) { if (this == o) {
return true; return true;
} }
if (o == null || getClass() != o.getClass()) { if (o == null || !(o instanceof MetadataFieldConfig)) {
return false; return false;
} }
@@ -43,11 +43,7 @@ public class MetadataFieldConfig {
if (qualifier != null ? !qualifier.equals(that.qualifier) : that.qualifier != null) { if (qualifier != null ? !qualifier.equals(that.qualifier) : that.qualifier != null) {
return false; return false;
} }
if (!schema.equals(that.schema)) { return schema.equals(that.schema);
return false;
}
return true;
} }
/** /**

View File

@@ -15,6 +15,7 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.StringWriter; import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@@ -38,7 +39,8 @@ import org.dspace.content.service.ItemService;
import org.dspace.core.Context; import org.dspace.core.Context;
/** /**
* Cleanup class for CC Licenses, corrects XML formating errors by replacing the license_rdf bitstream. * Cleanup class for CC Licenses, corrects XML formatting errors by replacing
* the license_rdf bitstream.
* *
* @author mdiggory * @author mdiggory
*/ */
@@ -130,7 +132,7 @@ public class LicenseCleanup {
AuthorizeException, IOException { AuthorizeException, IOException {
List<Bundle> bundles = itemService.getBundles(item, "CC-LICENSE"); List<Bundle> bundles = itemService.getBundles(item, "CC-LICENSE");
if (bundles == null || bundles.size() == 0) { if (bundles == null || bundles.isEmpty()) {
return; return;
} }
@@ -138,7 +140,7 @@ public class LicenseCleanup {
Bitstream bitstream = bundleService.getBitstreamByName(bundle, "license_rdf"); Bitstream bitstream = bundleService.getBitstreamByName(bundle, "license_rdf");
String license_rdf = new String(copy(context, bitstream)); String license_rdf = new String(copy(context, bitstream), StandardCharsets.UTF_8);
/* quickly fix xml by ripping out offensive parts */ /* quickly fix xml by ripping out offensive parts */
license_rdf = license_rdf.replaceFirst("<license", ""); license_rdf = license_rdf.replaceFirst("<license", "");
@@ -148,7 +150,7 @@ public class LicenseCleanup {
try { try {
templates.newTransformer().transform( templates.newTransformer().transform(
new StreamSource(new ByteArrayInputStream(license_rdf.getBytes())), new StreamSource(new ByteArrayInputStream(license_rdf.getBytes(StandardCharsets.UTF_8))),
new StreamResult(result)); new StreamResult(result));
} catch (TransformerException e) { } catch (TransformerException e) {
throw new IllegalStateException(e.getMessage(), e); throw new IllegalStateException(e.getMessage(), e);
@@ -158,7 +160,7 @@ public class LicenseCleanup {
Bitstream newBitstream = bitstreamService Bitstream newBitstream = bitstreamService
.create(context, bundle, new ByteArrayInputStream(buffer.toString() .create(context, bundle, new ByteArrayInputStream(buffer.toString()
.getBytes())); .getBytes(StandardCharsets.UTF_8)));
newBitstream.setName(context, bitstream.getName()); newBitstream.setName(context, bitstream.getName());
newBitstream.setDescription(context, bitstream.getDescription()); newBitstream.setDescription(context, bitstream.getDescription());

View File

@@ -14,7 +14,8 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder;
/** /**
* This class serves as a representation of a command line parameter by holding a String name and a String value * This class serves as a representation of a command line parameter by holding
* a String name and a String value.
*/ */
public class DSpaceCommandLineParameter { public class DSpaceCommandLineParameter {
private String name; private String name;
@@ -23,7 +24,7 @@ public class DSpaceCommandLineParameter {
public static String SEPARATOR = "|||"; public static String SEPARATOR = "|||";
/** /**
* This constructor will take a String key and String value and store them in their appriopriate fields * This constructor will take a String key and String value and store them in their appropriate fields.
* @param key The String value to be stored as the name of the parameter * @param key The String value to be stored as the name of the parameter
* @param value The String value to be stored as the value of the parameter * @param value The String value to be stored as the value of the parameter
*/ */
@@ -64,9 +65,10 @@ public class DSpaceCommandLineParameter {
/** /**
* Converts the DSpaceCommandLineParameter into a String format by concatenating the value and the name String * Converts the DSpaceCommandLineParameter into a String format by concatenating the value and the name String
* values by separating them with a space * values by separating them with a space.
* @return The String representation of a DSpaceCommandlineParameter object * @return The String representation of a DSpaceCommandlineParameter object
*/ */
@Override
public String toString() { public String toString() {
String stringToReturn = ""; String stringToReturn = "";
stringToReturn += getName(); stringToReturn += getName();
@@ -92,7 +94,7 @@ public class DSpaceCommandLineParameter {
} }
/** /**
* Will return a boolean indicating whether the given param is equal to this object * Will return a boolean indicating whether the given parameter is equal to this object.
* @param other The other object * @param other The other object
* @return A boolean indicating equality * @return A boolean indicating equality
*/ */
@@ -101,7 +103,7 @@ public class DSpaceCommandLineParameter {
if (other == null) { if (other == null) {
return false; return false;
} }
if (other.getClass() != DSpaceCommandLineParameter.class) { if (!(other instanceof DSpaceCommandLineParameter)) {
return false; return false;
} }
return StringUtils.equals(this.getName(), ((DSpaceCommandLineParameter) other).getName()) && StringUtils return StringUtils.equals(this.getName(), ((DSpaceCommandLineParameter) other).getName()) && StringUtils

View File

@@ -8,7 +8,7 @@
package org.dspace.scripts; package org.dspace.scripts;
import java.io.InputStream; import java.io.InputStream;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -37,7 +37,7 @@ public abstract class DSpaceRunnable<T extends ScriptConfiguration> implements R
protected CommandLine commandLine; protected CommandLine commandLine;
/** /**
* This EPerson identifier variable is the uuid of the eperson that's running the script * This EPerson identifier variable is the UUID of the EPerson that's running the script
*/ */
private UUID epersonIdentifier; private UUID epersonIdentifier;
@@ -129,7 +129,7 @@ public abstract class DSpaceRunnable<T extends ScriptConfiguration> implements R
* @return The list of Strings representing filenames from the options given to the script * @return The list of Strings representing filenames from the options given to the script
*/ */
public List<String> getFileNamesFromInputStreamOptions() { public List<String> getFileNamesFromInputStreamOptions() {
List<String> fileNames = new LinkedList<>(); List<String> fileNames = new ArrayList<>();
for (Option option : getScriptConfiguration().getOptions().getOptions()) { for (Option option : getScriptConfiguration().getOptions().getOptions()) {
if (option.getType() == InputStream.class && if (option.getType() == InputStream.class &&
@@ -151,8 +151,8 @@ public abstract class DSpaceRunnable<T extends ScriptConfiguration> implements R
} }
/** /**
* Generic setter for the epersonIdentifier * Generic setter for the epersonIdentifier.
* This EPerson identifier variable is the uuid of the eperson that's running the script * This EPerson identifier variable is the UUID of the EPerson that's running the script.
* @param epersonIdentifier The epersonIdentifier to be set on this DSpaceRunnable * @param epersonIdentifier The epersonIdentifier to be set on this DSpaceRunnable
*/ */
public void setEpersonIdentifier(UUID epersonIdentifier) { public void setEpersonIdentifier(UUID epersonIdentifier) {

View File

@@ -7,8 +7,8 @@
*/ */
package org.dspace.scripts; package org.dspace.scripts;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@@ -91,6 +91,7 @@ public class Process implements ReloadableEntity<Integer> {
* This method returns the ID that the Process holds within the Database * This method returns the ID that the Process holds within the Database
* @return The ID that the process holds within the database * @return The ID that the process holds within the database
*/ */
@Override
public Integer getID() { public Integer getID() {
return processId; return processId;
} }
@@ -162,7 +163,8 @@ public class Process implements ReloadableEntity<Integer> {
/** /**
* To get the parameters, use ProcessService.getParameters() to get a parsed list of DSpaceCommandLineParameters * To get the parameters, use ProcessService.getParameters() to get a parsed list of DSpaceCommandLineParameters
* This String representation is the parameter in an unparsed fashion. For example "-c test" * This String representation is the parameter in an unparsed fashion.For example "-c test"
* @return the raw parameter string.
*/ */
protected String getParameters() { protected String getParameters() {
return parameters; return parameters;
@@ -179,7 +181,7 @@ public class Process implements ReloadableEntity<Integer> {
*/ */
public List<Bitstream> getBitstreams() { public List<Bitstream> getBitstreams() {
if (bitstreams == null) { if (bitstreams == null) {
bitstreams = new LinkedList<>(); bitstreams = new ArrayList<>();
} }
return bitstreams; return bitstreams;
} }

View File

@@ -11,7 +11,6 @@ import java.sql.SQLException;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@@ -43,7 +42,6 @@ import org.dspace.handle.service.HandleService;
* withdrawn within a particular range of dates. * withdrawn within a particular range of dates.
* *
* @author Robert Tansley * @author Robert Tansley
* @version $Revision$
*/ */
public class Harvest { public class Harvest {
/** /**
@@ -129,7 +127,7 @@ public class Harvest {
// several smaller operations (e.g. for OAI resumption tokens.) // several smaller operations (e.g. for OAI resumption tokens.)
discoverQuery.setSortField("search.resourceid", DiscoverQuery.SORT_ORDER.asc); discoverQuery.setSortField("search.resourceid", DiscoverQuery.SORT_ORDER.asc);
List<HarvestedItemInfo> infoObjects = new LinkedList<HarvestedItemInfo>(); List<HarvestedItemInfo> infoObjects = new ArrayList<>();
// Count of items read from the record set that match the selection criteria. // Count of items read from the record set that match the selection criteria.
// Note : Until 'index > offset' the records are not added to the output set. // Note : Until 'index > offset' the records are not added to the output set.
@@ -155,7 +153,7 @@ public class Harvest {
if (collections) { if (collections) {
// Add collections data // Add collections data
fillCollections(context, itemInfo); fillCollections(itemInfo);
} }
if (items) { if (items) {
@@ -163,7 +161,7 @@ public class Harvest {
itemInfo.item = itemService.find(context, itemInfo.itemID); itemInfo.item = itemService.find(context, itemInfo.itemID);
} }
if ((nonAnon) || (itemInfo.item == null) || (withdrawn && itemInfo.withdrawn)) { if (nonAnon || (itemInfo.item == null) || (withdrawn && itemInfo.withdrawn)) {
index++; index++;
if (index > offset) { if (index > offset) {
infoObjects.add(itemInfo); infoObjects.add(itemInfo);
@@ -221,7 +219,7 @@ public class Harvest {
// Get the sets // Get the sets
if (collections) { if (collections) {
fillCollections(context, itemInfo); fillCollections(itemInfo);
} }
return itemInfo; return itemInfo;
@@ -230,12 +228,10 @@ public class Harvest {
/** /**
* Fill out the containers field of the HarvestedItemInfo object * Fill out the containers field of the HarvestedItemInfo object
* *
* @param context DSpace context
* @param itemInfo HarvestedItemInfo object to fill out * @param itemInfo HarvestedItemInfo object to fill out
* @throws SQLException if database error * @throws SQLException if database error
*/ */
private static void fillCollections(Context context, private static void fillCollections(HarvestedItemInfo itemInfo) throws SQLException {
HarvestedItemInfo itemInfo) throws SQLException {
// Get the collection Handles from DB // Get the collection Handles from DB
List<Collection> collections = itemInfo.item.getCollections(); List<Collection> collections = itemInfo.item.getCollections();
itemInfo.collectionHandles = new ArrayList<>(); itemInfo.collectionHandles = new ArrayList<>();

View File

@@ -10,6 +10,7 @@ package org.dspace.statistics;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -24,7 +25,7 @@ import org.apache.commons.lang3.StringUtils;
/** /**
* @author kevinvandevelde at atmire.com * @author kevinvandevelde at atmire.com
* Date: 21-jan-2009 * Date: 21-Jan-2009
* Time: 13:44:48 * Time: 13:44:48
*/ */
public class Dataset { public class Dataset {
@@ -66,20 +67,20 @@ public class Dataset {
} }
private void initRowLabels(int rows) { private void initRowLabels(int rows) {
rowLabels = new ArrayList<String>(rows); rowLabels = new ArrayList<>(rows);
rowLabelsAttrs = new ArrayList<Map<String, String>>(); rowLabelsAttrs = new ArrayList<>();
for (int i = 0; i < rows; i++) { for (int i = 0; i < rows; i++) {
rowLabels.add("Row " + (i + 1)); rowLabels.add("Row " + (i + 1));
rowLabelsAttrs.add(new HashMap<String, String>()); rowLabelsAttrs.add(new HashMap<>());
} }
} }
private void initColumnLabels(int nbCols) { private void initColumnLabels(int nbCols) {
colLabels = new ArrayList<String>(nbCols); colLabels = new ArrayList<>(nbCols);
colLabelsAttrs = new ArrayList<Map<String, String>>(); colLabelsAttrs = new ArrayList<>();
for (int i = 0; i < nbCols; i++) { for (int i = 0; i < nbCols; i++) {
colLabels.add("Column " + (i + 1)); colLabels.add("Column " + (i + 1));
colLabelsAttrs.add(new HashMap<String, String>()); colLabelsAttrs.add(new HashMap<>());
} }
} }
@@ -233,7 +234,9 @@ public class Dataset {
public ByteArrayOutputStream exportAsCSV() throws IOException { public ByteArrayOutputStream exportAsCSV() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
ICSVWriter ecsvp = new CSVWriterBuilder(new OutputStreamWriter(baos)).withSeparator(';').build(); ICSVWriter ecsvp = new CSVWriterBuilder(new OutputStreamWriter(baos, StandardCharsets.UTF_8))
.withSeparator(';')
.build();
//Generate the item row //Generate the item row
List<String> colLabels = getColLabels(); List<String> colLabels = getColLabels();
colLabels.add(0, ""); colLabels.add(0, "");

View File

@@ -7,9 +7,10 @@
*/ */
package org.dspace.statistics; package org.dspace.statistics;
import java.util.LinkedList; 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.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.services.model.Event; import org.dspace.services.model.Event;
@@ -28,7 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired;
*/ */
public class SolrLoggerUsageEventListener extends AbstractUsageEventListener { public class SolrLoggerUsageEventListener extends AbstractUsageEventListener {
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(SolrLoggerUsageEventListener.class); private static final Logger log = LogManager.getLogger(SolrLoggerUsageEventListener.class);
protected SolrLoggerService solrLoggerService; protected SolrLoggerService solrLoggerService;
@@ -56,7 +57,7 @@ public class SolrLoggerUsageEventListener extends AbstractUsageEventListener {
} }
} else if (UsageEvent.Action.SEARCH == ue.getAction()) { } else if (UsageEvent.Action.SEARCH == ue.getAction()) {
UsageSearchEvent usageSearchEvent = (UsageSearchEvent) ue; UsageSearchEvent usageSearchEvent = (UsageSearchEvent) ue;
List<String> queries = new LinkedList<>(); List<String> queries = new ArrayList<>();
queries.add(usageSearchEvent.getQuery()); queries.add(usageSearchEvent.getQuery());
solrLoggerService.postSearch(usageSearchEvent.getObject(), usageSearchEvent.getRequest(), solrLoggerService.postSearch(usageSearchEvent.getObject(), usageSearchEvent.getRequest(),
currentUser, queries, usageSearchEvent.getPage().getSize(), currentUser, queries, usageSearchEvent.getPage().getSize(),

View File

@@ -285,13 +285,8 @@ public class StatisticsDataVisits extends StatisticsData {
DatasetQuery firsDataset = datasetQueries.get(0); DatasetQuery firsDataset = datasetQueries.get(0);
//Do the first query //Do the first query
ObjectCount[] topCounts1 = null; ObjectCount[] topCounts1 =
// if (firsDataset.getQueries().size() == 1) {
topCounts1 =
queryFacetField(firsDataset, firsDataset.getQueries().get(0).getQuery(), filterQuery, facetMinCount); queryFacetField(firsDataset, firsDataset.getQueries().get(0).getQuery(), filterQuery, facetMinCount);
// } else {
// TODO: do this
// }
// Check if we have more queries that need to be done // Check if we have more queries that need to be done
if (datasetQueries.size() == 2) { if (datasetQueries.size() == 2) {
DatasetQuery secondDataSet = datasetQueries.get(1); DatasetQuery secondDataSet = datasetQueries.get(1);
@@ -313,7 +308,6 @@ public class StatisticsDataVisits extends StatisticsData {
} }
for (int i = 0; i < topCounts1.length; i++) { for (int i = 0; i < topCounts1.length; i++) {
ObjectCount count1 = topCounts1[i]; ObjectCount count1 = topCounts1[i];
ObjectCount[] currentResult = new ObjectCount[topCounts2.length];
// Make sure we have a dataSet // Make sure we have a dataSet
if (dataset == null) { if (dataset == null) {
@@ -645,7 +639,7 @@ public class StatisticsDataVisits extends StatisticsData {
// be null if a handle has not yet been assigned. In this case reference the // be null if a handle has not yet been assigned. In this case reference the
// item its internal id. In the last case where the bitstream is not associated // item its internal id. In the last case where the bitstream is not associated
// with an item (such as a community logo) then reference the bitstreamID directly. // with an item (such as a community logo) then reference the bitstreamID directly.
String identifier = null; String identifier;
if (owningItem != null && owningItem.getHandle() != null) { if (owningItem != null && owningItem.getHandle() != null) {
identifier = "handle/" + owningItem.getHandle(); identifier = "handle/" + owningItem.getHandle();
} else if (owningItem != null) { } else if (owningItem != null) {

View File

@@ -19,8 +19,6 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.CharEncoding;
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.dspace.content.DCDate; import org.dspace.content.DCDate;
import org.dspace.content.Entity; import org.dspace.content.Entity;
import org.dspace.content.EntityType; import org.dspace.content.EntityType;
@@ -42,8 +40,6 @@ import org.dspace.statistics.export.service.OpenUrlService;
*/ */
public abstract class ExportEventProcessor { public abstract class ExportEventProcessor {
private static final Logger log = LogManager.getLogger();
protected static final String ENTITY_TYPE_DEFAULT = "Publication"; protected static final String ENTITY_TYPE_DEFAULT = "Publication";
protected static final String ITEM_VIEW = "Investigation"; protected static final String ITEM_VIEW = "Investigation";
@@ -130,8 +126,10 @@ public abstract class ExportEventProcessor {
//Start adding our data //Start adding our data
StringBuilder data = new StringBuilder(); StringBuilder data = new StringBuilder();
data.append(URLEncoder.encode("url_ver", UTF_8) + "=" + data.append(URLEncoder.encode("url_ver", UTF_8))
URLEncoder.encode(configurationService.getProperty("irus.statistics.tracker.urlversion"), UTF_8)); .append("=")
.append(URLEncoder.encode(configurationService.getProperty("irus.statistics.tracker.urlversion"),
UTF_8));
data.append("&").append(URLEncoder.encode("req_id", UTF_8)).append("=") data.append("&").append(URLEncoder.encode("req_id", UTF_8)).append("=")
.append(URLEncoder.encode(clientIP, UTF_8)); .append(URLEncoder.encode(clientIP, UTF_8));
data.append("&").append(URLEncoder.encode("req_dat", UTF_8)).append("=") data.append("&").append(URLEncoder.encode("req_dat", UTF_8)).append("=")

View File

@@ -24,9 +24,10 @@ import org.dspace.services.factory.DSpaceServicesFactory;
*/ */
public class ItemEventProcessor extends ExportEventProcessor { public class ItemEventProcessor extends ExportEventProcessor {
private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); private final ConfigurationService configurationService
= DSpaceServicesFactory.getInstance().getConfigurationService();
private Item item; private final Item item;
/** /**
* Creates a new ItemEventProcessor that will set the params * Creates a new ItemEventProcessor that will set the params
@@ -48,6 +49,7 @@ public class ItemEventProcessor extends ExportEventProcessor {
* @throws SQLException * @throws SQLException
* @throws IOException * @throws IOException
*/ */
@Override
public void processEvent() throws SQLException, IOException { public void processEvent() throws SQLException, IOException {
if (shouldProcessItem(item)) { if (shouldProcessItem(item)) {
String baseParam = getBaseParameters(item); String baseParam = getBaseParameters(item);

View File

@@ -15,8 +15,6 @@ import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException; import org.apache.commons.cli.ParseException;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamService;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.storage.bitstore.factory.StorageServiceFactory; import org.dspace.storage.bitstore.factory.StorageServiceFactory;
import org.dspace.storage.bitstore.service.BitstreamStorageService; import org.dspace.storage.bitstore.service.BitstreamStorageService;
@@ -31,8 +29,6 @@ public class BitStoreMigrate {
*/ */
private static final Logger log = LogManager.getLogger(BitStoreMigrate.class); private static final Logger log = LogManager.getLogger(BitStoreMigrate.class);
private static final BitstreamService bitstreamService
= ContentServiceFactory.getInstance().getBitstreamService();
private static final BitstreamStorageService bitstreamStorageService private static final BitstreamStorageService bitstreamStorageService
= StorageServiceFactory.getInstance().getBitstreamStorageService(); = StorageServiceFactory.getInstance().getBitstreamStorageService();

View File

@@ -12,6 +12,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@@ -133,7 +134,7 @@ public class DatabaseUtils {
System.err.println("\nError running 'test': "); System.err.println("\nError running 'test': ");
System.err.println(" - " + sqle); System.err.println(" - " + sqle);
System.err.println("\nPlease see the DSpace documentation for assistance.\n"); System.err.println("\nPlease see the DSpace documentation for assistance.\n");
sqle.printStackTrace(); sqle.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
} else if (argv[0].equalsIgnoreCase("info") || argv[0].equalsIgnoreCase("status")) { } else if (argv[0].equalsIgnoreCase("info") || argv[0].equalsIgnoreCase("status")) {
@@ -173,15 +174,16 @@ public class DatabaseUtils {
} }
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Info exception:"); System.err.println("Info exception:");
e.printStackTrace(); e.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
} else if (argv[0].equalsIgnoreCase("migrate")) { } else if (argv[0].equalsIgnoreCase("migrate")) {
try (Connection connection = dataSource.getConnection()) { try (Connection connection = dataSource.getConnection()) {
System.out.println("\nDatabase URL: " + connection.getMetaData().getURL()); System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
// "migrate" allows for an OPTIONAL second argument: // "migrate" allows for an OPTIONAL second argument (only one may be specified):
// - "ignored" = Also run any previously "ignored" migrations during the migration // - "ignored" = Also run any previously "ignored" migrations during the migration
// - "force" = Even if no pending migrations exist, still run a migration to trigger callbacks.
// - [version] = ONLY run migrations up to a specific DSpace version (ONLY FOR TESTING) // - [version] = ONLY run migrations up to a specific DSpace version (ONLY FOR TESTING)
if (argv.length == 2) { if (argv.length == 2) {
if (argv[1].equalsIgnoreCase("ignored")) { if (argv[1].equalsIgnoreCase("ignored")) {
@@ -191,11 +193,14 @@ public class DatabaseUtils {
// Update the database to latest version, but set "outOfOrder=true" // Update the database to latest version, but set "outOfOrder=true"
// This will ensure any old migrations in the "ignored" state are now run // This will ensure any old migrations in the "ignored" state are now run
updateDatabase(dataSource, connection, null, true); updateDatabase(dataSource, connection, null, true);
} else if (argv[1].equalsIgnoreCase("force")) {
updateDatabase(dataSource, connection, null, false, true);
} else { } else {
// Otherwise, we assume "argv[1]" is a valid migration version number // Otherwise, we assume "argv[1]" is a valid migration version number
// This is only for testing! Never specify for Production! // This is only for testing! Never specify for Production!
String migrationVersion = argv[1]; String migrationVersion = argv[1];
BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); BufferedReader input = new BufferedReader(
new InputStreamReader(System.in, StandardCharsets.UTF_8));
System.out.println( System.out.println(
"You've specified to migrate your database ONLY to version " + migrationVersion + " " + "You've specified to migrate your database ONLY to version " + migrationVersion + " " +
@@ -231,7 +236,7 @@ public class DatabaseUtils {
System.exit(0); System.exit(0);
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Migration exception:"); System.err.println("Migration exception:");
e.printStackTrace(); e.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
} else if (argv[0].equalsIgnoreCase("repair")) { } else if (argv[0].equalsIgnoreCase("repair")) {
@@ -247,7 +252,7 @@ public class DatabaseUtils {
System.exit(0); System.exit(0);
} catch (SQLException | FlywayException e) { } catch (SQLException | FlywayException e) {
System.err.println("Repair exception:"); System.err.println("Repair exception:");
e.printStackTrace(); e.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
} else if (argv[0].equalsIgnoreCase("validate")) { } else if (argv[0].equalsIgnoreCase("validate")) {
@@ -262,7 +267,7 @@ public class DatabaseUtils {
System.exit(0); System.exit(0);
} catch (SQLException | FlywayException e) { } catch (SQLException | FlywayException e) {
System.err.println("Validation exception:"); System.err.println("Validation exception:");
e.printStackTrace(); e.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
} else if (argv[0].equalsIgnoreCase("clean")) { } else if (argv[0].equalsIgnoreCase("clean")) {
@@ -305,7 +310,7 @@ public class DatabaseUtils {
} }
} }
BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); BufferedReader input = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
System.out.println("\nDatabase URL: " + connection.getMetaData().getURL()); System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
System.out System.out
@@ -332,7 +337,7 @@ public class DatabaseUtils {
} }
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Clean exception:"); System.err.println("Clean exception:");
e.printStackTrace(); e.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
} else if (argv[0].equalsIgnoreCase("update-sequences")) { } else if (argv[0].equalsIgnoreCase("update-sequences")) {
@@ -384,14 +389,14 @@ public class DatabaseUtils {
} catch (Exception e) { } catch (Exception e) {
System.err.println("Caught exception:"); System.err.println("Caught exception:");
e.printStackTrace(); e.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
} }
/** /**
* Print basic information about the current database to System.out. * Print basic information about the current database to System.out.
* This is utilized by both the 'test' and 'info' commandline options. * This is utilized by both the 'test' and 'info' command line options.
* *
* @param connection current database connection * @param connection current database connection
* @throws SQLException if database error occurs * @throws SQLException if database error occurs
@@ -654,6 +659,34 @@ public class DatabaseUtils {
protected static synchronized void updateDatabase(DataSource datasource, protected static synchronized void updateDatabase(DataSource datasource,
Connection connection, String targetVersion, boolean outOfOrder) Connection connection, String targetVersion, boolean outOfOrder)
throws SQLException { throws SQLException {
updateDatabase(datasource, connection, targetVersion, outOfOrder, false);
}
/**
* Ensures the current database is up-to-date with regards
* to the latest DSpace DB schema. If the scheme is not up-to-date,
* then any necessary database migrations are performed.
* <P>
* FlywayDB (http://flywaydb.org/) is used to perform database migrations.
* If a Flyway DB migration fails it will be rolled back to the last
* successful migration, and any errors will be logged.
*
* @param datasource DataSource object (retrieved from DatabaseManager())
* @param connection Database connection
* @param targetVersion If specified, only migrate the database to a particular *version* of DSpace. This is
* just useful for testing migrations, and should NOT be used in Production.
* If null, the database is migrated to the latest version.
* @param outOfOrder If true, Flyway will run any lower version migrations that were previously "ignored".
* If false, Flyway will only run new migrations with a higher version number.
* @param forceMigrate If true, always run a Flyway migration, even if no "Pending" migrations exist. This can be
* used to trigger Flyway Callbacks manually.
* If false, only run migration if pending migrations exist, otherwise do nothing.
* @throws SQLException if database error
* If database cannot be upgraded.
*/
protected static synchronized void updateDatabase(DataSource datasource, Connection connection,
String targetVersion, boolean outOfOrder, boolean forceMigrate)
throws SQLException {
if (null == datasource) { if (null == datasource) {
throw new SQLException("The datasource is a null reference -- cannot continue."); throw new SQLException("The datasource is a null reference -- cannot continue.");
} }
@@ -730,6 +763,10 @@ public class DatabaseUtils {
// Flag that Discovery will need reindexing, since database was updated // Flag that Discovery will need reindexing, since database was updated
setReindexDiscovery(reindexAfterUpdate); setReindexDiscovery(reindexAfterUpdate);
} else if (forceMigrate) {
log.info("DSpace database schema is up to date, but 'force' was specified. " +
"Running migrate command to trigger callbacks.");
flyway.migrate();
} else { } else {
log.info("DSpace database schema is up to date"); log.info("DSpace database schema is up to date");
} }

View File

@@ -110,7 +110,7 @@ public abstract class InitialArticleWord implements TextFilter {
return str.substring(cutPos); return str.substring(cutPos);
} else { } else {
// No - move the initial article word to the end // No - move the initial article word to the end
return new StringBuffer(str.substring(cutPos)) return new StringBuilder(str.substring(cutPos))
.append(wordSeparator) .append(wordSeparator)
.append(str.substring(initialStart, initialEnd)) .append(str.substring(initialStart, initialEnd))
.toString(); .toString();
@@ -124,10 +124,12 @@ public abstract class InitialArticleWord implements TextFilter {
} }
protected InitialArticleWord(boolean stripWord) { protected InitialArticleWord(boolean stripWord) {
this.wordSeparator = ", ";
stripInitialArticle = stripWord; stripInitialArticle = stripWord;
} }
protected InitialArticleWord() { protected InitialArticleWord() {
this.wordSeparator = ", ";
stripInitialArticle = false; stripInitialArticle = false;
} }
@@ -138,9 +140,8 @@ public abstract class InitialArticleWord implements TextFilter {
* @return An array of definite/indefinite article words * @return An array of definite/indefinite article words
*/ */
protected abstract String[] getArticleWords(String lang); protected abstract String[] getArticleWords(String lang);
// Separator to use when appending article to end // Separator to use when appending article to end
private String wordSeparator = ", "; private final String wordSeparator;
// Flag to signify initial article word should be removed // Flag to signify initial article word should be removed
// If false, then the initial article word is appended to the end // If false, then the initial article word is appended to the end

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