SLING-11361 : Sonor findings (excluding complexity)
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/JcrListenerBaseConfig.java b/src/main/java/org/apache/sling/jcr/resource/internal/JcrListenerBaseConfig.java
index bc9ddf4..2351efd 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/JcrListenerBaseConfig.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/JcrListenerBaseConfig.java
@@ -79,7 +79,8 @@
final OakEventFilter filter = FilterFactory.wrap(new JackrabbitEventFilter());
// paths
final Set<String> paths = config.getPaths().toStringSet();
- int globCount = 0, pathCount = 0;
+ int globCount = 0;
+ int pathCount = 0;
for (final String p : paths) {
if (p.startsWith(Path.GLOB_PREFIX)) {
globCount++;
@@ -140,7 +141,7 @@
* @param c The configuration
* @return The event type mask
*/
- private int getTypes(final ObserverConfiguration c) {
+ private static int getTypes(final ObserverConfiguration c) {
int result = 0;
for (ChangeType t : c.getChangeTypes()) {
switch (t) {
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/JcrResourceListener.java b/src/main/java/org/apache/sling/jcr/resource/internal/JcrResourceListener.java
index de06723..122a2bb 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/JcrResourceListener.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/JcrResourceListener.java
@@ -154,21 +154,20 @@
}
- private ResourceChange createResourceChange(final Event event,
- final String path,
- final ChangeType changeType) {
- final String fullPath = path;
- final boolean isExternal = this.isExternal(event);
+ private static ResourceChange createResourceChange(final Event event,
+ final String path,
+ final ChangeType changeType) {
+ final boolean isExternal = isExternal(event);
final String userId;
if (!isExternal) {
userId = event.getUserID();
} else {
userId = null;
}
- return new JcrResourceChange(changeType, fullPath, isExternal, userId);
+ return new JcrResourceChange(changeType, path, isExternal, userId);
}
- private boolean isExternal(final Event event) {
+ private static boolean isExternal(final Event event) {
if (event instanceof JackrabbitEvent) {
final JackrabbitEvent jEvent = (JackrabbitEvent) event;
return jEvent.isExternal();
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/JcrSystemUserValidator.java b/src/main/java/org/apache/sling/jcr/resource/internal/JcrSystemUserValidator.java
index f5268cf..2260089 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/JcrSystemUserValidator.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/JcrSystemUserValidator.java
@@ -17,7 +17,6 @@
package org.apache.sling.jcr.resource.internal;
import java.lang.reflect.Method;
-import java.security.Principal;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
@@ -206,12 +205,7 @@
}
}
- Authorizable authorizable = userManager.getAuthorizable(new Principal() {
- @Override
- public String getName() {
- return pName;
- }
- });
+ Authorizable authorizable = userManager.getAuthorizable(() -> pName);
if (isValidSystemUser(authorizable)) {
validPrincipalNames.add(pName);
log.debug("The provided service principal name {} is a known JCR system user", pName);
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/JcrValueMap.java b/src/main/java/org/apache/sling/jcr/resource/internal/JcrValueMap.java
index 99b098d..ede96f4 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/JcrValueMap.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/JcrValueMap.java
@@ -132,8 +132,7 @@
public Object get(final Object aKey) {
final String key = checkKey(aKey.toString());
final JcrPropertyMapCacheEntry entry = this.read(key);
- final Object value = (entry == null ? null : entry.getPropertyValueOrNull());
- return value;
+ return (entry == null ? null : entry.getPropertyValueOrNull());
}
/**
@@ -236,7 +235,7 @@
// calculate the key
final String name = prop.getName();
String key = null;
- if (name.indexOf("_x") != -1) {
+ if (name.contains("_x")) {
// for compatibility with older versions we use the (wrong)
// ISO9075 path encoding
key = ISO9075.decode(name);
@@ -391,7 +390,7 @@
// ---------- Implementation helper
- private Class<?> normalizeClass(Class<?> type) {
+ private static Class<?> normalizeClass(Class<?> type) {
if (Calendar.class.isAssignableFrom(type)) {
type = Calendar.class;
} else if (Date.class.isAssignableFrom(type)) {
@@ -404,7 +403,7 @@
return type;
}
- private Map<String, Object> transformEntries(final Map<String, JcrPropertyMapCacheEntry> map) {
+ private static Map<String, Object> transformEntries(final Map<String, JcrPropertyMapCacheEntry> map) {
final Map<String, Object> transformedEntries = new LinkedHashMap<>(map.size());
for (final Map.Entry<String, JcrPropertyMapCacheEntry> entry : map.entrySet())
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/NodeUtil.java b/src/main/java/org/apache/sling/jcr/resource/internal/NodeUtil.java
index a8351f1..a108b58 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/NodeUtil.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/NodeUtil.java
@@ -25,6 +25,7 @@
import static javax.jcr.nodetype.NodeType.NT_FROZEN_NODE;
import static javax.jcr.nodetype.NodeType.NT_LINKED_FILE;
+import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -38,6 +39,8 @@
import org.jetbrains.annotations.NotNull;
public abstract class NodeUtil {
+
+ private NodeUtil() {}
/**
* Update the mixin node types
@@ -49,9 +52,7 @@
public static void handleMixinTypes(final Node node, final String[] mixinTypes) throws RepositoryException {
final Set<String> newTypes = new HashSet<>();
if (mixinTypes != null) {
- for (final String value : mixinTypes) {
- newTypes.add(value);
- }
+ Collections.addAll(newTypes, mixinTypes);
}
final Set<String> oldTypes = new HashSet<>();
for (final NodeType mixinType : node.getMixinNodeTypes()) {
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/BooleanConverter.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/BooleanConverter.java
index 7c9e20e..939d2ea 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/BooleanConverter.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/BooleanConverter.java
@@ -43,7 +43,7 @@
}
private Integer getNumber() {
- return ( value.booleanValue() ? 1 : 0);
+ return (value.booleanValue() ? 1 : 0);
}
/**
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntry.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntry.java
index 71afa07..49c7d4b 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntry.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntry.java
@@ -26,6 +26,7 @@
import java.io.Serializable;
import java.lang.reflect.Array;
import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
@@ -47,7 +48,7 @@
public class JcrPropertyMapCacheEntry {
/** Global logger */
- private static Logger LOGGER = LoggerFactory.getLogger(JcrPropertyMapCacheEntry.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(JcrPropertyMapCacheEntry.class);
/** The JCR property - only set for existing values. */
private final Property property;
@@ -87,21 +88,21 @@
// check if values can be stored in JCR
if (isArray) {
final Object[] values = convertToObjectArray(value);
- for (int i = 0; i < values.length; i++) {
- failIfCannotStore(values[i], node);
+ for (Object o : values) {
+ failIfCannotStore(o, node);
}
} else {
failIfCannotStore(value, node);
}
}
- private void failIfCannotStore(final Object value, final Node node) throws RepositoryException {
+ private static void failIfCannotStore(final Object value, final Node node) throws RepositoryException {
if (value instanceof InputStream) {
// InputStream is storable and calling createValue for nothing
// eats its contents
return;
}
- final Value val = this.createValue(value, node);
+ final Value val = createValue(value, node);
if (val == null) {
throw new IllegalArgumentException("Value can't be stored in the repository: " + value);
}
@@ -117,7 +118,7 @@
* @param node the node
* @return the converted value
*/
- private Value createValue(final Object obj, final Node node) throws RepositoryException {
+ private static Value createValue(final Object obj, final Node node) throws RepositoryException {
final Session session = node.getSession();
Value value = JcrResourceUtil.createValue(obj, session);
if (value == null && obj instanceof Serializable) {
@@ -140,7 +141,7 @@
* @param value The array
* @return an object array
*/
- private Object[] convertToObjectArray(final Object value) {
+ private static Object[] convertToObjectArray(final Object value) {
final Object[] values;
if (value instanceof long[]) {
values = ArrayUtils.toObject((long[]) value);
@@ -229,17 +230,10 @@
}
}
- } catch (final NumberFormatException vfe) {
- LOGGER.info("converToType: Cannot convert value of " + this.getPropertyValueOrNull()
- + " to " + type, vfe);
- } catch (final IllegalArgumentException vfe) {
- LOGGER.info("converToType: Cannot convert value of " + this.getPropertyValueOrNull()
- + " to " + type, vfe);
- } catch (final ValueFormatException vfe) {
- LOGGER.info("converToType: Cannot convert value of " + this.getPropertyValueOrNull()
- + " to " + type, vfe);
+ } catch (final IllegalArgumentException | ValueFormatException vfe) {
+ LOGGER.info("convertToType: Cannot convert value of {} to {}.", this.getPropertyValueOrNull(), type, vfe);
} catch (RepositoryException re) {
- LOGGER.info("converToType: Cannot get value of " + this.getPropertyValueOrNull(), re);
+ LOGGER.info("convertToType: Cannot get value of {}", this.getPropertyValueOrNull(), re);
}
// fall back to nothing
@@ -306,7 +300,7 @@
baos.write(buffer, 0, l);
}
}
- value = new String(baos.toByteArray(), "UTF-8");
+ value = new String(baos.toByteArray(), StandardCharsets.UTF_8);
} catch (final IOException e) {
throw new IllegalArgumentException(e);
} finally {
@@ -327,9 +321,7 @@
return (T) obj;
}
value = obj;
- } catch (final ClassNotFoundException cnfe) {
- // ignore and use fallback
- } catch (final IOException ioe) {
+ } catch (final ClassNotFoundException | IOException cnfe) {
// ignore and use fallback
} finally {
if (ois != null) {
@@ -381,7 +373,7 @@
return (T) ZonedDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId().normalized());
} else if (Value.class == type) {
- return (T) this.createValue(value, node);
+ return (T) createValue(value, node);
} else if (Property.class == type) {
return (T) this.property;
@@ -397,7 +389,7 @@
* @param value The object to convert
* @return A converter for {@code value}
*/
- private Converter getConverter(final Object value) {
+ private static Converter getConverter(final Object value) {
if (value instanceof Number) {
// byte, short, int, long, double, float, BigDecimal
return new NumberConverter((Number) value);
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrResourceUtil.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrResourceUtil.java
index 0b35906..94dbe1d 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrResourceUtil.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/JcrResourceUtil.java
@@ -40,6 +40,8 @@
*
*/
public class JcrResourceUtil {
+
+ private JcrResourceUtil() {}
/**
* Helper method to execute a JCR query.
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BasicQueryLanguageProvider.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BasicQueryLanguageProvider.java
index e178f2f..2bc3bfc 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BasicQueryLanguageProvider.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BasicQueryLanguageProvider.java
@@ -40,6 +40,7 @@
import org.apache.sling.spi.resource.provider.ProviderContext;
import org.apache.sling.spi.resource.provider.QueryLanguageProvider;
import org.apache.sling.spi.resource.provider.ResolveContext;
+import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -98,85 +99,91 @@
try {
final QueryResult result = JcrResourceUtil.query(ctx.getProviderState().getSession(), query, queryLanguage);
- final String[] colNames = result.getColumnNames();
- final RowIterator rows = result.getRows();
-
- return new Iterator<ValueMap>() {
-
- private ValueMap next;
-
- {
- next = seek();
- }
-
- @Override
- public boolean hasNext() {
- return next != null;
- }
-
- @Override
- public ValueMap next() {
- if (next == null) {
- throw new NoSuchElementException();
- }
- final ValueMap result = next;
- next = seek();
- return result;
- }
-
- private ValueMap seek() {
- ValueMap result = null;
- while (result == null && rows.hasNext()) {
- try {
- final Row jcrRow = rows.nextRow();
- final String resourcePath = jcrRow.getPath();
- if (resourcePath != null && providerContext.getExcludedPaths().matches(resourcePath) == null) {
- final Map<String, Object> row = new HashMap<>();
-
- boolean didPath = false;
- boolean didScore = false;
- final Value[] values = jcrRow.getValues();
- for (int i = 0; i < values.length; i++) {
- Value v = values[i];
- if (v != null) {
- String colName = colNames[i];
- row.put(colName,
- JcrResourceUtil.toJavaObject(values[i]));
- if (colName.equals(QUERY_COLUMN_PATH)) {
- didPath = true;
- row.put(colName, JcrResourceUtil.toJavaObject(values[i]).toString());
- }
- if (colName.equals(QUERY_COLUMN_SCORE)) {
- didScore = true;
- }
- }
- }
- if (!didPath) {
- row.put(QUERY_COLUMN_PATH, jcrRow.getPath());
- }
- if (!didScore) {
- row.put(QUERY_COLUMN_SCORE, jcrRow.getScore());
- }
- result = new ValueMapDecorator(row);
- }
- } catch (final RepositoryException re) {
- logger.error("queryResources$next: Problem accessing row values", re);
- }
- }
- return result;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException("remove");
- }
- };
+ return new ValueMapIterator(result.getColumnNames(), result.getRows());
} catch (final javax.jcr.query.InvalidQueryException iqe) {
throw new QuerySyntaxException(iqe.getMessage(), query, language, iqe);
} catch (final RepositoryException re) {
throw new SlingException(re.getMessage(), re);
}
-
}
+ private class ValueMapIterator implements Iterator<ValueMap> {
+
+ private final String[] colNames;
+ private final RowIterator rows;
+
+ private ValueMap next;
+
+ private ValueMapIterator(@NotNull String[] colNames, @NotNull RowIterator rows) {
+ this.colNames = colNames;
+ this.rows = rows;
+
+ next = seek();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return next != null;
+ }
+
+ @Override
+ public ValueMap next() {
+ if ( next == null ) {
+ throw new NoSuchElementException();
+ }
+ final ValueMap result = next;
+ next = seek();
+ return result;
+ }
+
+ private ValueMap seek() {
+ ValueMap result = null;
+ while (result == null && rows.hasNext()) {
+ try {
+ final Row jcrRow = rows.nextRow();
+ final String resourcePath = jcrRow.getPath();
+ if (resourcePath != null && providerContext.getExcludedPaths().matches(resourcePath) == null) {
+ result = new ValueMapDecorator(getRow(jcrRow));
+ }
+ } catch (final RepositoryException re) {
+ logger.error("queryResources$next: Problem accessing row values", re);
+ }
+ }
+ return result;
+ }
+
+ private Map<String, Object> getRow(@NotNull Row jcrRow) throws RepositoryException {
+ final Map<String, Object> row = new HashMap<>();
+
+ boolean didPath = false;
+ boolean didScore = false;
+ final Value[] values = jcrRow.getValues();
+ for (int i = 0; i < values.length; i++) {
+ Value v = values[i];
+ if (v != null) {
+ String colName = colNames[i];
+ row.put(colName, JcrResourceUtil.toJavaObject(values[i]));
+ if (colName.equals(QUERY_COLUMN_PATH)) {
+ didPath = true;
+ row.put(colName, JcrResourceUtil.toJavaObject(values[i]).toString());
+ }
+ if (colName.equals(QUERY_COLUMN_SCORE)) {
+ didScore = true;
+ }
+ }
+ }
+ if (!didPath) {
+ row.put(QUERY_COLUMN_PATH, jcrRow.getPath());
+ }
+ if (!didScore) {
+ row.put(QUERY_COLUMN_SCORE, jcrRow.getScore());
+ }
+ return row;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("remove");
+ }
+ }
}
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProvider.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProvider.java
index 8c9e6f1..640dbc3 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProvider.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProvider.java
@@ -104,7 +104,7 @@
return NodeUtil.getPrimaryProperty(node);
}
- private boolean isRelevantScopeAndOperation(@NotNull Scope scope, @NotNull Operation operation) {
+ private static boolean isRelevantScopeAndOperation(@NotNull Scope scope, @NotNull Operation operation) {
return ((Scope.PUBLIC.equals(scope) || Scope.EXTERNAL.equals(scope)) && Operation.READ.equals(operation));
}
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactory.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactory.java
index 96bc306..23c03cd 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactory.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactory.java
@@ -70,8 +70,7 @@
*/
public JcrItemResource<?> createResource(final ResourceResolver resourceResolver, final String resourcePath,
final Resource parent, final Map<String, String> parameters) throws RepositoryException {
- final String jcrPath = resourcePath;
- if (jcrPath == null) {
+ if (resourcePath == null) {
log.debug("createResource: {} maps to an empty JCR path", resourcePath);
return null;
}
@@ -98,7 +97,7 @@
}
item = getSubitem(parentNode, subPath);
} else {
- item = getItemOrNull(jcrPath);
+ item = getItemOrNull(resourcePath);
}
if (item != null && version != null) {
@@ -106,7 +105,7 @@
}
if (item == null) {
- log.debug("createResource: No JCR Item exists at path '{}'", jcrPath);
+ log.debug("createResource: No JCR Item exists at path '{}'", resourcePath);
return null;
} else {
final JcrItemResource<?> resource;
@@ -153,7 +152,7 @@
return null;
}
} catch (RepositoryException e) {
- log.debug("getSubitem: Can't get subitem {} of {}: {}", relPath, node.toString(), e.toString());
+ log.debug("getSubitem: Can't get subitem {} of {}: {}", relPath, node, e.toString());
return null;
}
}
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResource.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResource.java
index 2662923..912ffd0 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResource.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResource.java
@@ -52,7 +52,7 @@
})
class JcrNodeResource extends JcrItemResource<Node> { // this should be package private, see SLING-1414
- /** marker value for the resourceSupertType before trying to evaluate */
+ /** marker value for the resourceSuperType before trying to evaluate */
private static final String UNSET_RESOURCE_SUPER_TYPE = "<unset>";
/** default log */
@@ -178,7 +178,7 @@
data = NodeUtil.getPrimaryProperty(node);
} catch (ItemNotFoundException infe) {
// we don't actually care, but log for completeness
- LOGGER.debug("getInputStream: No primary items for {}", toString(), infe);
+ LOGGER.debug("getInputStream: No primary items for {}", this, infe);
data = null;
}
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceMetadata.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceMetadata.java
index 1000d4e..155464b 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceMetadata.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceMetadata.java
@@ -47,7 +47,7 @@
private static final long serialVersionUID = 1L;
/** default log */
- private static final Logger LOGGER = LoggerFactory.getLogger(JcrNodeResource.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(JcrNodeResourceMetadata.class);
private final Node node;
private Node contentNode;
@@ -89,7 +89,7 @@
} catch (RepositoryException e) {
// ignore
}
- LOGGER.info("setMetaData: Problem extracting metadata information for " + nodePath, re);
+ LOGGER.info("setMetaData: Problem extracting metadata information for {}", nodePath, re);
}
@Override
@@ -180,7 +180,7 @@
return null;
}
- private Item getPrimaryItem(final Node node) throws RepositoryException {
+ private static Item getPrimaryItem(final Node node) throws RepositoryException {
String name = node.getPrimaryNodeType().getPrimaryItemName();
if (name == null) {
return null;
@@ -240,14 +240,11 @@
if (super.containsKey(key)) {
return true;
}
- if (CREATION_TIME.equals(key) ||
+ return CREATION_TIME.equals(key) ||
CONTENT_TYPE.equals(key) ||
CHARACTER_ENCODING.equals(key) ||
MODIFICATION_TIME.equals(key) ||
- CONTENT_LENGTH.equals(key)) {
- return true;
- }
- return false;
+ CONTENT_LENGTH.equals(key);
}
@Override
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrProviderStateFactory.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrProviderStateFactory.java
index 0bc3063..a31976d 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrProviderStateFactory.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrProviderStateFactory.java
@@ -20,7 +20,6 @@
import static org.apache.sling.api.resource.ResourceResolverFactory.NEW_PASSWORD;
-import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
@@ -71,7 +70,7 @@
* @throws LoginException if no calling bundle info provided
*/
@Nullable
- private Bundle extractCallingBundle(@NotNull Map<String, Object> authenticationInfo) throws LoginException {
+ private static Bundle extractCallingBundle(@NotNull Map<String, Object> authenticationInfo) throws LoginException {
final Object obj = authenticationInfo.get(ResourceProvider.AUTH_SERVICE_BUNDLE);
if (obj != null && !(obj instanceof Bundle)) {
throw new LoginException("Invalid calling bundle object in authentication info");
@@ -285,9 +284,7 @@
* copied as credentials attributes.
*/
private static void copyAttributes(final SimpleCredentials target, final Map<String, Object> source) {
- final Iterator<Map.Entry<String, Object>> i = source.entrySet().iterator();
- while (i.hasNext()) {
- final Map.Entry<String, Object> current = i.next();
+ for (Map.Entry<String, Object> current : source.entrySet()) {
if (isAttributeVisible(current.getKey())) {
target.setAttribute(current.getKey(), current.getValue());
}
diff --git a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrResourceProvider.java b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrResourceProvider.java
index f2bb1a7..d9cbf5c 100644
--- a/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrResourceProvider.java
+++ b/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrResourceProvider.java
@@ -123,13 +123,13 @@
private final AtomicReference<DynamicClassLoaderManager> classLoaderManagerReference = new AtomicReference<>();
- private AtomicReference<URIProvider[]> uriProviderReference = new AtomicReference<>();
+ private final AtomicReference<URIProvider[]> uriProviderReference = new AtomicReference<>();
@Activate
protected void activate(final ComponentContext context) {
- SlingRepository repository = context.locateService(REPOSITORY_REFERENCE_NAME,
+ SlingRepository slingRepository = context.locateService(REPOSITORY_REFERENCE_NAME,
this.repositoryReference);
- if (repository == null) {
+ if (slingRepository == null) {
// concurrent unregistration of SlingRepository service
// don't care, this component is going to be deactivated
// so we just stop working
@@ -137,9 +137,9 @@
return;
}
- this.repository = repository;
+ this.repository = slingRepository;
- this.stateFactory = new JcrProviderStateFactory(repositoryReference, repository,
+ this.stateFactory = new JcrProviderStateFactory(repositoryReference, slingRepository,
classLoaderManagerReference, uriProviderReference);
}
@@ -151,10 +151,12 @@
@Reference(name = "dynamicClassLoaderManager",
service = DynamicClassLoaderManager.class,
cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
+ @SuppressWarnings("unused")
protected void bindDynamicClassLoaderManager(final DynamicClassLoaderManager dynamicClassLoaderManager) {
this.classLoaderManagerReference.set(dynamicClassLoaderManager);
}
-
+
+ @SuppressWarnings("unused")
protected void unbindDynamicClassLoaderManager(final DynamicClassLoaderManager dynamicClassLoaderManager) {
this.classLoaderManagerReference.compareAndSet(dynamicClassLoaderManager, null);
}
@@ -167,18 +169,20 @@
bind = "bindUriProvider",
unbind = "unbindUriProvider"
)
+ @SuppressWarnings("unused")
private void bindUriProvider(ServiceReference<URIProvider> srUriProvider, URIProvider uriProvider) {
providers.put(srUriProvider, uriProvider);
updateURIProviders();
}
+ @SuppressWarnings("unused")
private void unbindUriProvider(ServiceReference<URIProvider> srUriProvider) {
providers.remove(srUriProvider);
updateURIProviders();
}
private void updateURIProviders() {
- URIProvider[] ups = providers.values().toArray(new URIProvider[providers.size()]);
+ URIProvider[] ups = providers.values().toArray(new URIProvider[0]);
this.uriProviderReference.set(ups);
}
@@ -423,20 +427,19 @@
nodeType = null;
}
}
- final String jcrPath = path;
- if (jcrPath == null) {
+ if (path == null) {
throw new PersistenceException("Unable to create node at " + path, null, path, null);
}
Node node = null;
try {
- final int lastPos = jcrPath.lastIndexOf('/');
+ final int lastPos = path.lastIndexOf('/');
final Node parent;
if (lastPos == 0) {
parent = ctx.getProviderState().getSession().getRootNode();
} else {
- parent = (Node) ctx.getProviderState().getSession().getItem(jcrPath.substring(0, lastPos));
+ parent = (Node) ctx.getProviderState().getSession().getItem(path.substring(0, lastPos));
}
- final String name = jcrPath.substring(lastPos + 1);
+ final String name = path.substring(lastPos + 1);
if (nodeType != null) {
node = parent.addNode(name, nodeType);
} else {
@@ -469,7 +472,7 @@
return new JcrNodeResource(ctx.getResourceResolver(), path, null, node, ctx.getProviderState().getHelperData());
} catch (final RepositoryException e) {
- throw new PersistenceException("Unable to create node at " + jcrPath, e, path, null);
+ throw new PersistenceException("Unable to create node at " + path, e, path, null);
}
}
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/JcrModifiableValueMapTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/JcrModifiableValueMapTest.java
index f1d831b..b335add 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/JcrModifiableValueMapTest.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/JcrModifiableValueMapTest.java
@@ -53,8 +53,6 @@
public class JcrModifiableValueMapTest extends SlingRepositoryTestBase {
- private String rootPath;
-
private Node rootNode;
public static final byte[] TEST_BYTE_ARRAY = {'T', 'e', 's', 't'};
@@ -63,7 +61,7 @@
@Override
protected void setUp() throws Exception {
super.setUp();
- rootPath = "/test_" + System.currentTimeMillis();
+ String rootPath = "/test_" + System.currentTimeMillis();
rootNode = getSession().getRootNode().addNode(rootPath.substring(1),
"nt:unstructured");
@@ -150,8 +148,7 @@
pvm.put("binary", stream);
getSession().save();
final ValueMap valueMap2 = new JcrValueMap(this.rootNode, getHelperData());
- assertTrue("The read stream is not what we wrote.", IOUtils.toString(valueMap2.get("binary", InputStream.class)).equals
- (TEST_BYTE_ARRAY_TO_STRING));
+ assertEquals("The read stream is not what we wrote.", IOUtils.toString(valueMap2.get("binary", InputStream.class)), TEST_BYTE_ARRAY_TO_STRING);
}
public void testPut()
@@ -189,7 +186,7 @@
final Object removedValue = pvm.remove(key);
assertTrue(removedValue instanceof Long);
- assertTrue(removedValue == longValue);
+ assertSame(removedValue, longValue);
assertFalse(pvm.containsKey(key));
}
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/JcrResourceListenerScalabilityTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/JcrResourceListenerScalabilityTest.java
deleted file mode 100644
index 8c4a4f8..0000000
--- a/src/test/java/org/apache/sling/jcr/resource/internal/JcrResourceListenerScalabilityTest.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.jcr.resource.internal;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.jcr.Session;
-import javax.jcr.Workspace;
-import javax.jcr.observation.Event;
-import javax.jcr.observation.EventIterator;
-import javax.jcr.observation.ObservationManager;
-
-import org.apache.sling.api.resource.observation.ResourceChange;
-import org.apache.sling.api.resource.observation.ResourceChange.ChangeType;
-import org.apache.sling.api.resource.path.PathSet;
-import org.apache.sling.jcr.api.SlingRepository;
-import org.apache.sling.jcr.resource.internal.helper.jcr.SlingRepositoryProvider;
-import org.apache.sling.spi.resource.provider.ObservationReporter;
-import org.apache.sling.spi.resource.provider.ObserverConfiguration;
-import org.apache.sling.spi.resource.provider.ProviderContext;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * This test case asserts that JcrResourceListener scales to an
- * arbitrary number of events.
- */
-public class JcrResourceListenerScalabilityTest {
-
- private JcrListenerBaseConfig config;
-
- private JcrResourceListener jcrResourceListener;
-
- private EventIterator events;
-
- @SuppressWarnings("deprecation")
- @Before
- public void setUp() throws Exception {
- ObservationManager observationManager = mock(ObservationManager.class);
-
- Workspace workspace = mock(Workspace.class);
- when(workspace.getObservationManager()).thenReturn(observationManager);
-
- Session session = mock(Session.class);
- when(session.getWorkspace()).thenReturn(workspace);
-
- SlingRepository repository = mock(SlingRepository.class);
- when(repository.loginAdministrative(null)).thenReturn(session);
-
- final ProviderContext ctx = new SimpleProviderContext();
- this.config = new JcrListenerBaseConfig(ctx.getObservationReporter(),
- SlingRepositoryProvider.getRepository());
- jcrResourceListener = new JcrResourceListener(this.config, ctx.getObservationReporter().getObserverConfigurations().get(0));
-
- Event event = mock(MockEvent.class);
- events = mock(EventIterator.class);
- when(events.hasNext()).thenReturn(true);
- when(event.getPath()).thenCallRealMethod();
- when(event.getType()).thenReturn(Event.NODE_ADDED);
- when(events.nextEvent()).thenReturn(event);
- }
-
- @Ignore("SLING-3399") // FIXME SLING-3399
- @Test
- public void testManyEvents() {
- jcrResourceListener.onEvent(events);
- }
-
- private abstract static class MockEvent implements Event {
- int count;
-
- @Override
- public String getPath() {
- return "path-" + count++;
- }
- }
-
- private static class SimpleProviderContext implements ProviderContext {
- @Override
- public ObservationReporter getObservationReporter() {
- return new ObservationReporter() {
-
- @Override
- public void reportChanges(Iterable<ResourceChange> changes, boolean distribute) {
- }
-
- @Override
- public void reportChanges(ObserverConfiguration config, Iterable<ResourceChange> changes,
- boolean distribute) {
- }
-
- @Override
- public List<ObserverConfiguration> getObserverConfigurations() {
- ObserverConfiguration config = new ObserverConfiguration() {
-
- @Override
- public boolean includeExternal() {
- return true;
- }
-
- @Override
- public PathSet getPaths() {
- return PathSet.fromStrings("/");
- }
-
- @Override
- public PathSet getExcludedPaths() {
- return PathSet.fromPaths();
- }
-
- @Override
- public Set<ChangeType> getChangeTypes() {
- return EnumSet.allOf(ChangeType.class);
- }
-
- @Override
- public boolean matches(String path) {
- return true;
- }
-
- @Override
- public Set<String> getPropertyNamesHint() {
- return new HashSet<>();
- }
- };
- return Collections.singletonList(config);
- }
- };
- }
-
- @Override
- public PathSet getExcludedPaths() {
- return PathSet.fromPaths();
- }
- }
-}
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/JcrResourceListenerTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/JcrResourceListenerTest.java
index dafcef9..edd2013 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/JcrResourceListenerTest.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/JcrResourceListenerTest.java
@@ -57,11 +57,11 @@
private Session adminSession;
- private String createdPath = "/test" + System.currentTimeMillis() + "-create";
+ private final String createdPath = "/test" + System.currentTimeMillis() + "-create";
- private String pathToDelete = "/test" + System.currentTimeMillis() + "-delete";
+ private final String pathToDelete = "/test" + System.currentTimeMillis() + "-delete";
- private String pathToModify = "/test" + System.currentTimeMillis() + "-modify";
+ private final String pathToModify = "/test" + System.currentTimeMillis() + "-modify";
private final List<ResourceChange> events = synchronizedList(new ArrayList<>());
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntryTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntryTest.java
index 34e4719..145a4fa 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntryTest.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/helper/JcrPropertyMapCacheEntryTest.java
@@ -18,60 +18,73 @@
*/
package org.apache.sling.jcr.resource.internal.helper;
-import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyZeroInteractions;
import org.junit.Test;
+import javax.jcr.Node;
+
/**
* Testcase for {@link JcrPropertyMapCacheEntry}
*/
public class JcrPropertyMapCacheEntryTest {
+ private final Node node = mock(Node.class);
+
@Test
public void testByteArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Byte[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new byte[0], null));
+ new JcrPropertyMapCacheEntry(new Byte[0], node);
+ new JcrPropertyMapCacheEntry(new byte[0], node);
+ verifyZeroInteractions(node);
}
@Test
public void testShortArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Short[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new short[0], null));
+ new JcrPropertyMapCacheEntry(new Short[0], node);
+ new JcrPropertyMapCacheEntry(new short[0], node);
+ verifyZeroInteractions(node);
}
@Test
public void testIntArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Integer[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new int[0], null));
+ new JcrPropertyMapCacheEntry(new Integer[0], node);
+ new JcrPropertyMapCacheEntry(new int[0], node);
+ verifyZeroInteractions(node);
}
@Test
public void testLongArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Long[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new long[0], null));
+ new JcrPropertyMapCacheEntry(new Long[0], node);
+ new JcrPropertyMapCacheEntry(new long[0], node);
+ verifyZeroInteractions(node);
}
@Test
public void testFloatArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Float[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new float[0], null));
+ new JcrPropertyMapCacheEntry(new Float[0], node);
+ new JcrPropertyMapCacheEntry(new float[0], node);
+ verifyZeroInteractions(node);
}
@Test
public void testDoubleArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Double[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new double[0], null));
+ new JcrPropertyMapCacheEntry(new Double[0], node);
+ new JcrPropertyMapCacheEntry(new double[0], node);
+ verifyZeroInteractions(node);
}
@Test
public void testBooleanArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Boolean[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new boolean[0], null));
+ new JcrPropertyMapCacheEntry(new Boolean[0], node);
+ new JcrPropertyMapCacheEntry(new boolean[0], node);
+ verifyZeroInteractions(node);
}
@Test
public void testCharArray() throws Exception {
- assertNotNull(new JcrPropertyMapCacheEntry(new Character[0], null));
- assertNotNull(new JcrPropertyMapCacheEntry(new char[0], null));
+ new JcrPropertyMapCacheEntry(new Character[0], node);
+ new JcrPropertyMapCacheEntry(new char[0], node);
+ verifyZeroInteractions(node);
}
}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProviderTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProviderTest.java
index 3678c0f..c17f09f 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProviderTest.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/BinaryDownloadUriProviderTest.java
@@ -57,7 +57,6 @@
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
- private Session session;
private BinaryDownloadUriProvider uriProvider;
private Resource fileResource;
@@ -70,7 +69,7 @@
@Before
public void setUp() throws IOException, RepositoryException {
uriProvider = new BinaryDownloadUriProvider(false);
- session = context.resourceResolver().adaptTo(Session.class);
+ Session session = context.resourceResolver().adaptTo(Session.class);
try (InputStream input = this.getClass().getResourceAsStream("/SLING-INF/nodetypes/folder.cnd")) {
JcrUtils.putFile(session.getRootNode(), "test", "myMimeType", input);
}
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactoryTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactoryTest.java
index 7e2c5d2..e01918d 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactoryTest.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceFactoryTest.java
@@ -31,8 +31,6 @@
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.security.Privilege;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.atomic.AtomicReference;
@@ -58,12 +56,7 @@
nonJackrabbitSession = (Session) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[]{Session.class},
- new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- return method.invoke(session, args);
- }
- });
+ (proxy, method, args) -> method.invoke(session, args));
AccessControlUtils.allow(node, EveryonePrincipal.NAME, Privilege.JCR_READ);
session.save();
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceTestBase.java b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceTestBase.java
index cb140b2..f6c0392 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceTestBase.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrItemResourceTestBase.java
@@ -26,10 +26,8 @@
import org.apache.sling.api.SlingConstants;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
-import org.junit.Ignore;
-@Ignore
-public class JcrItemResourceTestBase extends SlingRepositoryTestBase {
+public abstract class JcrItemResourceTestBase extends SlingRepositoryTestBase {
protected static final long TEST_MODIFIED = System.currentTimeMillis();
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceTest.java
index 60711e7..4b870af 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceTest.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceTest.java
@@ -20,6 +20,7 @@
import java.io.ByteArrayInputStream;
import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
@@ -250,7 +251,7 @@
}
public void testCorrectUTF8ByteLength() throws Exception {
- byte[] utf8bytes = "Übersättigung".getBytes("UTF-8");
+ byte[] utf8bytes = "Übersättigung".getBytes(StandardCharsets.UTF_8);
String name = "utf8file";
Node file = rootNode.addNode(name, JcrConstants.NT_FILE);
Node res = file.addNode(JcrConstants.JCR_CONTENT,
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrPropertyResourceTest.java b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrPropertyResourceTest.java
index bf93de7..c004b88 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrPropertyResourceTest.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrPropertyResourceTest.java
@@ -22,6 +22,7 @@
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map.Entry;
@@ -60,7 +61,7 @@
final ResourceResolver resolver = this.context.mock(ResourceResolver.class);
for (final Entry<Object, Integer> data : testData.entrySet()) {
final String stringValue = data.getKey().toString();
- final long stringByteLength = stringValue.getBytes("UTF-8").length;
+ final long stringByteLength = stringValue.getBytes(StandardCharsets.UTF_8).length;
final Property property = this.context.mock(Property.class, stringValue);
this.context.checking(new Expectations() {{
ignoring(resolver);
diff --git a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/SlingRepositoryTestBase.java b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/SlingRepositoryTestBase.java
index 52b46fa..92f7869 100644
--- a/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/SlingRepositoryTestBase.java
+++ b/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/SlingRepositoryTestBase.java
@@ -25,7 +25,7 @@
import junit.framework.TestCase;
-public class SlingRepositoryTestBase extends TestCase {
+public abstract class SlingRepositoryTestBase extends TestCase {
protected Node testRoot;
protected Session session;