diff --git a/mycore-base/src/main/java/org/mycore/access/MCRAccessCacheHelper.java b/mycore-base/src/main/java/org/mycore/access/MCRAccessCacheHelper.java index fdaa773beb..27e39d841a 100644 --- a/mycore-base/src/main/java/org/mycore/access/MCRAccessCacheHelper.java +++ b/mycore-base/src/main/java/org/mycore/access/MCRAccessCacheHelper.java @@ -40,7 +40,7 @@ public class MCRAccessCacheHelper { public static void clearPermissionCache(String id) { LOGGER.info("Invalidate all permissions for obj {} from local cache", id); - final ArrayList idsToClear = new ArrayList<>(); + List idsToClear = new ArrayList<>(); idsToClear.add(id); collectDescendants(idsToClear, id); MCRAccessManager.invalidPermissionCacheByID(idsToClear.toArray(new String[0])); @@ -53,7 +53,7 @@ public static void clearPermissionCache(String id) { public static void clearAllPermissionCaches(String id) { LOGGER.info("Invalidate all permissions for obj {} from all caches", id); - final ArrayList idsToClear = new ArrayList<>(); + List idsToClear = new ArrayList<>(); idsToClear.add(id); collectDescendants(idsToClear, id); MCRAccessManager.invalidAllPermissionCachesById(idsToClear.toArray(new String[0])); diff --git a/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessControlSystem.java b/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessControlSystem.java index 6a0ea20203..b727e40bf3 100644 --- a/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessControlSystem.java +++ b/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessControlSystem.java @@ -23,6 +23,7 @@ import java.util.Date; import java.util.HashMap; import java.util.Hashtable; +import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -45,7 +46,7 @@ */ public class MCRAccessControlSystem extends MCRAccessBaseImpl { private static MCRAccessControlSystem singleton; - private static final HashMap NEXT_FREE_RULE_ID = new HashMap<>(); + private static final Map NEXT_FREE_RULE_ID = new HashMap<>(); public static final String SYSTEM_RULE_PREFIX = "SYSTEMRULE"; @@ -61,14 +62,14 @@ public class MCRAccessControlSystem extends MCRAccessBaseImpl { boolean disabled = false; - static Hashtable ruleIDTable = new Hashtable<>(); + static Map ruleIDTable = new Hashtable<>(); private static final Logger LOGGER = LogManager.getLogger(MCRAccessControlSystem.class); private MCRAccessControlSystem() { String pools = MCRConfiguration2.getString("MCR.Access.AccessPermissions").orElse("read,write,delete"); - if (pools.trim().length() == 0) { + if (pools.isBlank()) { disabled = true; } @@ -101,7 +102,7 @@ public void createRule(Element rule, String creator, String description) { public void addRule(String id, String pool, Element rule, String description) throws MCRException { MCRRuleMapping ruleMapping = getAutoGeneratedRuleMapping(rule, "System", pool, id, description); String oldRuleID = accessStore.getRuleID(id, pool); - if (oldRuleID == null || oldRuleID.equals("")) { + if (oldRuleID == null || oldRuleID.isEmpty()) { accessStore.createAccessDefinition(ruleMapping); } else { accessStore.updateAccessDefinition(ruleMapping); @@ -135,7 +136,7 @@ public void removeAllRules(String id) throws MCRException { public void updateRule(String id, String pool, Element rule, String description) throws MCRException { MCRRuleMapping ruleMapping = getAutoGeneratedRuleMapping(rule, "System", pool, id, description); String oldRuleID = accessStore.getRuleID(id, pool); - if (oldRuleID == null || oldRuleID.equals("")) { + if (oldRuleID == null || oldRuleID.isEmpty()) { LOGGER.debug( "updateRule called for id <{}> and pool <{}>, but no rule is existing, so new rule was created", id, pool); @@ -347,7 +348,7 @@ public synchronized String getNextFreeRuleID(String prefix) { */ @Override public String getNormalizedRuleString(Element rule) { - if (rule.getChildren() == null || rule.getChildren().size() == 0) { + if (rule.getChildren() == null || rule.getChildren().isEmpty()) { return "false"; } Element normalizedRule = normalize(rule.getChildren().getFirst()); @@ -372,9 +373,9 @@ public MCRRuleMapping getAutoGeneratedRuleMapping(Element rule, String creator, String description) { String ruleString = getNormalizedRuleString(rule); String ruleID = ruleIDTable.get(ruleString); - if (ruleID == null || ruleID.length() == 0) { + if (ruleID == null || ruleID.isEmpty()) { Collection existingIDs = ruleStore.retrieveRuleIDs(ruleString, description); - if (existingIDs != null && existingIDs.size() > 0) { + if (existingIDs != null && !existingIDs.isEmpty()) { // rule yet exists ruleID = existingIDs.iterator().next(); } else { diff --git a/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessDefinition.java b/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessDefinition.java index 86be0b2972..a0c7a48256 100644 --- a/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessDefinition.java +++ b/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessDefinition.java @@ -19,17 +19,18 @@ package org.mycore.access.mcrimpl; import java.util.HashMap; +import java.util.Map; /** * Maps object ids to rules - * + * * @author Arne Seifert */ public class MCRAccessDefinition { private String objid; - private HashMap pools = new HashMap<>(); + private Map pools = new HashMap<>(); public MCRAccessDefinition() { pools.clear(); @@ -43,11 +44,11 @@ public void setObjID(String value) { objid = value; } - public HashMap getPool() { + public Map getPool() { return pools; } - public void setPool(HashMap pool) { + public void setPool(Map pool) { pools = pool; } diff --git a/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessStore.java b/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessStore.java index 7952815086..0bfe333924 100644 --- a/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessStore.java +++ b/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessStore.java @@ -24,6 +24,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import org.apache.logging.log4j.LogManager; @@ -37,7 +38,7 @@ * must implement this interface. Which database actually will be used can then * be configured by reading the value MCR.Persistence.Access.Store.Class * from mycore.properties.access - * + * * @author Arne Seifert */ public abstract class MCRAccessStore { @@ -71,7 +72,7 @@ public abstract class MCRAccessStore { public abstract boolean isRuleInUse(String ruleid); /** - * + * * @return a collection of all String IDs an access rule is assigned to */ public abstract Collection getDistinctStringIDs(); @@ -96,13 +97,13 @@ public static Collection getPools() { /** * alle Elemente eines Datentypes aufbereiten * @param type document type - * + * * @return List of MCRAccessDefinition * @see MCRAccessDefinition */ public Collection getDefinition(String type) { try { - HashMap> sqlDefinition = new HashMap<>(); + Map> sqlDefinition = new HashMap<>(); Collection pools = getInstance().getDatabasePools(); //merge pools pools.removeAll(getPools()); diff --git a/mycore-base/src/main/java/org/mycore/common/MCRConstants.java b/mycore-base/src/main/java/org/mycore/common/MCRConstants.java index ccd85b1e6a..248dcf073d 100644 --- a/mycore-base/src/main/java/org/mycore/common/MCRConstants.java +++ b/mycore-base/src/main/java/org/mycore/common/MCRConstants.java @@ -20,7 +20,8 @@ import java.lang.reflect.Field; import java.util.Collection; -import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.apache.logging.log4j.LogManager; import org.jdom2.Namespace; @@ -30,7 +31,7 @@ /** * This class replaces the deprecated MCRDefaults interface and provides some * final static fields of common use. - * + * * @author Jens Kupferschmidt * @author Thomas Scheffler (yagee) * @author Stefan Freitag (sasf) @@ -119,10 +120,10 @@ public final class MCRConstants { public static final Namespace MCR_NAMESPACE = Namespace.getNamespace("mcr", MCR_URL); - private static final HashMap NAMESPACES_BY_PREFIX; + private static final Map NAMESPACES_BY_PREFIX; static { - NAMESPACES_BY_PREFIX = new HashMap<>(); + NAMESPACES_BY_PREFIX = new ConcurrentHashMap<>(); Field[] fields = MCRConstants.class.getFields(); for (Field f : fields) { diff --git a/mycore-base/src/main/java/org/mycore/common/MCRMailer.java b/mycore-base/src/main/java/org/mycore/common/MCRMailer.java index 422bbfecb0..6863074160 100644 --- a/mycore-base/src/main/java/org/mycore/common/MCRMailer.java +++ b/mycore-base/src/main/java/org/mycore/common/MCRMailer.java @@ -78,12 +78,12 @@ /** * This class provides methods to send emails from within a MyCoRe application. - * + * * @author Marc Schluepmann * @author Frank Lützenkirchen * @author Werner Greßhoff * @author René Adler (eagle) - * + * */ public class MCRMailer extends MCRServlet { @@ -146,7 +146,7 @@ protected void doGetPost(MCRServletJob job) throws Exception { /** * This method sends a simple plaintext email with the given parameters. - * + * * @param sender * the sender of the email * @param recipient @@ -159,7 +159,7 @@ protected void doGetPost(MCRServletJob job) throws Exception { public static void send(String sender, String recipient, String subject, String body) { LOGGER.debug("Called plaintext send method with single recipient."); - ArrayList recipients = new ArrayList<>(); + List recipients = new ArrayList<>(); recipients.add(recipient); send(sender, null, recipients, null, subject, body, null); } @@ -167,7 +167,7 @@ public static void send(String sender, String recipient, String subject, String /** * This method sends a simple plaintext email to more than one recipient. If * flag BCC is true, the sender will also get the email as BCC recipient. - * + * * @param sender * the sender of the email * @param recipients @@ -194,7 +194,7 @@ public static void send(String sender, List recipients, String subject, /** * This method sends a multipart email with the given parameters. - * + * * @param sender * the sender of the email * @param recipient @@ -209,7 +209,7 @@ public static void send(String sender, List recipients, String subject, public static void send(String sender, String recipient, String subject, String body, List parts) { LOGGER.debug("Called multipart send method with single recipient."); - ArrayList recipients = new ArrayList<>(); + List recipients = new ArrayList<>(); recipients.add(recipient); send(sender, null, recipients, null, subject, body, parts); } @@ -217,7 +217,7 @@ public static void send(String sender, String recipient, String subject, String /** * This method sends a multipart email to more than one recipient. If flag * BCC is true, the sender will also get the email as BCC recipient. - * + * * @param sender * the sender of the email * @param recipients @@ -302,8 +302,8 @@ public static void send(Element email, Boolean allowException) throws Exception * Sends email. When sending email fails (for example, outgoing mail server * is not responding), sending will be retried after five minutes. This is * done up to 10 times. - * - * + * + * * @param from * the sender of the email * @param replyTo @@ -343,7 +343,7 @@ public static void send(final String from, final List replyTo, final Lis * Sends email. When sending email fails (for example, outgoing mail server * is not responding), sending will be retried after five minutes. This is * done up to 10 times. - * + * * @param mail the email */ public static void send(EMail mail) { @@ -457,12 +457,12 @@ private static void setMessageContent(EMail mail, Multipart multipart) /** * Generates e-mail from the given input document by transforming it with an xsl stylesheet, * and sends the e-mail afterwards. - * + * * @param input the xml input document - * @param stylesheet the xsl stylesheet that will generate the e-mail, without the ending ".xsl" + * @param stylesheet the xsl stylesheet that will generate the e-mail, without the ending ".xsl" * @param parameters the optionally empty table of xsl parameters * @return the generated e-mail - * + * * @see org.mycore.common.MCRMailer */ public static Element sendMail(Document input, String stylesheet, Map parameters) throws Exception { @@ -489,20 +489,20 @@ public static Element sendMail(Document input, String stylesheet, Map> buildAddressList(final List getTextMessage() { @@ -627,7 +627,7 @@ public Optional getTextMessage() { /** * Returns the HTML message part. - * + * * @return the HTML message part */ public Optional getHTMLMessage() { @@ -637,7 +637,7 @@ public Optional getHTMLMessage() { /** * Returns the {@link EMail} as XML. - * + * * @return the XML */ public Document toXML() { diff --git a/mycore-base/src/main/java/org/mycore/common/MCRRateLimitBuckets.java b/mycore-base/src/main/java/org/mycore/common/MCRRateLimitBuckets.java index 50c121f2a1..18c77c66e4 100644 --- a/mycore-base/src/main/java/org/mycore/common/MCRRateLimitBuckets.java +++ b/mycore-base/src/main/java/org/mycore/common/MCRRateLimitBuckets.java @@ -81,7 +81,7 @@ public static Bucket getOrCreateBucket(String configID) { } final String dsConfigLimits = MCRConfiguration2.getStringOrThrow(CONFIG_PREFIX + CONFIG_ID + ".Limits"); - final HashMap limitMap = Arrays.stream(dsConfigLimits.split(",")).collect( + final Map limitMap = Arrays.stream(dsConfigLimits.split(",")).collect( HashMap::new, (map, str) -> map.put(str.split("/")[1].trim(), Long.parseLong(str.split("/")[0].trim())), HashMap::putAll); @@ -96,7 +96,7 @@ public static Bucket getOrCreateBucket(String configID) { * @param limitMap a map of time units and the corresponding limit/amount of tokens. * @return the created bucket */ - private static Bucket createNewBucket(HashMap limitMap) { + private static Bucket createNewBucket(Map limitMap) { final LocalBucketBuilder builder = Bucket.builder(); for (Map.Entry entry : limitMap.entrySet()) { final String unit = entry.getKey(); diff --git a/mycore-base/src/main/java/org/mycore/common/MCRUtils.java b/mycore-base/src/main/java/org/mycore/common/MCRUtils.java index b9d076a09a..538d217e18 100644 --- a/mycore-base/src/main/java/org/mycore/common/MCRUtils.java +++ b/mycore-base/src/main/java/org/mycore/common/MCRUtils.java @@ -46,6 +46,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.HexFormat; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; @@ -174,8 +176,8 @@ public static Path writeTextToFile(String textToWrite, String fileName, Charset * the File instance of the basic directory * @return an ArrayList with file names as pathes */ - public static ArrayList getAllFileNames(File basedir) { - ArrayList out = new ArrayList<>(); + public static List getAllFileNames(File basedir) { + List out = new ArrayList<>(); File[] stage = basedir.listFiles(); for (File element : stage) { @@ -198,8 +200,8 @@ public static ArrayList getAllFileNames(File basedir) { * @param path the part of directory path * @return an ArrayList with file names as pathes */ - public static ArrayList getAllFileNames(File basedir, String path) { - ArrayList out = new ArrayList<>(); + public static List getAllFileNames(File basedir, String path) { + List out = new ArrayList<>(); File[] stage = basedir.listFiles(); for (File element : stage) { @@ -222,8 +224,8 @@ public static ArrayList getAllFileNames(File basedir, String path) { * the File instance of the basic directory * @return an ArrayList with directory names as pathes */ - public static ArrayList getAllDirectoryNames(File basedir) { - ArrayList out = new ArrayList<>(); + public static List getAllDirectoryNames(File basedir) { + List out = new ArrayList<>(); File[] stage = basedir.listFiles(); for (File element : stage) { @@ -245,8 +247,8 @@ public static ArrayList getAllDirectoryNames(File basedir) { * the part of directory path * @return an ArrayList with directory names as pathes */ - public static ArrayList getAllDirectoryNames(File basedir, String path) { - ArrayList out = new ArrayList<>(); + public static List getAllDirectoryNames(File basedir, String path) { + List out = new ArrayList<>(); File[] stage = basedir.listFiles(); for (File element : stage) { @@ -408,7 +410,7 @@ public static void untar(Path source, Path expandToDirectory) throws IOException try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) { TarArchiveEntry tarEntry; FileSystem targetFS = expandToDirectory.getFileSystem(); - HashMap directoryTimes = new HashMap<>(); + Map directoryTimes = new HashMap<>(); while ((tarEntry = tain.getNextEntry()) != null) { Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName()); Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath(); diff --git a/mycore-base/src/main/java/org/mycore/common/config/MCRConcurrentHashMap.java b/mycore-base/src/main/java/org/mycore/common/config/MCRConcurrentHashMap.java index ce7f67c125..fe96de005d 100644 --- a/mycore-base/src/main/java/org/mycore/common/config/MCRConcurrentHashMap.java +++ b/mycore-base/src/main/java/org/mycore/common/config/MCRConcurrentHashMap.java @@ -23,6 +23,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; +import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; @@ -40,7 +41,7 @@ */ @SuppressWarnings("unchecked") class MCRConcurrentHashMap extends ConcurrentHashMap { - private HashMap keyMap = new HashMap<>(); + private Map keyMap = new HashMap<>(); // Disable serialization @SuppressWarnings("unused") @@ -61,7 +62,7 @@ private void writeObject(ObjectOutputStream ois) * In case of collision, the key is automatically remapped via {@link RemappedKey}. * It is a wrapper to modify the hashcode of the given SingletonKey to assign a different bucket * within the internal table, in an attempt to resolve the collision. - * + * *

The mapping function must not modify the map during computation of any key other then a {@link SingletonKey} * @see java.util.concurrent.ConcurrentHashMap#computeIfAbsent(java.lang.Object, java.util.function.Function) */ diff --git a/mycore-base/src/main/java/org/mycore/common/config/MCRConfiguration2.java b/mycore-base/src/main/java/org/mycore/common/config/MCRConfiguration2.java index 533c48cae8..e0e6baa579 100644 --- a/mycore-base/src/main/java/org/mycore/common/config/MCRConfiguration2.java +++ b/mycore-base/src/main/java/org/mycore/common/config/MCRConfiguration2.java @@ -75,15 +75,15 @@ * * Using the set methods allows client code to set new configuration properties or * overwrite existing ones with new values. - * + * * @author Thomas Scheffler (yagee) * @since 2018.05 */ public class MCRConfiguration2 { - private static ConcurrentHashMap LISTENERS = new ConcurrentHashMap<>(); + private static Map LISTENERS = new ConcurrentHashMap<>(); - static ConcurrentHashMap instanceHolder = new MCRConcurrentHashMap<>(); + static Map instanceHolder = new MCRConcurrentHashMap<>(); public static Map getPropertiesMap() { return Collections.unmodifiableMap(MCRConfigurationBase.getResolvedProperties().getAsMap()); @@ -126,7 +126,7 @@ public static Map getSubPropertiesMap(String propertyPrefix) { * MCRConfiguration2.getInstanceOf(name) * .ifPresent(myTypeObj -> myTypeObj.method()); * } - * + * * @param name * the non-null and non-empty name of the configuration property * @return the value of the configuration property as a String, or null @@ -272,7 +272,7 @@ public static Optional getString(String name) { /** * Returns the configuration property with the specified name as String. - * + * * @param name * the non-null and non-empty name of the configuration property * @throws MCRConfigurationException @@ -284,7 +284,7 @@ public static String getStringOrThrow(String name) { /** * Returns the configuration property with the specified name. - * + * * @param name * the non-null and non-empty name of the configuration property * @param mapper @@ -361,7 +361,7 @@ public static Map> getInstances(String prefix) { /** * Returns the configuration property with the specified name as an * int value. - * + * * @param name * the non-null and non-empty name of the configuration property * @return the value of the configuration property as an int value @@ -375,7 +375,7 @@ public static Optional getInt(String name) throws NumberFormatException /** * Returns the configuration property with the specified name as a * long value. - * + * * @param name * the non-null and non-empty name of the configuration property * @return the value of the configuration property as a long value @@ -389,7 +389,7 @@ public static Optional getLong(String name) throws NumberFormatException { /** * Returns the configuration property with the specified name as a * float value. - * + * * @param name * the non-null and non-empty name of the configuration property * @return the value of the configuration property as a float value @@ -403,7 +403,7 @@ public static Optional getFloat(String name) throws NumberFormatException /** * Returns the configuration property with the specified name as a * double value. - * + * * @param name * the non-null and non-empty name of the configuration property * @return the value of the configuration property as a double @@ -418,7 +418,7 @@ public static Optional getDouble(String name) throws NumberFormatExcepti /** * Returns the configuration property with the specified name as a * boolean value. - * + * * @param name * the non-null and non-empty name of the configuration property * @return true, if and only if the specified property has the value true @@ -431,7 +431,7 @@ public static Optional getBoolean(String name) { * Sets the configuration property with the specified name to a new * String value. If the parameter value is * null, the property will be deleted. - * + * * @param name * the non-null and non-empty name of the configuration property * @param value @@ -458,7 +458,7 @@ public static void set(String name, T value, Function mapper) { /** * Adds a listener that is called after a new value is set. - * + * * @param keyPredicate * a filter upon the property name that if matches executes the listener * @param listener diff --git a/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationInputStream.java b/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationInputStream.java index f979251106..2a734612ca 100644 --- a/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationInputStream.java +++ b/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationInputStream.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.Objects; import java.util.Properties; +import java.util.SequencedMap; import org.apache.logging.log4j.LogManager; import org.mycore.common.content.MCRContent; @@ -47,7 +48,7 @@ *

  • application modules
  • *
  • installation specific files
  • * - * + * * @author Thomas Scheffler (yagee) * @author Robert Stephan * @since 2013.12 @@ -68,7 +69,7 @@ public class MCRConfigurationInputStream extends InputStream { /** * Combined Stream of all config files named filename available via * {@link MCRRuntimeComponentDetector#getAllComponents()}. - * + * * @param filename * , e.g. mycore.properties or messages_de.properties */ @@ -89,7 +90,7 @@ private MCRConfigurationInputStream(String filename, InputStream initStream) thr * {@link InputStream} that includes all properties from {@link MCRRuntimeComponentDetector#getAllComponents()} and * mycore.properties. Use system property MCR.Configuration.File to configure * alternative property file. - * + * * @since 2014.04 */ public static MCRConfigurationInputStream getMyCoRePropertiesInstance() throws IOException { @@ -174,11 +175,17 @@ private static InputStream getConfigFileStream(String filename) throws IOExcepti } /** - * return an enumeration of input streams of configuration files - * found in MyCoRe components and modules, respecting the proper loading order + * Returns the contents of the given config file from all available sources. + * + * @param filename + * the name of the config file + * @return a map with the component name as key and the file content as value + * found in MyCoRe components and modules, respecting the proper loading order + * @throws IOException + * if an I/O error occurs */ - public static LinkedHashMap getConfigFileContents(String filename) throws IOException { - LinkedHashMap map = new LinkedHashMap<>(); + public static SequencedMap getConfigFileContents(String filename) throws IOException { + SequencedMap map = new LinkedHashMap<>(); for (MCRComponent component : MCRRuntimeComponentDetector.getAllComponents()) { try (InputStream is = component.getConfigFileStream(filename)) { if (is != null) { diff --git a/mycore-base/src/main/java/org/mycore/common/config/MCRRuntimeComponentDetector.java b/mycore-base/src/main/java/org/mycore/common/config/MCRRuntimeComponentDetector.java index f3feeaf1d5..c04fd36cfd 100644 --- a/mycore-base/src/main/java/org/mycore/common/config/MCRRuntimeComponentDetector.java +++ b/mycore-base/src/main/java/org/mycore/common/config/MCRRuntimeComponentDetector.java @@ -118,6 +118,7 @@ private static SortedSet getConfiguredComponents() { } private static MCRComponent buildComponent(Manifest manifest, URL manifestURL) throws IOException { + @SuppressWarnings("PMD.LooseCoupling") Attributes mainAttributes = manifest.getMainAttributes(); String artifactId = mainAttributes.getValue(ATT_MCR_ARTIFACT_ID); String pomPropertiesPath = mainAttributes.getValue(ATT_POM); diff --git a/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRContentTransformerFactory.java b/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRContentTransformerFactory.java index d0f28b7c0f..90dd893841 100644 --- a/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRContentTransformerFactory.java +++ b/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRContentTransformerFactory.java @@ -19,20 +19,21 @@ package org.mycore.common.content.transformer; import java.util.HashMap; +import java.util.Map; import org.mycore.common.config.MCRConfiguration2; /** * Creates and returns MCRContentTransformer instances by their ID. - * + * * @author Frank Lützenkirchen */ public class MCRContentTransformerFactory { /** Map of transformer instances by ID */ - private static HashMap transformers = new HashMap<>(); + private static Map transformers = new HashMap<>(); - /** + /** * Returns the transformer with the given ID. If the transformer is not instantiated yet, * it is created and initialized. */ diff --git a/mycore-base/src/main/java/org/mycore/common/content/util/ContentUtils.java b/mycore-base/src/main/java/org/mycore/common/content/util/ContentUtils.java index 8ed03c3b62..0799789f99 100644 --- a/mycore-base/src/main/java/org/mycore/common/content/util/ContentUtils.java +++ b/mycore-base/src/main/java/org/mycore/common/content/util/ContentUtils.java @@ -33,6 +33,7 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -46,7 +47,7 @@ final class ContentUtils { static final int DEFAULT_BUFFER_SIZE = 65536; - static final ArrayList FULL = new ArrayList<>(); + static final List FULL = new ArrayList<>(); static final String MIME_BOUNDARY = "MYCORE_MIME_BOUNDARY"; diff --git a/mycore-base/src/main/java/org/mycore/common/content/util/MCRRestContentHelper.java b/mycore-base/src/main/java/org/mycore/common/content/util/MCRRestContentHelper.java index 15d2fd4b5e..c5e651ab74 100644 --- a/mycore-base/src/main/java/org/mycore/common/content/util/MCRRestContentHelper.java +++ b/mycore-base/src/main/java/org/mycore/common/content/util/MCRRestContentHelper.java @@ -153,7 +153,7 @@ private static MediaType getMediaType(MCRContent content) throws IOException { MediaType contentType = MediaType.valueOf(mimeType); String enc = content.getEncoding(); if (enc != null) { - HashMap param = new HashMap<>(contentType.getParameters()); + Map param = new HashMap<>(contentType.getParameters()); param.put(MediaType.CHARSET_PARAMETER, enc); contentType = new MediaType(contentType.getType(), contentType.getSubtype(), param); } diff --git a/mycore-base/src/main/java/org/mycore/common/content/util/Range.java b/mycore-base/src/main/java/org/mycore/common/content/util/Range.java index 84c41b3e26..e0cf5a7da3 100644 --- a/mycore-base/src/main/java/org/mycore/common/content/util/Range.java +++ b/mycore-base/src/main/java/org/mycore/common/content/util/Range.java @@ -52,7 +52,7 @@ public static List parseRanges(final String rangeHeader, long fileLength) String rangeValue = rangeHeader.substring(RANGE_UNIT.length() + 1); - final ArrayList result = new ArrayList<>(); + final List result = new ArrayList<>(); final StringTokenizer commaTokenizer = new StringTokenizer(rangeValue, ","); // Parsing the range list diff --git a/mycore-base/src/main/java/org/mycore/common/events/MCREvent.java b/mycore-base/src/main/java/org/mycore/common/events/MCREvent.java index 5b04a5e43f..e01ae89c6f 100644 --- a/mycore-base/src/main/java/org/mycore/common/events/MCREvent.java +++ b/mycore-base/src/main/java/org/mycore/common/events/MCREvent.java @@ -30,7 +30,7 @@ * object or file. They can be handled by MCREventHandler implementations. * Events are automatically created by some MyCoRe components and are forwarded * to the handlers by MCREventManager. - * + * * @author Frank Lützenkirchen */ public class MCREvent { @@ -110,7 +110,7 @@ public String toString() { private String customEventType; /** A hashtable to store event related, additional data */ - private Hashtable data = new Hashtable<>(); + private Map data = new Hashtable<>(); /** * Creates a new event object of the given object type (object, file) and @@ -171,7 +171,7 @@ public static MCREvent customEvent(String otherObjectType, EventType evtType) { /** * Returns the object type of this event - * + * * @return the object type of this event */ public ObjectType getObjectType() { @@ -189,7 +189,7 @@ public String getCustomObjectType() { /** * Returns the event type of this event - * + * * @return the event type of this event */ public EventType getEventType() { @@ -207,7 +207,7 @@ public String getCustomEventType() { /** * returns an object from event data - * + * * @param key - the object key * @return an object from event data */ @@ -226,7 +226,7 @@ public void put(String key, Object value) { /** * return the entries of the event data - * (1x called in wfc.mail.MCRMailEventhandler) + * (1x called in wfc.mail.MCRMailEventhandler) * @return the entrySet of the the data of the event */ public Set> entrySet() { diff --git a/mycore-base/src/main/java/org/mycore/common/events/MCREventManager.java b/mycore-base/src/main/java/org/mycore/common/events/MCREventManager.java index f5a2c9b5c4..a63d5f25a5 100644 --- a/mycore-base/src/main/java/org/mycore/common/events/MCREventManager.java +++ b/mycore-base/src/main/java/org/mycore/common/events/MCREventManager.java @@ -36,10 +36,10 @@ * Acts as a multiplexer to forward events that are created to all registered * event handlers, in the order that is configured in mycore properties. For * information how to configure, see MCREventHandler javadocs. - * + * * @see MCREventHandler * @see MCREventHandlerBase - * + * * @author Frank Lützenkirchen */ public class MCREventManager { @@ -57,7 +57,7 @@ public class MCREventManager { private static MCREventManager instance; /** Table of all configured event handlers * */ - private ConcurrentHashMap> handlers; + private Map> handlers; private MCREventManager() { handlers = new ConcurrentHashMap<>(); @@ -93,7 +93,7 @@ private MCREventManager() { /** * The singleton manager instance - * + * * @return the single event manager */ public static synchronized MCREventManager instance() { diff --git a/mycore-base/src/main/java/org/mycore/common/events/MCRShutdownHandler.java b/mycore-base/src/main/java/org/mycore/common/events/MCRShutdownHandler.java index 50fef8a9f3..00150ce19f 100644 --- a/mycore-base/src/main/java/org/mycore/common/events/MCRShutdownHandler.java +++ b/mycore-base/src/main/java/org/mycore/common/events/MCRShutdownHandler.java @@ -21,6 +21,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; +import java.util.NavigableSet; import java.util.Objects; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TimeUnit; @@ -56,7 +57,7 @@ public class MCRShutdownHandler { private static MCRShutdownHandler SINGLETON = new MCRShutdownHandler(); - final ConcurrentSkipListSet requests = new ConcurrentSkipListSet<>(); + final NavigableSet requests = new ConcurrentSkipListSet<>(); final ReentrantReadWriteLock shutdownLock = new ReentrantReadWriteLock(); diff --git a/mycore-base/src/main/java/org/mycore/common/log/MCRTableMessage.java b/mycore-base/src/main/java/org/mycore/common/log/MCRTableMessage.java index a2bfb8bd61..115aef42a2 100644 --- a/mycore-base/src/main/java/org/mycore/common/log/MCRTableMessage.java +++ b/mycore-base/src/main/java/org/mycore/common/log/MCRTableMessage.java @@ -69,7 +69,7 @@ public void add(T row) { } public List tableLines() { - LinkedList lines = new LinkedList<>(); + List lines = new LinkedList<>(); int[] lengths = new int[columns.size()]; String[] names = new String[columns.size()]; diff --git a/mycore-base/src/main/java/org/mycore/common/log/MCRTreeMessage.java b/mycore-base/src/main/java/org/mycore/common/log/MCRTreeMessage.java index 4389b04ffe..be28b1c2b7 100644 --- a/mycore-base/src/main/java/org/mycore/common/log/MCRTreeMessage.java +++ b/mycore-base/src/main/java/org/mycore/common/log/MCRTreeMessage.java @@ -60,7 +60,7 @@ public String logMessage(String introduction) { } public List treeLines() { - LinkedList lines = new LinkedList<>(); + List lines = new LinkedList<>(); treeLines(new LinkedList<>(), lines); return lines; } diff --git a/mycore-base/src/main/java/org/mycore/common/xml/MCRDOMUtils.java b/mycore-base/src/main/java/org/mycore/common/xml/MCRDOMUtils.java index 8ec2791a52..72a1c3e444 100644 --- a/mycore-base/src/main/java/org/mycore/common/xml/MCRDOMUtils.java +++ b/mycore-base/src/main/java/org/mycore/common/xml/MCRDOMUtils.java @@ -18,6 +18,7 @@ package org.mycore.common.xml; +import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.xml.parsers.DocumentBuilder; @@ -36,7 +37,7 @@ public class MCRDOMUtils implements Closeable { DocumentBuilderFactory docBuilderFactory; - ConcurrentLinkedQueue builderQueue; + Queue builderQueue; private MCRDOMUtils() { builderQueue = new ConcurrentLinkedQueue<>(); diff --git a/mycore-base/src/main/java/org/mycore/common/xml/MCRDynamicURIResolver.java b/mycore-base/src/main/java/org/mycore/common/xml/MCRDynamicURIResolver.java index e8419da0d1..ac73dad216 100644 --- a/mycore-base/src/main/java/org/mycore/common/xml/MCRDynamicURIResolver.java +++ b/mycore-base/src/main/java/org/mycore/common/xml/MCRDynamicURIResolver.java @@ -22,6 +22,7 @@ import java.io.FileNotFoundException; import java.util.Hashtable; import java.util.Iterator; +import java.util.Map; import java.util.Objects; import javax.xml.transform.URIResolver; @@ -61,7 +62,7 @@ *  <panel/> * </dynIncl> * - * + * * @see MCRTextResolver * @author Matthias Eichner */ @@ -84,7 +85,7 @@ public MCRDynamicURIResolver() { /** * Sets the xml file. From this file the jdom content * will be created. - * + * * @param xmlFile xml file object */ public void setXmlFile(File xmlFile) { @@ -97,7 +98,7 @@ public void setXmlFile(File xmlFile) { public Element resolveElement(String uri) { Objects.requireNonNull(xmlFile, "No xml file set in '" + this.getClass().getName() + "'!"); Element rootElement = getRootElement(); - Hashtable variablesMap = createVariablesMap(uri); + Map variablesMap = createVariablesMap(uri); resolveVariablesFromElement(rootElement, variablesMap); return rootElement; } @@ -130,12 +131,12 @@ protected Element getRootElement() { * For the first option the name of the variables is 'x', where 'x' is a number * for the position in the uri. To get the first value use {1}, to get the second * one use {2} and so on. - * + * * @param uri the whole uri * @return a hashtable with all variables from the uri */ - protected Hashtable createVariablesMap(String uri) { - Hashtable variablesMap = new Hashtable<>(); + protected Map createVariablesMap(String uri) { + Map variablesMap = new Hashtable<>(); String uriValue = uri.substring(uri.indexOf(':') + 1); String[] variablesArr = uriValue.split(":"); for (int i = 0; i < variablesArr.length; i++) { @@ -156,18 +157,18 @@ protected Hashtable createVariablesMap(String uri) { /** * This method runs through the whole content of the startElement and * tries to resolve all variables in texts and attributes. - * + * * @param startElement where to start to resolve the variables * @param variablesMap a map of all variables */ - protected void resolveVariablesFromElement(Element startElement, Hashtable variablesMap) { + protected void resolveVariablesFromElement(Element startElement, Map variablesMap) { Iterator it = startElement.getDescendants(Filters.element()); MCRTextResolver varResolver = new MCRTextResolver(variablesMap); while (it.hasNext()) { Element element = it.next(); // text String text = element.getText(); - if (text != null && !text.equals("") && text.contains("{")) { + if (text != null && !text.isEmpty() && text.contains("{")) { element.setText(varResolver.resolve(text)); } diff --git a/mycore-base/src/main/java/org/mycore/common/xml/MCRURIResolver.java b/mycore-base/src/main/java/org/mycore/common/xml/MCRURIResolver.java index adcaac575d..0ff3c80feb 100644 --- a/mycore-base/src/main/java/org/mycore/common/xml/MCRURIResolver.java +++ b/mycore-base/src/main/java/org/mycore/common/xml/MCRURIResolver.java @@ -35,7 +35,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Objects; @@ -196,14 +195,15 @@ public static synchronized void init(ServletContext ctx) { context = ctx; } - public static Hashtable getParameterMap(String key) { + public static Map getParameterMap(String key) { String[] param; StringTokenizer tok = new StringTokenizer(key, "&"); - Hashtable params = new Hashtable<>(); + Map params = new HashMap<>(); while (tok.hasMoreTokens()) { param = tok.nextToken().split("="); - params.put(param[0], param.length >= 2 ? param[1] : ""); + params.put(URLDecoder.decode(param[0], StandardCharsets.UTF_8), + param.length >= 2 ? URLDecoder.decode(param[1], StandardCharsets.UTF_8) : ""); } return params; } @@ -219,11 +219,11 @@ public static ServletContext getServletContext() { return context; } - private static HashMap getResolverMapping() { + private static Map getResolverMapping() { final Map extResolverMapping = EXT_RESOLVER.getURIResolverMapping(); extResolverMapping.putAll(new MCRModuleResolverProvider().getURIResolverMapping()); // set Map to final size with loadfactor: full - HashMap supportedSchemes = new HashMap<>(10 + extResolverMapping.size(), 1); + Map supportedSchemes = new HashMap<>(10 + extResolverMapping.size(), 1); // don't let interal mapping be overwritten supportedSchemes.putAll(extResolverMapping); supportedSchemes.put("webapp", new MCRWebAppResolver()); @@ -748,7 +748,7 @@ public Source resolve(String href, String base) { String[] param; StringTokenizer tok = new StringTokenizer(key, "&"); - Hashtable params = new Hashtable<>(); + Map params = new HashMap<>(); while (tok.hasMoreTokens()) { param = tok.nextToken().split("="); @@ -914,13 +914,13 @@ private static MCRCategory getMcrCategory(String uri, String axis, String categ, MCRCategory cl = null; LOGGER.debug("categoryCache entry invalid or not found: start MCRClassificationQuery"); if (axis.equals("children")) { - if (categ.length() > 0) { + if (!categ.isEmpty()) { cl = DAO.getCategory(new MCRCategoryID(classID, categ), levels); } else { cl = DAO.getCategory(MCRCategoryID.rootID(classID), levels); } } else if (axis.equals("parents")) { - if (categ.length() == 0) { + if (categ.isEmpty()) { LOGGER.error("Cannot resolve parent axis without a CategID. URI: {}", uri); throw new IllegalArgumentException( "Invalid format (categID is required in mode 'parents') " @@ -1005,7 +1005,7 @@ public Source resolve(String href, String base) { String target = href.substring(href.indexOf(":") + 1); // fixes exceptions if suburi is empty like "mcrobject:" String subUri = target.substring(target.indexOf(":") + 1); - if (subUri.length() == 0) { + if (subUri.isEmpty()) { return new JDOMSource(new Element("null")); } // end fix @@ -1184,7 +1184,7 @@ public Source resolve(String href, String base) throws TransformerException { String target = help.substring(help.indexOf(":") + 1); String subUri = target.substring(target.indexOf(":") + 1); - if (subUri.length() == 0) { + if (subUri.isEmpty()) { return new JDOMSource(new Element("null")); } @@ -1328,19 +1328,6 @@ public Source resolve(String href, String base) throws TransformerException { */ private static class MCRBuildXMLResolver implements URIResolver { - private static Hashtable getParameterMap(String key) { - String[] param; - StringTokenizer tok = new StringTokenizer(key, "&"); - Hashtable params = new Hashtable<>(); - - while (tok.hasMoreTokens()) { - param = tok.nextToken().split("="); - params.put(URLDecoder.decode(param[0], StandardCharsets.UTF_8), - URLDecoder.decode(param[1], StandardCharsets.UTF_8)); - } - return params; - } - private static void constructElement(Element current, String xpath, String value) { StringTokenizer st = new StringTokenizer(xpath, "/"); Element currentToken = current; @@ -1395,7 +1382,7 @@ public Source resolve(String href, String base) { String key = href.substring(href.indexOf(":") + 1); LOGGER.debug("Building xml from {}", key); - Hashtable params = getParameterMap(key); + Map params = getParameterMap(key); Element defaultRoot = new Element("root"); Element root = defaultRoot; @@ -1736,7 +1723,7 @@ public Source resolve(String href, String base) { final String[] translationKeys = target.split(","); // Combine translations to prevent duplicates - HashMap translations = new HashMap<>(); + Map translations = new HashMap<>(); for (String translationKey : translationKeys) { if (translationKey.endsWith("*")) { final String prefix = translationKey.substring(0, translationKey.length() - 1); diff --git a/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLHelper.java b/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLHelper.java index bb917ce483..33abdca8f2 100644 --- a/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLHelper.java +++ b/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLHelper.java @@ -25,6 +25,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import javax.xml.XMLConstants; import javax.xml.transform.Source; @@ -327,7 +328,7 @@ public static boolean equivalentAttributes(Element e1, Element e2) { } return false; } - HashSet orig = new HashSet<>(aList1.size()); + Set orig = new HashSet<>(aList1.size()); for (Attribute attr : aList1) { orig.add(attr.toString()); } diff --git a/mycore-base/src/main/java/org/mycore/common/xsl/MCRXSLInfoServlet.java b/mycore-base/src/main/java/org/mycore/common/xsl/MCRXSLInfoServlet.java index 1f9efba69d..c03a403053 100644 --- a/mycore-base/src/main/java/org/mycore/common/xsl/MCRXSLInfoServlet.java +++ b/mycore-base/src/main/java/org/mycore/common/xsl/MCRXSLInfoServlet.java @@ -57,10 +57,10 @@ import org.xml.sax.SAXException; /** - * Lists all *.xsl stylesheets in the web application located in any + * Lists all *.xsl stylesheets in the web application located in any * WEB-INF/lib/*.jar or WEB-INF/classes/[MCR.Layout.Transformer.Factory.XSLFolder]/ or in {@link MCRConfigurationDir}, * outputs the dependencies (import/include) and contained templates. - * + * * @author Frank Lützenkirchen */ public final class MCRXSLInfoServlet extends MCRServlet { @@ -302,7 +302,7 @@ private void listTemplates() { IteratorIterable callTemplateElements = xsl .getDescendants(Filters.element("call-template", MCRConstants.XSL_NAMESPACE)); List templates = new ArrayList<>(list); - HashSet callNames = new HashSet<>(); + Set callNames = new HashSet<>(); for (Element callTemplate : callTemplateElements) { String name = callTemplate.getAttributeValue("name"); if (callNames.add(name)) { diff --git a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRUnmappedCategoryRemover.java b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRUnmappedCategoryRemover.java index b4df306aa5..8f489a233e 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRUnmappedCategoryRemover.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRUnmappedCategoryRemover.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @@ -37,9 +38,9 @@ public class MCRUnmappedCategoryRemover { private final String classificationID; // contains mappings like mir_genres:article -> marcgt:article - private HashMap toFromMapping; + private Map toFromMapping; - private ArrayList filtered; + private List filtered; /** * @param classificationID of the classification to filter diff --git a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRAbstractCategoryImpl.java b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRAbstractCategoryImpl.java index 3b8312fce7..13b690377c 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRAbstractCategoryImpl.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRAbstractCategoryImpl.java @@ -25,6 +25,7 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; @@ -61,7 +62,7 @@ public abstract class MCRAbstractCategoryImpl implements MCRCategory { private String defaultLang; - private static HashSet LANGUAGES; + private static Set LANGUAGES; static { LANGUAGES = new HashSet<>(MCRConfiguration2.getString("MCR.Metadata.Languages") diff --git a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategLinkServiceImpl.java b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategLinkServiceImpl.java index dfb631f07a..1bcf2b2290 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategLinkServiceImpl.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategLinkServiceImpl.java @@ -167,7 +167,7 @@ public void deleteLinks(final Collection ids) { if (ids.isEmpty()) { return; } - HashMap> typeMap = new HashMap<>(); + Map> typeMap = new HashMap<>(); //prepare Collection objectIds = new ArrayList<>(); String currentType = ids.iterator().next().getType(); @@ -276,14 +276,14 @@ public Map hasLinks(MCRCategory category) { //Category does not exist, so it has no links return getNoLinksMap(category); } - HashMap boolMap = new HashMap<>(); + Map boolMap = new HashMap<>(); final BitSet linkedInternalIds = getLinkedInternalIds(); storeHasLinkValues(boolMap, linkedInternalIds, rootImpl); return boolMap; } private Map hasLinksForClassifications() { - HashMap boolMap = new HashMap<>() { + Map boolMap = new HashMap<>() { private static final long serialVersionUID = 1L; @Override @@ -302,14 +302,14 @@ public Boolean get(Object key) { } private Map getNoLinksMap(MCRCategory category) { - HashMap boolMap = new HashMap<>(); + Map boolMap = new HashMap<>(); for (MCRCategoryID categID : getAllCategIDs(category)) { boolMap.put(categID, false); } return boolMap; } - private void storeHasLinkValues(HashMap boolMap, BitSet internalIds, + private void storeHasLinkValues(Map boolMap, BitSet internalIds, MCRCategoryImpl parent) { final int internalID = parent.getInternalID(); if (internalID < internalIds.size() && internalIds.get(internalID)) { @@ -322,7 +322,7 @@ private void storeHasLinkValues(HashMap boolMap, BitSet } } - private void addParentHasValues(HashMap boolMap, MCRCategory parent) { + private void addParentHasValues(Map boolMap, MCRCategory parent) { boolMap.put(parent.getId(), true); if (parent.isCategory() && !Optional.ofNullable(boolMap.get(parent.getParent().getId())).orElse(false)) { addParentHasValues(boolMap, parent.getParent()); @@ -341,7 +341,7 @@ private BitSet getLinkedInternalIds() { .orderBy(cb.desc(internalId))) .getResultList(); - int maxSize = result.size() == 0 ? 1 : result.getFirst().intValue() + 1; + int maxSize = result.isEmpty() ? 1 : result.getFirst().intValue() + 1; BitSet linkSet = new BitSet(maxSize); for (Number internalID : result) { linkSet.set(internalID.intValue(), true); diff --git a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryDAOImpl.java b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryDAOImpl.java index 169a8b18f9..3eb3786cde 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryDAOImpl.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryDAOImpl.java @@ -52,9 +52,9 @@ import jakarta.persistence.TypedQuery; /** - * + * * @author Thomas Scheffler (yagee) - * + * * @since 2.0 */ public class MCRCategoryDAOImpl implements MCRCategoryDAO { @@ -69,7 +69,7 @@ public class MCRCategoryDAOImpl implements MCRCategoryDAO { private static final String NAMED_QUERY_NAMESPACE = "MCRCategory."; - private static HashMap LAST_MODIFIED_MAP = new HashMap<>(); + private static Map LAST_MODIFIED_MAP = new HashMap<>(); @Override public MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category) { @@ -165,7 +165,7 @@ public void deleteCategory(MCRCategoryID id) { /* * (non-Javadoc) - * + * * @see org.mycore.datamodel.classifications2.MCRCategoryDAO#exist(org.mycore.datamodel.classifications2.MCRCategoryID) */ @Override @@ -243,7 +243,7 @@ public MCRCategory getCategory(MCRCategoryID id, int childLevel) { /* * (non-Javadoc) - * + * * @see org.mycore.datamodel.classifications2.MCRClassificationService#getChildren(org.mycore.datamodel.classifications2.MCRCategoryID) */ @Override @@ -311,7 +311,7 @@ public List getRootCategories() { return resultList.parallelStream() .map(c -> c.merge(null)) .collect(Collector.of(ArrayList::new, - (ArrayList l, MCRCategoryImpl c) -> { + (List l, MCRCategoryImpl c) -> { if (l.isEmpty()) { l.add(c); } else { @@ -355,7 +355,7 @@ public MCRCategory getRootCategory(MCRCategoryID baseID, int childLevel) { /* * (non-Javadoc) - * + * * @see org.mycore.datamodel.classifications2.MCRClassificationService#hasChildren(org.mycore.datamodel.classifications2.MCRCategoryID) */ @Override @@ -511,8 +511,7 @@ private static void remove(MCRCategoryImpl category) { if (category.hasChildren()) { int parentPos = category.getPositionInParent(); MCRCategoryImpl parent = (MCRCategoryImpl) category.getParent(); - @SuppressWarnings("unchecked") - ArrayList copy = new ArrayList(category.children); + List copy = new ArrayList(category.children); copy.forEach(MCRCategoryImpl::detachFromParent); parent.children.addAll(parentPos, copy); copy.forEach(c -> c.parent = parent); //fixes MCR-1963 @@ -618,7 +617,7 @@ private static MCRCategoryImpl copyDeep(MCRCategory category, int level) { /** * returns database backed MCRCategoryImpl - * + * * every change to the returned MCRCategory is reflected in the database. */ public static MCRCategoryImpl getByNaturalID(EntityManager entityManager, MCRCategoryID id) { @@ -684,7 +683,7 @@ private static void updateLeftRightValue(EntityManager entityManager, String cla /** * Method updates the last modified timestamp, for the given root id. - * + * */ protected synchronized void updateLastModified(String root) { LAST_MODIFIED_MAP.put(root, System.currentTimeMillis()); @@ -692,7 +691,7 @@ protected synchronized void updateLastModified(String root) { /** * Gets the timestamp for the given root id. If there is not timestamp at the moment -1 is returned. - * + * * @return the last modified timestamp (if any) or -1 */ @Override diff --git a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryImpl.java b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryImpl.java index 70cd199bb1..46c66dd193 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryImpl.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryImpl.java @@ -60,9 +60,9 @@ import jakarta.persistence.UniqueConstraint; /** - * + * * @author Thomas Scheffler (yagee) - * + * * @since 2.0 */ @Entity @@ -241,7 +241,7 @@ public MCRCategory getParent() { @Override public boolean hasChildren() { //if children is initialized and has objects use it and don't depend on db values - if (children != null && children.size() > 0) { + if (children != null && !children.isEmpty()) { return true; } if (right != left) { @@ -288,7 +288,7 @@ public void setChildren(List children) { @Override protected void setChildrenUnlocked(List children) { - MCRCategoryChildList newChildren = new MCRCategoryChildList(root, this); + List newChildren = new MCRCategoryChildList(root, this); newChildren.addAll(children); this.children = newChildren; } @@ -323,7 +323,7 @@ public void setRight(int right) { /* * (non-Javadoc) - * + * * @see org.mycore.datamodel.classifications2.MCRCategory#setRoot(org.mycore.datamodel.classifications2.MCRClassificationObject) */ public void setRoot(MCRCategory root) { @@ -439,7 +439,7 @@ MCRCategoryImpl getRightSiblingOrParent() { /** * calculates left and right value throug the subtree rooted at * co. - * + * * @param leftStart * this.left will be set to this value * @param levelStart diff --git a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCREditorItemComparator.java b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCREditorItemComparator.java index 5b7bc8f3e5..df1cf75589 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCREditorItemComparator.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCREditorItemComparator.java @@ -23,6 +23,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import org.jdom2.Element; import org.jdom2.Namespace; @@ -30,7 +31,7 @@ public class MCREditorItemComparator implements Comparator { - private static final HashMap MY_COLLATORS = new HashMap<>(); + private static final Map MY_COLLATORS = new HashMap<>(); private Collator myCollator; diff --git a/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultObjectIDGenerator.java b/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultObjectIDGenerator.java index b6544995c1..345444140b 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultObjectIDGenerator.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultObjectIDGenerator.java @@ -19,6 +19,7 @@ import java.util.Collection; import java.util.HashMap; +import java.util.Map; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRObjectID; @@ -33,7 +34,7 @@ public class MCRDefaultObjectIDGenerator implements MCRObjectIDGenerator { // counter for the next IDs per project base ID - private HashMap lastNumber = new HashMap<>(); + private Map lastNumber = new HashMap<>(); /** * First invocation may return MCR.Metadata.ObjectID.InitialNumberDistance if set, @@ -47,7 +48,7 @@ public class MCRDefaultObjectIDGenerator implements MCRObjectIDGenerator { * Returns a MCRObjectID from a given base ID string * The additional parameter acts as a * lower limit for integer part of the ID. - * + * * Otherwise it is the next free number of an item in the database for the * given project ID and type ID, with the following additional restriction: * The ID returned can be divided by the configured numberDistance without remainder. @@ -61,7 +62,7 @@ public class MCRDefaultObjectIDGenerator implements MCRObjectIDGenerator { * last ID = 7, next ID = 10 * last ID = 8, next ID = 10 * last ID = 10, next ID = 20 - * + * * * @param baseId * project_id_type_id diff --git a/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultXMLMetadataManager.java b/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultXMLMetadataManager.java index 87a3121c2a..74ce17048e 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultXMLMetadataManager.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultXMLMetadataManager.java @@ -37,6 +37,7 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -108,7 +109,7 @@ public class MCRDefaultXMLMetadataManager implements MCRXMLMetadataManagerAdapte /** The singleton */ private static MCRDefaultXMLMetadataManager SINGLETON; - private HashSet createdStores; + private Set createdStores; /** * The default IFS2 Metadata store class to use, set by MCR.Metadata.Store.DefaultClass diff --git a/mycore-base/src/main/java/org/mycore/datamodel/common/MCRFileBaseCacheObjectIDGenerator.java b/mycore-base/src/main/java/org/mycore/datamodel/common/MCRFileBaseCacheObjectIDGenerator.java index 2e7a9ae1a8..26375a2f2b 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/common/MCRFileBaseCacheObjectIDGenerator.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/common/MCRFileBaseCacheObjectIDGenerator.java @@ -29,6 +29,7 @@ import java.nio.file.StandardOpenOption; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; @@ -50,7 +51,7 @@ public class MCRFileBaseCacheObjectIDGenerator implements MCRObjectIDGenerator { private static final Logger LOGGER = LogManager.getLogger(); - static ConcurrentHashMap locks = new ConcurrentHashMap<>(); + static Map locks = new ConcurrentHashMap<>(); private static Path getCacheFilePath(String baseId) { Path idCachePath = getCacheDirPath(); diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRDerivateDefaultClassEventHandler.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRDerivateDefaultClassEventHandler.java index 69b8f65ea0..6b41e459e9 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRDerivateDefaultClassEventHandler.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRDerivateDefaultClassEventHandler.java @@ -18,7 +18,6 @@ package org.mycore.datamodel.metadata; -import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -49,7 +48,7 @@ private static MCRMetaClassification asMetaClassification(MCRCategoryID category @Override protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) { - final ArrayList classifications = der.getDerivate().getClassifications(); + final List classifications = der.getDerivate().getClassifications(); if (!classifications.isEmpty()) { //already defined at creation return; diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRFileMetaEventHandler.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRFileMetaEventHandler.java index 5aa35fbda9..d51a5a6155 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRFileMetaEventHandler.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRFileMetaEventHandler.java @@ -26,6 +26,7 @@ import java.util.HashSet; import java.util.List; import java.util.Optional; +import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -67,13 +68,13 @@ protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) { @Override protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) { - HashSet before = new HashSet<>(CATEGLINK_SERVICE.getReferences(der.getId().toString())); + Set before = new HashSet<>(CATEGLINK_SERVICE.getReferences(der.getId().toString())); handleDerivateDeleted(evt, der); handleDerivateCreated(evt, der); - HashSet after = new HashSet<>(CATEGLINK_SERVICE.getReferences(der.getId().toString())); - HashSet combined = new HashSet<>(before); + Set after = new HashSet<>(CATEGLINK_SERVICE.getReferences(der.getId().toString())); + Set combined = new HashSet<>(before); combined.addAll(after); for (MCRCategLinkReference ref : combined) { MCRObjectID derId = der.getId(); diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaDerivateLink.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaDerivateLink.java index 721d1e8163..cb91333650 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaDerivateLink.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaDerivateLink.java @@ -23,6 +23,7 @@ import java.nio.file.Files; import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -40,7 +41,7 @@ public class MCRMetaDerivateLink extends MCRMetaLink { private static final Logger LOGGER = LogManager.getLogger(); - private HashMap map; + private Map map; /** Constructor initializes the HashMap */ public MCRMetaDerivateLink() { diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaElement.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaElement.java index de0189415e..fa440421a1 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaElement.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaElement.java @@ -43,7 +43,7 @@ * xlink:href attribute of the MCRMetaLink representing the link. The class name * of such a metadata element must be MCRMetaLink, and the metadata element is * considered to be a folder of links. - * + * * @author Jens Kupferschmidt * @author Mathias Hegner */ @@ -71,7 +71,7 @@ public class MCRMetaElement implements Iterable, Cloneable { private boolean notinherit; - private ArrayList list = null; + private List list = null; /** * This is the constructor of the MCRMetaElement class. The default language @@ -111,7 +111,7 @@ public MCRMetaElement(Class clazz, String tag, boole /** * This methode return the name of this metadata class as string. - * + * * @return the name of this metadata class as string */ public final String getClassName() { @@ -121,7 +121,7 @@ public final String getClassName() { /** * This method returns the instance of an element from the list with index * i. - * + * * @return the instance of an element, if index is out of range return null */ public final MCRMetaInterface getElement(int index) { @@ -132,9 +132,9 @@ public final MCRMetaInterface getElement(int index) { } /** - * This method returns the instance of an element from the list with the given + * This method returns the instance of an element from the list with the given * name - * + * * @return the instance of the element with the given name or null if there is no such element * */ public final MCRMetaInterface getElementByName(String name) { @@ -148,7 +148,7 @@ public final MCRMetaInterface getElementByName(String name) { /** * This methode return the heritable flag of this metadata as boolean value. - * + * * @return the heritable flag of this metadata class */ public final boolean isHeritable() { @@ -157,7 +157,7 @@ public final boolean isHeritable() { /** * This methode return the nonherit flag of this metadata as boolean value. - * + * * @return the notherit flag of this metadata class */ public final boolean inheritsNot() { @@ -166,7 +166,7 @@ public final boolean inheritsNot() { /** * This methode return the tag of this metadata class as string. - * + * * @return the tag of this metadata class as string */ public final String getTag() { @@ -175,7 +175,7 @@ public final String getTag() { /** * This methode set the heritable flag for the metadata class. - * + * * @param heritable * the heritable flag as boolean value */ @@ -185,7 +185,7 @@ public void setHeritable(boolean heritable) { /** * This methode set the notinherit flag for the metadata class. - * + * * @param notinherit * the notinherit flag as boolean value */ @@ -195,7 +195,7 @@ public void setNotInherit(boolean notinherit) { /** * This methode set the tag for the metadata class. - * + * * @param tag * the tag for the metadata class */ @@ -206,7 +206,7 @@ public void setTag(String tag) { /** * This methode set the element class for the metadata elements. - * + * * @param clazz * the class for the metadata elements */ @@ -220,7 +220,7 @@ public Class getClazz() { /** * size returns the number of elements in this instance. - * + * * @return int the size of "list" */ public final int size() { @@ -230,7 +230,7 @@ public final int size() { /** * The method add a metadata object, that implements the MCRMetaInterface to * this element. - * + * * @param obj * a metadata object * @exception MCRException @@ -244,7 +244,7 @@ public final void addMetaObject(MCRMetaInterface obj) { /** * This method remove the instance of an element from the list with index * i. - * + * * @return true if the instance is removed, otherwise return else */ public final boolean removeElement(int index) { @@ -258,7 +258,7 @@ public final boolean removeElement(int index) { /** * The method remove a metadata object, that implements the MCRMetaInterface to * this element. - * + * * @param obj * a metadata object * @exception MCRException @@ -281,7 +281,7 @@ public final void removeInheritedMetadata() { /** * This methode read the XML input stream part from a DOM part for the * metadata of the document. - * + * * @param element * a relevant JDOM element for the metadata * @exception MCRException @@ -331,7 +331,7 @@ public final void setFromDOM(Element element) throws MCRException { /** * This methode create a XML stream for all data in this class, defined by * the MyCoRe XML MCRLangText definition for the given subtag. - * + * * @param flag * true if all inherited data should be include, else false * @exception MCRException @@ -359,7 +359,7 @@ public final Element createXML(boolean flag) throws MCRException { /** * Creates the JSON representation of this metadata element. - * + * *
          *   {
          *      class: 'MCRMetaLangText',
    @@ -371,7 +371,7 @@ public final Element createXML(boolean flag) throws MCRException {
          *      ]
          *   }
          * 
    - * + * * @return a json gson representation of this metadata element */ public JsonObject createJSON(boolean flag) { @@ -399,7 +399,7 @@ public JsonObject createJSON(boolean flag) { *
  • the lang value was supported * * otherwise the methode return false - * + * * @return a boolean value */ public final boolean isValid() { @@ -420,7 +420,7 @@ public final boolean isValid() { *
  • if the list is empty
  • *
  • the lang value was supported
  • * - * + * * @throws MCRException the MCRMetaElement is invalid */ public void validate() throws MCRException { diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaHistoryDate.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaHistoryDate.java index 764ea6874d..814b08172e 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaHistoryDate.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaHistoryDate.java @@ -19,6 +19,7 @@ package org.mycore.datamodel.metadata; import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -50,7 +51,7 @@ public class MCRMetaHistoryDate extends MCRMetaDefault { public static final int MCRHISTORYDATE_MAX_TEXT = 512; // Data of this class - private ArrayList texts; + private List texts; private Calendar von; @@ -123,7 +124,7 @@ public final void setText(String text) { * the language of the text in the ISO format */ public final void setText(String text, String lang) { - if (text == null || text.length() == 0) { + if (text == null || text.isEmpty()) { LOGGER.warn("The text field of MCRMeataHistoryDate is empty."); return; } @@ -133,7 +134,7 @@ public final void setText(String text, String lang) { } else { textTrimmed = text.substring(0, MCRHISTORYDATE_MAX_TEXT); } - if (lang == null || lang.length() == 0) { + if (lang == null || lang.isEmpty()) { addText(textTrimmed, this.lang); } else { addText(textTrimmed, lang); @@ -151,11 +152,11 @@ public final void setText(String text, String lang) { */ public final void addText(String text, String lang) { - if (text == null || text.length() == 0) { + if (text == null || text.isEmpty()) { LOGGER.warn("The text field of MCRMeataHistoryDate is empty."); return; } - if (lang == null || lang.length() == 0) { + if (lang == null || lang.isEmpty()) { LOGGER.warn("The lang field of MCRMeataHistoryDate is empty."); return; } @@ -206,7 +207,7 @@ public final MCRMetaHistoryDateText getText(int index) { * * @return an ArrayList of MCRMetaHistoryDateTexts instances */ - public final ArrayList getTexts() { + public final List getTexts() { return texts; } @@ -226,7 +227,7 @@ public final int textSize() { * the calendar as String, one of CALENDARS. */ public final void setCalendar(String calstr) { - if (calstr == null || calstr.trim().length() == 0 || (!MCRCalendar.CALENDARS_LIST.contains(calstr))) { + if (calstr == null || calstr.trim().isEmpty() || (!MCRCalendar.CALENDARS_LIST.contains(calstr))) { calendar = MCRCalendar.TAG_GREGORIAN; LOGGER.warn("The calendar field of MCRMeataHistoryDate is set to default " + MCRCalendar.TAG_GREGORIAN + "."); @@ -473,7 +474,7 @@ public Element createXML() throws MCRException { public void validate() throws MCRException { super.validate(); texts.removeIf(textItem -> !textItem.isValid()); - if (texts.size() == 0) { + if (texts.isEmpty()) { throw new MCRException(getSubTag() + ": no texts defined"); } if (von == null || bis == null || calendar == null) { @@ -541,7 +542,7 @@ public boolean equals(Object obj) { return fieldTest && textTest; } - private boolean equalText(ArrayList objtexts) { + private boolean equalText(List objtexts) { boolean testflag = true; int size = texts.size() < objtexts.size() ? texts.size() : objtexts.size(); for (int i = 0; i < size; i++) { diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectDerivate.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectDerivate.java index 6b7af46b67..fb292c7fd9 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectDerivate.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectDerivate.java @@ -34,7 +34,7 @@ /** * This class implements all methode for handling one derivate data. - * + * * @author Jens Kupferschmidt */ public class MCRObjectDerivate { @@ -44,13 +44,13 @@ public class MCRObjectDerivate { // derivate data private MCRMetaLinkID linkmeta; - private final ArrayList externals; + private final List externals; private MCRMetaIFS internals; - private final ArrayList titles; + private final List titles; - private final ArrayList classifications; + private final List classifications; private String derivateURN; @@ -80,7 +80,7 @@ public MCRObjectDerivate(MCRObjectID derivateID, Element derivate) { /** * This methode read the XML input stream part from a DOM part for the * structure data of the document. - * + * * @param derivate * a list of relevant DOM elements for the derivate */ @@ -182,7 +182,7 @@ private void setMetadataFromDOM(Element derivate) { /** * returns link to the MCRObject. - * + * * @return a metadata link as MCRMetaLinkID */ public MCRMetaLinkID getMetaLink() { @@ -191,7 +191,7 @@ public MCRMetaLinkID getMetaLink() { /** * This method set the metadata link - * + * * @param link * the MCRMetaLinkID object */ @@ -208,7 +208,7 @@ public final int getExternalSize() { /** * This method get a single link from the external list as a MCRMetaLink. - * + * * @exception IndexOutOfBoundsException * throw this exception, if the index is false * @return a external link as MCRMetaLink @@ -230,7 +230,7 @@ public final int getTitleSize() { /** * This method get a single text from the titles list as a MCRMetaLangText. - * + * * @exception IndexOutOfBoundsException * throw this exception, if the index is false * @return a title text as MCRMetaLangText @@ -245,7 +245,7 @@ public final MCRMetaLangText getTitle(int index) throws IndexOutOfBoundsExceptio /** * This method get a single data from the internal list as a MCRMetaIFS. - * + * * @return a internal data as MCRMetaIFS */ public final MCRMetaIFS getInternals() { @@ -255,7 +255,7 @@ public final MCRMetaIFS getInternals() { /** * @param file the file to add * @param urn the urn of the file, if already known, if not provide null - * + * * @throws NullPointerException if first argument is null */ public MCRFileMetadata getOrCreateFileMetadata(MCRPath file, String urn) { @@ -340,7 +340,7 @@ public boolean deleteFileMetaData(String path) { /** * This method set the metadata internals (the IFS data) - * + * * @param ifs * the MCRMetaIFS object */ @@ -354,7 +354,7 @@ public final void setInternals(MCRMetaIFS ifs) { /** * This methode create a XML stream for all derivate data. - * + * * @exception MCRException * if the content of this class is not valid * @return a JDOM Element with the XML data of the structure data part @@ -371,7 +371,7 @@ public final Element createXML() throws MCRException { linkmetas.setAttribute("heritable", "false"); linkmetas.addContent(linkmeta.createXML()); elm.addContent(linkmetas); - if (externals.size() != 0) { + if (!externals.isEmpty()) { Element extEl = createExternalsElement(); elm.addContent(extEl); } @@ -379,11 +379,11 @@ public final Element createXML() throws MCRException { Element intEl = createInternalsElement(); elm.addContent(intEl); } - if (titles.size() != 0) { + if (!titles.isEmpty()) { Element titEl = createTitleElement(); elm.addContent(titEl); } - if (classifications.size() > 0) { + if (!classifications.isEmpty()) { Element clazzElement = createClassificationElement(); elm.addContent(clazzElement); } @@ -452,7 +452,7 @@ private Element createFilesetElement() { *
  • the linkmeta exist and the XLink type of linkmeta is not "arc"
  • *
  • no information in the external AND internal tags
  • * - * + * * @return a boolean value */ public final boolean isValid() { @@ -472,7 +472,7 @@ public final boolean isValid() { *
  • the linkmeta xlink:type is not 'locator'
  • *
  • the internals and the externals are empty
  • * - * + * * @throws MCRException the MCRObjectDerivate is invalid */ public void validate() throws MCRException { @@ -482,7 +482,7 @@ public void validate() throws MCRException { if (!linkmeta.getXLinkType().equals("locator")) { throw new MCRException("linkmeta type != locator"); } - if ((internals == null) && (externals.size() == 0)) { + if ((internals == null) && (externals.isEmpty())) { throw new MCRException("(internals == null) && (externals.size() == 0)"); } } @@ -499,11 +499,11 @@ void setDerivateID(MCRObjectID id) { this.derivateID = id; } - public ArrayList getClassifications() { + public List getClassifications() { return classifications; } - public ArrayList getTitles() { + public List getTitles() { return titles; } } diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectID.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectID.java index 1e29e0b548..b2037adaca 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectID.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectID.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -66,7 +67,7 @@ public final class MCRObjectID implements Comparable { private static Pattern ID_PATTERN = Pattern .compile("^(?[a-zA-Z][a-zA-Z0-9]*)_(?[a-zA-Z0-9]+)_(?[0-9]+)$"); - private static HashSet VALID_TYPE_LIST; + private static Set VALID_TYPE_LIST; private static Comparator COMPARATOR_FOR_MCR_OBJECT_ID = Comparator .comparing(MCRObjectID::getProjectId) diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectMetadata.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectMetadata.java index a771cf8d61..f73d7c7685 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectMetadata.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectMetadata.java @@ -40,7 +40,7 @@ * This class implements all methode for handling one object metadata part. This * class uses only metadata type classes of the general datamodel code of * MyCoRe. - * + * * @author Jens Kupferschmidt * @author Mathias Hegner */ @@ -51,13 +51,13 @@ public class MCRObjectMetadata implements Iterable { private boolean heritedXML; // metadata list - private final ArrayList metadataElements; + private final List metadataElements; /** * This is the constructor of the MCRObjectMetadata class. It set the * default language for all metadata to the value from the configuration * propertie MCR.Metadata.DefaultLang. - * + * * @exception MCRConfigurationException * a special exception for configuartion data */ @@ -68,7 +68,7 @@ public MCRObjectMetadata() throws MCRConfigurationException { /** * size returns the number of tag names in the ArrayList. - * + * * @return int number of tags and meta elements */ public int size() { @@ -78,7 +78,7 @@ public int size() { /** * getHeritableMetadata returns an instance of MCRObjectMetadata * containing all the heritable MetaElement's of this object. - * + * * @return MCRObjectMetadata the heritable part of this MCRObjectMetadata */ public final MCRObjectMetadata getHeritableMetadata() { @@ -91,7 +91,7 @@ public final MCRObjectMetadata getHeritableMetadata() { } /** - * removeInheritedMetadata removes all inherited metadata elements + * removeInheritedMetadata removes all inherited metadata elements */ public final void removeInheritedMetadata() { Iterator elements = metadataElements.iterator(); @@ -108,7 +108,7 @@ public final void removeInheritedMetadata() { /** * This method append MCRMetaElement's from a given MCRObjectMetadata to * this data set. - * + * * @param input * the MCRObjectMetadata, that should merged into this data set */ @@ -146,7 +146,7 @@ public final void appendMetadata(MCRObjectMetadata input) { /** * This method return the MCRMetaElement selected by tag. If this was not * found, null was returned. - * + * * @param tag * the element tag * @return the MCRMetaElement for the tag @@ -163,7 +163,7 @@ public final MCRMetaElement getMetadataElement(String tag) { /** * This method return the MCRMetaElement selected by an index. If this was * not found, null was returned. - * + * * @param index * the element index * @return the MCRMetaElement for the index @@ -175,7 +175,7 @@ public final MCRMetaElement getMetadataElement(int index) { /** * sets the given MCRMetaElement to the list. If the tag exists * the MCRMetaElement was replaced. - * + * * @param obj * the MCRMetaElement object */ @@ -202,7 +202,7 @@ public final boolean removeMetadataElement(MCRMetaElement element) { /** * This method remove the MCRMetaElement selected by tag from the list. - * + * * @return true if set was successful, otherwise false */ public final MCRMetaElement removeMetadataElement(String tag) { @@ -216,7 +216,7 @@ public final MCRMetaElement removeMetadataElement(String tag) { /** * This method remove the MCRMetaElement selected a index from the list. - * + * * @return true if set was successful, otherwise false */ public final MCRMetaElement removeMetadataElement(int index) { @@ -229,7 +229,7 @@ public final MCRMetaElement removeMetadataElement(int index) { /** * Finds the first, not inherited {@link MCRMetaInterface} with the given tag. - * + * * @param tag the metadata tag e.g. 'maintitles' * @return an optional of the first meta interface */ @@ -241,7 +241,7 @@ public final Optional findFirst(String tag) { * Finds the first, not inherited {@link MCRMetaInterface} with the given tag * where the @type attribute is equal to the given type. If the type is null, * this method doesn't care if the @type attribute is set or not. - * + * * @param tag the metadata tag e.g. 'subtitles' * @param type the @type attribute which have to match * @return an optional of the first meta interface @@ -253,7 +253,7 @@ public final Optional findFirst(String tag, Stri /** * Finds the first {@link MCRMetaInterface} with the given tag where the * inheritance level is equal the inherited value. - * + * * @param tag the metadata tag e.g. 'maintitles' * @param inherited level of inheritance. Zero is the current level, * parent is one and so on. @@ -268,7 +268,7 @@ public final Optional findFirst(String tag, Inte * inheritance level is equal the inherited value and the @type attribute * is equal to the given type. If the type is null, this method doesn't * care if the @type attribute is set or not. - * + * * @param tag the metadata tag e.g. 'subtitles' * @param type the @type attribute which have to match * @param inherited level of inheritance. Zero is the current level, @@ -298,7 +298,7 @@ public final Stream stream() { * Stream stream = mcrObjectMetadata.stream("maintitles"); * } * - * + * * @param tag tag the metadata tag e.g. 'maintitles' * @return a stream of the requested meta interfaces */ @@ -318,13 +318,13 @@ public final Stream stream(String tag) { * live list. Removals or adds are not reflected on the * {@link MCRMetaElement}. Use {@link #getMetadataElement(String)} * for those operations. - * + * *
         * {@code
         *   List list = mcrObjectMetadata.list("maintitles");
         * }
         * 
    - * + * * @param tag tag the metadata tag e.g. 'maintitles' * @return a list of the requested meta interfaces */ @@ -336,7 +336,7 @@ public final List list(String tag) { /** * Checks if the type of an {@link MCRMetaInterface} is equal * the given type. If the given type is null, true is returned. - * + * * @param type the type to compare * @return true if the types are equal */ @@ -347,7 +347,7 @@ private Predicate filterByType(String type) { /** * Checks if the inheritance level of an {@link MCRMetaInterface} * is equal the given inherited value. - * + * * @param inherited the inherited value * @return true if the inherited values are equal */ @@ -358,7 +358,7 @@ private Predicate filterByInherited(Integer inherited) { /** * This methode read the XML input stream part from a DOM part for the * metadata of the document. - * + * * @param element * a list of relevant DOM elements for the metadata * @exception MCRException @@ -376,7 +376,7 @@ public final void setFromDOM(Element element) throws MCRException { /** * This methode create a XML stream for all metadata. - * + * * @exception MCRException * if the content of this class is not valid * @return a JDOM Element with the XML data of the metadata part @@ -396,7 +396,7 @@ public final Element createXML() throws MCRException { /** * Creates the JSON representation of this metadata container. - * + * *
          *   {
          *    "def.maintitles": {
    @@ -408,7 +408,7 @@ public final Element createXML() throws MCRException {
          *    ...
          *   }
          * 
    - * + * * @return a json gson representation of this metadata container */ public JsonObject createJSON() { @@ -426,7 +426,7 @@ public JsonObject createJSON() { *
  • the default lang value was supported * * otherwise the methode return false - * + * * @return a boolean value */ public final boolean isValid() { @@ -444,7 +444,7 @@ public final boolean isValid() { *
      *
    • one of the MCRMetaElement children is invalid
    • *
    - * + * * @throws MCRException the MCRObjectMetadata is invalid */ public void validate() throws MCRException { diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectService.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectService.java index c58979aced..1ff13d337c 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectService.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectService.java @@ -97,15 +97,15 @@ public class MCRObjectService { */ public static final String FLAG_TYPE_MODIFIEDBY = "modifiedby"; - private final ArrayList dates = new ArrayList<>(); + private final List dates = new ArrayList<>(); - private final ArrayList rules = new ArrayList<>(); + private final List rules = new ArrayList<>(); - private final ArrayList flags = new ArrayList<>(); + private final List flags = new ArrayList<>(); - private final ArrayList messages = new ArrayList<>(); + private final List messages = new ArrayList<>(); - private final ArrayList classifications = new ArrayList<>(); + private final List classifications = new ArrayList<>(); private MCRCategoryID state; @@ -209,7 +209,7 @@ public final int getDateSize() { * * @return list of dates */ - protected ArrayList getDates() { + protected List getDates() { return dates; } @@ -244,7 +244,7 @@ public final Date getDate(String type) { } private MCRMetaISO8601Date getISO8601Date(String type) { - if (type == null || type.length() == 0) { + if (type == null || type.isEmpty()) { return null; } @@ -416,7 +416,7 @@ protected final List getFlagsAsList() { * a type as string. * @return a list of flag values */ - protected final ArrayList getFlagsAsMCRMetaLangText(String type) { + protected final List getFlagsAsMCRMetaLangText(String type) { return flags.stream() .filter(metaLangText -> StringUtils.equals(type, metaLangText.getType())) .collect(Collectors.toCollection(ArrayList::new)); @@ -429,7 +429,7 @@ protected final ArrayList getFlagsAsMCRMetaLangText(String type * a type as string. * @return a list of flag values */ - public final ArrayList getFlags(String type) { + public final List getFlags(String type) { return getFlagsAsMCRMetaLangText(type).stream() .map(MCRMetaLangText::getText) .collect(Collectors.toCollection(ArrayList::new)); @@ -592,7 +592,7 @@ public final int getRulesSize() { */ public final int getRuleIndex(String permission) { int notFound = -1; - if (permission == null || permission.trim().length() == 0) { + if (permission == null || permission.isBlank()) { return notFound; } return IntStream.range(0, rules.size()) @@ -650,7 +650,7 @@ public final void removeRule(int index) throws IndexOutOfBoundsException { * * @return list of rules */ - protected final ArrayList getRules() { + protected final List getRules() { return rules; } @@ -880,7 +880,7 @@ public final int getMessagesSize() { * * @return messages as list */ - protected final ArrayList getMessagesAsList() { + protected final List getMessagesAsList() { return messages; } @@ -891,7 +891,7 @@ protected final ArrayList getMessagesAsList() { * a type as string. * @return a list of message values */ - protected final ArrayList getMessagesAsMCRMetaDateLangText(String type) { + protected final List getMessagesAsMCRMetaDateLangText(String type) { return messages.stream() .filter(metaLangText -> type.equals(metaLangText.getType())) .collect(Collectors.toCollection(ArrayList::new)); @@ -902,7 +902,7 @@ protected final ArrayList getMessagesAsMCRMetaDateLangText( * * @return a list of message values */ - public final ArrayList getMessages() { + public final List getMessages() { return messages.stream() .map(MCRMetaDateLangText::getText) .collect(Collectors.toCollection(ArrayList::new)); @@ -915,7 +915,7 @@ public final ArrayList getMessages() { * a type as string. * @return a list of message values */ - public final ArrayList getMessages(String type) { + public final List getMessages(String type) { return getMessagesAsMCRMetaDateLangText(type).stream() .map(MCRMetaDateLangText::getText) .collect(Collectors.toCollection(ArrayList::new)); @@ -1083,7 +1083,7 @@ public final int getClassificationsSize() { * * @return classifications as list */ - protected final ArrayList getClassificationsAsList() { + protected final List getClassificationsAsList() { return classifications; } @@ -1094,7 +1094,7 @@ protected final ArrayList getClassificationsAsList() { * a type as string. * @return a list of classification values */ - protected final ArrayList getClassificationsAsMCRMetaClassification(String type) { + protected final List getClassificationsAsMCRMetaClassification(String type) { return classifications.stream() .filter(metaLangText -> type.equals(metaLangText.getType())) .collect(Collectors.toCollection(ArrayList::new)); @@ -1105,7 +1105,7 @@ protected final ArrayList getClassificationsAsMCRMetaClas * * @return a list of classification values */ - public final ArrayList getClassifications() { + public final List getClassifications() { return classifications.stream() .map(c -> new MCRCategoryID(c.getClassId(), c.getCategId())) .collect(Collectors.toCollection(ArrayList::new)); @@ -1118,7 +1118,7 @@ public final ArrayList getClassifications() { * a type as string. * @return a list of classification values */ - public final ArrayList getClassifications(String type) { + public final List getClassifications(String type) { return getClassificationsAsMCRMetaClassification(type).stream() .map(c -> new MCRCategoryID(c.getClassId(), c.getCategId())) .collect(Collectors.toCollection(ArrayList::new)); diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectStructure.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectStructure.java index 7af04e818a..5538266fad 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectStructure.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectStructure.java @@ -52,7 +52,7 @@ * (inner structure and combination of inner and outer structures of the * objects). This will possibly be done in a later extension of * MCRMetaLink and MCRObjectStructure. - * + * * @author Mathias Hegner * @author Jens Kupferschmidt */ @@ -60,9 +60,9 @@ public class MCRObjectStructure { private MCRMetaLinkID parent; - private final ArrayList children; + private final List children; - private final ArrayList derivates; + private final List derivates; private static final Logger LOGGER = LogManager.getLogger(); @@ -102,7 +102,7 @@ public final void clearDerivates() { /** * The method returns the parent link. - * + * * @return MCRMetaLinkID the corresponding link */ public final MCRMetaLinkID getParent() { @@ -111,7 +111,7 @@ public final MCRMetaLinkID getParent() { /** * The method return the parent reference as a MCRObjectID. - * + * * @return the parent MCRObjectID or null if there is no parent present */ public final MCRObjectID getParentID() { @@ -123,10 +123,10 @@ public final MCRObjectID getParentID() { /** * This method set the parent value from a given MCRMetaLinkID. - * + * * @param parent * the MCRMetaLinkID to set - * + * */ public final void setParent(MCRMetaLinkID parent) { this.parent = parent; @@ -153,7 +153,7 @@ public final void removeParent() { * The method appends a child ID to the child link list if and only if it is * not already contained in the list, preventing from doubly-linked objects. * If the link could be added a "true" will be returned, otherwise "false". - * + * * @param child * the MCRMetaLinkID of the child * @return boolean true, if successfully done @@ -173,7 +173,7 @@ public final boolean addChild(MCRMetaLinkID child) { * removes a child link to another object. * If the link was found a "true" will be returned, otherwise * "false". - * + * * @param href * the MCRObjectID of the child * @return boolean true, if successfully completed @@ -198,7 +198,7 @@ public final boolean containsChild(MCRObjectID childId) { * removes a derivate link. * If the link was found a "true" will be returned, otherwise * "false". - * + * * @param href * the MCRObjectID of the child * @return boolean true, if successfully completed @@ -231,7 +231,7 @@ public final List getChildren() { * addDerivate methode append the given derivate link data to the * derivate vector. If the link could be added a "true" will be returned, * otherwise "false". - * + * * @param derivate * the link to be added as MCRMetaLinkID */ @@ -251,7 +251,7 @@ public final boolean addDerivate(MCRMetaEnrichedLinkID derivate) { /** * Adds or updates the derivate link. Returns true if the derivate is added * or updated. Returns false when nothing is done. - * + * * @param derivateLink the link to add or update * @return true when the structure is changed */ @@ -272,7 +272,7 @@ public final boolean addOrUpdateDerivate(MCRMetaEnrichedLinkID derivateLink) { /** * Checks if the derivate is in the derivate vector. - * + * * @param derivateId derivate to check */ public final boolean containsDerivate(MCRObjectID derivateId) { @@ -289,7 +289,7 @@ public final MCRMetaEnrichedLinkID getDerivateLink(MCRObjectID derivateId) { .orElse(null); } - /** + /** * @return a list with all related derivate ids encapsulated within a {@link MCRMetaLinkID} * */ public List getDerivates() { @@ -301,7 +301,7 @@ public List getDerivates() { * only, the following three will affect the operations to or from datastore * too. Thereby setFromDOM will read the structure data from an * XML input stream (the "structure" entry). - * + * * @param element * the structure node list */ @@ -342,7 +342,7 @@ public final void setFromDOM(Element element) { /** * createXML is the inverse of setFromDOM and converts the * structure's memory copy into XML. - * + * * @exception MCRException * if the content of this class is not valid * @return the structure XML @@ -363,7 +363,7 @@ public final Element createXML() throws MCRException { elm.addContent(elmm); } - if (children.size() > 0) { + if (!children.isEmpty()) { Element elmm = new Element("children"); elmm.setAttribute("class", "MCRMetaLinkID"); for (MCRMetaLinkID child : getChildren()) { @@ -372,7 +372,7 @@ public final Element createXML() throws MCRException { elm.addContent(elmm); } - if (derivates.size() > 0) { + if (!derivates.isEmpty()) { Element elmm = new Element("derobjects"); elmm.setAttribute("class", "MCRMetaEnrichedLinkID"); for (MCRMetaLinkID derivate : getDerivates()) { @@ -386,7 +386,7 @@ public final Element createXML() throws MCRException { /** * Creates the JSON representation of this structure. - * + * *
          *   {
          *     parent: {@link MCRMetaLinkID#createJSON()},
    @@ -400,7 +400,7 @@ public final Element createXML() throws MCRException {
          *     ]
          *   }
          * 
    - * + * * @return a json gson representation of this structure */ public JsonObject createJSON() { @@ -438,7 +438,7 @@ public final void debug() { /** * isValid checks whether all of the MCRMetaLink's in the link * vectors are valid or not. - * + * * @return boolean true, if structure is valid */ public final boolean isValid() { @@ -458,7 +458,7 @@ public final boolean isValid() { *
  • one of the children is invalid
  • *
  • one of the derivates is invalid
  • * - * + * * @throws MCRException the MCRObjectStructure is invalid */ public void validate() throws MCRException { diff --git a/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryCommands.java b/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryCommands.java index 5834bd352c..8cfdf82fb6 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryCommands.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryCommands.java @@ -248,7 +248,7 @@ private static Stream buildDerivateHistory(MCRObjectID derId throws IOException { boolean exist = false; LogManager.getLogger().debug("Complete history rebuild of {} should be possible", derId); - ArrayList items = new ArrayList<>(100); + List items = new ArrayList<>(100); for (MCRAbstractMetadataVersion version : versions) { String user = version.getUser(); Instant revDate = version.getDate().toInstant(); @@ -291,7 +291,7 @@ private static Stream buildObjectHistory(MCRObjectID objId, throws IOException { boolean exist = false; LogManager.getLogger().debug("Complete history rebuild of {} should be possible", objId); - ArrayList items = new ArrayList<>(100); + List items = new ArrayList<>(100); for (MCRAbstractMetadataVersion version : versions) { String user = version.getUser(); Instant revDate = version.getDate().toInstant(); diff --git a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRBasicFileAttributeViewProperties.java b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRBasicFileAttributeViewProperties.java index c4ae97092f..0896611bed 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRBasicFileAttributeViewProperties.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRBasicFileAttributeViewProperties.java @@ -127,7 +127,7 @@ public Map getAttributeMap(String... attributes) throws IOExcept * @throws IOException if an I/O error occurs. */ protected Map buildMap(Set requested) throws IOException { - HashMap map = new HashMap<>(); + Map map = new HashMap<>(); BasicFileAttributes attrs = view.readAttributes(); for (String attributeName : requested) { Attribute attribute = Attribute.ofName(attributeName); diff --git a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRContentTypes.java b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRContentTypes.java index 76c2a55972..a02a97bd86 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRContentTypes.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRContentTypes.java @@ -51,7 +51,7 @@ private MCRContentTypes() { } private static List getInstalledDetectors() { - ArrayList detectors = new ArrayList<>(); + List detectors = new ArrayList<>(); ServiceLoader serviceLoader = ServiceLoader.load(FileTypeDetector.class); for (FileTypeDetector fileTypeDetector : serviceLoader) { LOGGER.info("Adding content type detector: {}", fileTypeDetector.getClass()); @@ -62,7 +62,7 @@ private static List getInstalledDetectors() { /** * Probes the content type of a file. - * + * * Same as {@link Files#probeContentType(Path)} but uses context class loader. * @param path * the path to the file to probe diff --git a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRFileSystemPromoter.java b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRFileSystemPromoter.java index 150daf0942..67d88d3f1d 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRFileSystemPromoter.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRFileSystemPromoter.java @@ -24,6 +24,7 @@ import java.util.HashSet; import java.util.List; import java.util.ServiceLoader; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @@ -35,7 +36,7 @@ /** * This {@link AutoExecutable} checks if the {@link FileSystem} implementations are available. - * + * * There is a documented "feature" in OpenJDK 8 that only {@link FileSystemProvider} * available to the system {@link ClassLoader} are available. * We try to fix (a.k.a. hack) it right. @@ -68,7 +69,7 @@ public int getPriority() { @Override public void startUp(ServletContext servletContext) { if (servletContext != null) { - HashSet installedSchemes = FileSystemProvider.installedProviders() + Set installedSchemes = FileSystemProvider.installedProviders() .stream() .map(FileSystemProvider::getScheme) .collect(Collectors.toCollection(HashSet::new)); diff --git a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPath.java b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPath.java index 36a157a426..a6d6ae6a34 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPath.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPath.java @@ -40,6 +40,7 @@ import java.text.Normalizer; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.Objects; @@ -99,7 +100,7 @@ public static MCRPath getPath(String owner, String path) { /** * Returns the root directory for a given derivate. - * + * * @param owner the file owner (usually the id of a derivate) * @return the root path */ @@ -742,7 +743,7 @@ private String getPathElement(final int index) { } private void initNameComponents() { - final ArrayList list = new ArrayList<>(); + final List list = new ArrayList<>(); if (isEmpty()) { if (!isAbsolute()) { // is empty path but not root component diff --git a/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRFileCollectingFileVisitor.java b/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRFileCollectingFileVisitor.java index e3df95bda3..ddaa20d34f 100644 --- a/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRFileCollectingFileVisitor.java +++ b/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRFileCollectingFileVisitor.java @@ -23,16 +23,17 @@ import java.nio.file.FileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; +import java.util.List; public class MCRFileCollectingFileVisitor implements FileVisitor { - private final ArrayList paths; + private final List paths; public MCRFileCollectingFileVisitor() { paths = new ArrayList<>(); } - public ArrayList getPaths() { + public List getPaths() { return paths; } diff --git a/mycore-base/src/main/java/org/mycore/frontend/MCRFrontendUtil.java b/mycore-base/src/main/java/org/mycore/frontend/MCRFrontendUtil.java index 24a5bee65e..41746b4a3b 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/MCRFrontendUtil.java +++ b/mycore-base/src/main/java/org/mycore/frontend/MCRFrontendUtil.java @@ -29,6 +29,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.function.Supplier; @@ -180,7 +181,7 @@ public static void configureSession(MCRSession session, HttpServletRequest reque .ifPresent(session::setCurrentLanguage); // Set the IP of the current session - if (session.getCurrentIP().length() == 0) { + if (session.getCurrentIP().isEmpty()) { session.setCurrentIP(getRemoteAddr(request)); } @@ -195,7 +196,7 @@ public static void configureSession(MCRSession session, HttpServletRequest reque /** * @param request current request to get property from - * @param name of request {@link HttpServletRequest#getAttribute(String) attribute} or + * @param name of request {@link HttpServletRequest#getAttribute(String) attribute} or * {@link HttpServletRequest#getParameter(String) parameter} * @return an Optional that is either empty or contains a trimmed non-empty String that is either * the value of the request attribute or a parameter (in that order) with the given name. @@ -297,7 +298,7 @@ private static void putParamsToSession(HttpServletRequest request) { if (name.startsWith("XSL.") && name.endsWith(".SESSION")) { String key = name.substring(0, name.length() - 8); // parameter is not empty -> store - if (!request.getParameter(name).trim().equals("")) { + if (!request.getParameter(name).trim().isEmpty()) { mcrSession.put(key, request.getParameter(name)); LOGGER.debug("Found HTTP-Req.-Parameter {}={} that should be saved in session, safed {}={}", name, request.getParameter(name), key, request.getParameter(name)); @@ -315,7 +316,7 @@ private static void putParamsToSession(HttpServletRequest request) { if (name.startsWith("XSL.") && name.endsWith(".SESSION")) { String key = name.substring(0, name.length() - 8); // attribute is not empty -> store - if (!request.getAttribute(name).toString().trim().equals("")) { + if (!request.getAttribute(name).toString().isBlank()) { mcrSession.put(key, request.getAttribute(name)); LOGGER.debug("Found HTTP-Req.-Attribute {}={} that should be saved in session, safed {}={}", name, request.getParameter(name), key, request.getParameter(name)); @@ -335,7 +336,7 @@ private static void putParamsToSession(HttpServletRequest request) { * automatically added to this list. * */ - private static TreeSet getTrustedProxies() { + private static SortedSet getTrustedProxies() { // Always trust the local host return Stream .concat(Stream.of("localhost", URI.create(getBaseURL()).getHost()), MCRConfiguration2 @@ -358,7 +359,7 @@ private static TreeSet getTrustedProxies() { /** * Sets cache-control, last-modified and expires parameter to the response header. * Use this method when the client should cache the response data. - * + * * @param response the response data to cache * @param cacheTime how long to cache * @param lastModified when the data was last modified diff --git a/mycore-base/src/main/java/org/mycore/frontend/MCRLayoutUtilities.java b/mycore-base/src/main/java/org/mycore/frontend/MCRLayoutUtilities.java index 485d726eee..37e3e26f95 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/MCRLayoutUtilities.java +++ b/mycore-base/src/main/java/org/mycore/frontend/MCRLayoutUtilities.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -106,7 +107,7 @@ public class MCRLayoutUtilities { private static final boolean ACCESS_CONTROLL_ON = MCRConfiguration2 .getOrThrow("MCR.Website.ReadAccessVerification", Boolean::parseBoolean); - private static HashMap itemStore = new HashMap<>(); + private static Map itemStore = new HashMap<>(); private static final LoadingCache NAV_DOCUMENT_CACHE = CacheBuilder.newBuilder() .refreshAfterWrite(STANDARD_CACHE_SECONDS, TimeUnit.SECONDS).build(new CacheLoader<>() { @@ -468,7 +469,7 @@ private static class DocumentHolder { } public boolean isValid(URL url) throws IOException { - return docURL.equals(url) && lastModified == getLastModified(); + return docURL.toString().equals(url.toString()) && lastModified == getLastModified(); } private void parseDocument() throws JDOMException, IOException { diff --git a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRAbstractCommands.java b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRAbstractCommands.java index 90859c4041..1b90364db2 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRAbstractCommands.java +++ b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRAbstractCommands.java @@ -19,16 +19,17 @@ package org.mycore.frontend.cli; import java.util.ArrayList; +import java.util.List; /** * This class is an abstract for the implementation of command classes for the * MyCoRe commandline system. - * + * * @author Jens Kupferschmidt */ public abstract class MCRAbstractCommands implements MCRExternalCommandInterface { /** The array holding all known commands */ - protected ArrayList command = null; + protected List command = null; private String displayName; @@ -56,10 +57,10 @@ protected MCRAbstractCommands(String displayName) { * The method return the list of possible commands of this class. Each * command has TWO Strings, a String of the user command syntax and a String * of the called method. - * + * * @return a ascending sorted command pair ArrayList */ - public ArrayList getPossibleCommands() { + public List getPossibleCommands() { return this.command; } @@ -81,7 +82,7 @@ public void addCommand(MCRCommand cmd) { this.command.add(cmd); } - private void setCommand(ArrayList command) { + private void setCommand(List command) { this.command = command; } } diff --git a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRBasicCommands.java b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRBasicCommands.java index 991786191b..9dec6b7901 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRBasicCommands.java +++ b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRBasicCommands.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.zip.ZipEntry; @@ -92,7 +93,7 @@ public static void listKnownCommands() { */ @MCRCommand(syntax = "help {0}", help = "Show the help text for the commands beginning with {0}.", order = 10) public static void listKnownCommandsBeginningWithPrefix(String pattern) { - TreeMap> matchingCommands = MCRCommandManager + SortedMap> matchingCommands = MCRCommandManager .getKnownCommands().entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream() .filter(cmd -> cmd.getSyntax().contains(pattern) || cmd.getHelpText().contains(pattern)) @@ -186,7 +187,7 @@ public static void getURI(String uri, String file) throws Exception { order = 130) public static void createConfigurationDirectory() throws IOException { File configurationDirectory = MCRConfigurationDir.getConfigurationDirectory(); - ArrayList directories = new ArrayList<>(3); + List directories = new ArrayList<>(3); directories.add(configurationDirectory); for (String dir : MCRConfiguration2.getString("MCR.ConfigurationDirectory.template.directories").orElse("") .split(",")) { @@ -270,7 +271,7 @@ public static void reloadJPAMappings() throws IOException, JDOMException { /** * changes an unconfigured H2 JDBC URL, * that the database files are created in the current MYCORE_HOME directory - * + * * @param persistenceDoc the persistence.xml as JDOM2 document * @return true if the Jdbc URL was change */ @@ -292,10 +293,10 @@ private static boolean updatePersistenceH2JdbcUrl(Document persistenceDoc) { return false; } - /** + /** * adds or removes mapping entries in persistence.xml, * that they match the defined JPA-mappings in the currently available MyCoRe components - * + * * @param persistenceDoc - the persistence.xml as JDOM2 document * @return true, if the mappings changed * @throws IOException diff --git a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRClassification2Commands.java b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRClassification2Commands.java index cc15b58331..93f72a25a7 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRClassification2Commands.java +++ b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRClassification2Commands.java @@ -505,7 +505,7 @@ public static List checkAllClassifications() { order = 150) public static void checkClassification(String id) { LOGGER.info("Checking classifcation {}", id); - ArrayList log = new ArrayList<>(); + List log = new ArrayList<>(); LOGGER.info("{}: checking for missing parentID", id); checkMissingParent(id, log); LOGGER.info("{}: checking for empty labels", id); diff --git a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandLineInterface.java b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandLineInterface.java index 603d5548fc..e9593dd6c8 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandLineInterface.java +++ b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandLineInterface.java @@ -32,9 +32,11 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; import java.util.List; import java.util.Locale; -import java.util.Vector; +import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; @@ -60,9 +62,9 @@ * to be used on the server side. It implements an interactive command prompt * and understands a set of commands. Each command is an instance of the class * MCRCommand. - * + * * @see MCRCommand - * + * * @author Frank Lützenkirchen * @author Detlev Degenhardt * @author Jens Kupferschmidt @@ -77,9 +79,10 @@ public class MCRCommandLineInterface { private static String system = null; /** A queue of commands waiting to be executed */ - protected static Vector commandQueue = new Vector<>(); + @SuppressWarnings("PMD.LooseCoupling") + protected static LinkedList commandQueue = new LinkedList<>(); - protected static Vector failedCommands = new Vector<>(); + protected static Queue failedCommands = new LinkedList<>(); private static boolean interactiveMode = true; @@ -137,8 +140,7 @@ public static void main(String[] args) { exit(); } } else { - command = commandQueue.firstElement(); - commandQueue.removeElementAt(0); + command = commandQueue.poll(); System.out.println(system + "> " + command); } @@ -183,7 +185,7 @@ private static void initSession() { /** * Processes a command entered by searching a matching command in the list * of known commands and executing its method. - * + * * @param command * The command string to be processed */ @@ -244,12 +246,9 @@ private static void rollbackTransaction() { } private static void addCommandsToQueue(List commandsReturned) { - if (commandsReturned.size() > 0) { + if (!commandsReturned.isEmpty()) { output("Queueing " + commandsReturned.size() + " commands to process"); - - for (int i = 0; i < commandsReturned.size(); i++) { - commandQueue.insertElementAt(commandsReturned.get(i), i); - } + commandQueue.addAll(0, commandsReturned); } } @@ -267,7 +266,7 @@ protected static void saveQueue(String lastCommand) { saveCommandQueueToFile(commandQueue, "unprocessed-commands.txt"); } - private static void saveCommandQueueToFile(final Vector queue, String fname) { + private static void saveCommandQueueToFile(final Collection queue, String fname) { output("Writing unprocessed commands to file " + fname); try (PrintWriter pw = new PrintWriter(new File(fname), Charset.defaultCharset())) { for (String command : queue) { @@ -290,7 +289,7 @@ protected static void saveFailedCommand(String lastCommand) { } protected static void handleFailedCommands() { - if (failedCommands.size() > 0) { + if (!failedCommands.isEmpty()) { System.err.println(system + " Several command failed."); saveCommandQueueToFile(failedCommands, "failed-commands.txt"); } @@ -298,7 +297,7 @@ protected static void handleFailedCommands() { /** * Show contents of a local text file, including line numbers. - * + * * @param fname * the filename */ @@ -323,7 +322,7 @@ public static void getURI(String uri, String file) throws Exception { * Reads a file containing a list of commands to be executed and adds them * to the commands queue for processing. This method implements the * "process ..." command. - * + * * @param file * The file holding the commands to be processed * @throws IOException @@ -369,7 +368,7 @@ private static List readCommandsFromBufferedReader(BufferedReader reader * Executes simple shell commands from inside the command line interface and * shows their output. This method implements commands entered beginning * with exclamation mark, like "! ls -l /temp" - * + * * @param command * the shell command to be executed * @throws IOException diff --git a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandManager.java b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandManager.java index 28cb39beec..8addb4e135 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandManager.java +++ b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandManager.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -47,7 +48,7 @@ public class MCRCommandManager { private static final Logger LOGGER = LogManager.getLogger(MCRCommandManager.class); - protected static TreeMap> knownCommands = new TreeMap<>(); + protected static SortedMap> knownCommands = new TreeMap<>(); public MCRCommandManager() { try { @@ -65,7 +66,7 @@ protected void handleInitException(Exception ex) { } - public static TreeMap> getKnownCommands() { + public static SortedMap> getKnownCommands() { return knownCommands; } @@ -114,7 +115,7 @@ protected void addAnnotatedCLIClass(Class cliClass) { .orElse(cliClass.getSimpleName()); final Class mcrCommandAnnotation; mcrCommandAnnotation = org.mycore.frontend.cli.annotation.MCRCommand.class; - ArrayList commands = Arrays.stream(cliClass.getMethods()) + List commands = Arrays.stream(cliClass.getMethods()) .filter(method -> method.getDeclaringClass().equals(cliClass)) .filter(method -> Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())) .filter(method -> method.isAnnotationPresent(mcrCommandAnnotation)) @@ -125,14 +126,14 @@ protected void addAnnotatedCLIClass(Class cliClass) { } //fixes MCR-1594 deep in the code - private List addCommandGroup(String groupName, ArrayList commands) { + private List addCommandGroup(String groupName, List commands) { return knownCommands.put(groupName, Collections.unmodifiableList(commands)); } protected void addDefaultCLIClass(String className) { Object obj = buildInstanceOfClass(className); MCRExternalCommandInterface commandInterface = (MCRExternalCommandInterface) obj; - ArrayList commandsToAdd = commandInterface.getPossibleCommands(); + List commandsToAdd = commandInterface.getPossibleCommands(); addCommandGroup(commandInterface.getDisplayName(), commandsToAdd); } diff --git a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRExternalCommandInterface.java b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRExternalCommandInterface.java index 7fa1e80fb4..f52fd9daf7 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/cli/MCRExternalCommandInterface.java +++ b/mycore-base/src/main/java/org/mycore/frontend/cli/MCRExternalCommandInterface.java @@ -18,11 +18,11 @@ package org.mycore.frontend.cli; -import java.util.ArrayList; +import java.util.List; /** * This interface is designed to incude external application commands. - * + * * @author Jens Kupferschmidt */ public interface MCRExternalCommandInterface { @@ -30,15 +30,15 @@ public interface MCRExternalCommandInterface { * The method return the list of possible commands of this class. Each * command has TWO Strings, a String of the user command syntax and a String * of the called method. - * + * * @return a command pair ArrayList */ - ArrayList getPossibleCommands(); + List getPossibleCommands(); /** * Returns the display name of the external commands. If the display name * has not been set the simple class name is returned - * + * * @return the display name of the external commands */ String getDisplayName(); diff --git a/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportCollection.java b/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportCollection.java index 7859ccc444..d581cfc69c 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportCollection.java +++ b/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportCollection.java @@ -29,11 +29,11 @@ /** * Represents a collection of XML data to export. - * XML can be added by URI or by JDOM Element, + * XML can be added by URI or by JDOM Element, * or the contents of a complete MCRBasket can be added. - * The collected XML data is wrapped by a root element + * The collected XML data is wrapped by a root element * thats name and namespace can be set. - * + * * @author Frank Lützenkirchen */ public class MCRExportCollection { @@ -59,6 +59,7 @@ public void setRootElement(String elementName, String namespaceURI) { /** * Adds the contents of the given basket. */ + @SuppressWarnings("PMD.LooseCoupling") public void add(MCRBasket basketOfMODS) { for (MCRBasketEntry entry : basketOfMODS) { collection.addContent(basketBuilder.buildXML(entry)); diff --git a/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportServlet.java b/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportServlet.java index a33e65884d..7f88c4875b 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportServlet.java +++ b/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportServlet.java @@ -30,29 +30,29 @@ import jakarta.servlet.http.HttpServletRequest; /** - * Provides functionality to export content. - * The content to export can be selected by specifying one or more - * URIs to read from, or by giving the ID of a basket to export. + * Provides functionality to export content. + * The content to export can be selected by specifying one or more + * URIs to read from, or by giving the ID of a basket to export. * The selected content is collected as MCRExportCollection thats - * root element name can be specified. + * root element name can be specified. * The content is then transformed using an MCRContentTransformer instance * and forwarded to the requesting client. - * + * * Request Parameters: - * uri=... + * uri=... * can be repeated to include content from one or more URIs to read XML from * basket=... - * the ID of a basket to read XML from + * the ID of a basket to read XML from * root=... * optional, name of the root element that wraps the selected content * ns=... * optional, URI of the namespace of the root element * transformer=... * the ID of the transformer to use to export the selected content. - * + * * @see MCRExportCollection * @see MCRContentTransformer - * + * * @author Frank Lützenkirchen */ public class MCRExportServlet extends MCRServlet { @@ -86,6 +86,7 @@ public void doGetPost(MCRServletJob job) throws Exception { private void fillCollection(HttpServletRequest req, MCRExportCollection collection) { String basketID = req.getParameter("basket"); if (basketID != null) { + @SuppressWarnings("PMD.LooseCoupling") MCRBasket basket = MCRBasketManager.getOrCreateBasketInSession(basketID); collection.add(basket); LOGGER.info("exporting basket {} via {}", basketID, req.getParameter("transformer")); diff --git a/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHelper.java b/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHelper.java index c72b7a0953..af69568af6 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHelper.java +++ b/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHelper.java @@ -23,7 +23,6 @@ import java.nio.CharBuffer; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -243,7 +242,7 @@ public static Optional detectMainFile(MCRPath rootPath) throws IOExcept Files.walkFileTree(rootPath, visitor); //sort files by name - ArrayList paths = visitor.getPaths(); + List paths = visitor.getPaths(); if (paths.isEmpty()) { return Optional.empty(); } diff --git a/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRResourceAccessCheckerFactory.java b/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRResourceAccessCheckerFactory.java index a7e548c3a0..57129cd7ea 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRResourceAccessCheckerFactory.java +++ b/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRResourceAccessCheckerFactory.java @@ -18,6 +18,7 @@ package org.mycore.frontend.jersey.filter.access; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** @@ -25,7 +26,7 @@ * */ public class MCRResourceAccessCheckerFactory { - private static ConcurrentHashMap, MCRResourceAccessChecker> implMap; + private static Map, MCRResourceAccessChecker> implMap; static { //static block as code style requires 120 character line width implMap = new ConcurrentHashMap<>(); diff --git a/mycore-base/src/main/java/org/mycore/frontend/support/MCRAutoDeploy.java b/mycore-base/src/main/java/org/mycore/frontend/support/MCRAutoDeploy.java index 1b294da76e..5ba1338112 100644 --- a/mycore-base/src/main/java/org/mycore/frontend/support/MCRAutoDeploy.java +++ b/mycore-base/src/main/java/org/mycore/frontend/support/MCRAutoDeploy.java @@ -44,7 +44,7 @@ /** * This StartupHandler deploys web resources and register filters/servlets to web container server, * for with MCR-Auto-Deploy = true marked JARs. - * + * * @author René Adler (eagle) * */ @@ -107,7 +107,7 @@ private void registerWebFragment(final ServletContext servletContext, final MCRC .map(fr -> () -> { final List dispatchers = mapping .getChildren("dispatcher", ns); - + @SuppressWarnings("PMD.LooseCoupling") final EnumSet eDT = dispatchers.isEmpty() ? null : dispatchers.stream() .map(d -> DispatcherType.valueOf(d.getTextTrim())) diff --git a/mycore-base/src/main/java/org/mycore/services/i18n/MCRTranslation.java b/mycore-base/src/main/java/org/mycore/services/i18n/MCRTranslation.java index c13a7ee50f..dbd8946967 100644 --- a/mycore-base/src/main/java/org/mycore/services/i18n/MCRTranslation.java +++ b/mycore-base/src/main/java/org/mycore/services/i18n/MCRTranslation.java @@ -55,7 +55,7 @@ /** * provides services for internationalization in mycore application. You have to provide a property file named * messages.properties in your classpath for this class to work. - * + * * @author Radi Radichev * @author Thomas Scheffler (yagee) */ @@ -84,7 +84,7 @@ public class MCRTranslation { /** * provides translation for the given label (property key). The current locale that is needed for translation is * gathered by the language of the current MCRSession. - * + * * @param label property key * @return translated String */ @@ -94,7 +94,7 @@ public static String translate(String label) { /** * Checks whether there is a value for the given label and current locale. - * + * * @param label property key * @return true if there is a value, false otherwise */ @@ -112,7 +112,7 @@ public static boolean exists(String label) { /** * provides translation for the given label (property key). The current locale that is needed for translation is * gathered by the language of the current MCRSession. - * + * * @param label property key * @param baseName * a fully qualified class name @@ -125,7 +125,7 @@ public static String translateWithBaseName(String label, String baseName) { /** * provides translation for the given label (property key). - * + * * @param label property key * @param locale * target locale of translation @@ -149,7 +149,7 @@ public static String translateToLocale(String label, String locale) { /** * provides translation for the given label (property key). - * + * * @param label property key * @param locale * target locale of translation @@ -196,7 +196,7 @@ public static String translateToLocale(String label, Locale locale, String baseN /** * Returns a map of label/value pairs which match with the given prefix. The current locale that is needed for * translation is gathered by the language of the current MCRSession. - * + * * @param prefix * label starts with * @return map of labels with translated values @@ -207,7 +207,7 @@ public static Map translatePrefix(String prefix) { /** * Returns a map of label/value pairs which match with the given prefix. - * + * * @param prefix * label starts with * @param locale @@ -216,7 +216,7 @@ public static Map translatePrefix(String prefix) { */ public static Map translatePrefixToLocale(String prefix, Locale locale) { LOGGER.debug("Translation for locale: {}", locale.getLanguage()); - HashMap map = new HashMap<>(); + Map map = new HashMap<>(); ResourceBundle message = getResourceBundle(MESSAGES_BUNDLE, locale); Enumeration keys = message.getKeys(); while (keys.hasMoreElements()) { @@ -231,7 +231,7 @@ public static Map translatePrefixToLocale(String prefix, Locale /** * provides translation for the given label (property key). The current locale that is needed for translation is * gathered by the language of the current MCRSession. - * + * * @param label property key * @param arguments * Objects that are inserted instead of placeholders in the property values @@ -265,7 +265,7 @@ public static String translateToLocale(String label, Locale locale, Object... ar * gathered by the language of the current MCRSession. Be aware that any occurence of ';' and '\' in * argument has to be masked by '\'. You can use ';' to build an array of arguments: "foo;bar" would * result in {"foo","bar"} (the array) - * + * * @param label property key * @param argument * String that is inserted instead of placeholders in the property values @@ -433,7 +433,7 @@ static Set loadLanguagesByMessagesBundle() { Set languages = new HashSet<>(); for (Locale locale : Locale.getAvailableLocales()) { try { - if (!locale.getLanguage().equals("")) { + if (!locale.getLanguage().isEmpty()) { ResourceBundle bundle = getResourceBundle(MESSAGES_BUNDLE, locale); languages.add(bundle.getLocale().toString()); } diff --git a/mycore-base/src/main/java/org/mycore/tools/MCRPNGTools.java b/mycore-base/src/main/java/org/mycore/tools/MCRPNGTools.java index ab322c3ca0..3a58295db7 100644 --- a/mycore-base/src/main/java/org/mycore/tools/MCRPNGTools.java +++ b/mycore-base/src/main/java/org/mycore/tools/MCRPNGTools.java @@ -20,6 +20,7 @@ import java.awt.image.BufferedImage; import java.io.IOException; +import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; @@ -42,7 +43,7 @@ public class MCRPNGTools implements AutoCloseable { private ImageWriteParam imageWriteParam; - private ConcurrentLinkedQueue imageWriters = new ConcurrentLinkedQueue<>(); + private Queue imageWriters = new ConcurrentLinkedQueue<>(); public MCRPNGTools() { imageWriteParam = ImageIO.getImageWritersBySuffix("png").next().getDefaultWriteParam(); diff --git a/mycore-base/src/main/java/org/mycore/tools/MCRTopologicalSort.java b/mycore-base/src/main/java/org/mycore/tools/MCRTopologicalSort.java index ad14542513..e0aa98ab69 100644 --- a/mycore-base/src/main/java/org/mycore/tools/MCRTopologicalSort.java +++ b/mycore-base/src/main/java/org/mycore/tools/MCRTopologicalSort.java @@ -29,6 +29,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; @@ -67,11 +68,11 @@ public class MCRTopologicalSort { private static final Logger LOGGER = LogManager.getLogger(); - /** + /** * store the edges as adjacent list * for each target node a list of corresponding source node is stored */ - Map> edgeSources = new TreeMap<>(); + Map> edgeSources = new TreeMap<>(); /** * store the position of elements to sort in BiMap @@ -88,7 +89,7 @@ public class MCRTopologicalSort { * * @param ts - the topological sort data structure * @param files - a list of file names - * @param dir - the directory where the files can be found + * @param dir - the directory where the files can be found */ public static void prepareData(MCRTopologicalSort ts, String[] files, Path dir) { ts.reset(); @@ -233,7 +234,7 @@ public void addEdge(Integer from, Integer to) { * ([to] = leaf node) */ public boolean removeEdge(Integer from, Integer to) { - TreeSet ts = edgeSources.get(to); + SortedSet ts = edgeSources.get(to); if (ts != null) { ts.remove(from); if (ts.isEmpty()) { diff --git a/mycore-base/src/main/java/org/mycore/util/concurrent/processing/MCRProcessableFactory.java b/mycore-base/src/main/java/org/mycore/util/concurrent/processing/MCRProcessableFactory.java index ce2038d1d4..b487f3b344 100644 --- a/mycore-base/src/main/java/org/mycore/util/concurrent/processing/MCRProcessableFactory.java +++ b/mycore-base/src/main/java/org/mycore/util/concurrent/processing/MCRProcessableFactory.java @@ -108,6 +108,7 @@ public static MCRProcessableExecutor newPool(ExecutorService delegate, MCRProces * * @return a new priority blocking queue */ + @SuppressWarnings("PMD.LooseCoupling") public static PriorityBlockingQueue newPriorityBlockingQueue() { int initialCapacity = 11; //taken from java.util.concurrent.PriorityBlockingQueue.DEFAULT_INITIAL_CAPACITY return new PriorityBlockingQueue<>(initialCapacity, Comparator.nullsLast(new MCRRunnableComperator())); diff --git a/mycore-base/src/test/java/org/mycore/common/events/MCRShutdownHandlerTest.java b/mycore-base/src/test/java/org/mycore/common/events/MCRShutdownHandlerTest.java index db5723b834..5959cab043 100644 --- a/mycore-base/src/test/java/org/mycore/common/events/MCRShutdownHandlerTest.java +++ b/mycore-base/src/test/java/org/mycore/common/events/MCRShutdownHandlerTest.java @@ -143,7 +143,7 @@ public String toString() { * It only used by {@link #mark} and {@link #resetCloseables()}. */ private record MCRShutdownHandlerState(boolean shuttingDown, - ConcurrentSkipListSet requests) { + java.util.NavigableSet requests) { /** * Constructs an instance of MCRShutdownHandlerState with the given parameters. diff --git a/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/access/MCRClassificationWritePermission.java b/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/access/MCRClassificationWritePermission.java index dbae842b7a..d300b88044 100644 --- a/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/access/MCRClassificationWritePermission.java +++ b/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/access/MCRClassificationWritePermission.java @@ -20,7 +20,6 @@ import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; -import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -54,7 +53,7 @@ public boolean isPermitted(ContainerRequestContext request) { String value = convertStreamToString(request.getEntityStream()); try { // Set categories = MCRCategUtils.getRootCategoryIDs(value); - HashMap categories = MCRCategUtils.getCategoryIDMap(value); + Map categories = MCRCategUtils.getCategoryIDMap(value); if (categories == null) { LOGGER.error("Could not parse {}", value); return false; diff --git a/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/utils/MCRCategUtils.java b/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/utils/MCRCategUtils.java index a1972cde5e..3590ecd4c9 100644 --- a/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/utils/MCRCategUtils.java +++ b/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/utils/MCRCategUtils.java @@ -19,6 +19,7 @@ package org.mycore.frontend.classeditor.utils; import java.util.HashMap; +import java.util.Map; import java.util.SortedSet; import org.mycore.datamodel.classifications2.MCRCategory; @@ -47,8 +48,8 @@ public static String maskCategID(MCRCategoryID categoryID) { return rootID + "." + (id == null ? "" : id); } - public static HashMap getCategoryIDMap(String json) { - HashMap categories = new HashMap<>(); + public static Map getCategoryIDMap(String json) { + Map categories = new HashMap<>(); JsonStreamParser jsonStreamParser = new JsonStreamParser(json); if (jsonStreamParser.hasNext()) { JsonArray saveObjArray = jsonStreamParser.next().getAsJsonArray(); diff --git a/mycore-csl/src/main/java/org/mycore/csl/MCRCSLTransformer.java b/mycore-csl/src/main/java/org/mycore/csl/MCRCSLTransformer.java index 77755b1846..94e1a2d77c 100644 --- a/mycore-csl/src/main/java/org/mycore/csl/MCRCSLTransformer.java +++ b/mycore-csl/src/main/java/org/mycore/csl/MCRCSLTransformer.java @@ -18,8 +18,9 @@ package org.mycore.csl; +import java.util.ArrayDeque; +import java.util.Deque; import java.util.Map; -import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; @@ -43,7 +44,7 @@ public class MCRCSLTransformer extends MCRParameterizedTransformer { private static final String CONFIG_PREFIX = "MCR.ContentTransformer."; - private final Map> transformerInstances = new ConcurrentHashMap<>(); + private final Map> transformerInstances = new ConcurrentHashMap<>(); private String configuredFormat; @@ -76,7 +77,7 @@ public MCRContent transform(MCRContent source) { private MCRCSLTransformerInstance getTransformerInstance(String style, String format) { synchronized (transformerInstances) { - if (getStyleFormatTransformerStack(style, format).size() > 0) { + if (!getStyleFormatTransformerStack(style, format).isEmpty()) { return transformerInstances.get(mapKey(style, format)).pop(); } } @@ -88,8 +89,8 @@ private MCRCSLTransformerInstance getTransformerInstance(String style, String fo return newInstance; } - private Stack getStyleFormatTransformerStack(String style, String format) { - return transformerInstances.computeIfAbsent(mapKey(style, format), (a) -> new Stack<>()); + private Deque getStyleFormatTransformerStack(String style, String format) { + return transformerInstances.computeIfAbsent(mapKey(style, format), (a) -> new ArrayDeque<>()); } private String mapKey(String style, String format) { @@ -105,7 +106,7 @@ private void returnTransformerInstance(MCRCSLTransformerInstance instance, Strin return; } synchronized (transformerInstances) { - final Stack styleFormatTransformerStack = getStyleFormatTransformerStack(style, + final Deque styleFormatTransformerStack = getStyleFormatTransformerStack(style, format); if (!styleFormatTransformerStack.contains(instance)) { styleFormatTransformerStack.push(instance); diff --git a/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileSystemProvider.java b/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileSystemProvider.java index b68d340c31..52c2be18be 100644 --- a/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileSystemProvider.java +++ b/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileSystemProvider.java @@ -43,7 +43,6 @@ import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; -import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -230,7 +229,7 @@ public void copy(Path source, Path target, CopyOption... options) throws IOExcep return; //that was easy } checkCopyOptions(options); - HashSet copyOptions = Sets.newHashSet(options); + Set copyOptions = Sets.newHashSet(options); boolean createNew = !copyOptions.contains(StandardCopyOption.REPLACE_EXISTING); MCRPath src = MCRFileSystemUtils.checkPathAbsolute(source); MCRPath tgt = MCRFileSystemUtils.checkPathAbsolute(target); @@ -259,7 +258,7 @@ public void copy(Path source, Path target, CopyOption... options) throws IOExcep } } - private static void copyFile(MCRFile srcFile, MCRPath target, HashSet copyOptions, boolean createNew) + private static void copyFile(MCRFile srcFile, MCRPath target, Set copyOptions, boolean createNew) throws IOException { boolean fireCreateEvent = createNew || Files.notExists(target); MCRFile targetFile = MCRFileSystemUtils.getMCRFile(target, true, createNew, !fireCreateEvent); @@ -274,7 +273,7 @@ private static void copyFile(MCRFile srcFile, MCRPath target, HashSet copyOptions) + private static void copyDirectory(MCRDirectory srcNode, MCRPath target, Set copyOptions) throws IOException { MCRDirectory tgtParentDir = MCRFileSystemUtils.resolvePath(target.getParent()); MCRStoredNode child = (MCRStoredNode) tgtParentDir.getChild(target.getFileName().toString()); @@ -328,7 +327,7 @@ private static void copyDirectoryAttributes(MCRDirectory source, MCRDirectory ta */ @Override public void move(Path source, Path target, CopyOption... options) throws IOException { - HashSet copyOptions = Sets.newHashSet(options); + Set copyOptions = Sets.newHashSet(options); if (copyOptions.contains(StandardCopyOption.ATOMIC_MOVE)) { throw new AtomicMoveNotSupportedException(source.toString(), target.toString(), "ATOMIC_MOVE not supported yet"); diff --git a/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackage.java b/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackage.java index 096c4f0a47..6ac17ea736 100644 --- a/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackage.java +++ b/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackage.java @@ -27,6 +27,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.SequencedSet; import java.util.Set; import java.util.stream.Collectors; @@ -56,7 +57,7 @@ * all required objects and checks if they are valid. Call {@link #getContent()} * to retrieve the content afterwards. *

    - * + * * @author Silvio Hermann * @author Matthias Eichner */ @@ -74,7 +75,7 @@ public class MCRTransferPackage { * Set of objects including the source, its descendants and all resolved links. * Its linked because the import order matters. */ - protected LinkedHashSet objects; + protected SequencedSet objects; /** * List of transfer package file containers. @@ -92,11 +93,11 @@ public MCRTransferPackage(MCRObject source) { /** * Builds the transfer package. - * + * * @throws MCRUsageException is thrown if some of the referenced objects or derivates couldn't be retrieved */ public void build() throws MCRUsageException { - LinkedHashMap objectMap = new LinkedHashMap<>(); + Map objectMap = new LinkedHashMap<>(); Set categories = new HashSet<>(); resolveChildrenAndLinks(source, objectMap, categories); @@ -108,11 +109,11 @@ public void build() throws MCRUsageException { /** * Fills the given objectMap with all children and links of the object. The object * itself is also added. - * + * * @param object the source object * @param objectMap the map which will be created */ - protected void resolveChildrenAndLinks(MCRObject object, LinkedHashMap objectMap, + protected void resolveChildrenAndLinks(MCRObject object, Map objectMap, Set categories) { // add links for (MCRObject entityLink : MCRObjectUtils.getLinkedObjects(object)) { @@ -141,9 +142,9 @@ protected void resolveChildrenAndLinks(MCRObject object, LinkedHashMapTODO: derivates of linked objects are not added

    - * + * * @param object the object * @return list of transfer packages file container */ @@ -168,8 +169,8 @@ protected List buildFileContainers(MCRObject ob /** * Generates an xml file, which contains import configuration. - * - * @return import configuration document + * + * @return import configuration document */ public Document buildImportConfiguration() { Element configElement = new Element("config"); @@ -186,7 +187,7 @@ public Document buildImportConfiguration() { /** * Returns the content for this transfer package. You have to call {@link #build()} * before you can retrieve this data. - * + * * @return a map where key = filename; value = MCRContent */ public Map getContent() throws IOException { @@ -233,7 +234,7 @@ public Map getContent() throws IOException { /** * Returns the source of this transfer package. - * + * * @return the source */ public MCRObject getSource() { diff --git a/mycore-iview2/src/main/java/org/mycore/iview2/events/MCRImageTileEventHandler.java b/mycore-iview2/src/main/java/org/mycore/iview2/events/MCRImageTileEventHandler.java index 2607ad60c4..2df0bb5295 100644 --- a/mycore-iview2/src/main/java/org/mycore/iview2/events/MCRImageTileEventHandler.java +++ b/mycore-iview2/src/main/java/org/mycore/iview2/events/MCRImageTileEventHandler.java @@ -36,6 +36,7 @@ */ public class MCRImageTileEventHandler extends MCREventHandlerBase { + @SuppressWarnings("PMD.LooseCoupling") MCRTilingQueue tq = MCRTilingQueue.getInstance(); /** diff --git a/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRIView2Commands.java b/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRIView2Commands.java index 8ebb785dfe..a2f39803c2 100644 --- a/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRIView2Commands.java +++ b/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRIView2Commands.java @@ -383,7 +383,7 @@ private static List forAllDerivatesOfObject(String objectID, String batc if (derivateIds == null) { LOGGER.error("Object does not exist: {}", mcrobjid); } - ArrayList cmds = new ArrayList<>(derivateIds.size()); + List cmds = new ArrayList<>(derivateIds.size()); for (MCRObjectID derId : derivateIds) { cmds.add(new MessageFormat(batchCommandSyntax, Locale.ROOT).format(new String[] { derId.toString() })); } @@ -437,7 +437,7 @@ private static void deleteFileAndEmptyDirectories(Path file) throws IOException } private static List getSupportedFiles(MCRPath rootNode) throws IOException { - final ArrayList files = new ArrayList<>(); + final List files = new ArrayList<>(); SimpleFileVisitor test = new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { diff --git a/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRThumbnailServlet.java b/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRThumbnailServlet.java index 604d96ae86..90c28d3b75 100644 --- a/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRThumbnailServlet.java +++ b/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRThumbnailServlet.java @@ -31,6 +31,7 @@ import java.util.Date; import java.util.Locale; import java.util.Objects; +import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -73,7 +74,7 @@ public class MCRThumbnailServlet extends MCRServlet { private ImageWriteParam imageWriteParam; - private ConcurrentLinkedQueue imageWriters = new ConcurrentLinkedQueue<>(); + private Queue imageWriters = new ConcurrentLinkedQueue<>(); private static Logger LOGGER = LogManager.getLogger(MCRThumbnailServlet.class); @@ -157,7 +158,7 @@ protected void render(MCRServletJob job, Exception ex) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(maxPngSize.get()); ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(bout)) { imageWriter.setOutput(imageOutputStream); - //tile = addWatermark(scaleBufferedImage(tile)); + //tile = addWatermark(scaleBufferedImage(tile)); IIOImage iioImage = new IIOImage(thumbnail, null, null); imageWriter.write(null, iioImage, imageWriteParam); int contentLength = bout.size(); diff --git a/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRImageTiler.java b/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRImageTiler.java index bf84429cbf..cbd9248387 100644 --- a/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRImageTiler.java +++ b/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRImageTiler.java @@ -20,6 +20,7 @@ import java.lang.reflect.Constructor; import java.util.Arrays; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; @@ -51,7 +52,7 @@ /** * Master image tiler thread. - * + * * @author Thomas Scheffler (yagee) */ public class MCRImageTiler implements Runnable, Closeable { @@ -59,6 +60,7 @@ public class MCRImageTiler implements Runnable, Closeable { private static final Logger LOGGER = LogManager.getLogger(MCRImageTiler.class); + @SuppressWarnings("PMD.LooseCoupling") private static final MCRTilingQueue TQ = MCRTilingQueue.getInstance(); private MCRProcessableExecutor tilingServe; @@ -223,7 +225,7 @@ private void processNextTileJob(MCRProcessableDefaultCollection imageTilerCollec private static MCRProcessableExecutor getProcessableExecutor( MCRProcessableDefaultCollection imageTilerCollection, int tilingThreadCount, ThreadFactory slaveFactory, AtomicInteger activeThreads) { - final LinkedBlockingQueue workQueue = new LinkedBlockingQueue<>(); + final BlockingQueue workQueue = new LinkedBlockingQueue<>(); ThreadPoolExecutor baseExecutor = new ThreadPoolExecutor(tilingThreadCount, tilingThreadCount, 1, TimeUnit.DAYS, workQueue, slaveFactory) { diff --git a/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRStalledJobResetter.java b/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRStalledJobResetter.java index 03e320d984..39246bcb8d 100644 --- a/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRStalledJobResetter.java +++ b/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRStalledJobResetter.java @@ -20,6 +20,7 @@ import java.util.Date; import java.util.HashMap; +import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -45,7 +46,7 @@ public class MCRStalledJobResetter implements Runnable { private static int maxResetCount = Integer.parseInt(MCRIView2Tools.getIView2Property("MaxResetCount")); - private HashMap jobCounter; + private Map jobCounter; private MCRStalledJobResetter() { jobCounter = new HashMap<>(); diff --git a/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRTilingQueue.java b/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRTilingQueue.java index 8363ac6cb6..dde2458b76 100644 --- a/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRTilingQueue.java +++ b/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRTilingQueue.java @@ -43,6 +43,7 @@ import jakarta.persistence.TypedQuery; public class MCRTilingQueue extends AbstractQueue implements Closeable { + @SuppressWarnings("PMD.LooseCoupling") private static MCRTilingQueue instance = new MCRTilingQueue(); private static Logger LOGGER = LogManager.getLogger(); @@ -69,6 +70,7 @@ private MCRTilingQueue() { /** * @return singleton instance of this class */ + @SuppressWarnings("PMD.LooseCoupling") public static MCRTilingQueue getInstance() { if (!instance.running) { return null; @@ -117,7 +119,7 @@ public MCRTileJob remove() throws NoSuchElementException { } /** - * get next job without modifying it state to {@link MCRJobState#PROCESSING} + * get next job without modifying it state to {@link MCRJobState#PROCESSING} */ public MCRTileJob peek() { if (!running) { @@ -183,7 +185,7 @@ public void clear() { /** * iterates of jobs of status {@link MCRJobState#NEW} - * + * * does not change the status. */ @Override diff --git a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueManager.java b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueManager.java index 5010fb3919..afe7a8f944 100644 --- a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueManager.java +++ b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueManager.java @@ -37,6 +37,7 @@ public class MCRJobQueueManager { private static final Logger LOGGER = LogManager.getLogger(); + @SuppressWarnings("PMD.LooseCoupling") final Map queueInstances = new ConcurrentHashMap<>(); final Map jobThreadStartInstances = new ConcurrentHashMap<>(); diff --git a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobThreadStarter.java b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobThreadStarter.java index 5220fd8e0d..0f2099328f 100644 --- a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobThreadStarter.java +++ b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobThreadStarter.java @@ -21,6 +21,7 @@ import java.lang.reflect.Constructor; import java.time.Duration; import java.util.List; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; @@ -49,7 +50,7 @@ /** * Pulls {@link MCRJob}s from Database and starts {@link MCRJobRunnable}s. - * + * * @author René Adler * @author Sebastian Hofmann */ @@ -69,7 +70,7 @@ public class MCRJobThreadStarter implements Runnable, Closeable { private final MCRProcessableDefaultCollection processableCollection; - private final LinkedBlockingQueue workQueue = new LinkedBlockingQueue<>(); + private final BlockingQueue workQueue = new LinkedBlockingQueue<>(); private final ReentrantLock runLock; @@ -281,7 +282,7 @@ private String getSimpleActionName() { /** * Returns the name of this job manager. - * + * * @return the name */ public String getName() { @@ -290,7 +291,7 @@ public String getName() { /** * Returns the processable collection assigned to this job manager. - * + * * @return the processable collection */ public MCRProcessableCollection getProcessableCollection() { @@ -373,7 +374,7 @@ private static final class ActiveCountingThreadPoolExecutor extends ThreadPoolEx private final AtomicInteger activeThreads; ActiveCountingThreadPoolExecutor(int maxJobThreadCount, - LinkedBlockingQueue workQueue, + BlockingQueue workQueue, JobThreadFactory jobThreadFactory, AtomicInteger activeThreads) { super(maxJobThreadCount, maxJobThreadCount, 1, TimeUnit.DAYS, workQueue, jobThreadFactory); diff --git a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/rest/resources/MCRJobQueueResource.java b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/rest/resources/MCRJobQueueResource.java index 97fd846237..5f4bb408b7 100644 --- a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/rest/resources/MCRJobQueueResource.java +++ b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/rest/resources/MCRJobQueueResource.java @@ -25,6 +25,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.stream.Collectors; import org.mycore.common.MCRClassTools; @@ -108,7 +109,7 @@ public Response queueJSON(@PathParam("name") String name, @QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit) { - HashMap parameterMap = new HashMap<>(); + Map parameterMap = new HashMap<>(); parameters.forEach(p -> { String[] split = p.split(":"); diff --git a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/staticcontent/MCRJobStaticContentGenerator.java b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/staticcontent/MCRJobStaticContentGenerator.java index bfd390b62e..b0c6e15742 100644 --- a/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/staticcontent/MCRJobStaticContentGenerator.java +++ b/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/staticcontent/MCRJobStaticContentGenerator.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -40,7 +41,7 @@ public MCRJobStaticContentGenerator(String configID) { @Override public void generate(MCRObject object) throws IOException { - HashMap parameters = new HashMap<>(); + Map parameters = new HashMap<>(); parameters.put(MCRStaticContentGeneratorJobAction.CONFIG_ID_PARAMETER, configID); parameters.put(MCRStaticContentGeneratorJobAction.OBJECT_ID_PARAMETER, object.getId().toString()); diff --git a/mycore-media/src/main/java/org/mycore/media/video/MCRMediaSourceProvider.java b/mycore-media/src/main/java/org/mycore/media/video/MCRMediaSourceProvider.java index bfa5de3cb3..235043db68 100644 --- a/mycore-media/src/main/java/org/mycore/media/video/MCRMediaSourceProvider.java +++ b/mycore-media/src/main/java/org/mycore/media/video/MCRMediaSourceProvider.java @@ -54,7 +54,7 @@ public class MCRMediaSourceProvider { private Optional wowzaToken; - private ArrayList sources; + private List sources; public MCRMediaSourceProvider(String derivateId, String path, Optional userAgent, Supplier parameterSupplier) throws IOException, URISyntaxException { @@ -76,7 +76,7 @@ public MCRMediaSourceProvider(String derivateId, String path, Optional u } throw e; } - ArrayList mediaSources = new ArrayList<>(4); + List mediaSources = new ArrayList<>(4); getDashStream() .map(s -> new MCRMediaSource(s, MCRMediaSourceType.dash_stream)) .ifPresent(mediaSources::add); diff --git a/mycore-mets/src/main/java/org/mycore/mets/frontend/MCRMetsCommands.java b/mycore-mets/src/main/java/org/mycore/mets/frontend/MCRMetsCommands.java index d61d7c3464..6e765abe84 100644 --- a/mycore-mets/src/main/java/org/mycore/mets/frontend/MCRMetsCommands.java +++ b/mycore-mets/src/main/java/org/mycore/mets/frontend/MCRMetsCommands.java @@ -23,6 +23,7 @@ import java.io.OutputStream; import java.nio.file.Files; import java.util.List; +import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Collectors; @@ -54,7 +55,7 @@ public class MCRMetsCommands extends MCRAbstractCommands { private static final Logger LOGGER = LogManager.getLogger(MCRMetsCommands.class); - public static ConcurrentLinkedQueue invalidMetsQueue = new ConcurrentLinkedQueue<>(); + public static Queue invalidMetsQueue = new ConcurrentLinkedQueue<>(); @MCRCommand(syntax = "validate selected mets", help = "validates all mets.xml of selected derivates", order = 10) public static void validateSelectedMets() { @@ -69,7 +70,7 @@ public static void validateSelectedMets() { InputStream metsIS = content.getInputStream(); METSValidator mv = new METSValidator(metsIS); List validationExceptionList = mv.validate(); - if (validationExceptionList.size() > 0) { + if (!validationExceptionList.isEmpty()) { invalidMetsQueue.add(objectID); } for (ValidationException validationException : validationExceptionList) { diff --git a/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSDefaultGenerator.java b/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSDefaultGenerator.java index 16764d8b17..5782c65ef1 100644 --- a/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSDefaultGenerator.java +++ b/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSDefaultGenerator.java @@ -74,7 +74,7 @@ public class MCRMETSDefaultGenerator extends MCRMETSAbstractGenerator { private static final List EXCLUDED_ROOT_FOLDERS = Arrays.asList("alto", "tei"); - private HashMap hrefIdMap = new HashMap<>(); + private Map hrefIdMap = new HashMap<>(); @Override public Mets generate() throws MCRException { diff --git a/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRJSONSimpleModelConverter.java b/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRJSONSimpleModelConverter.java index f92aa24886..e5d0013680 100644 --- a/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRJSONSimpleModelConverter.java +++ b/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRJSONSimpleModelConverter.java @@ -20,6 +20,7 @@ import static java.util.stream.Collectors.toList; +import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; @@ -52,12 +53,12 @@ public static MCRMetsSimpleModel toSimpleModel(String model) { MCRMetsSimpleModel metsSimpleModel = gsonBuilder.create().fromJson(model, MCRMetsSimpleModel.class); - Hashtable idPageMap = new Hashtable<>(); + Map idPageMap = new HashMap<>(); metsSimpleModel.getMetsPageList().stream().forEach(page -> idPageMap.put(page.getId(), page)); final Map idMCRMetsFileMap = extractIdFileMap(metsSimpleModel.getMetsPageList()); - Hashtable idSectionMap = new Hashtable<>(); + Map idSectionMap = new HashMap<>(); processSections(metsSimpleModel.getRootSection(), idSectionMap, idMCRMetsFileMap); List sectionPageLinkList = metsSimpleModel.getSectionPageLinkList(); @@ -88,7 +89,7 @@ private static Map extractIdFileMap(List pages return idFileMap; } - private static void processSections(MCRMetsSection current, Hashtable idSectionTable, + private static void processSections(MCRMetsSection current, Map idSectionTable, Map idFileMap) { idSectionTable.put(current.getId(), current); diff --git a/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRSimpleModelXMLConverter.java b/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRSimpleModelXMLConverter.java index 174d4d0228..fa48037277 100644 --- a/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRSimpleModelXMLConverter.java +++ b/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRSimpleModelXMLConverter.java @@ -18,7 +18,7 @@ package org.mycore.mets.model.converter; -import java.util.Hashtable; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -64,11 +64,11 @@ public class MCRSimpleModelXMLConverter { public static Document toXML(MCRMetsSimpleModel msm) { Mets mets = new Mets(); - Hashtable pageIdMap = new Hashtable<>(); - Map idToNewIDMap = new Hashtable<>(); + Map pageIdMap = new HashMap<>(); + Map idToNewIDMap = new HashMap<>(); buildPhysicalPages(msm, mets, pageIdMap, idToNewIDMap); - Hashtable sectionIdMap = new Hashtable<>(); + Map sectionIdMap = new HashMap<>(); buildLogicalPages(msm, mets, sectionIdMap, idToNewIDMap); StructLink structLink = mets.getStructLink(); @@ -147,7 +147,7 @@ private static void buildLogicalSubDiv(MCRMetsSection metsSection, LogicalDiv pa String id = metsSection.getId(); LogicalDiv logicalSubDiv = new LogicalDiv(id, metsSection.getType(), metsSection.getLabel()); - if (metsSection.getAltoLinks().size() > 0) { + if (!metsSection.getAltoLinks().isEmpty()) { Fptr fptr = new Fptr(); List seqList = fptr.getSeqList(); diff --git a/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsLock.java b/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsLock.java index d14cc93d4b..7a73d5445e 100644 --- a/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsLock.java +++ b/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsLock.java @@ -18,8 +18,9 @@ package org.mycore.mets.tools; -import java.util.Hashtable; +import java.util.HashMap; import java.util.Locale; +import java.util.Map; import java.util.Objects; import org.apache.logging.log4j.LogManager; @@ -30,14 +31,14 @@ import org.mycore.datamodel.metadata.MCRObjectID; /** - * + * * Used to lock the mets editor for a specific Derivate - * + * * @author Sebastian Hofmann (mcrshofm) */ public class MCRMetsLock { - private static Hashtable metsAccessSessionTable = new Hashtable<>(); + private static Map metsAccessSessionTable = new HashMap<>(); private static final Logger LOGGER = LogManager.getLogger(MCRMetsLock.class); diff --git a/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsSave.java b/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsSave.java index 4f91170c34..a8eb692f27 100644 --- a/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsSave.java +++ b/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsSave.java @@ -225,7 +225,7 @@ private static Document updateOnFileAdd(Document mets, MCRPath file) { XPathExpression xpath = XPathFactory.instance().compile(fileExistPathString, Filters.element(), null, MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); - if (xpath.evaluate(mets).size() > 0) { + if (!xpath.evaluate(mets).isEmpty()) { String msgTemplate = "The File : '%s' already exists in mets.xml"; LOGGER.warn(String.format(Locale.ROOT, msgTemplate, relPath)); return null; @@ -496,7 +496,7 @@ public static void updateMetsOnUrnGenerate(MCRDerivate derivate) { } try { Map urnFileMap = derivate.getUrnMap(); - if (urnFileMap.size() > 0) { + if (!urnFileMap.isEmpty()) { updateMetsOnUrnGenerate(derivate.getId(), urnFileMap); } else { LOGGER.debug("There are no URN to insert"); @@ -573,10 +573,10 @@ private static Document updateOnFileDelete(Document mets, MCRPath file) { File fileToRemove = fileGrp.getFileByHref(href); fileGrp.removeFile(fileToRemove); - ArrayList physicalSubDivsToRemove = new ArrayList<>(); + List physicalSubDivsToRemove = new ArrayList<>(); // remove file from mets:mets/mets:structMap[@TYPE='PHYSICAL'] for (PhysicalSubDiv physicalSubDiv : divContainer.getChildren()) { - ArrayList fptrsToRemove = new ArrayList<>(); + List fptrsToRemove = new ArrayList<>(); for (Fptr fptr : physicalSubDiv.getChildren()) { if (fptr.getFileId().equals(fileToRemove.getId())) { if (fileGrp.getUse().equals(FileGrp.USE_MASTER)) { @@ -619,12 +619,12 @@ private static Document updateOnFileDelete(Document mets, MCRPath file) { } // there are still files for this logical sub div, nothing to do - if (modifiedMets.getStructLink().getSmLinkByFrom(logicalDiv.getId()).size() > 0) { + if (!modifiedMets.getStructLink().getSmLinkByFrom(logicalDiv.getId()).isEmpty()) { continue; } // the logical div has other divs included, nothing to do - if (logicalDiv.getChildren().size() > 0) { + if (!logicalDiv.getChildren().isEmpty()) { continue; } @@ -653,7 +653,7 @@ private static void handleParents(LogicalDiv logDiv, Mets mets) { LogicalDiv parent = logDiv.getParent(); // there are files for the parent of the log div, thus nothing to do - if (mets.getStructLink().getSmLinkByFrom(parent.getId()).size() > 0) { + if (!mets.getStructLink().getSmLinkByFrom(parent.getId()).isEmpty()) { return; } @@ -740,9 +740,9 @@ public static void updateFiles(Mets mets, final MCRPath derivatePath) throws IOE .map(path -> path.substring(1)).filter(href -> !Objects.equals(href, "mets.xml")) .collect(Collectors.toList()); - ArrayList removedFiles = new ArrayList<>(metsFiles); + List removedFiles = new ArrayList<>(metsFiles); removedFiles.removeAll(derivateFiles); - ArrayList addedFiles = new ArrayList<>(derivateFiles); + List addedFiles = new ArrayList<>(derivateFiles); Collections.sort(addedFiles); addedFiles.removeAll(metsFiles); diff --git a/mycore-migration/src/main/java/org/mycore/migration/cli/MCRMigrationCommands.java b/mycore-migration/src/main/java/org/mycore/migration/cli/MCRMigrationCommands.java index 518edde6eb..abba58b6b0 100644 --- a/mycore-migration/src/main/java/org/mycore/migration/cli/MCRMigrationCommands.java +++ b/mycore-migration/src/main/java/org/mycore/migration/cli/MCRMigrationCommands.java @@ -28,6 +28,7 @@ import java.util.Collection; import java.util.Date; import java.util.List; +import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; @@ -92,8 +93,8 @@ public class MCRMigrationCommands { help = "Create missing servflags for createdby and modifiedby. (MCR-786)", order = 20) public static List addServFlags() { - TreeSet ids = new TreeSet<>(MCRXMLMetadataManager.instance().listIDs()); - ArrayList cmds = new ArrayList<>(ids.size()); + SortedSet ids = new TreeSet<>(MCRXMLMetadataManager.instance().listIDs()); + List cmds = new ArrayList<>(ids.size()); for (String id : ids) { cmds.add("migrate author servflags for " + id); } @@ -323,7 +324,7 @@ public static List migrateAllDerivates() { objectTypes.remove("derivate"); objectTypes.remove("class"); - ArrayList commands = new ArrayList<>(); + List commands = new ArrayList<>(); for (String t : objectTypes) { for (String objID : MCRXMLMetadataManager.instance().listIDsOfType(t)) { commands.add("migrate derivatelinks for object " + objID); @@ -366,7 +367,7 @@ public static void setOrderOfDerivate(String derivateIDStr, String orderStr) thr //migrate title: //in professorenkatalog we used a service flag to store the title -> should be moved to titles/tile - if (derivate.getService().getFlags("title").size() > 0) { + if (!derivate.getService().getFlags("title").isEmpty()) { String title = derivate.getService().getFlags("title").getFirst(); derivate.getDerivate().getTitles().add(new MCRMetaLangText("title", "de", null, 0, "main", title)); derivate.getService().removeFlags("title"); diff --git a/mycore-mods/src/main/java/org/mycore/mods/MCRMODSLinksEventHandler.java b/mycore-mods/src/main/java/org/mycore/mods/MCRMODSLinksEventHandler.java index cb986531fb..649a24d19e 100644 --- a/mycore-mods/src/main/java/org/mycore/mods/MCRMODSLinksEventHandler.java +++ b/mycore-mods/src/main/java/org/mycore/mods/MCRMODSLinksEventHandler.java @@ -20,6 +20,7 @@ import java.util.HashSet; import java.util.List; +import java.util.Set; import org.jdom2.Element; import org.mycore.common.MCRConstants; @@ -34,7 +35,7 @@ /** * Eventhandler for linking MODS_OBJECTTYPE document to MyCoRe classifications. - * + * * @author Thomas Scheffler (yagee) */ public class MCRMODSLinksEventHandler extends MCREventHandlerBase { @@ -48,7 +49,7 @@ protected void handleObjectCreated(final MCREvent evt, final MCRObject obj) { return; } MCRMODSWrapper modsWrapper = new MCRMODSWrapper(obj); - final HashSet categories = new HashSet<>(modsWrapper.getMcrCategoryIDs()); + final Set categories = new HashSet<>(modsWrapper.getMcrCategoryIDs()); if (!categories.isEmpty()) { final MCRCategLinkReference objectReference = new MCRCategLinkReference(obj.getId()); MCRCategLinkServiceFactory.getInstance().setLinks(objectReference, categories); diff --git a/mycore-mods/src/main/java/org/mycore/mods/csl/MCRListModsItemDataProvider.java b/mycore-mods/src/main/java/org/mycore/mods/csl/MCRListModsItemDataProvider.java index 534bfce8fa..ef198b3742 100644 --- a/mycore-mods/src/main/java/org/mycore/mods/csl/MCRListModsItemDataProvider.java +++ b/mycore-mods/src/main/java/org/mycore/mods/csl/MCRListModsItemDataProvider.java @@ -23,6 +23,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.SequencedMap; import org.jdom2.Document; import org.jdom2.Element; @@ -44,7 +45,7 @@ public class MCRListModsItemDataProvider extends MCRItemDataProvider { protected static MCRCache cslCache = new MCRCache<>(2000, "CSL Mods Data"); - private LinkedHashMap store = new LinkedHashMap<>(); + private SequencedMap store = new LinkedHashMap<>(); @Override public void addContent(MCRContent content) throws IOException, JDOMException, SAXException { diff --git a/mycore-mods/src/main/java/org/mycore/mods/csl/MCRModsItemDataProvider.java b/mycore-mods/src/main/java/org/mycore/mods/csl/MCRModsItemDataProvider.java index 0290c3572b..1e49256d20 100644 --- a/mycore-mods/src/main/java/org/mycore/mods/csl/MCRModsItemDataProvider.java +++ b/mycore-mods/src/main/java/org/mycore/mods/csl/MCRModsItemDataProvider.java @@ -25,6 +25,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -127,7 +128,7 @@ private void processSubject(CSLItemDataBuilder idb) { .stream() .map(Element::getTextNormalize) .collect(Collectors.joining(", ")); - if (keyword.length() > 0) { + if (!keyword.isEmpty()) { idb.keyword(keyword); } } @@ -148,7 +149,7 @@ protected void processURL(String id, CSLItemDataBuilder idb) { .or(() -> Optional.ofNullable(wrapper.getElement("mods:location/mods:url")) .map(Element::getTextNormalize)) .or(() -> Optional.of(MCRFrontendUtil.getBaseURL() + "receive/" + id) - .filter(url -> this.wrapper.getMCRObject().getStructure().getDerivates().size() > 0)) + .filter(url -> !this.wrapper.getMCRObject().getStructure().getDerivates().isEmpty())) .or(() -> Optional.ofNullable(wrapper.getElement("mods:relatedItem[@type='host']/mods:location/mods:url")) .map(Element::getTextNormalize)) .ifPresent(idb::URL); @@ -429,7 +430,7 @@ protected void processTitles(CSLItemDataBuilder idb) { protected void processNames(CSLItemDataBuilder idb) { final List modsNameElements = wrapper.getElements("mods:name"); - HashMap> roleNameMap = new HashMap<>(); + Map> roleNameMap = new HashMap<>(); for (Element modsName : modsNameElements) { final CSLName cslName = buildName(modsName); if (isNameEmpty(cslName)) { @@ -440,7 +441,7 @@ protected void processNames(CSLItemDataBuilder idb) { mapRolesToCSLNames(idb, roleNameMap); - HashMap> parentRoleMap = new HashMap<>(); + Map> parentRoleMap = new HashMap<>(); final List parentModsNameElements = wrapper.getElements("mods:relatedItem/mods:name"); for (Element modsName : parentModsNameElements) { @@ -462,7 +463,7 @@ protected void processNames(CSLItemDataBuilder idb) { }); } - private void mapRolesToCSLNames(CSLItemDataBuilder idb, HashMap> roleNameMap) { + private void mapRolesToCSLNames(CSLItemDataBuilder idb, Map> roleNameMap) { roleNameMap.forEach((role, list) -> { final CSLName[] cslNames = list.toArray(list.toArray(new CSLName[0])); switch (role) { @@ -488,7 +489,7 @@ private void mapRolesToCSLNames(CSLItemDataBuilder idb, HashMap> roleNameMap, Element modsName, CSLName cslName) { + private void fillRoleMap(Map> roleNameMap, Element modsName, CSLName cslName) { final Element roleElement = modsName.getChild("role", MODS_NAMESPACE); if (roleElement != null) { final List roleTerms = roleElement.getChildren("roleTerm", MODS_NAMESPACE); @@ -512,7 +513,7 @@ private CSLName buildName(Element modsName) { nameBuilder.isInstitution(isInstitution); if (!isInstitution) { - HashMap> typeContentsMap = new HashMap<>(); + Map> typeContentsMap = new HashMap<>(); modsName.getChildren("namePart", MODS_NAMESPACE).forEach(namePart -> { final String type = namePart.getAttributeValue("type"); final String content = namePart.getTextNormalize(); @@ -582,7 +583,7 @@ protected String buildTitle(Element titleInfoElement) { .collect(Collectors.joining(" "))); final String subTitle = getModsElementTextStream(titleInfoElement, "subTitle").collect(Collectors.joining(" ")); - if (subTitle.length() > 0) { + if (!subTitle.isEmpty()) { titleBuilder.append(": ").append(subTitle); } diff --git a/mycore-mods/src/main/java/org/mycore/mods/rss/MCRRSSFeedImporter.java b/mycore-mods/src/main/java/org/mycore/mods/rss/MCRRSSFeedImporter.java index 02b7f4624c..702c8ce8f2 100644 --- a/mycore-mods/src/main/java/org/mycore/mods/rss/MCRRSSFeedImporter.java +++ b/mycore-mods/src/main/java/org/mycore/mods/rss/MCRRSSFeedImporter.java @@ -29,6 +29,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -261,7 +262,7 @@ private void sendNotificationMail(List importedObjects) throws Except xml.addContent(obj.createXML().detachRootElement()); } - HashMap parameters = new HashMap<>(); + Map parameters = new HashMap<>(); parameters.put(PROPERTY_MAIL_ADDRESS, MCRConfiguration2.getStringOrThrow(PROPERTY_MAIL_ADDRESS)); MCRMailer.sendMail(new Document(xml), xsl2BuildNotificationMail, parameters); } diff --git a/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/index/MCRNeo4JIndexEventHandler.java b/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/index/MCRNeo4JIndexEventHandler.java index cdc7593043..8d9ec72dc1 100644 --- a/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/index/MCRNeo4JIndexEventHandler.java +++ b/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/index/MCRNeo4JIndexEventHandler.java @@ -56,6 +56,7 @@ public class MCRNeo4JIndexEventHandler extends MCREventHandlerBase { private static final boolean ENABLED = MCRConfiguration2 .getString(MCRNeo4JConstants.DEFAULT_NEO4J_SERVER_URL).isPresent(); + @SuppressWarnings("PMD.LooseCoupling") private static final DelayQueue NEO4J_TASK_QUEUE = new DelayQueue<>(); private static final ScheduledExecutorService NEO4J_TASK_EXECUTOR = Executors.newSingleThreadScheduledExecutor(); diff --git a/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISolrSetHandler.java b/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISolrSetHandler.java index eb0fefd34d..82ed3a1e9f 100644 --- a/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISolrSetHandler.java +++ b/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISolrSetHandler.java @@ -32,7 +32,7 @@ public abstract class MCROAISolrSetHandler implements MCROAISetHandler setMap; + private Map setMap; @Override public void init(String configPrefix, String handlerPrefix) { diff --git a/mycore-ocfl/src/main/java/org/mycore/ocfl/commands/MCROCFLCommands.java b/mycore-ocfl/src/main/java/org/mycore/ocfl/commands/MCROCFLCommands.java index 611071512a..4fa5bbedaf 100644 --- a/mycore-ocfl/src/main/java/org/mycore/ocfl/commands/MCROCFLCommands.java +++ b/mycore-ocfl/src/main/java/org/mycore/ocfl/commands/MCROCFLCommands.java @@ -105,10 +105,10 @@ protected static void migrateWithPrunersAndRepositoryKeyOrMetadataManager(String migration.start(); - ArrayList success = migration.getSuccess(); - ArrayList failed = migration.getFailed(); - ArrayList invalidState = migration.getInvalidState(); - ArrayList withoutHistory = migration.getWithoutHistory(); + List success = migration.getSuccess(); + List failed = migration.getFailed(); + List invalidState = migration.getInvalidState(); + List withoutHistory = migration.getWithoutHistory(); LOGGER.info("The migration resulted in \n" + SUCCESS + ": {} \n" + diff --git a/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLCombineComparePruner.java b/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLCombineComparePruner.java index f08fd92e81..9ae4110d6b 100644 --- a/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLCombineComparePruner.java +++ b/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLCombineComparePruner.java @@ -44,7 +44,7 @@ public abstract class MCROCFLCombineComparePruner implements MCROCFLRevisionPrun @Override public List prune(List revisions) throws IOException, JDOMException { - ArrayList newRevisions = new ArrayList<>(); + List newRevisions = new ArrayList<>(); Iterator iterator = revisions.listIterator(); if (!iterator.hasNext()) { diff --git a/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLMigration.java b/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLMigration.java index 33ebddfaaf..8d494d24cf 100644 --- a/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLMigration.java +++ b/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLMigration.java @@ -44,13 +44,13 @@ public class MCROCFLMigration { private final MCROCFLXMLMetadataManager target; - private final ArrayList invalidState; + private final List invalidState; - private final ArrayList withoutHistory; + private final List withoutHistory; - private final ArrayList success; + private final List success; - private final ArrayList failed; + private final List failed; private final List pruners; @@ -76,19 +76,19 @@ public MCROCFLMigration(String newRepoKey, List pruners, this.pruners = pruners; } - public ArrayList getInvalidState() { + public List getInvalidState() { return invalidState; } - public ArrayList getWithoutHistory() { + public List getWithoutHistory() { return withoutHistory; } - public ArrayList getSuccess() { + public List getSuccess() { return success; } - public ArrayList getFailed() { + public List getFailed() { return failed; } diff --git a/mycore-pi/src/main/java/org/mycore/pi/MCRPIJobService.java b/mycore-pi/src/main/java/org/mycore/pi/MCRPIJobService.java index 75a4c27d08..f5f8a4c94e 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/MCRPIJobService.java +++ b/mycore-pi/src/main/java/org/mycore/pi/MCRPIJobService.java @@ -78,7 +78,7 @@ private static MCRJobQueue getJobQueue() { /** * Hook in to rollback mechanism of {@link MCRJobAction#rollback()} by overwriting this method. * - * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map)} + * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map)} * with piJobAction = 'DELETE' * @throws MCRPersistentIdentifierException throw {@link MCRPersistentIdentifierException} if something goes * wrong during rollback @@ -91,7 +91,7 @@ protected void rollbackDeleteJob(Map parameters) throws MCRPersi /** * Hook in to rollback mechanism of {@link MCRJobAction#rollback()} by overwriting this method. * - * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map)} + * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map)} * with piJobAction = 'UPDATE' * @throws MCRPersistentIdentifierException throw {@link MCRPersistentIdentifierException} if something goes * wrong during rollback @@ -104,7 +104,7 @@ protected void rollbackUpdateJob(Map parameters) throws MCRPersi /** * Hook in to rollback mechanism of {@link MCRJobAction#rollback()} by overwriting this method. * - * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map)} + * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map)} * with piJobAction = 'REGISTER' * @throws MCRPersistentIdentifierException throw {@link MCRPersistentIdentifierException} if something goes * wrong during rollback @@ -143,11 +143,11 @@ protected void delete(T identifier, MCRBase obj, String additional) throws MCRPe } /** - * Adds a job for a given PIAction, which will be called in the persistent {@link MCRJob} environment + * Adds a job for a given PIAction, which will be called in the persistent {@link MCRJob} environment * in an extra thread. * * @param piJobAction the action that the job executes (REGISTER, UPDATE, DELETE) - * + * * @param contextParameters pass parameters which are needed to register the PI. The parameter action and * registrationServiceID will be added, because they are necessary to reassign the job to * the right {@link MCRPIJobService} and method. @@ -233,7 +233,7 @@ protected Optional parseIdentifier(String identifier) { private MCRJob createJob(Map contextParameters, PiJobAction action) { MCRJob job = new MCRJob(MCRPIRegisterJobAction.class); - HashMap params = new HashMap<>(contextParameters); + Map params = new HashMap<>(contextParameters); params.put("action", action.toString()); params.put("registrationServiceID", this.getServiceID()); job.setParameters(params); @@ -370,7 +370,7 @@ protected void update(T identifier, MCRBase obj, String additional) protected abstract boolean validateRegistrationDocument(MCRBase obj, T identifier, String additional); - protected abstract HashMap createJobContextParams(PiJobAction action, MCRBase obj, T identifier, + protected abstract Map createJobContextParams(PiJobAction action, MCRBase obj, T identifier, String additional); public enum PiJobAction { diff --git a/mycore-pi/src/main/java/org/mycore/pi/MCRPIService.java b/mycore-pi/src/main/java/org/mycore/pi/MCRPIService.java index 494fd2256a..f0f44335d3 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/MCRPIService.java +++ b/mycore-pi/src/main/java/org/mycore/pi/MCRPIService.java @@ -132,7 +132,7 @@ public static void addFlagToObject(MCRBase obj, MCRPI databaseEntry) { */ public static MCRPI removeFlagFromObject(MCRBase obj, MCRPI databaseEntry) { MCRObjectService service = obj.getService(); - ArrayList flags = service.getFlags(PI_FLAG); + List flags = service.getFlags(PI_FLAG); int flagCount = flags.size(); for (int flagIndex = 0; flagIndex < flagCount; flagIndex++) { String flag = flags.get(flagIndex); @@ -155,7 +155,7 @@ public static boolean hasFlag(MCRObjectID id, String additional, MCRPIRegistrati public static boolean hasFlag(MCRBase obj, String additional, MCRPIRegistrationInfo mcrpi) { MCRObjectService service = obj.getService(); - ArrayList flags = service.getFlags(PI_FLAG); + List flags = service.getFlags(PI_FLAG); Gson gson = getGson(); return flags.stream().anyMatch(_stringFlag -> { MCRPI flag = gson.fromJson(_stringFlag, MCRPI.class); @@ -165,7 +165,7 @@ public static boolean hasFlag(MCRBase obj, String additional, MCRPIRegistrationI public static boolean hasFlag(MCRBase obj, String additional, MCRPIService piService) { MCRObjectService service = obj.getService(); - ArrayList flags = service.getFlags(PI_FLAG); + List flags = service.getFlags(PI_FLAG); Gson gson = getGson(); return flags.stream().anyMatch(_stringFlag -> { MCRPI flag = gson.fromJson(_stringFlag, MCRPI.class); @@ -461,7 +461,7 @@ protected MCRPI getTableEntry(MCRObjectID id, String additional) { public void updateFlag(MCRObjectID id, String additional, MCRPI mcrpi) { MCRBase obj = MCRMetadataManager.retrieve(id); MCRObjectService service = obj.getService(); - ArrayList flags = service.getFlags(PI_FLAG); + List flags = service.getFlags(PI_FLAG); Gson gson = getGson(); String stringFlag = flags.stream().filter(_stringFlag -> { MCRPI flag = gson.fromJson(_stringFlag, MCRPI.class); diff --git a/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIBaseService.java b/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIBaseService.java index 848efd675a..920495d175 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIBaseService.java +++ b/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIBaseService.java @@ -114,9 +114,9 @@ protected boolean checkJobValid(String mycoreID, PiJobAction action) { } @Override - protected HashMap createJobContextParams(PiJobAction action, MCRBase obj, + protected Map createJobContextParams(PiJobAction action, MCRBase obj, MCRDigitalObjectIdentifier doi, String additional) { - HashMap params = new HashMap<>(); + Map params = new HashMap<>(); params.put(CONTEXT_DOI, doi.asString()); params.put(CONTEXT_OBJ, obj.getId().toString()); return params; diff --git a/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIService.java b/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIService.java index 707f401ffd..96c75fde1d 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIService.java +++ b/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIService.java @@ -304,7 +304,7 @@ public void delete(MCRDigitalObjectIdentifier doi, MCRBase obj, String additiona LOGGER.warn("Object {} with registered doi {} got deleted. Try to set DOI inactive.", obj.getId(), doi.asString()); if (this.isRegistered(obj.getId(), additional)) { - HashMap contextParameters = new HashMap<>(); + Map contextParameters = new HashMap<>(); contextParameters.put(CONTEXT_DOI, doi.asString()); contextParameters.put(CONTEXT_OBJ, obj.getId().toString()); this.addJob(PiJobAction.DELETE, contextParameters); diff --git a/mycore-pi/src/main/java/org/mycore/pi/doi/cli/MCRDOICommands.java b/mycore-pi/src/main/java/org/mycore/pi/doi/cli/MCRDOICommands.java index 19a4a6a476..de7029be73 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/doi/cli/MCRDOICommands.java +++ b/mycore-pi/src/main/java/org/mycore/pi/doi/cli/MCRDOICommands.java @@ -235,7 +235,7 @@ public static void updateMediaListForDOI(String doiString, String serviceID) { oldMediaList = new ArrayList<>(); } - HashMap newHashMap = new HashMap<>(); + Map newHashMap = new HashMap<>(); newMediaList.forEach(e -> newHashMap.put(e.getKey(), e.getValue())); oldMediaList.forEach(e -> { diff --git a/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteClient.java b/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteClient.java index 3ddcf130a4..1ea1bf2aac 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteClient.java +++ b/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteClient.java @@ -133,7 +133,7 @@ private static String getStatusString(final ClassicHttpResponse resp) throws IOE public List> getMediaList(final MCRDigitalObjectIdentifier doi) throws MCRPersistentIdentifierException { - ArrayList> entries = new ArrayList<>(); + List> entries = new ArrayList<>(); URI requestURI = getRequestURI("/media/" + doi.asString()); HttpGet httpGet = new HttpGet(requestURI); diff --git a/mycore-pi/src/main/java/org/mycore/pi/frontend/resources/MCRPersistentIdentifierResolvingResource.java b/mycore-pi/src/main/java/org/mycore/pi/frontend/resources/MCRPersistentIdentifierResolvingResource.java index 4e435ad7cc..d5881b4351 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/frontend/resources/MCRPersistentIdentifierResolvingResource.java +++ b/mycore-pi/src/main/java/org/mycore/pi/frontend/resources/MCRPersistentIdentifierResolvingResource.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import org.mycore.pi.MCRPIManager; @@ -40,7 +41,7 @@ public class MCRPersistentIdentifierResolvingResource { @Path("{identifier:.+}") @Produces(MediaType.APPLICATION_JSON) public Response resolve(@PathParam("identifier") String identifier) { - HashMap> resolveMap = new HashMap<>(); + Map> resolveMap = new HashMap<>(); MCRPIManager.getInstance().getResolvers().forEach(resolver -> MCRPIManager .getInstance().get(identifier) .forEach(mcrPersistentIdentifier -> resolveMap.put(resolver.getName(), diff --git a/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicService.java b/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicService.java index 8e457b61c9..c67ec8da27 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicService.java +++ b/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicService.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -89,7 +90,7 @@ public class MCREpicService extends MCRPIJobService { @MCRProperty(name = "MetadataIndex", required = false) public String metadataIndex = null; - public ConcurrentHashMap idLockMap = new ConcurrentHashMap<>(); + public Map idLockMap = new ConcurrentHashMap<>(); public MCREpicService() { super("handle"); @@ -141,7 +142,7 @@ private void createOrUpdate(String epic, String objId) throws MCRPersistentIdent final String urlForObject = getURLForObject(objId); try { - final ArrayList handleInfos = new ArrayList<>(); + final List handleInfos = new ArrayList<>(); processMedataData(objectID, handleInfos); ReentrantLock reentrantLock = idLockMap.computeIfAbsent(epic, (l) -> new ReentrantLock()); @@ -157,7 +158,7 @@ private void createOrUpdate(String epic, String objId) throws MCRPersistentIdent } - private void processMedataData(MCRObjectID objectID, ArrayList handleInfos) throws IOException { + private void processMedataData(MCRObjectID objectID, List handleInfos) throws IOException { if (transformerID != null && metadataType != null && metadataIndex != null) { final int index = Integer.parseInt(metadataIndex, 10); final Document xml = MCRMetadataManager.retrieve(objectID).createXML(); @@ -186,9 +187,9 @@ protected Optional getJobInformation(Map contextParamete } @Override - protected HashMap createJobContextParams(PiJobAction action, MCRBase obj, MCRHandle epic, + protected Map createJobContextParams(PiJobAction action, MCRBase obj, MCRHandle epic, String additional) { - HashMap contextParameters = new HashMap<>(); + Map contextParameters = new HashMap<>(); contextParameters.put(EPIC_KEY, epic.asString()); contextParameters.put(OBJECT_ID_KEY, obj.getId().toString()); return contextParameters; diff --git a/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURLService.java b/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURLService.java index 9cb5870426..88507a82e1 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURLService.java +++ b/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURLService.java @@ -134,9 +134,9 @@ protected boolean validateRegistrationDocument(MCRBase obj, MCRPURL identifier, } @Override - protected HashMap createJobContextParams(PiJobAction action, MCRBase obj, MCRPURL purl, + protected Map createJobContextParams(PiJobAction action, MCRBase obj, MCRPURL purl, String additional) { - HashMap params = new HashMap<>(); + Map params = new HashMap<>(); params.put(CONTEXT_PURL, purl.asString()); params.put(CONTEXT_OBJECT, obj.getId().toString()); return params; diff --git a/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRURNGranularRESTService.java b/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRURNGranularRESTService.java index a9fb32cbdc..9e6122e721 100644 --- a/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRURNGranularRESTService.java +++ b/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRURNGranularRESTService.java @@ -31,6 +31,7 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; +import java.util.SequencedMap; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Predicate; @@ -144,7 +145,7 @@ private MCRDNBURN registerURN(MCRDerivate deriv, String filePath) throws MCRPers GranularURNGenerator granularURNGen = new GranularURNGenerator(seed, derivURN, setID); Function> generateURN = p -> granularURNGen.getURNSupplier(); - LinkedHashMap, MCRPath> urnPathMap = derivateFileStream.apply(deriv) + SequencedMap, MCRPath> urnPathMap = derivateFileStream.apply(deriv) .filter(notInIgnoreList().and(matchFile(filePath))) .sorted() .collect(Collectors.toMap(generateURN, p -> p, (m1, m2) -> m1, @@ -275,7 +276,7 @@ protected void update(MCRDNBURN identifier, MCRBase obj, String additional) { public void updateFlag(MCRObjectID id, String additional, MCRPI mcrpi) { MCRBase obj = MCRMetadataManager.retrieve(id); MCRObjectService service = obj.getService(); - ArrayList flags = service.getFlags(PI_FLAG); + List flags = service.getFlags(PI_FLAG); Gson gson = getGson(); //just update flag for derivate, where additional is "" diff --git a/mycore-restapi/src/main/java/org/mycore/restapi/MCRCORSResponseFilter.java b/mycore-restapi/src/main/java/org/mycore/restapi/MCRCORSResponseFilter.java index 285cdca6fe..a3104e966d 100644 --- a/mycore-restapi/src/main/java/org/mycore/restapi/MCRCORSResponseFilter.java +++ b/mycore-restapi/src/main/java/org/mycore/restapi/MCRCORSResponseFilter.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; @@ -119,7 +120,7 @@ public void filter(ContainerRequestContext requestContext, ContainerResponseCont private void addExposedHeadersToResponseHeaders(ContainerRequestContext requestContext, MultivaluedMap responseHeaders, boolean authenticatedRequest) { - ArrayList exposedHeaders = new ArrayList<>(); + List exposedHeaders = new ArrayList<>(); //MCR-3041 expose all header starting with X- responseHeaders.keySet().stream() .filter(name -> name.startsWith("x-") || name.startsWith("X-")) diff --git a/mycore-restapi/src/main/java/org/mycore/restapi/MCRSessionFilter.java b/mycore-restapi/src/main/java/org/mycore/restapi/MCRSessionFilter.java index 37aef95314..3b2e5cf104 100644 --- a/mycore-restapi/src/main/java/org/mycore/restapi/MCRSessionFilter.java +++ b/mycore-restapi/src/main/java/org/mycore/restapi/MCRSessionFilter.java @@ -222,7 +222,7 @@ private MCRUserInformation extractUserFromBasicAuth(String authorization) { return Optional.ofNullable(MCRUserManager.checkPassword(username, password)) .map(MCRUserInformation.class::cast) .orElseThrow(() -> { - LinkedHashMap attrs = new LinkedHashMap<>(); + Map attrs = new LinkedHashMap<>(); attrs.put("error", "invalid_login"); attrs.put("error_description", "Wrong login or password."); return new NotAuthorizedException(Response.status(Response.Status.UNAUTHORIZED) @@ -276,7 +276,7 @@ private MCRUserInformation extractUserFromBearerAuth(ContainerRequestContext req } } catch (JWTVerificationException e) { LOGGER.error(e.getMessage()); - LinkedHashMap attrs = new LinkedHashMap<>(); + Map attrs = new LinkedHashMap<>(); attrs.put("error", "invalid_token"); attrs.put("error_description", e.getMessage()); throw new NotAuthorizedException(e.getMessage(), e, diff --git a/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRWrappedXMLWriter.java b/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRWrappedXMLWriter.java index 55be672c9e..bc6247a9fb 100644 --- a/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRWrappedXMLWriter.java +++ b/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRWrappedXMLWriter.java @@ -29,6 +29,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Locale; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.function.Supplier; @@ -53,7 +54,7 @@ @Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_XML }) public class MCRWrappedXMLWriter implements MessageBodyWriter { - private static final ConcurrentHashMap CTX_MAP = new ConcurrentHashMap<>(); + private static final Map CTX_MAP = new ConcurrentHashMap<>(); private static final Predicate JAXB_CHECKER = type -> type.isAnnotationPresent(XmlRootElement.class) || type.isAnnotationPresent(XmlType.class); diff --git a/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPIUtil.java b/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPIUtil.java index 5a04a78dd3..3ac4c44d70 100644 --- a/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPIUtil.java +++ b/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPIUtil.java @@ -27,13 +27,13 @@ /** * This class contains some generic utility functions for the REST API - * + * * @author Thomas Scheffler (yagee) */ public class MCRRestAPIUtil { public static String getWWWAuthenticateHeader(String s, Map attributes, Application app) { - LinkedHashMap attrMap = new LinkedHashMap<>(); + Map attrMap = new LinkedHashMap<>(); String realm = app.getProperties() .getOrDefault(ServerProperties.APPLICATION_NAME, "REST API") .toString(); @@ -47,7 +47,7 @@ public static String getWWWAuthenticateHeader(String s, } private static void appendField(StringBuilder b, String field) { - if (b.length() > 0) { + if (!b.isEmpty()) { b.append(", "); } b.append(field); diff --git a/mycore-solr/src/main/java/org/mycore/solr/cloud/configsets/MCRSolrResourceConfigSetProvider.java b/mycore-solr/src/main/java/org/mycore/solr/cloud/configsets/MCRSolrResourceConfigSetProvider.java index 47382883bd..363df74fd2 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/cloud/configsets/MCRSolrResourceConfigSetProvider.java +++ b/mycore-solr/src/main/java/org/mycore/solr/cloud/configsets/MCRSolrResourceConfigSetProvider.java @@ -68,7 +68,7 @@ public void setBase(String base) { @Override public Supplier getStreamSupplier() { return () -> { - HashSet createdDirs = new HashSet<>(); + Set createdDirs = new HashSet<>(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try (ZipOutputStream outputStream = new ZipOutputStream(baos)) { List files = MCRConfiguration2.splitValue(this.getFilesString()).toList(); diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexEventHandler.java b/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexEventHandler.java index 4648b7a7cc..d68da15a44 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexEventHandler.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexEventHandler.java @@ -61,6 +61,7 @@ public class MCRSolrIndexEventHandler extends MCREventHandlerBase { private static long DELAY_IN_MS = MCRConfiguration2.getLong("MCR.Solr.DelayIndexing_inMS").orElse(2000L); + @SuppressWarnings("PMD.LooseCoupling") private static DelayQueue SOLR_TASK_QUEUE = new DelayQueue<>(); private static ScheduledExecutorService SOLR_TASK_EXECUTOR = Executors.newSingleThreadScheduledExecutor(); diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexer.java b/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexer.java index 858d4dcfd6..a48446100d 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexer.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexer.java @@ -28,6 +28,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; @@ -374,7 +375,7 @@ public static void rebuildMetadataIndex(List list, List sol MCRXMLMetadataManager metadataMgr = MCRXMLMetadataManager.instance(); MCRSolrIndexStatistic statistic = null; - HashMap contentMap = new HashMap<>((int) (BULK_SIZE * 1.4)); + Map contentMap = new HashMap<>((int) (BULK_SIZE * 1.4)); int i = 0; for (String id : list) { i++; diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/document/MCRSolrInputDocumentGenerator.java b/mycore-solr/src/main/java/org/mycore/solr/index/document/MCRSolrInputDocumentGenerator.java index 0bb20cc8fc..818475fa55 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/document/MCRSolrInputDocumentGenerator.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/document/MCRSolrInputDocumentGenerator.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -58,7 +59,7 @@ private static JAXBContext initContext() { public static SolrInputDocument getSolrInputDocument(MCRSolrInputDocument jaxbDoc) { SolrInputDocument doc = new SolrInputDocument(); - HashSet duplicateFilter = new HashSet<>(); + Set duplicateFilter = new HashSet<>(); for (Object o : jaxbDoc.getFieldOrDoc()) { if (o instanceof MCRSolrInputField field) { if (field.getValue().isEmpty() || duplicateFilter.contains(field)) { @@ -89,7 +90,7 @@ public static List getSolrInputDocument(MCRContent source) th } public static List getSolrInputDocuments(List inputDocuments) { - ArrayList returnList = new ArrayList<>(inputDocuments.size()); + List returnList = new ArrayList<>(inputDocuments.size()); for (MCRSolrInputDocument doc : inputDocuments) { returnList.add(getSolrInputDocument(doc)); } @@ -98,7 +99,7 @@ public static List getSolrInputDocuments(List duplicateFilter = new HashSet<>(); + Set duplicateFilter = new HashSet<>(); List fieldElements = input.getChildren("field"); for (Element fieldElement : fieldElements) { MCRSolrInputField field = new MCRSolrInputField(); diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/file/MCRSolrFileIndexBaseAccumulator.java b/mycore-solr/src/main/java/org/mycore/solr/index/file/MCRSolrFileIndexBaseAccumulator.java index 7545a0f44b..ef56e1acf8 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/file/MCRSolrFileIndexBaseAccumulator.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/file/MCRSolrFileIndexBaseAccumulator.java @@ -25,6 +25,7 @@ import java.util.Collection; import java.util.Date; import java.util.HashSet; +import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; @@ -77,7 +78,7 @@ public void accumulate(SolrInputDocument doc, Path input, BasicFileAttributes at doc.setField("derivateModified", getDerivateModified(ownerID)); Collection linksFromReference = MCRCategLinkServiceFactory.getInstance() .getLinksFromReference(new MCRCategLinkReference(mcrPath)); - HashSet linkedCategories = new HashSet<>(linksFromReference); + Set linkedCategories = new HashSet<>(linksFromReference); for (MCRCategoryID category : linksFromReference) { for (MCRCategory parent : CATEGORY_DAO.getParents(category)) { linkedCategories.add(parent.getId()); diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrIndexHandlerFactory.java b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrIndexHandlerFactory.java index 785e042bf3..9f96c275f9 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrIndexHandlerFactory.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrIndexHandlerFactory.java @@ -61,7 +61,7 @@ public MCRSolrIndexHandler getIndexHandler(MCRObjectID... ids) throws IOExceptio MCRContent content = MCRXMLMetadataManager.instance().retrieveContent(ids[0]); return getIndexHandler(content, ids[0]); } - HashMap contentMap = new HashMap<>(); + Map contentMap = new HashMap<>(); for (MCRObjectID id : ids) { MCRContent content = MCRXMLMetadataManager.instance().retrieveContent(id); contentMap.put(id, content); @@ -74,7 +74,7 @@ public MCRSolrIndexHandler getIndexHandler(MCRBase... derOrObjs) { MCRBaseContent content = new MCRBaseContent(derOrObjs[0]); return getIndexHandler(content, derOrObjs[0].getId()); } - HashMap contentMap = new HashMap<>(); + Map contentMap = new HashMap<>(); for (MCRBase derOrObj : derOrObjs) { MCRBaseContent content = new MCRBaseContent(derOrObj); contentMap.put(derOrObj.getId(), content); diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrLazyInputDocumentHandlerFactory.java b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrLazyInputDocumentHandlerFactory.java index 66f95b7daf..a0ed690d4b 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrLazyInputDocumentHandlerFactory.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrLazyInputDocumentHandlerFactory.java @@ -39,13 +39,10 @@ public MCRSolrIndexHandler getIndexHandler(MCRContent content, MCRObjectID id) { return new MCRSolrMCRContentIndexHandler(id, content, MCRSolrCoreType.MAIN); } - /* (non-Javadoc) - * @see org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory#getIndexHandler(java.util.Map) - */ @Override public MCRSolrIndexHandler getIndexHandler(Map contentMap) { //contentMap is reused in different threads - HashMap copyMap = new HashMap<>(contentMap); + Map copyMap = new HashMap<>(contentMap); return new MCRSolrMCRContentMapIndexHandler(copyMap, MCRSolrCoreType.MAIN); } diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/content/MCRSolrMCRContentMapIndexHandler.java b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/content/MCRSolrMCRContentMapIndexHandler.java index 3384635b35..9e3bec7d11 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/content/MCRSolrMCRContentMapIndexHandler.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/content/MCRSolrMCRContentMapIndexHandler.java @@ -87,7 +87,7 @@ public void index() { } if (LOGGER.isDebugEnabled()) { - ArrayList debugList = new ArrayList<>(); + List debugList = new ArrayList<>(); while (documents.hasNext()) { debugList.add(documents.next()); } @@ -98,7 +98,7 @@ public void index() { UpdateRequest req = new UpdateRequest(); getSolrAuthenticationFactory().applyAuthentication(req, MCRSolrAuthenticationLevel.INDEX); - ArrayList docs = new ArrayList<>(totalCount); + List docs = new ArrayList<>(totalCount); while (documents.hasNext()) { docs.add(documents.next()); } diff --git a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/MCRSolrFileIndexHandler.java b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/MCRSolrFileIndexHandler.java index a69c2d8211..6c6bc50c26 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/MCRSolrFileIndexHandler.java +++ b/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/MCRSolrFileIndexHandler.java @@ -25,6 +25,7 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; +import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -112,7 +113,7 @@ private ModifiableSolrParams getSolrParams(Path file, BasicFileAttributes attrs) } private String[] getValues(Collection values) { - ArrayList strValues = new ArrayList<>(values.size()); + List strValues = new ArrayList<>(values.size()); for (Object o : values) { strValues.add(o.toString()); } diff --git a/mycore-solr/src/main/java/org/mycore/solr/proxy/MCRSolrProxyServlet.java b/mycore-solr/src/main/java/org/mycore/solr/proxy/MCRSolrProxyServlet.java index 79813c26dd..2fb4242797 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/proxy/MCRSolrProxyServlet.java +++ b/mycore-solr/src/main/java/org/mycore/solr/proxy/MCRSolrProxyServlet.java @@ -75,7 +75,7 @@ /** * This class implements a proxy for access to the SOLR backend.

    * - * With the following configuration properties + * With the following configuration properties * you can manipulate the response header. The entries will be replace the attributes of the incomming header. * If the new attribute text is empty, it will be remove the attribute.

    * MCR.Solr.HTTPResponseHeader.{response_header_attribute_name}={new_response_header_attribute} @@ -179,7 +179,7 @@ static Map toMultiMap(ModifiableSolrParams solrQueryParameter) NamedList namedList = solrQueryParameter.toNamedList(); //disabled for MCR-953 and https://issues.apache.org/jira/browse/SOLR-7508 //Map parameters = ModifiableSolrParams.toMultiMap(namedList); - HashMap parameters = new HashMap<>(); + Map parameters = new HashMap<>(); for (int i = 0; i < namedList.size(); i++) { String name = namedList.getName(i); Object val = namedList.getVal(i); @@ -198,7 +198,7 @@ static Map toMultiMap(ModifiableSolrParams solrQueryParameter) */ private static void redirectToQueryHandler(Document input, HttpServletResponse resp) throws IOException { - LinkedHashMap parameters = new LinkedHashMap<>(); + Map parameters = new LinkedHashMap<>(); List children = input.getRootElement().getChildren(); for (Element param : children) { String attribute = param.getAttributeValue("name"); @@ -342,7 +342,7 @@ public void destroy() { private static ModifiableSolrParams toSolrParams(Map parameters) { // to maintain order - LinkedHashMap copy = new LinkedHashMap<>(parameters); + Map copy = new LinkedHashMap<>(parameters); ModifiableSolrParams solrParams = new ModifiableSolrParams(copy); if (!parameters.containsKey("version") && !parameters.containsKey("wt")) { solrParams.set("version", SOLR_QUERY_XML_PROTOCOL_VERSION); diff --git a/mycore-solr/src/main/java/org/mycore/solr/search/MCRConditionTransformer.java b/mycore-solr/src/main/java/org/mycore/solr/search/MCRConditionTransformer.java index 853875e82a..1cbf07d76a 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/search/MCRConditionTransformer.java +++ b/mycore-solr/src/main/java/org/mycore/solr/search/MCRConditionTransformer.java @@ -62,7 +62,7 @@ public class MCRConditionTransformer { */ protected static final String MIXED = "--mixed--"; - private static volatile HashSet joinFields = null; + private static volatile Set joinFields = null; public static String toSolrQueryString(@SuppressWarnings("rawtypes") MCRCondition condition, Set usedFields) { @@ -182,7 +182,7 @@ private static StringBuilder handleNotCondition(MCRNotCondition notCond, Set 0 ? returnFields.stream().collect(Collectors.joining(",")) : "*"); + q.setFields(!returnFields.isEmpty() ? returnFields.stream().collect(Collectors.joining(",")) : "*"); } String sort = q.getSortField(); LOGGER.info("MyCoRe Query transformed to: {}{} {}", q.getQuery(), sort != null ? " " + sort : "", @@ -299,17 +299,17 @@ public static SolrQuery applySortOptions(SolrQuery q, List sortBy) { /** * Builds SOLR query. - * + * * Automatically builds JOIN-Query if content search fields are used in query. * @param sortBy sort criteria * @param not true, if all conditions should be negated - * @param and AND or OR connective between conditions + * @param and AND or OR connective between conditions * @param table conditions per "content" or "metadata" * @param maxHits maximum hits */ @SuppressWarnings("rawtypes") public static SolrQuery buildMergedSolrQuery(List sortBy, boolean not, boolean and, - HashMap> table, int maxHits, List returnFields) { + Map> table, int maxHits, List returnFields) { List queryConditions = table.get("metadata"); MCRCondition combined = buildSubCondition(queryConditions, and, not); SolrQuery solrRequestQuery = getSolrQuery(combined, sortBy, maxHits, returnFields); @@ -346,9 +346,8 @@ protected static MCRCondition buildSubCondition(List conditions, b * index */ @SuppressWarnings("rawtypes") - public static HashMap> groupConditionsByIndex(MCRSetCondition cond) { - HashMap> table = new HashMap<>(); - @SuppressWarnings("unchecked") + public static Map> groupConditionsByIndex(MCRSetCondition cond) { + Map> table = new HashMap<>(); List children = cond.getChildren(); for (MCRCondition child : children) { @@ -385,7 +384,7 @@ public static String getIndex(String fieldName) { return getJoinFields().contains(fieldName) ? "content" : "metadata"; } - private static HashSet getJoinFields() { + private static Set getJoinFields() { if (joinFields == null) { synchronized (MCRConditionTransformer.class) { if (joinFields == null) { diff --git a/mycore-solr/src/main/java/org/mycore/solr/search/MCRQLSearchUtils.java b/mycore-solr/src/main/java/org/mycore/solr/search/MCRQLSearchUtils.java index 568d5cbdb1..6d79bb9b9b 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/search/MCRQLSearchUtils.java +++ b/mycore-solr/src/main/java/org/mycore/solr/search/MCRQLSearchUtils.java @@ -19,12 +19,11 @@ package org.mycore.solr.search; import java.util.ArrayList; -import java.util.Arrays; import java.util.Enumeration; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.StringTokenizer; import org.apache.logging.log4j.LogManager; @@ -48,8 +47,8 @@ public class MCRQLSearchUtils { private static final Logger LOGGER = LogManager.getLogger(MCRQLSearchUtils.class); - private static HashSet SEARCH_PARAMETER = new HashSet<>(Arrays.asList("search", "query", "maxResults", - "numPerPage", "page", "mask", "mode", "redirect", "qt")); + private static Set SEARCH_PARAMETER = Set.of("search", "query", "maxResults", + "numPerPage", "page", "mask", "mode", "redirect", "qt"); /** * Build MCRQuery from editor XML input @@ -114,7 +113,7 @@ protected static void renameElements(Element element) { element.setAttribute("operator", operator); List values = element.getChildren("value"); - if (values != null && values.size() > 0) { + if (values != null && !values.isEmpty()) { element.removeAttribute("field"); element.setAttribute("operator", "or"); element.setName("boolean"); @@ -209,7 +208,7 @@ protected static Document setQueryOptions(MCRQuery query, HttpServletRequest req } } - if (sortFields.size() > 0) { + if (!sortFields.isEmpty()) { sortFields.sort((arg0, arg1) -> { String s0 = arg0.substring(arg0.indexOf(".sortField")); String s1 = arg1.substring(arg1.indexOf(".sortField")); @@ -233,7 +232,7 @@ protected static Document setQueryOptions(MCRQuery query, HttpServletRequest req protected static String getReqParameter(HttpServletRequest req, String name, String defaultValue) { String value = req.getParameter(name); - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return defaultValue; } else { return value.trim(); diff --git a/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchServlet.java b/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchServlet.java index 01ca741072..95b82bb125 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchServlet.java +++ b/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchServlet.java @@ -113,7 +113,7 @@ private enum SolrParameterGroup { private void addFieldToQuery(StringBuilder query, String[] fieldValues, String fieldName, QueryType queryType) throws ServletException { for (String fieldValue : fieldValues) { - if (fieldValue.length() == 0) { + if (fieldValue.isEmpty()) { continue; } switch (queryType) { @@ -137,11 +137,11 @@ private void addFieldToQuery(StringBuilder query, String[] fieldValues, String f protected Map buildSelectParameterMap(Map queryParameters, Map typeParameters, Map sortParameters, Set phraseQuery) throws ServletException { - HashMap queryParameterMap = new HashMap<>(); + Map queryParameterMap = new HashMap<>(); - HashMap fieldTypeMap = createFieldTypeMap(typeParameters); + Map fieldTypeMap = createFieldTypeMap(typeParameters); - HashMap filterQueryMap = new HashMap<>(); + Map filterQueryMap = new HashMap<>(); StringBuilder query = new StringBuilder(); for (Entry queryParameter : queryParameters.entrySet()) { String fieldName = queryParameter.getKey(); @@ -194,7 +194,7 @@ private String buildSolrSortParameter(Map sortParameters) { } } - ArrayList sortedPositions = new ArrayList<>(positionFieldMap.keySet()); + List sortedPositions = new ArrayList<>(positionFieldMap.keySet()); Collections.sort(sortedPositions); StringBuilder sortBuilder = new StringBuilder(); @@ -210,7 +210,7 @@ private String buildSolrSortParameter(Map sortParameters) { } sortBuilder.append(order); } - if (sortBuilder.length() != 0) { + if (!sortBuilder.isEmpty()) { sortBuilder.deleteCharAt(0); } @@ -222,8 +222,8 @@ private String buildSolrSortParameter(Map sortParameters) { * the type of the field as value. * */ - private HashMap createFieldTypeMap(Map typeParameters) { - HashMap fieldTypeMap = new HashMap<>(); + private Map createFieldTypeMap(Map typeParameters) { + Map fieldTypeMap = new HashMap<>(); for (Entry currentType : typeParameters.entrySet()) { for (String typeMember : currentType.getValue()) { @@ -289,7 +289,7 @@ protected void extractParameterList(Map requestParameter, Map< case QueryParameter -> { String[] strings = currentEntry.getValue(); for (String v : strings) { - if (v != null && v.length() > 0) { + if (v != null && !v.isEmpty()) { queryParameter.put(parameterName, currentEntry.getValue()); } } @@ -308,7 +308,7 @@ protected void extractParameterList(Map requestParameter, Map< * a map wich contains all {@link StringBuilder} * @return a {@link StringBuilder} for the specific fieldType */ - private StringBuilder getFilterQueryBuilder(HashMap filterQueryMap, String fieldType) { + private StringBuilder getFilterQueryBuilder(Map filterQueryMap, String fieldType) { if (!filterQueryMap.containsKey(fieldType)) { filterQueryMap.put(fieldType, new StringBuilder(JOIN_PATTERN)); } diff --git a/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchUtils.java b/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchUtils.java index 0e3afa94cc..f499fb780c 100644 --- a/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchUtils.java +++ b/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchUtils.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Spliterator; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -85,7 +86,7 @@ public static SolrQuery getSolrQuery(MCRQuery query, Document input, HttpServlet int rows = query.getNumPerPage(); List returnFields = query.getReturnFields(); MCRCondition condition = query.getCondition(); - HashMap> table; + Map> table; if (condition instanceof MCRSetCondition setCondition) { table = MCRConditionTransformer.groupConditionsByIndex(setCondition); @@ -94,7 +95,7 @@ public static SolrQuery getSolrQuery(MCRQuery query, Document input, HttpServlet LOGGER.warn("Condition is not SetCondition."); table = new HashMap<>(); - ArrayList conditionList = new ArrayList<>(); + List conditionList = new ArrayList<>(); conditionList.add(condition); table.put("metadata", conditionList); diff --git a/mycore-sword/src/main/java/org/mycore/sword/MCRSword.java b/mycore-sword/src/main/java/org/mycore/sword/MCRSword.java index c3440f1dcf..5c9a4b71f4 100644 --- a/mycore-sword/src/main/java/org/mycore/sword/MCRSword.java +++ b/mycore-sword/src/main/java/org/mycore/sword/MCRSword.java @@ -20,9 +20,11 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.Hashtable; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; @@ -36,9 +38,9 @@ public class MCRSword { private static final Logger LOGGER = LogManager.getLogger(MCRSword.class); - private static volatile Hashtable collections = null; + private static volatile Map collections = null; - private static volatile Hashtable> workspaceCollectionTable = null; + private static volatile Map> workspaceCollectionTable = null; private static void initConfigThreadSafe() { if (collections == null) { @@ -51,8 +53,8 @@ private static void initConfigThreadSafe() { } private static void initConfig() { - collections = new Hashtable<>(); - workspaceCollectionTable = new Hashtable<>(); + collections = new ConcurrentHashMap<>(); + workspaceCollectionTable = new ConcurrentHashMap<>(); LOGGER.info("--- INITIALIZE SWORD SERVER ---"); final int lengthOfPropertyPrefix = MCRSwordConstants.MCR_SWORD_COLLECTION_PREFIX.length(); MCRConfiguration2.getPropertiesMap() diff --git a/mycore-sword/src/main/java/org/mycore/sword/MCRSwordUtil.java b/mycore-sword/src/main/java/org/mycore/sword/MCRSwordUtil.java index 5f24e00ba6..af0a4fb94c 100644 --- a/mycore-sword/src/main/java/org/mycore/sword/MCRSwordUtil.java +++ b/mycore-sword/src/main/java/org/mycore/sword/MCRSwordUtil.java @@ -312,7 +312,7 @@ public static List validateZipFile(final MCRFileValidator v throws IOException, URISyntaxException { try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFile.toUri()), new HashMap<>())) { final Path sourcePath = zipfs.getPath("/"); - ArrayList validationResults = new ArrayList<>(); + List validationResults = new ArrayList<>(); Files.walkFileTree(sourcePath, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { @@ -355,7 +355,7 @@ public static DepositReceipt buildDepositReceipt(IRI iri) { public static void addDatesToEntry(Entry entry, MCRObject mcrObject) { MCRObjectService serviceElement = mcrObject.getService(); - ArrayList flags = serviceElement.getFlags(MCRObjectService.FLAG_TYPE_CREATEDBY); + List flags = serviceElement.getFlags(MCRObjectService.FLAG_TYPE_CREATEDBY); flags.addAll(serviceElement.getFlags(MCRObjectService.FLAG_TYPE_MODIFIEDBY)); Set clearedFlags = new LinkedHashSet<>(flags); clearedFlags.forEach(entry::addAuthor); @@ -435,7 +435,7 @@ public static Integer getPaginationFromCollectionIRI(IRI collectionIRI) { Matcher matcher = COLLECTION_IRI_PATTERN.matcher(uriPathAsString); if (matcher.matches() && matcher.groupCount() > 1) { String numberGroup = matcher.group(2); - if (numberGroup.length() > 0) { + if (!numberGroup.isEmpty()) { return Integer.parseInt(numberGroup); } } diff --git a/mycore-tei/src/main/java/org/mycore/tei/MCRTEIValidator.java b/mycore-tei/src/main/java/org/mycore/tei/MCRTEIValidator.java index 45d9c83ec0..2e054c3d27 100644 --- a/mycore-tei/src/main/java/org/mycore/tei/MCRTEIValidator.java +++ b/mycore-tei/src/main/java/org/mycore/tei/MCRTEIValidator.java @@ -20,8 +20,9 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.Hashtable; +import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.xml.XMLConstants; import javax.xml.transform.Source; @@ -43,22 +44,22 @@ public class MCRTEIValidator implements ErrorHandler { */ public static final String MCR_TRANSCRIPTION_SCHEMA = "xsd/mcrtranscr.xsd"; - /** - * Exception map key: fatalError + /** + * Exception map key: fatalError */ public static final String FATAL_ERROR = "fatalError"; - /** - * Exception map key: error + /** + * Exception map key: error */ public static final String ERROR = "error"; - /** - * Exception map key: warning + /** + * Exception map key: warning */ public static final String WARNING = "warning"; - private Hashtable> exceptionMap; + private Map> exceptionMap; private Source teiSource; @@ -69,7 +70,7 @@ public class MCRTEIValidator implements ErrorHandler { public MCRTEIValidator(Source teiSource) { this.teiSource = teiSource; - this.exceptionMap = new Hashtable<>(); + this.exceptionMap = new HashMap<>(); this.exceptionMap.put(WARNING, new ArrayList<>()); this.exceptionMap.put(ERROR, new ArrayList<>()); this.exceptionMap.put(FATAL_ERROR, new ArrayList<>()); diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRRealm.java b/mycore-user2/src/main/java/org/mycore/user2/MCRRealm.java index cd4d518a4b..78c3df42ed 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRRealm.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRRealm.java @@ -22,6 +22,7 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Map; import java.util.Map.Entry; import org.mycore.common.MCRConstants; @@ -29,10 +30,10 @@ import org.mycore.common.config.MCRConfiguration2; /** - * Represents a realm of users. Each user belongs to a realm. Realms are configured + * Represents a realm of users. Each user belongs to a realm. Realms are configured * in the file realms.xml. A realm determines the method that is used to login the user. * There is always a local default realm, which is defined by the attribute local in realms.xml. - * + * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ @@ -41,7 +42,7 @@ public class MCRRealm { private String id; /** The labels of the realm */ - private HashMap labels = new HashMap<>(); + private Map labels = new HashMap<>(); /** The URL where users from this realm can change their password */ private String passwordChangeURL; @@ -61,9 +62,9 @@ public class MCRRealm { public static final String USER_INFORMATION_ATTR = "realmId"; - /** + /** * Creates a new realm. - * + * * @param id the unique ID of the realm */ MCRRealm(String id) { @@ -72,7 +73,7 @@ public class MCRRealm { /** * Returns the unique ID of the realm. - * + * * @return the unique ID of the realm. */ public String getID() { @@ -102,29 +103,29 @@ void setLabel(String lang, String label) { labels.put(lang, label); } - /** - * Returns the URL where users from this realm can change their password + /** + * Returns the URL where users from this realm can change their password */ public String getPasswordChangeURL() { return passwordChangeURL; } - /** - * Sets the URL where users from this realm can change their password + /** + * Sets the URL where users from this realm can change their password */ void setPasswordChangeURL(String url) { this.passwordChangeURL = url; } - /** - * Returns the URL where users from this realm can login + /** + * Returns the URL where users from this realm can login */ public String getLoginURL() { return loginURL; } - /** - * Sets the URL where users from this realm can login + /** + * Sets the URL where users from this realm can login */ void setLoginURL(String url) { this.loginURL = url; @@ -170,7 +171,7 @@ public String toString() { * @return the same as {@link #getLoginURL()} if redirectParameter is undefined for this realm */ public String getLoginURL(String redirectURL) { - LinkedHashMap parameter = new LinkedHashMap<>(); + Map parameter = new LinkedHashMap<>(); String redirect = getRedirectParameter(); if (redirect != null && redirectURL != null) { parameter.put(redirect, redirectURL); diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRRealmFactory.java b/mycore-user2/src/main/java/org/mycore/user2/MCRRealmFactory.java index eb9ecd82ce..0a9b014b70 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRRealmFactory.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRRealmFactory.java @@ -25,6 +25,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; @@ -63,9 +64,9 @@ public class MCRRealmFactory { private static long lastModified = 0; /** Map of defined realms, key is the ID of the realm */ - private static HashMap realmsMap = new HashMap<>(); + private static Map realmsMap = new HashMap<>(); - private static HashMap attributeMapper = new HashMap<>(); + private static Map attributeMapper = new HashMap<>(); /** List of defined realms */ private static List realmsList = new ArrayList<>(); @@ -119,9 +120,9 @@ private static void loadRealms() { throw new MCRException("Could not load realms from URI: " + realmsURI); } String localRealmID = root.getAttributeValue("local"); - HashMap realmsMap = new HashMap<>(); + Map realmsMap = new HashMap<>(); - HashMap attributeMapper = new HashMap<>(); + Map attributeMapper = new HashMap<>(); List realmsList = new ArrayList<>(); @@ -178,7 +179,7 @@ private static Document getRealms() throws JDOMException, TransformerException, /** * Returns the realm with the given ID. - * + * * @param id the ID of the realm * @return the realm with that ID, or null */ @@ -194,7 +195,7 @@ public static MCRUserAttributeMapper getAttributeMapper(String id) { /** * Returns a list of all defined realms. - * + * * @return a list of all realms. */ public static List listRealms() { @@ -203,7 +204,7 @@ public static List listRealms() { } /** - * Returns the Realms JDOM document clone. + * Returns the Realms JDOM document clone. */ public static Document getRealmsDocument() { reInitIfNeeded(); @@ -220,7 +221,7 @@ static Source getRealmsSource() { /** * Returns the local default realm, as specified by the attribute 'local' in realms.xml - * + * * @return the local default realm. */ public static MCRRealm getLocalRealm() { diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRRole.java b/mycore-user2/src/main/java/org/mycore/user2/MCRRole.java index 2c671a1485..ae80bdba3e 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRRole.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRRole.java @@ -20,6 +20,7 @@ import java.util.Collection; import java.util.HashMap; +import java.util.Map; import java.util.Set; import org.mycore.common.MCRSessionMgr; @@ -34,7 +35,7 @@ * Represents a role of users. * Roles are {@link MCRCategory} instances and every category from {@link MCRUser2Constants#ROLE_CLASSID} * {@link MCRRole#isSystemRole()}. - * + * * @author Thomas Scheffler (yagee) */ @XmlRootElement(name = "role") @@ -44,7 +45,7 @@ public class MCRRole { private String name; /** The labels of the role */ - private HashMap labels; + private Map labels; private boolean isSystemRole; @@ -53,8 +54,8 @@ private MCRRole() { } /** - * Creates a new role instance. - * + * Creates a new role instance. + * * @param name the unique role ID * @param labels a set of MCRLabel in different languages */ @@ -68,7 +69,7 @@ public MCRRole(String name, Set labels) { /** * Returns the roles's name - * + * * @return the roles's name */ @XmlAttribute @@ -85,7 +86,7 @@ public MCRLabel getLabel() { } /** - * Returns all labels available for this role. + * Returns all labels available for this role. */ public Collection getLabels() { return labels.values(); @@ -93,7 +94,7 @@ public Collection getLabels() { /** * Returns true if this role is a system role. - * A system role is every category in {@link MCRUser2Constants#ROLE_CLASSID}. + * A system role is every category in {@link MCRUser2Constants#ROLE_CLASSID}. * @return false if category has not the same root ID as the system role classification. */ public boolean isSystemRole() { diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRRoleManager.java b/mycore-user2/src/main/java/org/mycore/user2/MCRRoleManager.java index 778e3a0798..8b80ae17da 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRRoleManager.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRRoleManager.java @@ -23,6 +23,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; @@ -40,7 +41,7 @@ /** * Manages roles and role assignments using a database table. - * + * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ @@ -49,7 +50,7 @@ public class MCRRoleManager { private static Logger LOGGER = LogManager.getLogger(MCRRoleManager.class); /** Map of defined roles, key is the unique role name */ - private static HashMap rolesByName = new HashMap<>(); + private static Map rolesByName = new HashMap<>(); /** List of all defined roles */ private static List rolesList = new ArrayList<>(); @@ -85,7 +86,7 @@ private static void loadSystemRoles() { /** * Returns the role with the given role name, or null. - * + * * @param name the unique role name * @return the role with the given role name, or null. */ @@ -118,7 +119,7 @@ public static MCRRole getExternalRole(String name) { } /** - * Returns a role array for the given role names. + * Returns a role array for the given role names. * @param names unique role names * @return array each element either MCRRole instance, or null */ @@ -149,7 +150,7 @@ public static Collection getRoles(Collection names) { /** * Returns a list of all defined roles - * + * * @return a list of all defined roles */ public static List listSystemRoles() { @@ -158,7 +159,7 @@ public static List listSystemRoles() { /** * Removes user from all roles - * + * * @param user the user to remove from all roles */ static void unassignRoles(MCRUser user) { @@ -167,8 +168,8 @@ static void unassignRoles(MCRUser user) { /** * Stores role membership information of the user - * - * @param user the user + * + * @param user the user */ static void storeRoleAssignments(MCRUser user) { MCRCategLinkReference ref = getLinkID(user); @@ -203,7 +204,7 @@ private static MCRCategLinkReference getLinkID(MCRUser user) { /** * Adds role to the classification system. * If the representing {@link MCRCategory} already exists this method does nothing. - * It will create any category if necessary. + * It will create any category if necessary. */ public static void addRole(MCRRole role) { MCRCategoryID categoryID = null; diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRRoleServlet.java b/mycore-user2/src/main/java/org/mycore/user2/MCRRoleServlet.java index 354bd58e2f..3f9797cfb1 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRRoleServlet.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRRoleServlet.java @@ -111,7 +111,7 @@ private void chooseRoleRoot(HttpServletRequest request) { } private Collection getRoleElements() { - ArrayList list = new ArrayList<>(roleCategories.size()); + List list = new ArrayList<>(roleCategories.size()); for (MCRCategoryID categID : roleCategories) { Element role = new Element("role"); role.setAttribute("categID", categID.toString()); diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRUser.java b/mycore-user2/src/main/java/org/mycore/user2/MCRUser.java index aae44c3b18..b7913e8657 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRUser.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRUser.java @@ -24,6 +24,7 @@ import java.util.Collection; import java.util.Date; import java.util.HashSet; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -686,7 +687,7 @@ private MCRRole[] getRoles() { if (getSystemRoleIDs().isEmpty() && getExternalRoleIDs().isEmpty()) { return null; } - ArrayList roleIds = new ArrayList<>(getSystemRoleIDs().size() + getExternalRoleIDs().size()); + List roleIds = new ArrayList<>(getSystemRoleIDs().size() + getExternalRoleIDs().size()); Collection roles = new ArrayList<>(roleIds.size()); roleIds.addAll(getSystemRoleIDs()); roleIds.addAll(getExternalRoleIDs()); diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRUserAttributeMapper.java b/mycore-user2/src/main/java/org/mycore/user2/MCRUserAttributeMapper.java index 0faa562986..41e29f57df 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRUserAttributeMapper.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRUserAttributeMapper.java @@ -64,7 +64,7 @@ * <attribute name="userName" mapping="eduPersonPrincipalName" /> * <attribute name="realName" mapping="displayName" /> * <attribute name="eMail" mapping="mail" /> - * <attribute name="roles" mapping="eduPersonAffiliation" separator="," + * <attribute name="roles" mapping="eduPersonAffiliation" separator="," * converter="org.mycore.user2.utils.MCRRolesConverter"> * <valueMapping name="employee">editor</valueMapping> * </attribute> @@ -75,7 +75,7 @@ * </realms> * * - * + * * @author René Adler (eagle) * */ @@ -83,7 +83,7 @@ public class MCRUserAttributeMapper { private static Logger LOGGER = LogManager.getLogger(MCRUserAttributeMapper.class); - private HashMap> attributeMapping = new HashMap<>(); + private Map> attributeMapping = new HashMap<>(); public static MCRUserAttributeMapper instance(Element attributeMapping) { try { @@ -103,7 +103,7 @@ public static MCRUserAttributeMapper instance(Element attributeMapping) { /** * Maps configured attributes to {@link Object}. - * + * * @param object the {@link Object} * @param attributes a collection of attributes to map * @return true if any attribute was changed @@ -212,7 +212,7 @@ private boolean updateFieldOrMethod(Object object, Object annotated, Attribute a /** * Returns a collection of mapped attribute names. - * + * * @return a collection of mapped attribute names */ public Set getAttributeNames() { diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRUserCommands.java b/mycore-user2/src/main/java/org/mycore/user2/MCRUserCommands.java index ba4c83584c..785b3ec3ac 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRUserCommands.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRUserCommands.java @@ -374,7 +374,7 @@ public static List exportAllUserToDirectory(String directory) { throw new MCRException("Directory does not exist: " + dir.getAbsolutePath()); } List users = MCRUserManager.listUsers(null, null, null, null); - ArrayList commands = new ArrayList<>(users.size()); + List commands = new ArrayList<>(users.size()); for (MCRUser user : users) { File userFile = new File(dir, user.getUserID() + ".xml"); commands.add("export user " + user.getUserID() + " to file " + userFile.getAbsolutePath()); @@ -408,7 +408,7 @@ public static List batchLoadFromDirectory(String cmd, String directory) return null; } Arrays.sort(listFiles); - ArrayList cmds = new ArrayList<>(listFiles.length); + List cmds = new ArrayList<>(listFiles.length); for (File file : listFiles) { cmds.add(new MessageFormat("{0} {1}", Locale.ROOT).format(new Object[] { cmd, file.getAbsolutePath() })); } diff --git a/mycore-user2/src/main/java/org/mycore/user2/MCRUserManager.java b/mycore-user2/src/main/java/org/mycore/user2/MCRUserManager.java index 84a5cc056e..2d18402f6a 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/MCRUserManager.java +++ b/mycore-user2/src/main/java/org/mycore/user2/MCRUserManager.java @@ -344,10 +344,10 @@ private static boolean isValidSearchPattern(String searchPattern) { private static Predicate[] buildCondition(CriteriaBuilder cb, Root root, String userPattern, String realm, String namePattern, String mailPattern, String attributeNamePattern, String attributeValuePattern) { - ArrayList predicates = new ArrayList<>(2); + List predicates = new ArrayList<>(2); addEqualsPredicate(cb, root, MCRUser_.realmID, realm, predicates); - ArrayList searchPredicates = new ArrayList<>(3); + List searchPredicates = new ArrayList<>(3); addSearchPredicate(cb, root, MCRUser_.userName, userPattern, searchPredicates); addSearchPredicate(cb, root, MCRUser_.realName, namePattern, searchPredicates); addSearchPredicate(cb, root, MCRUser_.EMail, mailPattern, searchPredicates); @@ -376,14 +376,14 @@ private static Predicate[] buildCondition(CriteriaBuilder cb, Root root } private static void addEqualsPredicate(CriteriaBuilder cb, Root root, - SingularAttribute attribute, String string, ArrayList predicates) { + SingularAttribute attribute, String string, List predicates) { if (isValidSearchPattern(string)) { predicates.add(cb.equal(root.get(attribute), string)); } } private static void addSearchPredicate(CriteriaBuilder cb, Root root, - SingularAttribute attribute, String searchPattern, ArrayList predicates) { + SingularAttribute attribute, String searchPattern, List predicates) { if (isValidSearchPattern(searchPattern)) { predicates.add(buildSearchPredicate(cb, root, attribute, searchPattern)); } diff --git a/mycore-user2/src/main/java/org/mycore/user2/login/MCRLDAPClient.java b/mycore-user2/src/main/java/org/mycore/user2/login/MCRLDAPClient.java index 76aaf2dcd5..62189dca24 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/login/MCRLDAPClient.java +++ b/mycore-user2/src/main/java/org/mycore/user2/login/MCRLDAPClient.java @@ -47,36 +47,36 @@ /** * Queries an LDAP server for the user's properties. - * - * # Timeout when connecting to LDAP server + * + * # Timeout when connecting to LDAP server * MCR.user2.LDAP.ReadTimeout=5000 - * + * * # LDAP server * MCR.user2.LDAP.ProviderURL=ldap://idp.uni-duisburg-essen.de - * + * * # Security principal for logging in at LDAP server * MCR.user2.LDAP.SecurityPrincipal=cn=duepublico,dc=idp - * + * * # Security credentials for logging in at LDAP server * MCR.user2.LDAP.SecurityCredentials=XXXXXX - * + * * # Base DN * MCR.user2.LDAP.BaseDN=ou=people,dc=idp - * + * * # Filter for user ID * MCR.user2.LDAP.UIDFilter=(uid=%s) - * + * * # LDAP attribute mappings - * + * * # Mapping from LDAP attribute to real name of user * MCR.user2.LDAP.Mapping.Name=cn - * + * * # Mapping from LDAP attribute to E-Mail address of user * MCR.user2.LDAP.Mapping.E-Mail=mail - * - * # Mapping of any attribute.value combination to group membership of user + * + * # Mapping of any attribute.value combination to group membership of user * MCR.user2.LDAP.Mapping.Group.eduPersonScopedAffiliation.staff@uni-duisburg-essen.de=creators - * + * * # Default group membership (optional) * MCR.user2.LDAP.Mapping.Group.DefaultGroup=submitters * @@ -103,6 +103,7 @@ public class MCRLDAPClient { /** Default group of user */ private MCRRole defaultGroup; + @SuppressWarnings("PMD.LooseCoupling") private Hashtable ldapEnv; private MCRLDAPClient() { diff --git a/mycore-user2/src/main/java/org/mycore/user2/login/MCRLoginServlet.java b/mycore-user2/src/main/java/org/mycore/user2/login/MCRLoginServlet.java index afce69539c..d0133af7a1 100644 --- a/mycore-user2/src/main/java/org/mycore/user2/login/MCRLoginServlet.java +++ b/mycore-user2/src/main/java/org/mycore/user2/login/MCRLoginServlet.java @@ -62,8 +62,8 @@ * Provides functionality to select login method, * change login user and show a welcome page. * Login methods and realms are configured in realms.xml. - * The login form for local users is login.xml. - * + * The login form for local users is login.xml. + * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ @@ -95,7 +95,7 @@ protected static String getReturnURL(HttpServletRequest req) { } protected static void addFormFields(MCRLogin login, String loginToRealm) { - ArrayList fields = new ArrayList<>(); + List fields = new ArrayList<>(); if (loginToRealm != null) { //realmParameter MCRRealm realm = MCRRealmFactory.getRealm(loginToRealm); @@ -171,7 +171,7 @@ public void init() throws ServletException { * MCRLoginServlet?url=foo&realm=ID * stores foo as redirect url and redirects * to the login URL of the given realm. - + * MCRLoginServlet?action=login * checks input from editor login form and * changes the current login user and redirects diff --git a/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationI18nItem.java b/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationI18nItem.java index 0f741abff4..e06fdf00cd 100644 --- a/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationI18nItem.java +++ b/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationI18nItem.java @@ -19,6 +19,7 @@ package org.mycore.wcms2.datamodel; import java.util.HashMap; +import java.util.Map; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; @@ -32,7 +33,7 @@ public abstract class MCRNavigationI18nItem implements MCRNavigationBaseItem { @XmlAttribute(name = "i18nKey") private String i18nKey; - private HashMap labelMap; + private Map labelMap; public MCRNavigationI18nItem() { this.labelMap = new HashMap<>(); diff --git a/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSFileBrowserResource.java b/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSFileBrowserResource.java index 373cf8e8e9..b9ee295311 100644 --- a/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSFileBrowserResource.java +++ b/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSFileBrowserResource.java @@ -24,6 +24,7 @@ import java.io.OutputStream; import java.nio.file.Files; import java.util.ArrayList; +import java.util.List; import java.util.Objects; import javax.xml.parsers.DocumentBuilder; @@ -69,7 +70,7 @@ @MCRRestrictedAccess(MCRWCMSPermission.class) public class MCRWCMSFileBrowserResource { - private final ArrayList folderList = new ArrayList<>(); + private final List folderList = new ArrayList<>(); private static final Logger LOGGER = LogManager.getLogger(); @@ -271,7 +272,7 @@ protected JsonObject getFolder(File node, boolean folderallowed) { } } } - if (jsonArray.size() > 0) { + if (!jsonArray.isEmpty()) { jsonObj.add("children", jsonArray); } return jsonObj; diff --git a/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSNavigationResource.java b/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSNavigationResource.java index 0598ee9cd0..a269a4832f 100644 --- a/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSNavigationResource.java +++ b/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSNavigationResource.java @@ -104,7 +104,7 @@ public Response save(String json) throws Exception { } /** - * Returns a json object containing all available templates. + * Returns a json object containing all available templates. */ @GET @Path("templates") @@ -113,7 +113,7 @@ public String getTemplates(@Context ServletContext servletContext) { // templates of navigation.xml Document xml = MCRWCMSNavigationUtils.getNavigationAsXML(); List elementList = TEMPLATE_PATH.evaluate(xml); - HashSet entries = elementList.stream() + Set entries = elementList.stream() .map(e -> e.getAttributeValue("template")) .collect(Collectors.toCollection(HashSet::new)); diff --git a/mycore-webcli/src/main/java/org/mycore/webcli/cli/MCRWebCLICommandManager.java b/mycore-webcli/src/main/java/org/mycore/webcli/cli/MCRWebCLICommandManager.java index cd23d41daa..c8a2bf957b 100644 --- a/mycore-webcli/src/main/java/org/mycore/webcli/cli/MCRWebCLICommandManager.java +++ b/mycore-webcli/src/main/java/org/mycore/webcli/cli/MCRWebCLICommandManager.java @@ -19,7 +19,7 @@ package org.mycore.webcli.cli; import java.util.List; -import java.util.TreeMap; +import java.util.SortedMap; import org.apache.logging.log4j.LogManager; import org.mycore.frontend.cli.MCRCommand; @@ -27,7 +27,7 @@ /** * @author Thomas Scheffler (yagee) - * + * */ public class MCRWebCLICommandManager extends MCRCommandManager { @@ -45,7 +45,7 @@ protected void initBuiltInCommands() { addAnnotatedCLIClass(MCRBasicWebCLICommands.class); } - public TreeMap> getCommandsMap() { + public SortedMap> getCommandsMap() { return knownCommands; } diff --git a/mycore-webcli/src/main/java/org/mycore/webcli/flow/MCRCommandListProcessor.java b/mycore-webcli/src/main/java/org/mycore/webcli/flow/MCRCommandListProcessor.java index 715a67e2c8..606df93f56 100644 --- a/mycore-webcli/src/main/java/org/mycore/webcli/flow/MCRCommandListProcessor.java +++ b/mycore-webcli/src/main/java/org/mycore/webcli/flow/MCRCommandListProcessor.java @@ -40,7 +40,7 @@ public void onSubscribe(Flow.Subscription subscription) { @Override public void onNext(List item) { try { - ArrayList copy; + List copy; synchronized (item) { copy = new ArrayList<>(item); } diff --git a/mycore-webtools/src/main/java/org/mycore/webtools/properties/MCRPropertyHelper.java b/mycore-webtools/src/main/java/org/mycore/webtools/properties/MCRPropertyHelper.java index e762a4414c..d945b9db5c 100644 --- a/mycore-webtools/src/main/java/org/mycore/webtools/properties/MCRPropertyHelper.java +++ b/mycore-webtools/src/main/java/org/mycore/webtools/properties/MCRPropertyHelper.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.Optional; import java.util.Properties; +import java.util.SequencedMap; import java.util.concurrent.atomic.AtomicReference; import org.mycore.common.config.MCRConfigurationInputStream; @@ -33,18 +34,18 @@ class MCRPropertyHelper { - private final LinkedHashMap configFileContents; + private final SequencedMap configFileContents; MCRPropertyHelper() throws IOException { configFileContents = MCRConfigurationInputStream.getConfigFileContents("mycore.properties"); } - public Map> analyzeProperties() { + public SequencedMap> analyzeProperties() { Properties properties = new MCRProperties(); Properties currentProperties = new MCRProperties(); final AtomicReference oldProperties = new AtomicReference(null); - LinkedHashMap> analyzedProperties = new LinkedHashMap<>(); + SequencedMap> analyzedProperties = new LinkedHashMap<>(); for (Map.Entry componentContentEntry : configFileContents.entrySet()) { String component = componentContentEntry.getKey(); diff --git a/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRFileUploadBucket.java b/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRFileUploadBucket.java index ed2305fcc4..8274a476e1 100644 --- a/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRFileUploadBucket.java +++ b/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRFileUploadBucket.java @@ -43,7 +43,7 @@ */ public class MCRFileUploadBucket implements MCRSessionListener, MCRShutdownHandler.Closeable { - private static final ConcurrentHashMap BUCKET_MAP = new ConcurrentHashMap<>(); + private static final Map BUCKET_MAP = new ConcurrentHashMap<>(); private final String bucketID; diff --git a/mycore-wfc/src/main/java/org/mycore/wfc/mail/MCRMailEventHandler.java b/mycore-wfc/src/main/java/org/mycore/wfc/mail/MCRMailEventHandler.java index 86ae6d0858..0c8fc76316 100644 --- a/mycore-wfc/src/main/java/org/mycore/wfc/mail/MCRMailEventHandler.java +++ b/mycore-wfc/src/main/java/org/mycore/wfc/mail/MCRMailEventHandler.java @@ -40,9 +40,9 @@ /** * Uses "e-mail-events.xsl" to transform derivate, object and files to emails. - * + * * See {@link MCRMailer} for email xml format. - * + * * @author Thomas Scheffler (yagee) * */ @@ -52,7 +52,7 @@ public class MCRMailEventHandler extends MCREventHandlerBase { private void sendNotificationMail(MCREvent evt, MCRContent doc, String description) throws Exception { LOGGER.info("Preparing mail for: {}", description); - HashMap parameters = new HashMap<>(); + Map parameters = new HashMap<>(); for (Map.Entry entry : evt.entrySet()) { parameters.put(entry.getKey(), entry.getValue().toString()); } diff --git a/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXEditorTransformer.java b/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXEditorTransformer.java index 7a496f4d51..4a3d25b23a 100644 --- a/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXEditorTransformer.java +++ b/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXEditorTransformer.java @@ -117,7 +117,7 @@ public void setCancelURL(String cancelURL) { public void initializePostprocessor(Node postProcessorNode) { NamedNodeMap attributes = postProcessorNode.getAttributes(); int attributesLength = attributes.getLength(); - HashMap attributeMap = new HashMap<>(); + Map attributeMap = new HashMap<>(); for (int i = 0; i < attributesLength; i++) { Attr item = (Attr) attributes.item(i); // this should be save because we called getAttributes earlier String attrName = item.getName(); diff --git a/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRValidationResults.java b/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRValidationResults.java index bf05e1402d..1b8fe7b8f8 100644 --- a/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRValidationResults.java +++ b/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRValidationResults.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import java.util.SequencedMap; import org.mycore.common.config.MCRConfiguration2; @@ -42,7 +43,7 @@ public class MCRValidationResults { private Map xPath2Marker = new HashMap<>(); - private LinkedHashMap xPath2FailedRule = new LinkedHashMap<>(); + private SequencedMap xPath2FailedRule = new LinkedHashMap<>(); private boolean isValid = true; diff --git a/ruleset.xml b/ruleset.xml index 0e5ac2b463..c66c1aaae5 100644 --- a/ruleset.xml +++ b/ruleset.xml @@ -44,10 +44,17 @@ --> - - + + + + + >