Another batch of Error Prone fixes. (#3061)

This commit is contained in:
Mark H. Wood
2021-09-10 11:32:58 -04:00
parent 4b96106ea3
commit 384d46348a
32 changed files with 199 additions and 135 deletions

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

@@ -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

@@ -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

@@ -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

@@ -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,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

@@ -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

@@ -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

@@ -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

@@ -33,7 +33,7 @@ public abstract class AbstractIndexableObject<T extends ReloadableEntity<PK>, PK
if (!(obj instanceof IndexableObject)) { if (!(obj instanceof IndexableObject)) {
return false; return false;
} }
AbstractIndexableObject other = (AbstractIndexableObject) obj; IndexableObject other = (IndexableObject) obj;
return other.getIndexedObject().equals(getIndexedObject()); return other.getIndexedObject().equals(getIndexedObject());
} }

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

@@ -15,7 +15,6 @@ import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.app.sherpa.SHERPAService; import org.dspace.app.sherpa.SHERPAService;
import org.dspace.app.sherpa.v2.SHERPAJournal; import org.dspace.app.sherpa.v2.SHERPAJournal;
import org.dspace.app.sherpa.v2.SHERPAResponse; import org.dspace.app.sherpa.v2.SHERPAResponse;
@@ -33,8 +32,6 @@ import org.dspace.external.provider.ExternalDataProvider;
*/ */
public class SHERPAv2JournalDataProvider implements ExternalDataProvider { public class SHERPAv2JournalDataProvider implements ExternalDataProvider {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SHERPAv2JournalDataProvider.class);
// Source identifier (configured in spring configuration) // Source identifier (configured in spring configuration)
private String sourceIdentifier; private String sourceIdentifier;

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

@@ -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

@@ -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,7 +174,7 @@ 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")) {
@@ -195,7 +196,8 @@ public class DatabaseUtils {
// 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 +233,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 +249,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 +264,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 +307,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 +334,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 +386,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

View File

@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration strict='true'
xmlns='http://logging.apache.org/log4j/2.0/config'>
<Properties>
<!-- Log level for all DSpace-specific code (org.dspace.*)
Possible values (from most to least info):
DEBUG, INFO, WARN, ERROR, FATAL -->
<Property name='loglevel.dspace'>DEBUG</Property>
<!-- Log level for other third-party tools/APIs used by DSpace
Possible values (from most to least info):
DEBUG, INFO, WARN, ERROR, FATAL -->
<Property name='loglevel.other'>INFO</Property>
</Properties>
<Appenders>
<!-- A1 is for most DSpace activity -->
<Appender name='A1'
type='Console'>
<Layout type='PatternLayout'
pattern='%d %-5p %c @ %m%n'/>
</Appender>
</Appenders>
<Loggers>
<!-- Most parts of DSpace -->
<Logger name='org.dspace'
level='${loglevel.dspace}'
additivity='false'>
<AppenderRef ref='A1'/>
</Logger>
<!-- Block services logging except on exceptions -->
<Logger name='org.dspace.kernel'
level='ERROR'/>
<Logger name='org.dspace.services'
level='ERROR'/>
<Logger name='org.dspace.servicemanager'
level='WARN'/>
<Logger name='org.dspace.providers'
level='ERROR'/>
<Logger name='org.dspace.utils'
level='ERROR'/>
<!-- Block passwords from being exposed in Axis logs.
(DEBUG exposes passwords in Basic Auth) -->
<Logger name='org.apache.axis.handlers.http.HTTPAuthHandler'
level='INFO'/>
<!-- Anything not a part of DSpace -->
<Root level='${loglevel.other}'>
<AppenderRef ref='A1'/>
</Root>
</Loggers>
</Configuration>