diff --git a/.codeclimate.yml b/.codeclimate.yml
new file mode 100644
index 0000000000..3c6b6906e5
--- /dev/null
+++ b/.codeclimate.yml
@@ -0,0 +1,49 @@
+---
+engines:
+ sonar-java:
+ enabled: true
+ config:
+ sonar.java.source: 8
+ checkstyle:
+ enabled: true
+ config:
+ file: ".codeclimate/checkstyle.xml"
+# csslint:
+# enabled: true
+# duplication:
+# enabled: true
+# config:
+# languages:
+# - javascript
+# eslint:
+# enabled: true
+# fixme:
+# enabled: true
+ pmd:
+ enabled: true
+ratings:
+ paths:
+ - "**.java"
+ - "**.css"
+ - "**.js"
+exclude_paths:
+- ".idea/"
+- "**/vendor/"
+- "**/extensions/contentfinder/"
+- "**/src/test/"
+- "*/target/"
+
+
+# Common exclusions
+# squid:S3776 - Cognitive Complexity
+# squid:S1214 - constants in interface
+# squid:S1141 - nested try
+# squid:S1192 - literals
+# squid:S1149 - Hashtable
+# squid:S00112 - specific exceptions
+# squid:S2095 - close stream
+# squid:S1172 - unused method param
+# squid:S00115 - constant name
+# squid:S1144 - unused private method
+#
+# checkstyle:abbreviationaswordinname - abbreviation
\ No newline at end of file
diff --git a/.codeclimate/checkstyle.xml b/.codeclimate/checkstyle.xml
new file mode 100644
index 0000000000..b5c4e4922d
--- /dev/null
+++ b/.codeclimate/checkstyle.xml
@@ -0,0 +1,157 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.csslintrc b/.csslintrc
new file mode 100644
index 0000000000..aacba956e5
--- /dev/null
+++ b/.csslintrc
@@ -0,0 +1,2 @@
+--exclude-exts=.min.css
+--ignore=adjoining-classes,box-model,ids,order-alphabetical,unqualified-attributes
diff --git a/.eslintignore b/.eslintignore
new file mode 100644
index 0000000000..96212a3593
--- /dev/null
+++ b/.eslintignore
@@ -0,0 +1 @@
+**/*{.,-}min.js
diff --git a/.eslintrc.yml b/.eslintrc.yml
new file mode 100644
index 0000000000..dec0e53b1f
--- /dev/null
+++ b/.eslintrc.yml
@@ -0,0 +1,277 @@
+---
+parserOptions:
+ sourceType: module
+ ecmaFeatures:
+ jsx: true
+
+env:
+ amd: true
+ browser: true
+ es6: true
+ jquery: true
+ node: true
+
+# http://eslint.org/docs/rules/
+rules:
+ # Possible Errors
+ no-await-in-loop: off
+ no-cond-assign: error
+ no-console: off
+ no-constant-condition: error
+ no-control-regex: error
+ no-debugger: error
+ no-dupe-args: error
+ no-dupe-keys: error
+ no-duplicate-case: error
+ no-empty-character-class: error
+ no-empty: error
+ no-ex-assign: error
+ no-extra-boolean-cast: error
+ no-extra-parens: off
+ no-extra-semi: error
+ no-func-assign: error
+ no-inner-declarations:
+ - error
+ - functions
+ no-invalid-regexp: error
+ no-irregular-whitespace: error
+ no-negated-in-lhs: error
+ no-obj-calls: error
+ no-prototype-builtins: off
+ no-regex-spaces: error
+ no-sparse-arrays: error
+ no-template-curly-in-string: off
+ no-unexpected-multiline: error
+ no-unreachable: error
+ no-unsafe-finally: off
+ no-unsafe-negation: off
+ use-isnan: error
+ valid-jsdoc: off
+ valid-typeof: error
+
+ # Best Practices
+ accessor-pairs: error
+ array-callback-return: off
+ block-scoped-var: off
+ class-methods-use-this: off
+ complexity:
+ - error
+ - 6
+ consistent-return: off
+ curly: off
+ default-case: off
+ dot-location: off
+ dot-notation: off
+ eqeqeq: error
+ guard-for-in: error
+ no-alert: error
+ no-caller: error
+ no-case-declarations: error
+ no-div-regex: error
+ no-else-return: off
+ no-empty-function: off
+ no-empty-pattern: error
+ no-eq-null: error
+ no-eval: error
+ no-extend-native: error
+ no-extra-bind: error
+ no-extra-label: off
+ no-fallthrough: error
+ no-floating-decimal: off
+ no-global-assign: off
+ no-implicit-coercion: off
+ no-implied-eval: error
+ no-invalid-this: off
+ no-iterator: error
+ no-labels:
+ - error
+ - allowLoop: true
+ allowSwitch: true
+ no-lone-blocks: error
+ no-loop-func: error
+ no-magic-number: off
+ no-multi-spaces: off
+ no-multi-str: off
+ no-native-reassign: error
+ no-new-func: error
+ no-new-wrappers: error
+ no-new: error
+ no-octal-escape: error
+ no-octal: error
+ no-param-reassign: off
+ no-proto: error
+ no-redeclare: error
+ no-restricted-properties: off
+ no-return-assign: error
+ no-return-await: off
+ no-script-url: error
+ no-self-assign: off
+ no-self-compare: error
+ no-sequences: off
+ no-throw-literal: off
+ no-unmodified-loop-condition: off
+ no-unused-expressions: error
+ no-unused-labels: off
+ no-useless-call: error
+ no-useless-concat: error
+ no-useless-escape: off
+ no-useless-return: off
+ no-void: error
+ no-warning-comments: off
+ no-with: error
+ prefer-promise-reject-errors: off
+ radix: error
+ require-await: off
+ vars-on-top: off
+ wrap-iife: error
+ yoda: off
+
+ # Strict
+ strict: off
+
+ # Variables
+ init-declarations: off
+ no-catch-shadow: error
+ no-delete-var: error
+ no-label-var: error
+ no-restricted-globals: off
+ no-shadow-restricted-names: error
+ no-shadow: off
+ no-undef-init: error
+ no-undef: off
+ no-undefined: off
+ no-unused-vars: off
+ no-use-before-define: off
+
+ # Node.js and CommonJS
+ callback-return: error
+ global-require: error
+ handle-callback-err: error
+ no-mixed-requires: off
+ no-new-require: off
+ no-path-concat: error
+ no-process-env: off
+ no-process-exit: error
+ no-restricted-modules: off
+ no-sync: off
+
+ # Stylistic Issues
+ array-bracket-spacing: off
+ block-spacing: off
+ brace-style: off
+ camelcase: off
+ capitalized-comments: off
+ comma-dangle:
+ - error
+ - never
+ comma-spacing: off
+ comma-style: off
+ computed-property-spacing: off
+ consistent-this: off
+ eol-last: off
+ func-call-spacing: off
+ func-name-matching: off
+ func-names: off
+ func-style: off
+ id-length: off
+ id-match: off
+ indent: off
+ jsx-quotes: off
+ key-spacing: off
+ keyword-spacing: off
+ line-comment-position: off
+ linebreak-style: off
+ lines-around-comment: off
+ lines-around-directive: off
+ max-depth: off
+ max-len: off
+ max-nested-callbacks: off
+ max-params: off
+ max-statements-per-line: off
+ max-statements:
+ - error
+ - 30
+ multiline-ternary: off
+ new-cap: off
+ new-parens: off
+ newline-after-var: off
+ newline-before-return: off
+ newline-per-chained-call: off
+ no-array-constructor: off
+ no-bitwise: off
+ no-continue: off
+ no-inline-comments: off
+ no-lonely-if: off
+ no-mixed-operators: off
+ no-mixed-spaces-and-tabs: off
+ no-multi-assign: off
+ no-multiple-empty-lines: off
+ no-negated-condition: off
+ no-nested-ternary: off
+ no-new-object: off
+ no-plusplus: off
+ no-restricted-syntax: off
+ no-spaced-func: off
+ no-tabs: error
+ no-ternary: off
+ no-trailing-spaces: off
+ no-underscore-dangle: off
+ no-unneeded-ternary: off
+ object-curly-newline: off
+ object-curly-spacing: off
+ object-property-newline: off
+ one-var-declaration-per-line: off
+ one-var: off
+ operator-assignment: off
+ operator-linebreak: off
+ padded-blocks: off
+ quote-props: off
+ quotes: off
+ require-jsdoc: off
+ semi-spacing: off
+ semi: off
+ sort-keys: off
+ sort-vars: off
+ space-before-blocks: off
+ space-before-function-paren: off
+ space-in-parens: off
+ space-infix-ops: off
+ space-unary-ops: off
+ spaced-comment: off
+ template-tag-spacing: off
+ unicode-bom: off
+ wrap-regex: off
+
+ # ECMAScript 6
+ arrow-body-style: off
+ arrow-parens: off
+ arrow-spacing: off
+ constructor-super: off
+ generator-star-spacing: off
+ no-class-assign: off
+ no-confusing-arrow: off
+ no-const-assign: off
+ no-dupe-class-members: off
+ no-duplicate-imports: off
+ no-new-symbol: off
+ no-restricted-imports: off
+ no-this-before-super: off
+ no-useless-computed-key: off
+ no-useless-constructor: off
+ no-useless-rename: off
+ no-var: off
+ object-shorthand: off
+ prefer-arrow-callback: off
+ prefer-const: off
+ prefer-destructuring: off
+ prefer-numeric-literals: off
+ prefer-rest-params: off
+ prefer-reflect: off
+ prefer-spread: off
+ prefer-template: off
+ require-yield: off
+ rest-spread-spacing: off
+ sort-imports: off
+ symbol-description: off
+ template-curly-spacing: off
+ yield-star-spacing: off
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6efd72560c..a9cacc7b87 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/)
- #1145 - New Redirect Map Manager feature
+### Changed
+
+- #1174 - Introduced CodeClimate quality checks. Resulted in lots of miscellaneous non-API changes.
+
### Fixed
- #1171 - Reduce duplicate coverage comments in pull requests.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 91bd564247..cf81dd18fa 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -37,7 +37,7 @@ There's a good guide to performing pull requests at [https://help.github.com/art
The best pull request are small and focused. Don't try to change the world in one pull request. And while the focus of this project is reusability, that doesn't mean that every option under the sun needs to be available. Stick to the 80/20 rule and provide a way to extend for that extra 20% on a project.
-* Run Maven build by running `mvn -Panalysis clean install` to run the static analysis checks.
+* Check code quality proactively by using [https://github.com/codeclimate/codeclimate](CodeClimate CLI).
* Ensure license is applied correctly by running `mvn license:update-file-header`
* Add JUnit test for Java code. Our coverage ratio isn't great, but we don't want it to get worse.
* Until explicitly enabled, features should be invisible to AEM users and excluded from any execution stack.
diff --git a/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterAdapterFactory.java b/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterAdapterFactory.java
index 1f553e465d..9098a7de06 100644
--- a/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterAdapterFactory.java
+++ b/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterAdapterFactory.java
@@ -86,9 +86,9 @@ public class TwitterAdapterFactory implements AdapterFactory {
public AdapterType getAdapter(Object adaptable, Class type) {
TwitterClient client = null;
if (adaptable instanceof Page) {
- client = createTwitterClient((Page) adaptable);
+ client = createTwitterClientFromPage((Page) adaptable);
} else if (adaptable instanceof com.day.cq.wcm.webservicesupport.Configuration) {
- client = createTwitterClient((com.day.cq.wcm.webservicesupport.Configuration) adaptable);
+ client = createTwitterClientFromConfiguration((com.day.cq.wcm.webservicesupport.Configuration) adaptable);
}
if (client != null) {
@@ -114,19 +114,19 @@ private Configuration buildConfiguration() {
return builder.build();
}
- private TwitterClient createTwitterClient(com.day.cq.wcm.webservicesupport.Configuration config) {
+ private TwitterClient createTwitterClientFromConfiguration(com.day.cq.wcm.webservicesupport.Configuration config) {
Resource oauthConfig = config.getContentResource().listChildren().next();
ValueMap oauthProps = oauthConfig.getValueMap();
String consumerKey = oauthProps.get("oauth.client.id", String.class);
String consumerSecret = oauthProps.get("oauth.client.secret", String.class);
if (consumerKey != null && consumerSecret != null) {
- Twitter t = getInstance();
+ Twitter twitter = getInstance();
log.debug("Creating client for key {}.", consumerKey);
- t.setOAuthConsumer(consumerKey, consumerSecret);
+ twitter.setOAuthConsumer(consumerKey, consumerSecret);
try {
- t.getOAuth2Token();
- return new TwitterClientImpl(t, config);
+ twitter.getOAuth2Token();
+ return new TwitterClientImpl(twitter, config);
} catch (TwitterException e) {
log.error("Unable to create Twitter client.", e);
return null;
@@ -143,10 +143,10 @@ Twitter getInstance() {
return factory.getInstance();
}
- private TwitterClient createTwitterClient(Page page) {
+ private TwitterClient createTwitterClientFromPage(Page page) {
com.day.cq.wcm.webservicesupport.Configuration config = findTwitterConfiguration(page);
if (config != null) {
- return createTwitterClient(config);
+ return createTwitterClientFromConfiguration(config);
}
return null;
}
diff --git a/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedScheduler.java b/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedScheduler.java
index ce70b0b81b..561e529981 100644
--- a/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedScheduler.java
+++ b/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedScheduler.java
@@ -50,6 +50,7 @@ public final class TwitterFeedScheduler extends RunnableOnMaster {
private static final String SERVICE_NAME = "twitter-updater";
private static final Map AUTH_INFO;
+
static {
AUTH_INFO = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object) SERVICE_NAME);
}
diff --git a/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedUpdaterImpl.java b/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedUpdaterImpl.java
index d9b65b65e1..21024d2ef6 100644
--- a/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedUpdaterImpl.java
+++ b/bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedUpdaterImpl.java
@@ -84,6 +84,7 @@ protected void activate(ComponentContext ctx) {
}
@Override
+ @SuppressWarnings("squid:S3776")
public void updateTwitterFeedComponents(ResourceResolver resourceResolver) {
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
@@ -120,7 +121,7 @@ public void updateTwitterFeedComponents(ResourceResolver resourceResolver) {
map.put("tweetsJson", jsonList.toArray(new String[jsonList.size()]));
twitterResource.getResourceResolver().commit();
- handleReplication(pageManager, twitterResource);
+ handleReplication(twitterResource);
}
}
@@ -150,9 +151,9 @@ private List findTwitterResources(ResourceResolver resourceResolver) {
predicateMap.put("path", "/content");
predicateMap.put("property", "sling:resourceType");
- int i = 1;
+ int counter = 1;
for (String path : twitterComponentPaths) {
- predicateMap.put("property." + (i++) + "_value", path.toString());
+ predicateMap.put("property." + (counter++) + "_value", path.toString());
}
@@ -182,7 +183,7 @@ private String processTweet(Status status) {
}
- private void handleReplication(PageManager pageManager, Resource twitterResource) throws ReplicationException {
+ private void handleReplication(Resource twitterResource) throws ReplicationException {
if (isReplicationEnabled(twitterResource)) {
Session session = twitterResource.getResourceResolver().adaptTo(Session.class);
replicator.replicate(session, ReplicationActionType.ACTIVATE, twitterResource.getPath());
diff --git a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/ChecksumGeneratorOptions.java b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/ChecksumGeneratorOptions.java
index adf7e78bc2..ef1549753e 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/ChecksumGeneratorOptions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/ChecksumGeneratorOptions.java
@@ -25,6 +25,7 @@
import java.util.Set;
@ProviderType
+@SuppressWarnings("squid:S1214")
public interface ChecksumGeneratorOptions {
String DATA = "data";
diff --git a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/JSONGenerator.java b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/JSONGenerator.java
index 9505036407..78050a290e 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/JSONGenerator.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/JSONGenerator.java
@@ -112,17 +112,16 @@ private static void traverseTree(Node node, ChecksumGeneratorOptions opts,
String primaryNodeType;
try {
primaryNodeType = node.getPrimaryNodeType().getName();
- NodeIterator nIt;
if (nodeTypes.contains(primaryNodeType)
&& !nodeTypeExcludes.contains(primaryNodeType)) {
- generateJSON(node, opts, out);
+ generateNodeJSON(node, opts, out);
} else {
- nIt = node.getNodes();
- while (nIt.hasNext()) {
+ NodeIterator nodeIterator = node.getNodes();
+ while (nodeIterator.hasNext()) {
primaryNodeType = node.getPrimaryNodeType().getName();
- Node child = nIt.nextNode();
+ Node child = nodeIterator.nextNode();
if (nodeTypes.contains(primaryNodeType)) {
- generateJSON(child, opts, out);
+ generateNodeJSON(child, opts, out);
} else {
traverseTree(child, opts, out);
}
@@ -134,8 +133,8 @@ private static void traverseTree(Node node, ChecksumGeneratorOptions opts,
}
}
- private static void generateJSON(Node node,
- ChecksumGeneratorOptions opts, JSONWriter out)
+ private static void generateNodeJSON(Node node,
+ ChecksumGeneratorOptions opts, JSONWriter out)
throws RepositoryException, JSONException {
out.key(node.getPath());
out.object();
@@ -174,77 +173,74 @@ private static void outputProperties(Node node,
ChecksumGeneratorOptions opts, JSONWriter out)
throws RepositoryException, JSONException, ValueFormatException {
Set excludes = opts.getExcludedProperties();
- Set sortValues = opts.getSortedProperties();
SortedMap props = new TreeMap();
- PropertyIterator pi = node.getProperties();
+ PropertyIterator propertyIterator = node.getProperties();
// sort the properties by name as the JCR makes no guarantees on property order
- while (pi.hasNext()) {
- Property p = pi.nextProperty();
+ while (propertyIterator.hasNext()) {
+ Property property = propertyIterator.nextProperty();
//skip the property if it is in the excludes list
- if (excludes.contains(p.getName())) {
+ if (excludes.contains(property.getName())) {
continue;
} else {
- props.put(p.getName(), p);
+ props.put(property.getName(), property);
}
}
- pi = null;
- for (Property p : props.values()) {
- int type = p.getType();
+ for (Property property : props.values()) {
+ outputProperty(property, opts, out);
+ }
+ }
- if (p.isMultiple()) {
- out.key(p.getName());
- // create an array for multi value output
- out.array();
- boolean isSortedValues = sortValues.contains(p.getName());
- Value[] values = p.getValues();
- TreeMap sortedValueMap = new TreeMap();
- for (Value v : values) {
- type = v.getType();
- if (type == PropertyType.BINARY) {
- if (isSortedValues) {
- try {
- java.io.InputStream stream =
- v.getBinary().getStream();
- String ckSum = DigestUtils.shaHex(stream);
- stream.close();
- sortedValueMap.put(ckSum, v);
- } catch (IOException e) {
- sortedValueMap.put("ERROR: generating hash for binary of "
- + p.getPath() + " : " + e.getMessage(), v);
- }
- } else {
- outputPropertyValue(p, v, out);
+ @SuppressWarnings("squid:S3776")
+ private static void outputProperty(Property property, ChecksumGeneratorOptions opts, JSONWriter out)
+ throws RepositoryException, JSONException {
+ Set sortValues = opts.getSortedProperties();
+ if (property.isMultiple()) {
+ out.key(property.getName());
+ // create an array for multi value output
+ out.array();
+ boolean isSortedValues = sortValues.contains(property.getName());
+ Value[] values = property.getValues();
+ TreeMap sortedValueMap = new TreeMap();
+ for (Value v : values) {
+ int type = v.getType();
+ if (type == PropertyType.BINARY) {
+ if (isSortedValues) {
+ try {
+ java.io.InputStream stream =
+ v.getBinary().getStream();
+ String ckSum = DigestUtils.shaHex(stream);
+ stream.close();
+ sortedValueMap.put(ckSum, v);
+ } catch (IOException e) {
+ sortedValueMap.put("ERROR: generating hash for binary of "
+ + property.getPath() + " : " + e.getMessage(), v);
}
} else {
- String val = v.getString();
- if (isSortedValues) {
- sortedValueMap.put(val, v);
- } else {
- outputPropertyValue(p, v, out);
- }
+ outputPropertyValue(property, v, out);
}
- }
- if (isSortedValues) {
- for (Value v : sortedValueMap.values()) {
- outputPropertyValue(p, v, out);
+ } else {
+ String val = v.getString();
+ if (isSortedValues) {
+ sortedValueMap.put(val, v);
+ } else {
+ outputPropertyValue(property, v, out);
}
}
- out.endArray();
- // end multi value property output
- } else {
- out.key(p.getName());
- outputPropertyValue(p, p.getValue(), out);
}
+ if (isSortedValues) {
+ for (Value v : sortedValueMap.values()) {
+ outputPropertyValue(property, v, out);
+ }
+ }
+ out.endArray();
+ // end multi value property output
+ } else {
+ out.key(property.getName());
+ outputPropertyValue(property, property.getValue(), out);
}
- // if (nodeTypes.contains(primaryNodeType)) {
- // out.print(node.getPath());
- // out.print("\t");
- // out.println(DigestUtils.shaHex(checkSums.toString()));
- // out.flush();
- // }
}
/**
@@ -258,17 +254,17 @@ private static void outputChildNodes(Node node, ChecksumGeneratorOptions opts, J
throws RepositoryException, JSONException {
Set nodeTypeExcludes = opts.getExcludedNodeTypes();
- NodeIterator nIt;
- nIt = node.getNodes();
+ NodeIterator nodeIterator = node.getNodes();
TreeMap childSortMap = new TreeMap();
boolean hasOrderedChildren = false;
try {
hasOrderedChildren = node.getPrimaryNodeType().hasOrderableChildNodes();
- } catch (Exception e) {
+ } catch (Exception expected) {
+ // ignore
}
- while (nIt.hasNext()) {
- Node child = nIt.nextNode();
+ while (nodeIterator.hasNext()) {
+ Node child = nodeIterator.nextNode();
if (!nodeTypeExcludes
.contains(child.getPrimaryNodeType().getName())) {
if (hasOrderedChildren) {
@@ -293,44 +289,44 @@ private static void outputChildNodes(Node node, ChecksumGeneratorOptions opts, J
}
}
- private static void outputPropertyValue(Property p, Value v, JSONWriter out)
+ private static void outputPropertyValue(Property property, Value value, JSONWriter out)
throws RepositoryException, JSONException {
- if (v.getType() == PropertyType.STRING) {
- out.value(v.getString());
- } else if (v.getType() == PropertyType.BINARY) {
+ if (value.getType() == PropertyType.STRING) {
+ out.value(value.getString());
+ } else if (value.getType() == PropertyType.BINARY) {
try {
- java.io.InputStream stream = v.getBinary().getStream();
+ java.io.InputStream stream = value.getBinary().getStream();
String ckSum = DigestUtils.shaHex(stream);
stream.close();
out.value(ckSum);
} catch (IOException e) {
- out.value("ERROR: calculating hash for binary of " + p.getPath() + " : " + e.getMessage());
+ out.value("ERROR: calculating hash for binary of " + property.getPath() + " : " + e.getMessage());
}
- } else if (v.getType() == PropertyType.BOOLEAN) {
- out.value(v.getBoolean());
- } else if (v.getType() == PropertyType.DATE) {
- Calendar cal = v.getDate();
+ } else if (value.getType() == PropertyType.BOOLEAN) {
+ out.value(value.getBoolean());
+ } else if (value.getType() == PropertyType.DATE) {
+ Calendar cal = value.getDate();
if (cal != null) {
out.object();
out.key("type");
- out.value(PropertyType.nameFromValue(v.getType()));
+ out.value(PropertyType.nameFromValue(value.getType()));
out.key("val");
out.value(cal.getTime().toString());
out.endObject();
}
- } else if (v.getType() == PropertyType.LONG) {
- out.value(v.getLong());
- } else if (v.getType() == PropertyType.DOUBLE) {
- out.value(v.getDouble());
- } else if (v.getType() == PropertyType.DECIMAL) {
- out.value(v.getDecimal());
+ } else if (value.getType() == PropertyType.LONG) {
+ out.value(value.getLong());
+ } else if (value.getType() == PropertyType.DOUBLE) {
+ out.value(value.getDouble());
+ } else if (value.getType() == PropertyType.DECIMAL) {
+ out.value(value.getDecimal());
} else {
out.object();
out.key("type");
- out.value(PropertyType.nameFromValue(v.getType()));
+ out.value(PropertyType.nameFromValue(value.getType()));
out.key("val");
- out.value(v.getString());
+ out.value(value.getString());
out.endObject();
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/ChecksumGeneratorOptionsFactory.java b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/ChecksumGeneratorOptionsFactory.java
index c621c2a86c..b6f7db2d19 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/ChecksumGeneratorOptionsFactory.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/ChecksumGeneratorOptionsFactory.java
@@ -23,13 +23,10 @@
import com.adobe.acs.commons.analysis.jcrchecksum.ChecksumGeneratorOptions;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.IOException;
public class ChecksumGeneratorOptionsFactory {
- private static final Logger log = LoggerFactory.getLogger(ChecksumGeneratorOptionsFactory.class);
private ChecksumGeneratorOptionsFactory() {
// Private cstor
diff --git a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/CustomChecksumGeneratorOptions.java b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/CustomChecksumGeneratorOptions.java
index e700d61a46..dd00c21988 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/CustomChecksumGeneratorOptions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/CustomChecksumGeneratorOptions.java
@@ -20,57 +20,48 @@
package com.adobe.acs.commons.analysis.jcrchecksum.impl.options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Collection;
public class CustomChecksumGeneratorOptions extends AbstractChecksumGeneratorOptions {
- private static final Logger log = LoggerFactory.getLogger(DefaultChecksumGeneratorOptions.class);
-
- public CustomChecksumGeneratorOptions() {
-
- }
@Override
public void addIncludedNodeTypes(String[] arr) {
super.addIncludedNodeTypes(arr);
}
- @Override
- public void addExcludedNodeTypes(String[] arr) {
- super.addExcludedNodeTypes(arr);
- }
-
- @Override
- public void addExcludedProperties(String[] arr) {
- super.addExcludedProperties(arr);
- }
-
- @Override
- public void addSortedProperties(String[] arr) {
- super.addSortedProperties(arr);
- }
-
-
public void addIncludedNodeTypes(Collection col) {
if (col != null) {
super.addIncludedNodeTypes(col.toArray(new String[col.size()]));
}
}
+ @Override
+ public void addExcludedNodeTypes(String[] arr) {
+ super.addExcludedNodeTypes(arr);
+ }
+
public void addExcludedNodeTypes(Collection col) {
if (col != null) {
super.addExcludedNodeTypes(col.toArray(new String[col.size()]));
}
}
+ @Override
+ public void addExcludedProperties(String[] arr) {
+ super.addExcludedProperties(arr);
+ }
+
public void addExcludedProperties(Collection col) {
if (col != null) {
super.addExcludedProperties(col.toArray(new String[col.size()]));
}
}
+ @Override
+ public void addSortedProperties(String[] arr) {
+ super.addSortedProperties(arr);
+ }
+
public void addSortedProperties(Collection col) {
if (col != null) {
super.addSortedProperties(col.toArray(new String[col.size()]));
diff --git a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/DefaultChecksumGeneratorOptions.java b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/DefaultChecksumGeneratorOptions.java
index 2f50713931..50bf77448a 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/DefaultChecksumGeneratorOptions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/DefaultChecksumGeneratorOptions.java
@@ -22,12 +22,9 @@
import aQute.bnd.annotation.ProviderType;
import org.apache.sling.api.SlingHttpServletRequest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
@ProviderType
public class DefaultChecksumGeneratorOptions extends AbstractChecksumGeneratorOptions {
- private static final Logger log = LoggerFactory.getLogger(DefaultChecksumGeneratorOptions.class);
public DefaultChecksumGeneratorOptions() {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/RequestChecksumGeneratorOptions.java b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/RequestChecksumGeneratorOptions.java
index 5b64065570..126a3a5e71 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/RequestChecksumGeneratorOptions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/options/RequestChecksumGeneratorOptions.java
@@ -26,8 +26,6 @@
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
@@ -43,7 +41,6 @@
@ProviderType
public class RequestChecksumGeneratorOptions extends AbstractChecksumGeneratorOptions {
- private static final Logger log = LoggerFactory.getLogger(RequestChecksumGeneratorOptions.class);
public RequestChecksumGeneratorOptions(SlingHttpServletRequest request) throws IOException {
this.addIncludedNodeTypes(request.getParameterValues(NODES_TYPES));
@@ -101,27 +98,14 @@ private static Set getPathsFromInputstream(InputStream is, String encodi
Set paths = new HashSet();
encoding = (encoding != null) ? encoding : Charset.defaultCharset().name();
- BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
- try {
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) {
String path;
while ((path = br.readLine()) != null) {
paths.add(path);
}
- } finally {
- if (br != null) {
- br.close();
- }
}
return paths;
}
-
- private static List asList(String[] arr) {
- if (arr == null) {
- return Collections.EMPTY_LIST;
- } else {
- return Arrays.asList(arr);
- }
- }
}
\ No newline at end of file
diff --git a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/servlets/BaseChecksumServlet.java b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/servlets/BaseChecksumServlet.java
index b79e91cb8f..03d222aa53 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/servlets/BaseChecksumServlet.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/servlets/BaseChecksumServlet.java
@@ -30,7 +30,7 @@
/**
* Provides CORS functionality required by the server-to-server XHR communication
*/
-@SuppressWarnings("serial")
+@SuppressWarnings({"serial", "checkstyle:abbreviationaswordinname"})
public class BaseChecksumServlet extends SlingAllMethodsServlet {
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
diff --git a/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/AuditLogSearchRequest.java b/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/AuditLogSearchRequest.java
index 6fca5304ae..1896c3265b 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/AuditLogSearchRequest.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/AuditLogSearchRequest.java
@@ -48,137 +48,137 @@
*/
public class AuditLogSearchRequest {
- private static final FastDateFormat HTML5_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm", TimeZone.getTimeZone("GMT"));
- private static final FastDateFormat QUERY_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss", TimeZone.getTimeZone("GMT"));
-
- private static String getJCRSQLDate(Date date) {
- return QUERY_DATE_FORMAT.format(date) + ".000Z";
- }
-
- private final String contentRoot;
- private final boolean includeChildren;
- private final String type;
- private final String user;
- private final Date startDate;
- private final Date endDate;
- private final String order;
- private Map userNames = new HashMap();
-
- private Map userPaths = new HashMap();
-
- /**
- * Constructs a new AuditLogSearchRequest from the SlingHttpServletRequest
- *
- * @param request
- * yep, that's a request... guess what it does
- * @throws ParseException
- * an exception occurred parsing the start / end date
- */
- public AuditLogSearchRequest(SlingHttpServletRequest request) throws ParseException {
- contentRoot = request.getParameter("contentRoot");
- includeChildren = "true".equals(request.getParameter("includeChildren"));
- type = request.getParameter("type");
- user = request.getParameter("user");
- startDate = loadDate(request.getParameter("startDate"));
- endDate = loadDate(request.getParameter("endDate"));
- order = request.getParameter("order");
- }
-
- public String getContentRoot() {
- return contentRoot;
- }
-
- public Date getEndDate() {
- return endDate;
- }
-
- public String getOrder() {
- return order;
- }
-
- public String getQueryParameters() {
- List expressions = new ArrayList();
-
- if (!StringUtils.isEmpty(type)) {
- expressions.add("[cq:type]='" + StringEscapeUtils.escapeSql(type) + "'");
- }
- if (!StringUtils.isEmpty(user)) {
- expressions.add("[cq:userid]='" + StringEscapeUtils.escapeSql(user) + "'");
- }
- if (StringUtils.isNotEmpty(contentRoot)) {
- if (includeChildren) {
- expressions.add("[cq:path] LIKE '" + StringEscapeUtils.escapeSql(contentRoot) + "%'");
- } else {
- expressions.add("[cq:path]='" + StringEscapeUtils.escapeSql(contentRoot) + "'");
- }
- }
- if (startDate != null) {
- expressions.add("[cq:time] > CAST('" + getJCRSQLDate(startDate) + "' AS DATE)");
- }
- if (endDate != null) {
- expressions.add("[cq:time] < CAST('" + getJCRSQLDate(endDate) + "' AS DATE)");
- }
- String q = StringUtils.join(expressions, " AND ");
- if (!StringUtils.isEmpty(order)) {
- q += " ORDER BY " + order;
- }
- return q;
- }
-
- public Date getStartDate() {
- return startDate;
- }
-
- public String getType() {
- return type;
- }
-
- public String getUser() {
- return user;
- }
-
- public String getUserName(ResourceResolver resolver, String userId) throws RepositoryException {
- if (!userNames.containsKey(userId)) {
- final UserPropertiesManager upm = resolver.adaptTo(UserPropertiesManager.class);
- UserProperties userProperties = upm.getUserProperties(userId, UserPropertiesService.PROFILE_PATH);
- String name = userId;
- if (userProperties != null && !StringUtils.isEmpty(userProperties.getDisplayName())) {
- name = userProperties.getDisplayName();
- }
- userNames.put(userId, name);
- }
- return userNames.get(userId);
- }
-
- public String getUserPath(ResourceResolver resolver, String userId)
- throws UnsupportedRepositoryOperationException, RepositoryException {
- if (!userPaths.containsKey(userId)) {
- final UserManager userManager = resolver.adaptTo(UserManager.class);
- final Authorizable usr = userManager.getAuthorizable(userId);
- if (usr != null) {
- userPaths.put(userId, usr.getPath());
- }
- }
- return userPaths.get(userId);
- }
-
- public boolean isIncludehildren() {
- return includeChildren;
- }
-
- private Date loadDate(String dateStr) throws ParseException {
- Date date = null;
- if (!StringUtils.isEmpty(dateStr)) {
- date = HTML5_DATETIME_FORMAT.parse(dateStr);
- }
- return date;
- }
-
- @Override
- public String toString() {
- return "AuditLogSearchRequest [contentRoot=" + contentRoot + ", includeChildren=" + includeChildren + ", type="
- + type + ", user=" + user + ", startDate=" + startDate + ", endDate=" + endDate + ", order=" + order
- + ", userNames=" + userNames + ", userPaths=" + userPaths + "]";
- }
+ private static final FastDateFormat HTML5_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm", TimeZone.getTimeZone("GMT"));
+ private static final FastDateFormat QUERY_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss", TimeZone.getTimeZone("GMT"));
+
+ private static String getJcrSqlDate(Date date) {
+ return QUERY_DATE_FORMAT.format(date) + ".000Z";
+ }
+
+ private final String contentRoot;
+ private final boolean includeChildren;
+ private final String type;
+ private final String user;
+ private final Date startDate;
+ private final Date endDate;
+ private final String order;
+ private Map userNames = new HashMap();
+
+ private Map userPaths = new HashMap();
+
+ /**
+ * Constructs a new AuditLogSearchRequest from the SlingHttpServletRequest
+ *
+ * @param request
+ * yep, that's a request... guess what it does
+ * @throws ParseException
+ * an exception occurred parsing the start / end date
+ */
+ public AuditLogSearchRequest(SlingHttpServletRequest request) throws ParseException {
+ contentRoot = request.getParameter("contentRoot");
+ includeChildren = "true".equals(request.getParameter("includeChildren"));
+ type = request.getParameter("type");
+ user = request.getParameter("user");
+ startDate = loadDate(request.getParameter("startDate"));
+ endDate = loadDate(request.getParameter("endDate"));
+ order = request.getParameter("order");
+ }
+
+ public String getContentRoot() {
+ return contentRoot;
+ }
+
+ public Date getEndDate() {
+ return endDate;
+ }
+
+ public String getOrder() {
+ return order;
+ }
+
+ public String getQueryParameters() {
+ List expressions = new ArrayList();
+
+ if (!StringUtils.isEmpty(type)) {
+ expressions.add("[cq:type]='" + StringEscapeUtils.escapeSql(type) + "'");
+ }
+ if (!StringUtils.isEmpty(user)) {
+ expressions.add("[cq:userid]='" + StringEscapeUtils.escapeSql(user) + "'");
+ }
+ if (StringUtils.isNotEmpty(contentRoot)) {
+ if (includeChildren) {
+ expressions.add("[cq:path] LIKE '" + StringEscapeUtils.escapeSql(contentRoot) + "%'");
+ } else {
+ expressions.add("[cq:path]='" + StringEscapeUtils.escapeSql(contentRoot) + "'");
+ }
+ }
+ if (startDate != null) {
+ expressions.add("[cq:time] > CAST('" + getJcrSqlDate(startDate) + "' AS DATE)");
+ }
+ if (endDate != null) {
+ expressions.add("[cq:time] < CAST('" + getJcrSqlDate(endDate) + "' AS DATE)");
+ }
+ String query = StringUtils.join(expressions, " AND ");
+ if (!StringUtils.isEmpty(order)) {
+ query += " ORDER BY " + order;
+ }
+ return query;
+ }
+
+ public Date getStartDate() {
+ return startDate;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public String getUserName(ResourceResolver resolver, String userId) throws RepositoryException {
+ if (!userNames.containsKey(userId)) {
+ final UserPropertiesManager upm = resolver.adaptTo(UserPropertiesManager.class);
+ UserProperties userProperties = upm.getUserProperties(userId, UserPropertiesService.PROFILE_PATH);
+ String name = userId;
+ if (userProperties != null && !StringUtils.isEmpty(userProperties.getDisplayName())) {
+ name = userProperties.getDisplayName();
+ }
+ userNames.put(userId, name);
+ }
+ return userNames.get(userId);
+ }
+
+ public String getUserPath(ResourceResolver resolver, String userId)
+ throws UnsupportedRepositoryOperationException, RepositoryException {
+ if (!userPaths.containsKey(userId)) {
+ final UserManager userManager = resolver.adaptTo(UserManager.class);
+ final Authorizable usr = userManager.getAuthorizable(userId);
+ if (usr != null) {
+ userPaths.put(userId, usr.getPath());
+ }
+ }
+ return userPaths.get(userId);
+ }
+
+ public boolean isIncludehildren() {
+ return includeChildren;
+ }
+
+ private Date loadDate(String dateStr) throws ParseException {
+ Date date = null;
+ if (!StringUtils.isEmpty(dateStr)) {
+ date = HTML5_DATETIME_FORMAT.parse(dateStr);
+ }
+ return date;
+ }
+
+ @Override
+ public String toString() {
+ return "AuditLogSearchRequest [contentRoot=" + contentRoot + ", includeChildren=" + includeChildren + ", type="
+ + type + ", user=" + user + ", startDate=" + startDate + ", endDate=" + endDate + ", order=" + order
+ + ", userNames=" + userNames + ", userPaths=" + userPaths + "]";
+ }
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/impl/AuditLogSearchServlet.java b/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/impl/AuditLogSearchServlet.java
index f8f2041139..d9cc44ed43 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/impl/AuditLogSearchServlet.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/audit_log_search/impl/AuditLogSearchServlet.java
@@ -1,4 +1,3 @@
-
/*
* #%L
* ACS AEM Commons Bundle
@@ -50,142 +49,135 @@
import java.util.Set;
@SlingServlet(label = "ACS AEM Commons - Audit Log Search Servlet", methods = { "GET" }, resourceTypes = {
- "acs-commons/components/utilities/audit-log-search" }, selectors = {
- "auditlogsearch" }, extensions = { "json" }, metatype = true)
+ "acs-commons/components/utilities/audit-log-search" }, selectors = {
+ "auditlogsearch" }, extensions = { "json" }, metatype = true)
+@SuppressWarnings("serial")
public class AuditLogSearchServlet extends SlingSafeMethodsServlet {
- private static final long serialVersionUID = 7661105540626580845L;
-
- private static final Logger log = LoggerFactory.getLogger(AuditLogSearchServlet.class);
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.
- * sling.api.SlingHttpServletRequest,
- * org.apache.sling.api.SlingHttpServletResponse)
- */
- @Override
- protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
- throws ServletException, IOException {
-
- log.trace("doGet");
-
- AuditLogSearchRequest req = null;
- try {
- JSONObject result = new JSONObject();
- boolean succeeded = true;
- try {
- req = new AuditLogSearchRequest(request);
- log.debug("Loaded search request: {}", req);
-
- JSONArray results = new JSONArray();
- long count = 0;
- String whereClause = req.getQueryParameters();
- StringBuilder queryBuilder = new StringBuilder("SELECT * FROM [cq:AuditEvent] AS s");
- if (StringUtils.isNotEmpty(whereClause)) {
- queryBuilder.append(" WHERE ").append(whereClause);
- }
- String queryStr = queryBuilder.toString();
- log.debug("Finding audit events with: {}", queryStr);
- ResourceResolver resolver = request.getResourceResolver();
- QueryManager queryManager = resolver.adaptTo(Session.class).getWorkspace().getQueryManager();
- Query query = queryManager.createQuery(queryStr, Query.JCR_SQL2);
-
- int limit = -1;
- if (StringUtils.isNotEmpty(request.getParameter("limit"))) {
- limit = Integer.parseInt(request.getParameter("limit"), 10);
- if (limit > 0) {
- log.debug("Limiting to {} results", limit);
- query.setLimit(limit);
- }
- }
-
- NodeIterator nodes = query.execute().getNodes();
- log.debug("Query execution complete!");
- while (nodes.hasNext()) {
- results.put(serializeAuditEvent(resolver.getResource(nodes.nextNode().getPath()), req));
- count++;
- }
- result.put("count", count);
- result.put("events", results);
- log.debug("Found {} audit events", count);
- } catch (ParseException e) {
- log.warn("Encountered exception parsing start / end date", e);
- succeeded = false;
- } catch (RepositoryException e) {
- log.warn("Encountered respository exception attempting to retrieve audit events", e);
- succeeded = false;
- } catch (ClassNotFoundException e) {
- log.warn("Encountered exception deserializing attributes", e);
- succeeded = false;
- }
-
- result.put("succeeded", succeeded);
-
- response.setContentType("application/json");
- response.getWriter().write(result.toString());
- } catch (JSONException e) {
- throw new ServletException("Failed to serialize JSON", e);
- }
- }
-
- private JSONObject serializeAuditEvent(Resource auditEventResource, AuditLogSearchRequest request)
- throws JSONException, RepositoryException, IOException, ClassNotFoundException {
- JSONObject auditEvent = new JSONObject();
- ValueMap properties = auditEventResource.getValueMap();
- auditEvent.put("category", properties.get("cq:category", String.class));
- auditEvent.put("eventPath", auditEventResource.getPath());
- auditEvent.put("path", properties.get("cq:path", String.class));
- auditEvent.put("type", properties.get("cq:type", String.class));
- String userId = properties.get("cq:userid", String.class);
- auditEvent.put("userId", userId);
- auditEvent.put("userName", request.getUserName(auditEventResource.getResourceResolver(), userId));
- auditEvent.put("userPath", request.getUserPath(auditEventResource.getResourceResolver(), userId));
- auditEvent.put("time", properties.get("cq:time", new Date()).getTime());
-
- JSONArray modified = getModifiedProperties(properties);
- if (properties.get("above", String.class) != null) {
- modified.put("above=" + properties.get("above", String.class));
- }
- if (properties.get("destination", String.class) != null) {
- modified.put("destination=" + properties.get("destination", String.class));
- }
- if (properties.get("versionId", String.class) != null) {
- modified.put("versionId=" + properties.get("versionId", String.class));
- }
- if (modified.length() != 0) {
- auditEvent.put("modified", modified);
- }
-
- return auditEvent;
- }
-
- @SuppressWarnings("unchecked")
- private JSONArray getModifiedProperties(ValueMap properties) throws IOException {
- JSONArray modifiedProperties = new JSONArray();
- InputStream is = properties.get("cq:properties", InputStream.class);
- if (is != null) {
- ObjectInputStream ois = new ObjectInputStream(is);
- ois.readInt();
-
- while (ois.available() != -1) {
- try {
- Object obj = ois.readObject();
- if (obj instanceof HashSet) {
- Set propertiesSet = (Set) obj;
- for (String property : propertiesSet) {
- modifiedProperties.put(property);
- }
- break;
- }
- } catch (Exception e) {
- break;
- }
- }
- }
- return modifiedProperties;
- }
+ private static final Logger log = LoggerFactory.getLogger(AuditLogSearchServlet.class);
+
+
+ @Override
+ @SuppressWarnings("squid:S1141")
+ protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
+ throws ServletException, IOException {
+
+ log.trace("doGet");
+
+ AuditLogSearchRequest req = null;
+ try {
+ JSONObject result = new JSONObject();
+ boolean succeeded = true;
+ try {
+ req = new AuditLogSearchRequest(request);
+ log.debug("Loaded search request: {}", req);
+
+ JSONArray results = new JSONArray();
+ long count = 0;
+ String whereClause = req.getQueryParameters();
+ StringBuilder queryBuilder = new StringBuilder("SELECT * FROM [cq:AuditEvent] AS s");
+ if (StringUtils.isNotEmpty(whereClause)) {
+ queryBuilder.append(" WHERE ").append(whereClause);
+ }
+ String queryStr = queryBuilder.toString();
+ log.debug("Finding audit events with: {}", queryStr);
+ ResourceResolver resolver = request.getResourceResolver();
+ QueryManager queryManager = resolver.adaptTo(Session.class).getWorkspace().getQueryManager();
+ Query query = queryManager.createQuery(queryStr, Query.JCR_SQL2);
+
+ int limit = -1;
+ if (StringUtils.isNotEmpty(request.getParameter("limit"))) {
+ limit = Integer.parseInt(request.getParameter("limit"), 10);
+ if (limit > 0) {
+ log.debug("Limiting to {} results", limit);
+ query.setLimit(limit);
+ }
+ }
+
+ NodeIterator nodes = query.execute().getNodes();
+ log.debug("Query execution complete!");
+ while (nodes.hasNext()) {
+ results.put(serializeAuditEvent(resolver.getResource(nodes.nextNode().getPath()), req));
+ count++;
+ }
+ result.put("count", count);
+ result.put("events", results);
+ log.debug("Found {} audit events", count);
+ } catch (ParseException e) {
+ log.warn("Encountered exception parsing start / end date", e);
+ succeeded = false;
+ } catch (RepositoryException e) {
+ log.warn("Encountered respository exception attempting to retrieve audit events", e);
+ succeeded = false;
+ } catch (ClassNotFoundException e) {
+ log.warn("Encountered exception deserializing attributes", e);
+ succeeded = false;
+ }
+
+ result.put("succeeded", succeeded);
+
+ response.setContentType("application/json");
+ response.getWriter().write(result.toString());
+ } catch (JSONException e) {
+ throw new ServletException("Failed to serialize JSON", e);
+ }
+ }
+
+ private JSONObject serializeAuditEvent(Resource auditEventResource, AuditLogSearchRequest request)
+ throws JSONException, RepositoryException, IOException, ClassNotFoundException {
+ JSONObject auditEvent = new JSONObject();
+ ValueMap properties = auditEventResource.getValueMap();
+ auditEvent.put("category", properties.get("cq:category", String.class));
+ auditEvent.put("eventPath", auditEventResource.getPath());
+ auditEvent.put("path", properties.get("cq:path", String.class));
+ auditEvent.put("type", properties.get("cq:type", String.class));
+ String userId = properties.get("cq:userid", String.class);
+ auditEvent.put("userId", userId);
+ auditEvent.put("userName", request.getUserName(auditEventResource.getResourceResolver(), userId));
+ auditEvent.put("userPath", request.getUserPath(auditEventResource.getResourceResolver(), userId));
+ auditEvent.put("time", properties.get("cq:time", new Date()).getTime());
+
+ JSONArray modified = getModifiedProperties(properties);
+ if (properties.get("above", String.class) != null) {
+ modified.put("above=" + properties.get("above", String.class));
+ }
+ if (properties.get("destination", String.class) != null) {
+ modified.put("destination=" + properties.get("destination", String.class));
+ }
+ if (properties.get("versionId", String.class) != null) {
+ modified.put("versionId=" + properties.get("versionId", String.class));
+ }
+ if (modified.length() != 0) {
+ auditEvent.put("modified", modified);
+ }
+
+ return auditEvent;
+ }
+
+ @SuppressWarnings("unchecked")
+ private JSONArray getModifiedProperties(ValueMap properties) throws IOException {
+ JSONArray modifiedProperties = new JSONArray();
+ InputStream is = properties.get("cq:properties", InputStream.class);
+ if (is != null) {
+ ObjectInputStream ois = new ObjectInputStream(is);
+ ois.readInt();
+
+ while (ois.available() != -1) {
+ try {
+ Object obj = ois.readObject();
+ if (obj instanceof HashSet) {
+ Set propertiesSet = (Set) obj;
+ for (String property : propertiesSet) {
+ modifiedProperties.put(property);
+ }
+ break;
+ }
+ } catch (Exception e) {
+ break;
+ }
+ }
+ }
+ return modifiedProperties;
+ }
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/components/longformtext/LongFormTextComponent.java b/bundle/src/main/java/com/adobe/acs/commons/components/longformtext/LongFormTextComponent.java
index b33ed1b5f3..a5ef753a12 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/components/longformtext/LongFormTextComponent.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/components/longformtext/LongFormTextComponent.java
@@ -25,6 +25,7 @@
import javax.jcr.RepositoryException;
@ProviderType
+@SuppressWarnings("squid:S1214")
public interface LongFormTextComponent {
String LONG_FORM_TEXT_PAR = "long-form-text-par-";
diff --git a/bundle/src/main/java/com/adobe/acs/commons/contentfinder/querybuilder/impl/ContentFinderHitBuilder.java b/bundle/src/main/java/com/adobe/acs/commons/contentfinder/querybuilder/impl/ContentFinderHitBuilder.java
index fed0deb1d6..16885669ee 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/contentfinder/querybuilder/impl/ContentFinderHitBuilder.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/contentfinder/querybuilder/impl/ContentFinderHitBuilder.java
@@ -36,6 +36,8 @@
import java.util.LinkedHashMap;
import java.util.Map;
+import static com.adobe.acs.commons.contentfinder.querybuilder.impl.viewhandler.ContentFinderConstants.*;
+
public final class ContentFinderHitBuilder {
private static final Long ONE_MILLION = 1000000L;
@@ -116,13 +118,13 @@ private static Map addPageData(final Page page, final Hit hit, M
}
}
- map.put("path", page.getPath());
- map.put("name", page.getName());
- map.put("title", title);
- map.put("excerpt", excerpt);
- map.put("ddGroups", "page");
- map.put("type", "Page");
- map.put("lastModified", getLastModified(page));
+ map.put(CF_PATH, page.getPath());
+ map.put(CF_NAME, page.getName());
+ map.put(CF_TITLE, title);
+ map.put(CF_EXCERPT, excerpt);
+ map.put(CF_DD_GROUPS, "page");
+ map.put(CF_TYPE, "Page");
+ map.put(CF_LAST_MODIFIED, getLastModified(page));
return map;
}
@@ -153,15 +155,15 @@ private static Map addAssetData(final Asset asset, final Hit hit
}
}
- map.put("path", asset.getPath());
- map.put("name", asset.getName());
- map.put("title", title);
- map.put("excerpt", excerpt);
- map.put("mimeType", asset.getMimeType());
- map.put("size", getSize(asset));
- map.put("ck", getCK(asset));
- map.put("type", "Asset");
- map.put("lastModified", getLastModified(asset));
+ map.put(CF_PATH, asset.getPath());
+ map.put(CF_NAME, asset.getName());
+ map.put(CF_TITLE, title);
+ map.put(CF_EXCERPT, excerpt);
+ map.put(CF_MIMETYPE, asset.getMimeType());
+ map.put(CF_SIZE, getSize(asset));
+ map.put(CF_CACHE_KILLER, getCacheKiller(asset));
+ map.put(CF_TYPE, "Asset");
+ map.put(CF_LAST_MODIFIED, getLastModified(asset));
return map;
}
@@ -179,12 +181,12 @@ private static Map addOtherData(final Hit hit, Map addName(final SlingHttpServletRequest request,
return map;
}
+ @SuppressWarnings("squid:S3776")
public static Map addOrder(final SlingHttpServletRequest request, Map map,
final String queryString) {
if (has(request, CF_ORDER)) {
@@ -113,11 +95,10 @@ public static Map addOrder(final SlingHttpServletRequest request
int count = 1;
for (String value : getAll(request, CF_ORDER)) {
value = StringUtils.trim(value);
- final String orderGroupId = String.valueOf(GROUP_ORDERBY_USERDEFINED + count) + "_orderby";
+ final String orderGroupId = String.valueOf(GROUP_ORDERBY_USERDEFINED + count) + SUFFIX_ORDERBY;
boolean sortAsc = false;
if (StringUtils.startsWith(value, "-")) {
- sortAsc = false;
value = StringUtils.removeStart(value, "-");
} else if (StringUtils.startsWith(value, "+")) {
sortAsc = true;
@@ -137,19 +118,19 @@ public static Map addOrder(final SlingHttpServletRequest request
final String prefix = getPropertyPrefix(request);
if (StringUtils.isNotBlank(queryString)) {
- map.put(GROUP_ORDERBY_SCORE + "_orderby", "@" + JcrConstants.JCR_SCORE);
- map.put(GROUP_ORDERBY_SCORE + "_orderby.sort", Predicate.SORT_DESCENDING);
+ map.put(GROUP_ORDERBY_SCORE + SUFFIX_ORDERBY, AT + JcrConstants.JCR_SCORE);
+ map.put(GROUP_ORDERBY_SCORE + SUFFIX_ORDERBY_SORT, Predicate.SORT_DESCENDING);
}
- String modifiedOrderProperty = "@" + JcrConstants.JCR_LASTMODIFIED;
+ String modifiedOrderProperty = AT + JcrConstants.JCR_LASTMODIFIED;
if (isPage) {
- modifiedOrderProperty = "@" + prefix + NameConstants.PN_PAGE_LAST_MOD;
+ modifiedOrderProperty = AT + prefix + NameConstants.PN_PAGE_LAST_MOD;
} else if (isAsset) {
- modifiedOrderProperty = "@" + prefix + JcrConstants.JCR_LASTMODIFIED;
+ modifiedOrderProperty = AT + prefix + JcrConstants.JCR_LASTMODIFIED;
}
- map.put(GROUP_ORDERBY_MODIFIED + "_orderby", modifiedOrderProperty);
- map.put(GROUP_ORDERBY_MODIFIED + "_orderby.sort", Predicate.SORT_DESCENDING);
+ map.put(GROUP_ORDERBY_MODIFIED + SUFFIX_ORDERBY, modifiedOrderProperty);
+ map.put(GROUP_ORDERBY_MODIFIED + SUFFIX_ORDERBY_SORT, Predicate.SORT_DESCENDING);
}
return map;
@@ -172,20 +153,20 @@ public static Map addTags(final SlingHttpServletRequest request,
if (has(request, CF_TAGS)) {
final String prefix = getPropertyPrefix(request);
- final String groupId = GROUP_TAGS + "_group";
+ final String groupId = GROUP_TAGS + SUFFIX_GROUP;
final String tagProperty = prefix + NameConstants.PN_TAGS;
- map.put(groupId + ".p.or", "true");
+ map.put(groupId + SUFFIX_P_OR, "true");
if (hasMany(request, CF_TAGS)) {
final String[] tags = getAll(request, CF_TAGS);
- int i = 1;
+ int counter = 1;
for (final String tag : tags) {
- map.put(groupId + "." + i + "_tagid.property", tagProperty);
- map.put(groupId + "." + i + "_tagid", tag);
+ map.put(groupId + "." + counter + "_tagid.property", tagProperty);
+ map.put(groupId + "." + counter + "_tagid", tag);
- i++;
+ counter++;
}
} else {
map.put(groupId + ".1_tagid.property", tagProperty);
@@ -196,13 +177,14 @@ public static Map addTags(final SlingHttpServletRequest request,
return map;
}
+ @SuppressWarnings("squid:S1172")
public static Map addFulltext(final SlingHttpServletRequest request, Map map,
final String queryString) {
if (StringUtils.isNotBlank(queryString)) {
- final String groupId = GROUP_FULLTEXT + "_group";
+ final String groupId = GROUP_FULLTEXT + SUFFIX_GROUP;
map.put(groupId + "." + FulltextPredicateEvaluator.FULLTEXT, queryString);
- map.put(groupId + ".p.or", "true");
+ map.put(groupId + SUFFIX_P_OR, "true");
}
return map;
}
@@ -340,7 +322,7 @@ public static Map putProperty(SlingHttpServletRequest request, M
*/
public static Map putAll(Map map, String predicate, String[] values,
int group, boolean or) {
- final String groupId = String.valueOf(group) + "_group";
+ final String groupId = String.valueOf(group) + SUFFIX_GROUP;
int count = 1;
for (final String value : values) {
@@ -350,7 +332,7 @@ public static Map putAll(Map map, String predica
count++;
}
- map.put(groupId + ".p.or", String.valueOf(or));
+ map.put(groupId + SUFFIX_P_OR, String.valueOf(or));
return map;
}
@@ -367,7 +349,7 @@ public static Map putAll(Map map, String predica
*/
public static Map putAll(Map map, String predicate, String predicateValue,
String predicateSuffix, String[] values, int group, boolean or) {
- final String groupId = String.valueOf(group) + "_group";
+ final String groupId = String.valueOf(group) + SUFFIX_GROUP;
map.put(groupId + "." + predicate, predicateValue);
@@ -379,7 +361,7 @@ public static Map putAll(Map map, String predica
count++;
}
- map.put(groupId + ".p.or", String.valueOf(or));
+ map.put(groupId + SUFFIX_P_OR, String.valueOf(or));
return map;
}
@@ -467,14 +449,9 @@ public static int getOffset(final SlingHttpServletRequest request) {
final String value = get(request, CF_LIMIT);
final String[] offsets = StringUtils.split(value, "..");
- if (value.matches("^(\\d)+\\.\\.(\\d)+$")) {
- // 10..20
- return Integer.parseInt(offsets[0]);
- } else if (value.matches("^\\.\\.(\\d)+$")) {
- // ..20
- return Integer.parseInt(offsets[0]);
- } else if (value.matches("^(\\d)+\\.\\.$")) {
- // 20..
+ if (value.matches("^(\\d)+\\.\\.(\\d)+$") // 10..20
+ || value.matches("^\\.\\.(\\d)+$") // ..20
+ || value.matches("^(\\d)+\\.\\.$") ) { // 20..
return Integer.parseInt(offsets[0]);
}
log.info("Could not find valid OFFSET for QueryBuilder-based ContentFinder: {}", value);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/ColorConversion.java b/bundle/src/main/java/com/adobe/acs/commons/dam/ColorConversion.java
index 899673cdb4..3921153c09 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/ColorConversion.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/ColorConversion.java
@@ -25,6 +25,7 @@
* Service interface for performing color space conversion operations.
*/
@ProviderType
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
public interface ColorConversion {
/**
@@ -57,15 +58,16 @@ public RGB(int red, int green, int blue) {
@Override
public String toString() {
- return "RGB{" +
- "red=" + red +
- ", green=" + green +
- ", blue=" + blue +
- '}';
+ return "RGB{"
+ + "red=" + red
+ + ", green=" + green
+ + ", blue=" + blue
+ + '}';
}
}
@ProviderType
+ @SuppressWarnings({"checkstyle:membername", "checkstyle:parametername"})
final class LAB {
public final float lightness;
public final int a;
@@ -79,11 +81,11 @@ public LAB(float lightness, int a, int b) {
@Override
public String toString() {
- return "LAB{" +
- "lightness=" + lightness +
- ", a=" + a +
- ", b=" + b +
- '}';
+ return "LAB{"
+ + "lightness=" + lightness
+ + ", a=" + a
+ + ", b=" + b
+ + '}';
}
}
@@ -103,12 +105,12 @@ public CMYK(int cyan, int magenta, int yellow, int black) {
@Override
public String toString() {
- return "CYMK{" +
- "cyan=" + cyan +
- ", magenta=" + magenta +
- ", yellow=" + yellow +
- ", black=" + black +
- '}';
+ return "CYMK{"
+ + "cyan=" + cyan
+ + ", magenta=" + magenta
+ + ", yellow=" + yellow
+ + ", black=" + black
+ + '}';
}
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/RenditionPatternPicker.java b/bundle/src/main/java/com/adobe/acs/commons/dam/RenditionPatternPicker.java
index 848460d65e..95a1523f34 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/RenditionPatternPicker.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/RenditionPatternPicker.java
@@ -42,20 +42,20 @@ public class RenditionPatternPicker implements RenditionPicker {
* Create an Asset Rendition Picker that will pick a Rendition by matching
* the supplied Regex pattern (as String).
*
- * @param p Regex pattern to match against Rendition names.
+ * @param pattern Regex pattern to match against Rendition names.
*/
- public RenditionPatternPicker(String p) {
- this.pattern = Pattern.compile(p);
+ public RenditionPatternPicker(String pattern) {
+ this.pattern = Pattern.compile(pattern);
}
/**
* Create an Asset Rendition Picker that will pick a Rendition by matching
* the supplied Regex pattern.
*
- * @param p Pattern used to find the Asset rendition
+ * @param pattern Pattern used to find the Asset rendition
*/
- public RenditionPatternPicker(final Pattern p) {
- this.pattern = p;
+ public RenditionPatternPicker(final Pattern pattern) {
+ this.pattern = pattern;
}
private Pattern getPattern() {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/AudioHelperImpl.java b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/AudioHelperImpl.java
index 0ab04ddf5d..0eb88a27b9 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/AudioHelperImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/AudioHelperImpl.java
@@ -59,31 +59,34 @@ public class AudioHelperImpl implements AudioHelper {
protected final void activate(ComponentContext ctx) {
String slingHome = ctx.getBundleContext().getProperty("sling.home");
workingDir = FFMpegAudioUtils.resolveWorkingDir(slingHome, (String) ctx.getProperties().get(PROP_WORKING_DIR));
- if (!workingDir.exists()) {
- if (!workingDir.mkdirs()) {
- throw new IllegalStateException("Could not create " + workingDir.getPath());
- }
+ if (!workingDir.exists() && !workingDir.mkdirs()) {
+ throw new IllegalStateException("Could not create " + workingDir.getPath());
}
}
@Override
+ @SuppressWarnings("squid:S2095")
public R process(Asset asset, ResourceResolver resourceResolver, A args, AudioProcessor audioProcessor)
throws AudioException {
File tmpDir = null;
File tmpWorkingDir = null;
- FileOutputStream fos = null;
- InputStream is = null;
+
try {
// creating temp directory
tmpDir = FFMpegAudioUtils.createTempDir(null);
// creating temp working directory for ffmpeg
tmpWorkingDir = FFMpegAudioUtils.createTempDir(workingDir);
+ } catch (IOException e) {
+ throw new AudioException(e);
+ }
+
+ // streaming file to temp directory
+ final File tmpFile = new File(tmpDir, asset.getName().replace(' ', '_'));
+
+ try (FileOutputStream fos = new FileOutputStream(tmpFile);
+ InputStream is = asset.getOriginal().getStream();) {
- // streaming file to temp directory
- final File tmpFile = new File(tmpDir, asset.getName().replace(' ', '_'));
- fos = new FileOutputStream(tmpFile);
- is = asset.getOriginal().getStream();
IOUtils.copy(is, fos);
return audioProcessor.processAudio(asset, resourceResolver, tmpFile, locator, tmpWorkingDir, args);
@@ -94,8 +97,6 @@ public R process(Asset asset, ResourceResolver resourceResolver, A args,
log.error(e.getMessage(), e);
return null;
} finally {
- IOUtils.closeQuietly(is);
- IOUtils.closeQuietly(fos);
try {
// cleaning up temp directory
if (tmpDir != null) {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioEncodeProcess.java b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioEncodeProcess.java
index ae1d008a57..e7a113c88e 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioEncodeProcess.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioEncodeProcess.java
@@ -22,6 +22,7 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
+import java.nio.file.Files;
import java.util.List;
import javax.jcr.Node;
@@ -61,6 +62,7 @@
@Component
@Service(WorkflowProcess.class)
@Properties({ @Property(name = "process.label", value = "Encode Audio") })
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
public final class FFMpegAudioEncodeProcess implements WorkflowProcess, AudioHelper.AudioProcessor {
@Reference
@@ -71,7 +73,7 @@ public final class FFMpegAudioEncodeProcess implements WorkflowProcess, AudioHel
private static final Logger log = LoggerFactory.getLogger(FFMpegAudioEncodeProcess.class);
- @SuppressWarnings("PMD.CollapsibleIfStatements")
+ @SuppressWarnings({"PMD.CollapsibleIfStatements", "squid:S1066"})
@Override
public final void execute(WorkItem workItem, WorkflowSession wfSession, MetaDataMap metaData)
throws WorkflowException {
@@ -86,7 +88,7 @@ public final void execute(WorkItem workItem, WorkflowSession wfSession, MetaData
}
final String assetMimeType = pair.asset.getMimeType();
- if (assetMimeType == null || !assetMimeType.startsWith("audio/")) {
+ if ((assetMimeType == null || !assetMimeType.startsWith("audio/"))) {
if (!pair.asset.getName().endsWith(".wav") || !pair.asset.getName().endsWith(".mp3")
|| !pair.asset.getName().endsWith(".ogg")) {
log.info("execute: asset [{}] is not of a audio mime type, asset ignored.", pair.asset.getPath());
@@ -104,6 +106,7 @@ public final void execute(WorkItem workItem, WorkflowSession wfSession, MetaData
}
@Override
+ @SuppressWarnings({"squid:S3776", "squid:S1141"})
public Void processAudio(final Asset asset, final ResourceResolver resourceResolver, final File tempFile,
final ExecutableLocator locator, final File workingDir, final MetaDataMap metaData) throws AudioException {
@@ -125,8 +128,10 @@ public Void processAudio(final Asset asset, final ResourceResolver resourceResol
final File transcodedAudio = ffmpegWrapper.transcode();
fis = new FileInputStream(transcodedAudio);
asset.addRendition(renditionName, fis, ffmpegWrapper.getOutputMimetype());
- if (!transcodedAudio.delete()) {
- log.error("Transcoded audio file @ {} coud not be deleted");
+ try {
+ Files.delete(transcodedAudio.toPath());
+ } catch (Exception e) {
+ log.error("Transcoded audio file @ " + transcodedAudio.getAbsolutePath() +" coud not be deleted", e);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioUtils.java b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioUtils.java
index 520d70decf..b34d0ca39a 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioUtils.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/impl/FFMpegAudioUtils.java
@@ -19,13 +19,14 @@
*/
package com.adobe.acs.commons.dam.audio.impl;
-import org.apache.felix.scr.annotations.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class FFMpegAudioUtils {
private static final Logger log = LoggerFactory.getLogger(FFMpegAudioUtils.class);
@@ -65,18 +66,6 @@ public static File resolveWorkingDir(String slingHome, String path) {
}
public static final File createTempDir(File parentDir) throws IOException {
- File tempDir = null;
- try {
- tempDir = File.createTempFile("cqdam", null, parentDir);
- if (!tempDir.delete()) {
- throw new IOException("Unable to delete temp directory.");
- }
- if (!tempDir.mkdir()) {
- throw new IOException("Unable to create temp directory.");
- }
- } catch (IOException e) {
- log.warn("could not create temp directory in the [{}] with the exception", parentDir, e);
- }
- return tempDir;
+ return Files.createTempDirectory(parentDir.toPath(), "cqdam").toFile();
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionProcess.java b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionProcess.java
index 2f99c2ecb1..6bf2180656 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionProcess.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionProcess.java
@@ -48,6 +48,7 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
+import java.nio.file.Files;
import java.util.Map;
@Component(metatype = true, label = "ACS AEM Commons - Watson Transcription Workflow Process",
@@ -104,6 +105,7 @@ public Serializable execute(WorkItem workItem, WorkflowSession workflowSession,
}
@Override
+ @SuppressWarnings("squid:S1141")
public Serializable processAudio(Asset asset, ResourceResolver resourceResolver, File tempFile,
ExecutableLocator locator, File workingDir, MetaDataMap args) throws AudioException {
final long start = System.currentTimeMillis();
@@ -122,8 +124,10 @@ public Serializable processAudio(Asset asset, ResourceResolver resourceResolver,
FileInputStream stream = new FileInputStream(transcodedAudio);
jobId = transcriptionService.startTranscriptionJob(stream, ffmpegWrapper.getOutputMimetype());
IOUtils.closeQuietly(stream);
- if (!transcodedAudio.delete()) {
- log.error("Transcoded audio file @ {} coud not be deleted");
+ try {
+ Files.delete(transcodedAudio.toPath());
+ } catch (Exception e) {
+ log.error("Transcoded audio file @ " + transcodedAudio.getAbsolutePath() + " coud not be deleted", e);
}
} catch (IOException e) {
log.error("processAudio: failed creating audio from profile [{}]: {}",
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionServiceImpl.java b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionServiceImpl.java
index a880c10752..5f334ab19c 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionServiceImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/audio/watson/impl/TranscriptionServiceImpl.java
@@ -46,15 +46,11 @@ public class TranscriptionServiceImpl implements TranscriptionService {
@Reference(target = "(factory.name=watson-speech-to-text)")
private HttpClientFactory httpClientFactory;
- @Activate
- protected void activate(Map config) {
- }
-
@Override
public String startTranscriptionJob(InputStream stream, String mimeType) {
- Request request = httpClientFactory.post("/speech-to-text/api/v1/recognitions?continuous=true×tamps=true").
- addHeader("Content-Type", mimeType).
- bodyStream(stream);
+ Request request = httpClientFactory.post("/speech-to-text/api/v1/recognitions?continuous=true×tamps=true")
+ .addHeader("Content-Type", mimeType)
+ .bodyStream(stream);
try {
JSONObject json = httpClientFactory.getExecutor().execute(request).handleResponse(HANDLER);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AddWatermarkToRenditionProcess.java b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AddWatermarkToRenditionProcess.java
index 03e5095054..aba13b2a77 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AddWatermarkToRenditionProcess.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AddWatermarkToRenditionProcess.java
@@ -70,6 +70,7 @@ private static void logMissingWatermark(final String path) {
log.warn("Watermark path {} is not found.", path);
}
}
+
private static void logInvalidWatermark(final String path) {
if (watermarkLogCache.putIfAbsent(path, new Object()) == null) {
log.warn("Watermark path {} is not valid.", path);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AssetsFolderPropertiesSupport.java b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AssetsFolderPropertiesSupport.java
index 914f0754e4..62e20c6ede 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AssetsFolderPropertiesSupport.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AssetsFolderPropertiesSupport.java
@@ -21,7 +21,12 @@
package com.adobe.acs.commons.dam.impl;
import org.apache.commons.lang3.StringUtils;
-import org.apache.felix.scr.annotations.*;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.ConfigurationPolicy;
+import org.apache.felix.scr.annotations.Properties;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
@@ -38,7 +43,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.servlet.*;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
@@ -148,6 +158,7 @@ public void process(SlingHttpServletRequest request, List changes)
* @param request the request
* @return true if Assets Folder Properties Support should process this request.
*/
+ @SuppressWarnings("squid:S3923")
protected boolean accepts(SlingHttpServletRequest request) {
if (!StringUtils.equalsIgnoreCase(POST_METHOD, request.getMethod())) {
// Only POST methods are processed
@@ -170,7 +181,7 @@ protected boolean accepts(SlingHttpServletRequest request) {
/**
* This method handles the READING of the properties so that granite UI widgets can display stored data in the form.
- * This needs to be included AFTER /apps/dam/gui/content/assets/foldersharewizard/jcr:content/body/items/form/items/wizard/items/settingStep/items/fixedColumns/items/fixedColumn2/items/tabs/items/tab1/items/folderproperties
+ * This needs to be included AFTER /apps/dam/gui/content/assets/foldersharewizard/jcr:content/body/items/form/items/wizard/items/settingStep/items/fixedColumns/items/fixedColumn2/items/tabs/items/tab1/items/folderproperties
* such that it can augment the Property map constructed by that OOTB script.
*
* Note that this exposes a value map for the [sling:*Folder] node, and NOT the [sling:*Folder]/jcr:content, so properties must be prefixed with jcr:content/...
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ColorConversionImpl.java b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ColorConversionImpl.java
index e6c4fc4682..fcf237d343 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ColorConversionImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ColorConversionImpl.java
@@ -35,6 +35,7 @@
@Component(label = "ACS AEM Commons - Color Conversion", description = "ACS AEM Commons - Color Conversion", metatype = true)
@Service
+@SuppressWarnings({"checkstyle:abbreviationaswordinname", "checkstyle:localvariablename"})
public final class ColorConversionImpl implements ColorConversion {
private static final String DEFAULT_CMYK_PROFILE = "JapanColor2001Coated";
@@ -171,6 +172,7 @@ private XYZ toXYZ(LAB lab) {
}
+ @SuppressWarnings("checkstyle.membername")
private class XYZ {
private double x;
private double y;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/MatteRenditionProcess.java b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/MatteRenditionProcess.java
index 61e9c64ce7..4dbded8648 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/MatteRenditionProcess.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/MatteRenditionProcess.java
@@ -44,6 +44,7 @@
@Component(metatype = false)
@Service
@Property(name = "process.label", value = "Matte Rendition")
+@SuppressWarnings({"squid:S00115", "checkstyle:localvariablename"})
public final class MatteRenditionProcess extends AbstractRenditionModifyingProcess implements WorkflowProcess {
private static final int RADIX_HEX = 16;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ReviewTaskAssetMoverHandler.java b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ReviewTaskAssetMoverHandler.java
index 990a0e8270..e296a39747 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ReviewTaskAssetMoverHandler.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/dam/impl/ReviewTaskAssetMoverHandler.java
@@ -31,6 +31,7 @@
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang.UnhandledException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
@@ -115,6 +116,7 @@ public class ReviewTaskAssetMoverHandler implements EventHandler {
private static final String SERVICE_NAME = "review-task-asset-mover";
private static final Map AUTH_INFO;
+
static {
AUTH_INFO = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object) SERVICE_NAME);
}
@@ -221,14 +223,7 @@ public void run() {
while (assets.hasNext()) {
final Asset asset = assets.next().adaptTo(Asset.class);
-
- try {
- moveAsset(resourceResolver, assetManager, asset, taskProperties);
- } catch (Exception e) {
- log.error("Could not move reviewed asset [ {} ]", asset.getPath(), e);
- resourceResolver.revert();
- resourceResolver.refresh();
- }
+ moveAsset(resourceResolver, assetManager, asset, taskProperties);
}
}
}
@@ -279,9 +274,9 @@ private Iterator findAssets(ResourceResolver resourceResolver, String
* @param destPath the folder the asset will be moved into
* @param assetName the asset name
* @return a unique asset path to the asset
- * @throws Exception
+ * @throws PersistenceException
*/
- private String createUniqueAssetPath(AssetManager assetManager, String destPath, String assetName) throws Exception {
+ private String createUniqueAssetPath(AssetManager assetManager, String destPath, String assetName) throws PersistenceException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String now = sdf.format(new Date());
String destAssetPath = destPath + "/" + assetName;
@@ -289,7 +284,7 @@ private String createUniqueAssetPath(AssetManager assetManager, String destPath,
int count = 0;
while (assetManager.assetExists(destAssetPath)) {
if (count > 1000) {
- throw new Exception("Unable to generate a unique name after 1000 attempts. Something must be wrong!");
+ throw new PersistenceException("Unable to generate a unique name after 1000 attempts. Something must be wrong!");
}
if (count == 0) {
@@ -352,60 +347,67 @@ private void createRevision(ResourceResolver resourceResolver, AssetManager asse
* @param asset the asset to move
* @param taskProperties the task properties containing the target onApproveMoveTo and onRejectMoveTo paths
*/
- private void moveAsset(ResourceResolver resourceResolver, AssetManager assetManager, Asset asset, ValueMap taskProperties) throws Exception {
- final String status = asset.getValueMap().get(REL_PN_DAM_STATUS, String.class);
- final String conflictResolution = taskProperties.get(PN_CONFLICT_RESOLUTION, defaultConflictResolution);
- final String onApprovePath = taskProperties.get(PN_ON_APPROVE, String.class);
- final String onRejectPath = taskProperties.get(PN_ON_REJECT, String.class);
-
- String destPath = null;
-
- if (StringUtils.equals(APPROVED, status)) {
- destPath = onApprovePath;
- } else if (StringUtils.equals(REJECTED, status)) {
- destPath = onRejectPath;
- }
+ @SuppressWarnings("squid:S3776")
+ private void moveAsset(ResourceResolver resourceResolver, AssetManager assetManager, Asset asset, ValueMap taskProperties) {
+ try {
+ final String status = asset.getValueMap().get(REL_PN_DAM_STATUS, String.class);
+ final String conflictResolution = taskProperties.get(PN_CONFLICT_RESOLUTION, defaultConflictResolution);
+ final String onApprovePath = taskProperties.get(PN_ON_APPROVE, String.class);
+ final String onRejectPath = taskProperties.get(PN_ON_REJECT, String.class);
- if (destPath != null) {
- if (StringUtils.startsWith(destPath, PATH_CONTENT_DAM)) {
+ String destPath = null;
- String destAssetPath = destPath + "/" + asset.getName();
- final boolean exists = assetManager.assetExists(destAssetPath);
+ if (StringUtils.equals(APPROVED, status)) {
+ destPath = onApprovePath;
+ } else if (StringUtils.equals(REJECTED, status)) {
+ destPath = onRejectPath;
+ }
- if (exists) {
- if (StringUtils.equals(asset.getPath(), destAssetPath)) {
- log.info("Reviewed asset [ {} ] is already in its final location, so there is nothing to do.", asset.getPath());
- } else if (CONFLICT_RESOLUTION_REPLACE.equals(conflictResolution)) {
- assetManager.removeAsset(destAssetPath);
- resourceResolver.commit();
- assetManager.moveAsset(asset.getPath(), destAssetPath);
- log.info("Moved with replace [ {} ] ~> [ {} ] based on approval status [ {} ]",
- new String[]{asset.getPath(), destAssetPath, status});
- } else if (CONFLICT_RESOLUTION_NEW_ASSET.equals(conflictResolution)) {
- destAssetPath = createUniqueAssetPath(assetManager, destPath, asset.getName());
+ if (destPath != null) {
+ if (StringUtils.startsWith(destPath, PATH_CONTENT_DAM)) {
+
+ String destAssetPath = destPath + "/" + asset.getName();
+ final boolean exists = assetManager.assetExists(destAssetPath);
+
+ if (exists) {
+ if (StringUtils.equals(asset.getPath(), destAssetPath)) {
+ log.info("Reviewed asset [ {} ] is already in its final location, so there is nothing to do.", asset.getPath());
+ } else if (CONFLICT_RESOLUTION_REPLACE.equals(conflictResolution)) {
+ assetManager.removeAsset(destAssetPath);
+ resourceResolver.commit();
+ assetManager.moveAsset(asset.getPath(), destAssetPath);
+ log.info("Moved with replace [ {} ] ~> [ {} ] based on approval status [ {} ]",
+ new String[]{asset.getPath(), destAssetPath, status});
+ } else if (CONFLICT_RESOLUTION_NEW_ASSET.equals(conflictResolution)) {
+ destAssetPath = createUniqueAssetPath(assetManager, destPath, asset.getName());
+ assetManager.moveAsset(asset.getPath(), destAssetPath);
+ log.info("Moved with unique asset name [ {} ] ~> [ {} ] based on approval status [ {} ]",
+ new String[]{asset.getPath(), destAssetPath, status});
+ } else if (CONFLICT_RESOLUTION_NEW_VERSION.equals(conflictResolution)) {
+ log.info("Creating new version of existing asset [ {} ] ~> [ {} ] based on approval status [ {} ]",
+ new String[]{asset.getPath(), destAssetPath, status});
+ createRevision(resourceResolver, assetManager, assetManager.getAsset(destAssetPath), asset);
+ } else if (CONFLICT_RESOLUTION_SKIP.equals(conflictResolution)) {
+ log.info("Skipping with due to existing asset at the same destination [ {} ] ~> [ {} ] based on approval status [ {} ]",
+ new String[]{asset.getPath(), destAssetPath, status});
+ }
+ } else {
assetManager.moveAsset(asset.getPath(), destAssetPath);
- log.info("Moved with unique asset name [ {} ] ~> [ {} ] based on approval status [ {} ]",
- new String[]{asset.getPath(), destAssetPath, status});
- } else if (CONFLICT_RESOLUTION_NEW_VERSION.equals(conflictResolution)) {
- log.info("Creating new version of existing asset [ {} ] ~> [ {} ] based on approval status [ {} ]",
+ log.info("Moved [ {} ] ~> [ {} ] based on approval status [ {} ]",
new String[]{asset.getPath(), destAssetPath, status});
- createRevision(resourceResolver, assetManager, assetManager.getAsset(destAssetPath), asset);
- } else if (CONFLICT_RESOLUTION_SKIP.equals(conflictResolution)) {
- log.info("Skipping with due to existing asset at the same destination [ {} ] ~> [ {} ] based on approval status [ {} ]",
- new String[] { asset.getPath(), destAssetPath, status });
}
} else {
- assetManager.moveAsset(asset.getPath(), destAssetPath);
- log.info("Moved [ {} ] ~> [ {} ] based on approval status [ {} ]",
- new String[]{asset.getPath(), destAssetPath, status});
+ log.warn("Request to move reviewed asset to a non DAM Asset path [ {} ]", destPath);
}
- } else {
- log.warn("Request to move reviewed asset to a non DAM Asset path [ {} ]", destPath);
}
- }
- if (resourceResolver.hasChanges()) {
- resourceResolver.commit();
+ if (resourceResolver.hasChanges()) {
+ resourceResolver.commit();
+ }
+ } catch (PersistenceException e) {
+ log.error("Could not move reviewed asset [ {} ]", asset.getPath(), e);
+ resourceResolver.revert();
+ resourceResolver.refresh();
}
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/designer/DesignHtmlLibraryManager.java b/bundle/src/main/java/com/adobe/acs/commons/designer/DesignHtmlLibraryManager.java
index bba7bb2b36..89fd7c9043 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/designer/DesignHtmlLibraryManager.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/designer/DesignHtmlLibraryManager.java
@@ -32,6 +32,7 @@
* A service interface for looking up client libraries based on a Design.
*/
@ProviderType
+@SuppressWarnings("squid:S1214")
public interface DesignHtmlLibraryManager {
/**
diff --git a/bundle/src/main/java/com/adobe/acs/commons/designer/impl/OptionsServlet.java b/bundle/src/main/java/com/adobe/acs/commons/designer/impl/OptionsServlet.java
index e5d9bb4e4e..080bb86f2f 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/designer/impl/OptionsServlet.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/designer/impl/OptionsServlet.java
@@ -51,6 +51,7 @@ public class OptionsServlet extends SlingSafeMethodsServlet {
private HtmlLibraryManager libraryManager;
@Override
+ @SuppressWarnings({"squid:S3776", "squid:S1141"})
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
diff --git a/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java b/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java
index d6c89f7858..7c0631d032 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/email/impl/EmailServiceImpl.java
@@ -73,6 +73,7 @@
public final class EmailServiceImpl implements EmailService {
private static final Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);
+ private static final String MSG_INVALID_RECIPIENTS = "Invalid Recipients";
@Reference
private MessageGatewayService messageGatewayService;
@@ -109,7 +110,7 @@ public List sendEmail(final String templatePath,
List failureList = new ArrayList();
if (recipients == null || recipients.length <= 0) {
- throw new IllegalArgumentException("Invalid Recipients");
+ throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
}
List addresses = new ArrayList(recipients.length);
@@ -138,7 +139,7 @@ public List sendEmail(final String templatePath, final Map failureList = new ArrayList();
if (recipients == null || recipients.length <= 0) {
- throw new IllegalArgumentException("Invalid Recipients");
+ throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
}
final MailTemplate mailTemplate = this.getMailTemplate(templatePath);
@@ -166,7 +167,7 @@ public List sendEmail(String templatePath, Map
List failureList = new ArrayList();
if (recipients == null || recipients.length <= 0) {
- throw new IllegalArgumentException("Invalid Recipients");
+ throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
}
final MailTemplate mailTemplate = this.getMailTemplate(templatePath);
@@ -205,7 +206,7 @@ public List sendEmail(String templatePath, Map emailPara
List failureList = new ArrayList();
if (recipients == null || recipients.length <= 0) {
- throw new IllegalArgumentException("Invalid Recipients");
+ throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
}
List addresses = new ArrayList(recipients.length);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailProcess.java b/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailProcess.java
index 52c3c64a02..079a2c853e 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailProcess.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailProcess.java
@@ -110,7 +110,7 @@ public class SendTemplatedEmailProcess implements WorkflowProcess {
* Service used to generate a link to the payload on author environment
*/
@Reference
- private AuthorUIHelper authorUIHelper;
+ private AuthorUIHelper authorUiHelper;
@Reference
private ResourceResolverFactory resourceResolverFactory;
@@ -203,16 +203,12 @@ public final void execute(WorkItem workItem, WorkflowSession workflowSession, Me
}
// Get Url params
- Map urlParams = getURLs(payloadRes);
- if (urlParams != null) {
- emailParams.putAll(urlParams);
- }
+ Map urlParams = getUrls(payloadRes);
+ emailParams.putAll(urlParams);
// Get Additional Parameters to add
Map wfParams = getAdditionalParams(workItem, workflowSession, payloadRes);
- if (wfParams != null) {
- emailParams.putAll(wfParams);
- }
+ emailParams.putAll(wfParams);
// get email addresses based on CQ user or group
String[] emailTo = getEmailAddrs(workItem, payloadRes, args);
@@ -292,7 +288,7 @@ protected Map getAdditionalParams(WorkItem workItem, WorkflowSes
* @param arguments
* @return String of the argument value or null if not found
*/
- protected String getValueFromArgs(String key, String arguments[]) {
+ protected String getValueFromArgs(String key, String[] arguments) {
for (String str : arguments) {
String trimmedStr = str.trim();
if (trimmedStr.startsWith(key + ":")) {
@@ -309,7 +305,7 @@ protected String getValueFromArgs(String key, String arguments[]) {
* @param payloadRes
* @return
*/
- private Map getURLs(Resource payloadRes) {
+ private Map getUrls(Resource payloadRes) {
Map urlParams = new HashMap();
if (payloadRes == null) {
@@ -321,7 +317,7 @@ private Map getURLs(Resource payloadRes) {
if (DamUtil.isAsset(payloadRes)) {
// add author url
- String assetDetailsUrl = authorUIHelper.generateEditAssetLink(payloadPath, true, resolver);
+ String assetDetailsUrl = authorUiHelper.generateEditAssetLink(payloadPath, true, resolver);
urlParams.put(SendTemplatedEmailConstants.AUTHOR_LINK, assetDetailsUrl);
// add publish url
@@ -331,7 +327,7 @@ private Map getURLs(Resource payloadRes) {
} else {
// add absolute author url
- String assetDetailsUrl = authorUIHelper.generateEditPageLink(payloadPath, true, resolver);
+ String assetDetailsUrl = authorUiHelper.generateEditPageLink(payloadPath, true, resolver);
urlParams.put(SendTemplatedEmailConstants.AUTHOR_LINK, assetDetailsUrl);
// add publish url
diff --git a/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailUtils.java b/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailUtils.java
index 796f2f59f6..74e0fc3fa9 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailUtils.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/email/process/impl/SendTemplatedEmailUtils.java
@@ -50,6 +50,8 @@ public class SendTemplatedEmailUtils {
private static final String PN_USER_EMAIL = "profile/email";
+ private SendTemplatedEmailUtils() {}
+
/***
* Tests whether the payload is a DAM asset or a cq:Page for DAM asset
* returns all properties at the metadata node for DAM assets for cq:Page
@@ -63,7 +65,7 @@ public class SendTemplatedEmailUtils {
* used by the method to transform Date properties into Strings
* @return Map String representation of jcr properties
*/
- protected final static Map getPayloadProperties(Resource payloadRes, SimpleDateFormat sdf) {
+ protected static final Map getPayloadProperties(Resource payloadRes, SimpleDateFormat sdf) {
Map emailParams = new HashMap();
@@ -103,7 +105,8 @@ protected final static Map getPayloadProperties(Resource payload
* path to a CQ user or group
* @return String[] of email(s) associated with account
*/
- protected final static String[] getEmailAddrsFromUserPath(ResourceResolver resourceResolver, String principlePath) {
+ @SuppressWarnings({"squid:S3776"})
+ protected static final String[] getEmailAddrsFromUserPath(ResourceResolver resourceResolver, String principlePath) {
List emailList = new LinkedList();
try {
@@ -120,14 +123,16 @@ protected final static String[] getEmailAddrsFromUserPath(ResourceResolver resou
Iterator memberIt = authGroup.getMembers();
while (memberIt.hasNext()) {
String currEmail = getAuthorizableEmail(memberIt.next());
- if (currEmail != null)
+ if (currEmail != null) {
emailList.add(currEmail);
+ }
}
} else {
// otherwise is an individual user
String authEmail = getAuthorizableEmail(authorizable);
- if (authEmail != null)
+ if (authEmail != null) {
emailList.add(authEmail);
+ }
}
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/ErrorPageHandlerService.java b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/ErrorPageHandlerService.java
index c200a708d3..6e8bbddfd1 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/ErrorPageHandlerService.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/ErrorPageHandlerService.java
@@ -31,6 +31,8 @@
* This service is used via the ACS-AEM-Commons error page handler implementation to create author-able error pages.
*/
@ProviderType
+
+@SuppressWarnings("squid:S1214")
public interface ErrorPageHandlerService {
int DEFAULT_STATUS_CODE = SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR;
@@ -117,6 +119,7 @@ public interface ErrorPageHandlerService {
* @param response the response
* @param path the path
*/
+ @SuppressWarnings("checkstyle:abbreviationaswordinname")
void includeUsingGET(SlingHttpServletRequest request, SlingHttpServletResponse response, String path);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheImpl.java b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheImpl.java
index 599ca77d26..224c2bdd1c 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheImpl.java
@@ -153,11 +153,7 @@ public final int getTotalHits() {
@Override
public final int getCacheEntriesCount() {
- if (this.cache == null) {
- return 0;
- } else {
- return this.cache.size();
- }
+ return this.cache.size();
}
@Override
@@ -188,6 +184,7 @@ public final long getCacheSizeInKB() {
}
+ @SuppressWarnings("squid:S1192")
public final TabularData getCacheEntries() throws OpenDataException {
final CompositeType cacheEntryType = new CompositeType(
diff --git a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheMBean.java b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheMBean.java
index 826d628595..3f63faa2f6 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheMBean.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/cache/impl/ErrorPageCacheMBean.java
@@ -43,6 +43,7 @@ public interface ErrorPageCacheMBean {
int getCacheEntriesCount();
@Description("Total cache size in KB")
+ @SuppressWarnings("checkstyle:abbreviationaswordinname")
long getCacheSizeInKB();
@Description("Details for each cache entry")
diff --git a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/impl/ErrorPageHandlerImpl.java b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/impl/ErrorPageHandlerImpl.java
index 74213188bf..6960012337 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/impl/ErrorPageHandlerImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/errorpagehandler/impl/ErrorPageHandlerImpl.java
@@ -32,12 +32,22 @@
import com.day.cq.search.QueryBuilder;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
-import org.apache.felix.scr.annotations.*;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.PropertyOption;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestProgressTracker;
-import org.apache.sling.api.resource.*;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper;
import org.apache.sling.auth.core.AuthUtil;
import org.apache.sling.commons.auth.Authenticator;
@@ -54,7 +64,16 @@
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.AbstractMap.SimpleEntry;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Locale;
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -90,8 +109,8 @@ public final class ErrorPageHandlerImpl implements ErrorPageHandlerService {
private boolean vanityDispatchCheckEnabled = DEFAULT_VANITY_DISPATCH_ENABLED;
@Property(label = "Vanity Dispatch Check", description = "Enables/Disables Vanity Dispatch check, "
- + "if this is enabled and current request URI is a valid vanity (after performing resource resolver mapping), "
- + "request will be forwarded to it. [Optional... but recommended when using resource resolver based out-going mapping] [Default: false]",
+ + "if this is enabled and current request URI is a valid vanity (after performing resource resolver mapping), "
+ + "request will be forwarded to it. [Optional... but recommended when using resource resolver based out-going mapping] [Default: false]",
boolValue = DEFAULT_VANITY_DISPATCH_ENABLED)
private static final String PROP_VANITY_DISPATCH_ENABLED = "vanity.dispatch.enabled";
@@ -236,7 +255,7 @@ public final class ErrorPageHandlerImpl implements ErrorPageHandlerService {
private ComponentHelper componentHelper;
@Reference
- private VanityURLService vanityURLService;
+ private VanityURLService vanityUrlService;
private ErrorPageCache cache;
@@ -251,6 +270,8 @@ public final class ErrorPageHandlerImpl implements ErrorPageHandlerService {
* @param errorResource
* @return
*/
+ @Override
+ @SuppressWarnings("squid:S3776")
public String findErrorPage(SlingHttpServletRequest request, Resource errorResource) {
if (!isEnabled()) {
return null;
@@ -260,12 +281,12 @@ public String findErrorPage(SlingHttpServletRequest request, Resource errorResou
Resource errorPage = null;
if (StringUtils.isNotBlank(errorsPath)) {
- final ResourceResolver resourceResolver = errorResource.getResourceResolver();
+ final ResourceResolver resourceResolver = errorResource.getResourceResolver();
final String errorPath = errorsPath + "/" + getErrorPageName(request);
errorPage = getResource(resourceResolver, errorPath);
if (errorPage == null && StringUtils.isNotBlank(errorsPath)) {
- log.trace("No error-specific errorPage could be found, use the 'default' error errorPage for the Root content path");
+ log.trace("No error-specific errorPage could be found, use the 'default' error errorPage for the Root content path");
errorPage = resourceResolver.resolve(errorsPath);
}
}
@@ -320,9 +341,9 @@ public String findErrorPage(SlingHttpServletRequest request, Resource errorResou
* @param errorResource
* @return path to the default error page or "root" error page
*/
- private String findErrorsPath(SlingHttpServletRequest request, Resource errorResource) {
- final String errorResourcePath = errorResource.getPath();
- Resource real = findFirstRealParentOrSelf(request, errorResource);
+ private String findErrorsPath(SlingHttpServletRequest request, Resource errorResource) {
+ final String errorResourcePath = errorResource.getPath();
+ Resource real = findFirstRealParentOrSelf(request, errorResource);
String errorsPath = null;
if (real != null) {
@@ -333,17 +354,17 @@ private String findErrorsPath(SlingHttpServletRequest request, Resource errorRes
real = tmp;
}
}
- final InheritanceValueMap pageProperties = new HierarchyNodeInheritanceValueMap(real);
- errorsPath = pageProperties.getInherited(ERROR_PAGE_PROPERTY, String.class);
+ final InheritanceValueMap pageProperties = new HierarchyNodeInheritanceValueMap(real);
+ errorsPath = pageProperties.getInherited(ERROR_PAGE_PROPERTY, String.class);
} else {
- log.trace("No page found for [ {} ]", errorResource);
+ log.trace("No page found for [ {} ]", errorResource);
}
if (errorsPath == null) {
- log.trace("could not find inherited property for [ {} ]", errorResource);
+ log.trace("could not find inherited property for [ {} ]", errorResource);
for (final Map.Entry mapPage : pathMap.entrySet()) {
if (errorResourcePath.startsWith(mapPage.getKey())) {
- log.trace("found error path in map [ {} ]", mapPage.getKey());
+ log.trace("found error path in map [ {} ]", mapPage.getKey());
errorsPath = mapPage.getValue();
break;
}
@@ -351,8 +372,8 @@ private String findErrorsPath(SlingHttpServletRequest request, Resource errorRes
}
log.debug("Best matching errors path for request is: {}", errorsPath);
- return errorsPath;
- }
+ return errorsPath;
+ }
/**
* Gets the resource object for the provided path.
@@ -382,6 +403,7 @@ private Resource getResource(ResourceResolver resourceResolver, String path) {
* @param request
* @return
*/
+ @Override
public int getStatusCode(SlingHttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute(SlingConstants.ERROR_STATUS);
@@ -400,6 +422,7 @@ public int getStatusCode(SlingHttpServletRequest request) {
* @param request
* @return
*/
+ @Override
public String getErrorPageName(SlingHttpServletRequest request) {
// Get status code from request
// Set the servlet name ot find to statusCode; update later if needed
@@ -408,23 +431,6 @@ public String getErrorPageName(SlingHttpServletRequest request) {
// Only support Status codes as error exception lookup scheme is too complex/expensive at this time.
// Using the 500 response code/default error page should suffice for all errors pages generated from exceptions.
- /*
- final Object tmp = request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE);
-
- if(tmp != null && tmp instanceof Class) {
- final Class clazz = (Class) tmp;
-
- final String exceptionName = clazz.getSimpleName();
- log.debug("Servlet path used to derived exception name: {} ", exceptionName);
-
- if(StringUtils.isNotBlank(exceptionName)) {
- servletName = exceptionName;
- }
- }
-
- if(StringUtils.isBlank(servletName)) { servletName = this.fallbackErrorName; }
- */
-
servletName = StringUtils.lowerCase(servletName);
log.debug("Error page name to (try to) use: {} ", servletName);
@@ -442,6 +448,7 @@ public String getErrorPageName(SlingHttpServletRequest request) {
*
* @return true is the Service should be considered enabled
*/
+ @Override
public boolean isEnabled() {
return enabled;
}
@@ -737,6 +744,7 @@ public String getException(SlingHttpServletRequest request) {
* @param request
* @return
*/
+ @Override
public String getRequestProgress(SlingHttpServletRequest request) {
StringWriter stringWriter = new StringWriter();
if (request != null) {
@@ -757,12 +765,10 @@ public String getRequestProgress(SlingHttpServletRequest request) {
* @param response
* @param statusCode
*/
+ @Override
public void resetRequestAndResponse(SlingHttpServletRequest request, SlingHttpServletResponse response,
int statusCode) {
- // Clear client libraries
-
- // Replace with proper API call is HtmlLibraryManager provides one in the future;
- // Currently this is our only option.
+ // Clear client libraries. Would be better if there was a proper API call for this, but there isn't at present.
request.setAttribute("com.day.cq.widget.HtmlLibraryManager.included",
new HashSet());
@@ -811,6 +817,7 @@ protected void deactivate(ComponentContext componentContext) {
}
}
+ @SuppressWarnings("squid:S1149")
private void configure(ComponentContext componentContext) {
Dictionary, ?> config = componentContext.getProperties();
final String legacyPrefix = "prop.";
@@ -981,6 +988,7 @@ private SortedMap configurePathMap(String[] paths) {
return sortedMap;
}
+ @Override
public void includeUsingGET(final SlingHttpServletRequest request, final SlingHttpServletResponse response,
final String path) {
if (cache == null
@@ -1018,9 +1026,10 @@ public String getMethod() {
return "GET";
}
}
-
+
+ @Override
public boolean isVanityDispatchCheckEnabled(){
- return this.vanityDispatchCheckEnabled;
+ return this.vanityDispatchCheckEnabled;
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/Parameters.java b/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/Parameters.java
index 027cd3e31c..dcc38db04b 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/Parameters.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/Parameters.java
@@ -49,28 +49,28 @@ public Parameters(Resource resource) {
public Parameters(SlingHttpServletRequest request) throws IOException, JSONException {
final JSONObject json = new JSONObject(request.getParameter("params"));
- final List customProperties = new ArrayList();
- final List groups = new ArrayList();
+ final List tmpCustomProperties = new ArrayList();
+ final List tmpGroups = new ArrayList();
groupFilter = json.getString(GROUP_FILTER);
JSONArray groupsJSON = json.getJSONArray(GROUPS);
for (int i = 0; i < groupsJSON.length(); i++) {
- groups.add(groupsJSON.getString(i));
+ tmpGroups.add(groupsJSON.getString(i));
}
- this.groups = groups.toArray(new String[groups.size()]);
+ this.groups = tmpGroups.toArray(new String[tmpGroups.size()]);
JSONArray customPropertiesJSON = json.getJSONArray(CUSTOM_PROPERTIES);
for (int i = 0; i < customPropertiesJSON.length(); i++) {
JSONObject tmp = customPropertiesJSON.getJSONObject(i);
String relativePropertyPath = tmp.optString(RELATIVE_PROPERTY_PATH);
if (StringUtils.isNotBlank(relativePropertyPath)) {
- customProperties.add(relativePropertyPath);
+ tmpCustomProperties.add(relativePropertyPath);
}
}
- this.customProperties = customProperties.toArray(new String[customProperties.size()]);
+ this.customProperties = tmpCustomProperties.toArray(new String[tmpCustomProperties.size()]);
}
public String[] getCustomProperties() {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersExportServlet.java b/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersExportServlet.java
index 6ed772b47d..e99ae93f78 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersExportServlet.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersExportServlet.java
@@ -30,7 +30,8 @@
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
-import org.apache.sling.api.resource.*;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.commons.json.JSONException;
import org.slf4j.Logger;
@@ -247,6 +248,7 @@ public String getPath() throws RepositoryException {
return authorizable.getPath();
}
+ @SuppressWarnings("checkstyle:abbreviationaswordinname")
public String getID() throws RepositoryException {
return authorizable.getID();
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersInitServlet.java b/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersInitServlet.java
index f157def7c4..067fcb375c 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersInitServlet.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersInitServlet.java
@@ -51,6 +51,8 @@
)
public class UsersInitServlet extends SlingSafeMethodsServlet {
private static final String QUERY = "SELECT * FROM [rep:Group] WHERE ISDESCENDANTNODE([/home/groups]) ORDER BY [rep:principalName]";
+ private static final String KEY_TEXT = "text";
+ private static final String KEY_VALUE = "value";
/**
* Returns a JSON containing the options available to the form, and any prior saved data that should pre-populate the form.
@@ -115,21 +117,20 @@ private JSONArray getGroupOptions(ResourceResolver resourceResolver) throws Repo
* @throws JSONException
*/
private JSONArray getGroupFilterOptions() throws JSONException {
- JSONArray jsonArray = new JSONArray();
-
JSONObject both = new JSONObject();
- both.put("text", "Direct or Indirect Membership");
- both.put("value", GROUP_FILTER_BOTH);
+ both.put(KEY_TEXT, "Direct or Indirect Membership");
+ both.put(KEY_VALUE, GROUP_FILTER_BOTH);
JSONObject direct = new JSONObject();
- direct.put("text", "Direct Membership");
- direct.put("value", GROUP_FILTER_DIRECT);
+ direct.put(KEY_TEXT, "Direct Membership");
+ direct.put(KEY_VALUE, GROUP_FILTER_DIRECT);
JSONObject indirect = new JSONObject();
- indirect.put("text", "Indirect Membership");
- indirect.put("value", GROUP_FILTER_INDIRECT);
+ indirect.put(KEY_TEXT, "Indirect Membership");
+ indirect.put(KEY_VALUE, GROUP_FILTER_INDIRECT);
+ JSONArray jsonArray = new JSONArray();
jsonArray.put(direct);
jsonArray.put(indirect);
jsonArray.put(both);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/ActionManager.java b/bundle/src/main/java/com/adobe/acs/commons/fam/ActionManager.java
index 78b01da226..0a05c314d6 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/ActionManager.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/ActionManager.java
@@ -34,6 +34,7 @@
*
*/
@ProviderType
+@SuppressWarnings("squid:S00112")
public interface ActionManager {
/**
@@ -48,7 +49,8 @@ public interface ActionManager {
* @return Count of items found in query
* @throws RepositoryException
* @throws PersistenceException
- * @throws Exception
+ * @throws Exception
+ * @deprecated Use the method which supports CheckedBiConsumer instead
*/
@Deprecated
int withQueryResults(final String queryStatement, final String language, final BiConsumer callback, final BiFunction... filters) throws RepositoryException, PersistenceException, Exception;
@@ -73,6 +75,7 @@ public interface ActionManager {
/**
* Perform action at some later time using a provided pooled resolver
* @param action Action to perform
+ * @deprecated Use the method which supports CheckedConsumer instead
*/
@Deprecated
void deferredWithResolver(final Consumer action);
@@ -87,6 +90,7 @@ public interface ActionManager {
* Perform action right now using a provided pooled resolver
* @param action Action to perform
* @throws java.lang.Exception
+ * @deprecated Use the method which supports CheckedConsumer instead
*/
@Deprecated
void withResolver(Consumer action) throws Exception;
@@ -110,26 +114,27 @@ public interface ActionManager {
* NOTE: This is automatic now -- only included for backwards compatibility.
* @deprecated No need to use this, cleanup is automatic.
*/
- void addCleanupTask();
+ @Deprecated
+ void addCleanupTask();
/**
* Register a handler to be fired when the work has completed with no errors.
* @param successTask
*/
- void onSuccess(CheckedConsumer successTask);
+ void onSuccess(CheckedConsumer successTask);
/**
* Register a handler to be fired when the work has completed and there was at least one error.
* @param failureTask
*/
- void onFailure(CheckedBiConsumer, ResourceResolver> failureTask);
+ void onFailure(CheckedBiConsumer, ResourceResolver> failureTask);
/**
* Register a handler to be fired when the work is completed, successfully or not.
* Note: These handlers are called after the success/fail handlers.
* @param finishHandler
*/
- void onFinish(Runnable finishHandler);
+ void onFinish(Runnable finishHandler);
/**
* Have all actions completed?
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/CancelHandler.java b/bundle/src/main/java/com/adobe/acs/commons/fam/CancelHandler.java
index be5c7797f3..bdf45ae333 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/CancelHandler.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/CancelHandler.java
@@ -28,7 +28,7 @@
public class CancelHandler implements Serializable {
private static final long serialVersionUID = 7526472295622776147L;
- transient private final Set activeWork = ConcurrentHashMap.newKeySet();
+ private final transient Set activeWork = ConcurrentHashMap.newKeySet();
private boolean cancelled = false;
private boolean force = false;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/DeferredActions.java b/bundle/src/main/java/com/adobe/acs/commons/fam/DeferredActions.java
index 93e31f6280..f18abd59ef 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/DeferredActions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/DeferredActions.java
@@ -18,14 +18,16 @@
import aQute.bnd.annotation.ProviderType;
import com.adobe.acs.commons.fam.actions.Actions;
import com.adobe.acs.commons.fam.actions.AssetActions;
-import com.adobe.acs.commons.fam.actions.ReplicationActions;
import com.adobe.acs.commons.fam.actions.Filters;
-import com.adobe.acs.commons.functions.*;
+import com.adobe.acs.commons.fam.actions.ReplicationActions;
+import com.adobe.acs.commons.functions.BiConsumer;
+import com.adobe.acs.commons.functions.BiFunction;
+import com.adobe.acs.commons.functions.Consumer;
+import com.adobe.acs.commons.functions.Function;
import com.adobe.acs.commons.workflow.synthetic.SyntheticWorkflowModel;
import com.adobe.acs.commons.workflow.synthetic.SyntheticWorkflowRunner;
import com.day.cq.replication.ReplicationOptions;
import com.day.cq.replication.Replicator;
-
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
@@ -38,6 +40,7 @@
@Component
@Service(DeferredActions.class)
@ProviderType
+@Deprecated
public final class DeferredActions {
public static final String ORIGINAL_RENDITION = Filters.ORIGINAL_RENDITION;
@@ -227,7 +230,7 @@ public Consumer retry(final int retries, final long pausePerRe
* @param path
* @return
*/
- final public Consumer startSyntheticWorkflow(SyntheticWorkflowModel model, String path) {
+ public final Consumer startSyntheticWorkflow(SyntheticWorkflowModel model, String path) {
return Consumer.adapt(Actions.startSyntheticWorkflow(model, path, workflowRunner));
}
@@ -237,7 +240,7 @@ final public Consumer startSyntheticWorkflow(SyntheticWorkflow
* @param path
* @return
*/
- final public Consumer removeRenditions(String path) {
+ public final Consumer removeRenditions(String path) {
return Consumer.adapt(AssetActions.removeRenditions(path));
}
@@ -248,7 +251,7 @@ final public Consumer removeRenditions(String path) {
* @param name
* @return
*/
- final public Consumer removeRenditionsNamed(String path, String name) {
+ public final Consumer removeRenditionsNamed(String path, String name) {
return Consumer.adapt(AssetActions.removeRenditionsNamed(path, name));
}
@@ -258,7 +261,7 @@ final public Consumer removeRenditionsNamed(String path, Strin
* @param path
* @return
*/
- final public Consumer activate(String path) {
+ public final Consumer activate(String path) {
return Consumer.adapt(ReplicationActions.activate(replicator, path));
}
@@ -269,7 +272,7 @@ final public Consumer activate(String path) {
* @param options
* @return
*/
- final public Consumer activateWithOptions(String path, ReplicationOptions options) {
+ public final Consumer activateWithOptions(String path, ReplicationOptions options) {
return Consumer.adapt(ReplicationActions.activateWithOptions(replicator, path, options));
}
@@ -279,7 +282,7 @@ final public Consumer activateWithOptions(String path, Replica
* @param path
* @return
*/
- final public Consumer deactivate(String path) {
+ public final Consumer deactivate(String path) {
return Consumer.adapt(ReplicationActions.deactivate(replicator, path));
}
@@ -290,7 +293,7 @@ final public Consumer deactivate(String path) {
* @param options
* @return
*/
- final public Consumer deactivateWithOptions(String path, ReplicationOptions options) {
+ public final Consumer deactivateWithOptions(String path, ReplicationOptions options) {
return Consumer.adapt(ReplicationActions.deactivateWithOptions(replicator, path, options));
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/Failure.java b/bundle/src/main/java/com/adobe/acs/commons/fam/Failure.java
index e3b9dc7091..e6af4cac4a 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/Failure.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/Failure.java
@@ -25,6 +25,7 @@
* Represents a failure on a specific node
*/
@ProviderType
+@SuppressWarnings("squid:S1068")
public final class Failure implements Serializable {
private static final long serialVersionUID = 7526472295622776148L;
@@ -32,7 +33,7 @@ public final class Failure implements Serializable {
private String error;
private String stackTrace;
private Long time;
- transient private Exception exception;
+ private transient Exception exception;
private final Calendar failedAt;
public Failure() {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/ThrottledTaskRunner.java b/bundle/src/main/java/com/adobe/acs/commons/fam/ThrottledTaskRunner.java
index 80f72521e4..0ed788cc4a 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/ThrottledTaskRunner.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/ThrottledTaskRunner.java
@@ -17,6 +17,7 @@
import aQute.bnd.annotation.ProviderType;
import com.adobe.acs.commons.fam.mbean.ThrottledTaskRunnerMBean;
+
/**
* In addition to MBean operations, a ThrottledTaskRunner lets the caller schedule work and provides a throttle method.
* The logCompletion method should also allow a runnable action provide appropriate notification of success/failure
@@ -30,14 +31,14 @@ public interface ThrottledTaskRunner extends ThrottledTaskRunnerMBean {
* Only call this BEFORE starting a critical section.
* @throws InterruptedException If the thread was interrupted
*/
- public void waitForLowCpuAndLowMemory() throws InterruptedException;
+ void waitForLowCpuAndLowMemory() throws InterruptedException;
/**
* Schedule some kind of work to run in the future using the internal thread pool.
* The work will be throttled according to the CPU/Memory settings
* @param work
*/
- public void scheduleWork(Runnable work);
+ void scheduleWork(Runnable work);
/**
* Schedule some kind of work to run in the future using the internal thread pool.
@@ -45,7 +46,7 @@ public interface ThrottledTaskRunner extends ThrottledTaskRunnerMBean {
* @param work
* @param cancelHandler
*/
- public void scheduleWork(Runnable work, CancelHandler cancelHandler);
+ void scheduleWork(Runnable work, CancelHandler cancelHandler);
/**
* Record statistics
@@ -56,11 +57,11 @@ public interface ThrottledTaskRunner extends ThrottledTaskRunnerMBean {
* @param successful If true, action concluded normally
* @param error Exception caught, if any.
*/
- public void logCompletion(long created, long started, long executed, long finished, boolean successful, Throwable error);
+ void logCompletion(long created, long started, long executed, long finished, boolean successful, Throwable error);
/**
* Get number of maximum threads supported by this thread manager
* @return Thread pool maximum size
*/
- public int getMaxThreads();
+ int getMaxThreads();
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Actions.java b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Actions.java
index 9fdcc70857..c746371c4a 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Actions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Actions.java
@@ -31,6 +31,7 @@
* Various deferred actions to be used with the ActionManager
*/
@ProviderType
+@SuppressWarnings({"squid:S1181", "squid:S1193"})
public final class Actions {
private Actions() {
}
@@ -38,6 +39,7 @@ private Actions() {
private static final Logger LOG = LoggerFactory.getLogger(Actions.class);
private static ThreadLocal currentActionManager = new ThreadLocal<>();
+
/**
* Obtain the current action manager -- this is necessary for additional tracking such as current item
* @return current action manager
@@ -126,6 +128,7 @@ public static final CheckedBiConsumer startSyntheticWo
* @param action Action to attempt
* @return New retry wrapper around provided action
*/
+ @SuppressWarnings("squid:S3776")
public static final CheckedConsumer retry(final int retries, final long pausePerRetry, final CheckedConsumer action) {
return (ResourceResolver r) -> {
int remaining = retries;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/AssetActions.java b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/AssetActions.java
index 0619cf625f..7261158c2b 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/AssetActions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/AssetActions.java
@@ -35,7 +35,8 @@ public class AssetActions {
private AssetActions() {
// Utility class cannot be instantiated directly.
}
-
+
+ @SuppressWarnings("squid:S3776")
public static final CheckedBiConsumer withAllRenditions(
final CheckedBiConsumer action,
final CheckedBiFunction... filters) {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Filters.java b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Filters.java
index b155e76581..de22ed83b1 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Filters.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/Filters.java
@@ -31,7 +31,7 @@ private Filters() {
// Utility class cannot be instantiated directly.
}
- static final public String ORIGINAL_RENDITION = "original";
+ public static final String ORIGINAL_RENDITION = "original";
//--- Filters (for using withQueryResults)
/**
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/ReplicationActions.java b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/ReplicationActions.java
index ab7a69d32d..1ab5cb7758 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/actions/ReplicationActions.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/actions/ReplicationActions.java
@@ -35,6 +35,10 @@
*/
@ProviderType
public class ReplicationActions {
+
+ private static final String PREFIX_ACTIVATE = "activate-";
+ private static final String PREFIX_DEACTIVATE = "deactivate-";
+
private ReplicationActions() {
// Utility class cannot be instantiated directly.
}
@@ -46,7 +50,7 @@ private ReplicationActions() {
*/
public static final CheckedBiConsumer activateAll(Replicator replicator) {
return (ResourceResolver r, String path) -> {
- nameThread("activate-" + path);
+ nameThread(PREFIX_ACTIVATE + path);
replicator.replicate(r.adaptTo(Session.class), ReplicationActionType.ACTIVATE, path);
};
}
@@ -61,7 +65,7 @@ public static final CheckedBiConsumer activateAll(Repl
*/
public static final CheckedBiConsumer activateAllWithOptions(Replicator replicator, final ReplicationOptions options) {
return (ResourceResolver r, String path) -> {
- nameThread("activate-" + path);
+ nameThread(PREFIX_ACTIVATE + path);
replicator.replicate(r.adaptTo(Session.class), ReplicationActionType.ACTIVATE, path, options);
};
}
@@ -78,7 +82,7 @@ public static final CheckedBiConsumer activateAllWithR
final List allTheOptions = Arrays.asList(options);
final Iterator roundRobin = new RoundRobin(allTheOptions).iterator();
return (ResourceResolver r, String path) -> {
- nameThread("activate-" + path);
+ nameThread(PREFIX_ACTIVATE + path);
replicator.replicate(r.adaptTo(Session.class), ReplicationActionType.ACTIVATE, path, roundRobin.next());
};
}
@@ -90,7 +94,7 @@ public static final CheckedBiConsumer activateAllWithR
*/
public static final CheckedBiConsumer deactivateAll(final Replicator replicator) {
return (ResourceResolver r, String path) -> {
- nameThread("deactivate-" + path);
+ nameThread(PREFIX_DEACTIVATE + path);
replicator.replicate(r.adaptTo(Session.class), ReplicationActionType.DEACTIVATE, path);
};
}
@@ -103,7 +107,7 @@ public static final CheckedBiConsumer deactivateAll(fi
*/
public static final CheckedBiConsumer deactivateAllWithOptions(final Replicator replicator, final ReplicationOptions options) {
return (ResourceResolver r, String path) -> {
- nameThread("deactivate-" + path);
+ nameThread(PREFIX_DEACTIVATE + path);
replicator.replicate(r.adaptTo(Session.class), ReplicationActionType.DEACTIVATE, path, options);
};
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ActionManagerImpl.java b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ActionManagerImpl.java
index 860b89ac79..4627027306 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ActionManagerImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ActionManagerImpl.java
@@ -15,20 +15,23 @@
*/
package com.adobe.acs.commons.fam.impl;
-import com.adobe.acs.commons.fam.CancelHandler;
import com.adobe.acs.commons.fam.ActionManager;
+import com.adobe.acs.commons.fam.CancelHandler;
import com.adobe.acs.commons.fam.Failure;
import com.adobe.acs.commons.fam.ThrottledTaskRunner;
import com.adobe.acs.commons.fam.actions.Actions;
-import com.adobe.acs.commons.functions.*;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
+import com.adobe.acs.commons.functions.BiConsumer;
+import com.adobe.acs.commons.functions.BiFunction;
+import com.adobe.acs.commons.functions.CheckedBiConsumer;
+import com.adobe.acs.commons.functions.CheckedBiFunction;
+import com.adobe.acs.commons.functions.CheckedConsumer;
+import com.adobe.acs.commons.functions.Consumer;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
@@ -42,25 +45,29 @@
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularType;
-import org.apache.sling.api.resource.LoginException;
-import org.apache.sling.api.resource.PersistenceException;
-import org.apache.sling.api.resource.ResourceResolver;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
/**
* Manages a pool of reusable resource resolvers and injects them into tasks
*/
+@SuppressWarnings("squid:S1192")
class ActionManagerImpl extends CancelHandler implements ActionManager, Serializable {
private static final long serialVersionUID = 7526472295622776150L;
- transient private static final Logger LOG = LoggerFactory.getLogger(ActionManagerImpl.class);
+ private static final transient Logger LOG = LoggerFactory.getLogger(ActionManagerImpl.class);
// This is a delay of how long an action manager should wait before it can safely assume it really is done and no more work is being added
// This helps prevent an action manager from closing itself down while the queue is warming up.
- transient public static final int HESITATION_DELAY = 50;
+ public static final transient int HESITATION_DELAY = 50;
// The cleanup task will wait this many milliseconds between its polling to see if the queue has been completely processed
- transient public static final int COMPLETION_CHECK_INTERVAL = 100;
+ public static final transient int COMPLETION_CHECK_INTERVAL = 100;
private final AtomicInteger tasksAdded = new AtomicInteger();
private final AtomicInteger tasksCompleted = new AtomicInteger();
private final AtomicInteger tasksFilteredOut = new AtomicInteger();
@@ -71,16 +78,16 @@ class ActionManagerImpl extends CancelHandler implements ActionManager, Serializ
private long finished;
private int saveInterval;
- transient private final ResourceResolver baseResolver;
- transient private final List resolvers = Collections.synchronizedList(new ArrayList<>());
- transient private final ThreadLocal currentResolver = new ThreadLocal<>();
- transient private final ThrottledTaskRunner taskRunner;
- transient private final ThreadLocal currentPath;
+ private final transient ResourceResolver baseResolver;
+ private final transient List resolvers = Collections.synchronizedList(new ArrayList<>());
+ private final transient ThreadLocal currentResolver = new ThreadLocal<>();
+ private final transient ThrottledTaskRunner taskRunner;
+ private final transient ThreadLocal currentPath;
private final List failures;
- transient private final AtomicBoolean cleanupHandlerRegistered = new AtomicBoolean(false);
- transient private final List> successHandlers = Collections.synchronizedList(new ArrayList<>());
- transient private final List, ResourceResolver>> errorHandlers = Collections.synchronizedList(new ArrayList<>());
- transient private final List finishHandlers = Collections.synchronizedList(new ArrayList<>());
+ private final transient AtomicBoolean cleanupHandlerRegistered = new AtomicBoolean(false);
+ private final transient List> successHandlers = Collections.synchronizedList(new ArrayList<>());
+ private final transient List, ResourceResolver>> errorHandlers = Collections.synchronizedList(new ArrayList<>());
+ private final transient List finishHandlers = Collections.synchronizedList(new ArrayList<>());
ActionManagerImpl(String name, ThrottledTaskRunner taskRunner, ResourceResolver resolver, int saveInterval) throws LoginException {
this.name = name;
@@ -136,12 +143,43 @@ public void deferredWithResolver(final CheckedConsumer action)
deferredWithResolver(action, false);
}
+ @SuppressWarnings("squid:S1181")
+ private void deferredWithResolver(
+ final CheckedConsumer action,
+ final boolean closesResolver) {
+ if (!closesResolver) {
+ tasksAdded.incrementAndGet();
+ }
+ taskRunner.scheduleWork(() -> {
+ started.compareAndSet(0, System.currentTimeMillis());
+ try {
+ withResolver(action);
+ if (!closesResolver) {
+ logCompletetion();
+ }
+ } catch (Exception ex) {
+ LOG.error("Error in error handler for action " + getName(), ex);
+ if (!closesResolver) {
+ logError(ex);
+ }
+ } catch (Throwable t) {
+ LOG.error("Fatal uncaught error in error handler for action " + getName(), t);
+ if (!closesResolver) {
+ logError(new RuntimeException(t));
+ }
+ throw t;
+ }
+ }, this);
+
+ }
+
@Override
public void withResolver(Consumer action) throws Exception {
withResolver((CheckedConsumer) action);
}
@Override
+ @SuppressWarnings({"squid:S1181", "squid:S1163", "squid:S1143"})
public void withResolver(CheckedConsumer action) throws Exception {
Actions.setCurrentActionManager(this);
ReusableResolver resolver = getResourceResolver();
@@ -174,6 +212,7 @@ public int withQueryResults(
}
@Override
+ @SuppressWarnings("squid:S3776")
public int withQueryResults(
final String queryStatement,
final String language,
@@ -258,6 +297,7 @@ private void runCompletionTasks() {
}
}
+ @SuppressWarnings("squid:S2142")
private void performAutomaticCleanup() {
if (!cleanupHandlerRegistered.getAndSet(true)) {
taskRunner.scheduleWork(() -> {
@@ -279,35 +319,6 @@ public void setCurrentItem(String item) {
currentPath.set(item);
}
- private void deferredWithResolver(
- final CheckedConsumer action,
- final boolean closesResolver) {
- if (!closesResolver) {
- tasksAdded.incrementAndGet();
- }
- taskRunner.scheduleWork(() -> {
- started.compareAndSet(0, System.currentTimeMillis());
- try {
- withResolver(action);
- if (!closesResolver) {
- logCompletetion();
- }
- } catch (Exception ex) {
- LOG.error("Error in error handler for action " + getName(), ex);
- if (!closesResolver) {
- logError(ex);
- }
- } catch (Throwable t) {
- LOG.error("Fatal uncaught error in error handler for action " + getName(), t);
- if (!closesResolver) {
- logError(new RuntimeException(t));
- }
- throw t;
- }
- }, this);
-
- }
-
private ReusableResolver getResourceResolver() throws LoginException {
ReusableResolver resolver = currentResolver.get();
if (resolver == null || !resolver.getResolver().isLive()) {
@@ -375,11 +386,13 @@ public static TabularType getStaticsTableType() {
}
@Override
+ @SuppressWarnings("squid:S2142")
public boolean isComplete() {
if (tasksCompleted.get() == tasksAdded.get()) {
try {
Thread.sleep(HESITATION_DELAY);
} catch (InterruptedException ex) {
+ // no-op
}
return tasksCompleted.get() == tasksAdded.get();
} else {
@@ -414,7 +427,7 @@ public synchronized void closeAllResolvers() {
baseResolver.close();
}
- static public TabularType getFailuresTableType() {
+ public static TabularType getFailuresTableType() {
return failureTabularType;
}
@@ -434,12 +447,12 @@ public List getFailures() throws OpenDataException {
return failureData;
}
- transient private static String[] statsItemNames;
- transient private static CompositeType statsCompositeType;
- transient private static TabularType statsTabularType;
- transient private static String[] failureItemNames;
- transient private static CompositeType failureCompositeType;
- transient private static TabularType failureTabularType;
+ private static transient String[] statsItemNames;
+ private static transient CompositeType statsCompositeType;
+ private static transient TabularType statsTabularType;
+ private static transient String[] failureItemNames;
+ private static transient CompositeType failureCompositeType;
+ private static transient TabularType failureTabularType;
static {
try {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/RunningStatistic.java b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/RunningStatistic.java
index 56bf5cea7d..44f5735caa 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/RunningStatistic.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/RunningStatistic.java
@@ -34,7 +34,7 @@
*/
public class RunningStatistic {
- static private int rollingAverageWidth = 20;
+ private static int rollingAverageWidth = 20;
private final String name;
private final AtomicLong counter = new AtomicLong();
private final AtomicLong min = new AtomicLong();
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ThrottledTaskRunnerImpl.java b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ThrottledTaskRunnerImpl.java
index 6d6bf0430e..755a1db6a5 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ThrottledTaskRunnerImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/ThrottledTaskRunnerImpl.java
@@ -19,10 +19,15 @@
import com.adobe.acs.commons.fam.ThrottledTaskRunner;
import com.adobe.acs.commons.fam.mbean.ThrottledTaskRunnerMBean;
import com.adobe.granite.jmx.annotation.AnnotatedStandardMBean;
-import java.lang.management.ManagementFactory;
-import java.util.Dictionary;
-import java.util.List;
-import java.util.concurrent.*;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Properties;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.sling.commons.osgi.PropertiesUtil;
+import org.osgi.service.component.ComponentContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
@@ -36,14 +41,14 @@
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularDataSupport;
-import org.apache.felix.scr.annotations.Component;
-import org.apache.felix.scr.annotations.Properties;
-import org.apache.felix.scr.annotations.Property;
-import org.apache.felix.scr.annotations.Service;
-import org.apache.sling.commons.osgi.PropertiesUtil;
-import org.osgi.service.component.ComponentContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.lang.management.ManagementFactory;
+import java.util.Dictionary;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
@Component(metatype = true, immediate = true, label = "ACS AEM Commons - Throttled Task Runner Service")
@Service({ThrottledTaskRunner.class, ThrottledTaskRunnerStats.class})
@@ -176,6 +181,7 @@ public int getMaxThreads() {
private long lastCheck = -1;
private boolean wasRecentlyBusy = false;
+ @SuppressWarnings("squid:S3776")
private boolean isTooBusy() throws InterruptedException {
if (maxCpu <= 0 && maxHeap <= 0) {
return false;
@@ -257,6 +263,7 @@ public void setThreadPoolSize(int newSize) {
initThreadPool();
}
+ @SuppressWarnings("squid:S2142")
private void initThreadPool() {
if (workQueue == null) {
workQueue = new LinkedBlockingDeque<>();
diff --git a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/TimedRunnable.java b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/TimedRunnable.java
index afab42d103..fd34d93e29 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/fam/impl/TimedRunnable.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/fam/impl/TimedRunnable.java
@@ -57,6 +57,7 @@ public TimedRunnable(Runnable work, ThrottledTaskRunner runner, int timeout, Tim
* throwing an interruption
*/
@Override
+ @SuppressWarnings("squid:S1181")
public void run() {
if (cancelHandler.isPresent() && cancelHandler.get().isCancelled()) {
return;
@@ -89,6 +90,7 @@ public void run() {
runner.logCompletion(created, started, executed, finished, successful, error);
}
+ @SuppressWarnings("squid:S2142")
private Runnable watchThread(Thread workThread, Semaphore timerSemaphore) {
return () -> {
boolean finished1 = false;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/FormsRouter.java b/bundle/src/main/java/com/adobe/acs/commons/forms/FormsRouter.java
index 83dac92172..0826d5b0de 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/FormsRouter.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/FormsRouter.java
@@ -29,6 +29,7 @@
* Internal routing used for internal routing of POST form submissions in the Filters.
*/
@ProviderType
+@SuppressWarnings("squid:S1214")
public interface FormsRouter {
String FORM_RESOURCE_INPUT = FormHelper.FORM_RESOURCE_INPUT;
String FORM_NAME_INPUT = FormHelper.FORM_NAME_INPUT;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/components/FormComponent.java b/bundle/src/main/java/com/adobe/acs/commons/forms/components/FormComponent.java
index 6d2e155cd2..76fc0291f0 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/components/FormComponent.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/components/FormComponent.java
@@ -1,74 +1,75 @@
-/*
- * #%L
- * ACS AEM Commons Bundle
- * %%
- * Copyright (C) 2013 Adobe
- * %%
- * Licensed 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.
- * #L%
- */
+/*
+ * #%L
+ * ACS AEM Commons Bundle
+ * %%
+ * Copyright (C) 2013 Adobe
+ * %%
+ * Licensed 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.
+ * #L%
+ */
package com.adobe.acs.commons.forms.components;
-import aQute.bnd.annotation.ProviderType;
-
+import aQute.bnd.annotation.ProviderType;
+
import com.adobe.acs.commons.forms.Form;
-
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
-
+
@ProviderType
+@SuppressWarnings("squid:S00112")
public interface FormComponent {
/**
- *
- * @return
- */
- public String getFormName();
-
- /**
- * Get the data from the HTTP Request and move into the Map-based Form abstraction
- * @param request
- * @return
- */
- public Form getForm(SlingHttpServletRequest request);
-
- /**
- * Validate the provided form data. Create any Error records on the form itself.
- *
- * @param form
- * @return
- */
- public Form validate(Form form);
-
- /**
- * Save the data to the underlying data store; implementation specific. This could be CRX or external data store.
- * @param form
- * @return
- */
- public boolean save(Form form);
-
- /**
- * Handle successful form submission. Typically includes a 302 redirect to a Success page.
- * @param form
- * @param request
- * @param response
- */
- public void onSuccess(Form form, SlingHttpServletRequest request, SlingHttpServletResponse response) throws Exception;
-
- /**
- * Handle unsuccessful form submission. Typically includes a 302 redirect back to self.
- * @param form
- * @param request
- * @param response
- */
- public void onFailure(Form form, SlingHttpServletRequest request, SlingHttpServletResponse response) throws Exception;
+ *
+ * @return
+ */
+ public String getFormName();
+
+ /**
+ * Get the data from the HTTP Request and move into the Map-based Form abstraction
+ * @param request
+ * @return
+ */
+ public Form getForm(SlingHttpServletRequest request);
+
+ /**
+ * Validate the provided form data. Create any Error records on the form itself.
+ *
+ * @param form
+ * @return
+ */
+ public Form validate(Form form);
+
+ /**
+ * Save the data to the underlying data store; implementation specific. This could be CRX or external data store.
+ * @param form
+ * @return
+ */
+ public boolean save(Form form);
+
+ /**
+ * Handle successful form submission. Typically includes a 302 redirect to a Success page.
+ * @param form
+ * @param request
+ * @param response
+ */
+ public void onSuccess(Form form, SlingHttpServletRequest request, SlingHttpServletResponse response) throws Exception;
+
+ /**
+ * Handle unsuccessful form submission. Typically includes a 302 redirect back to self.
+ * @param form
+ * @param request
+ * @param response
+ */
+ public void onFailure(Form form, SlingHttpServletRequest request, SlingHttpServletResponse response) throws Exception;
}
\ No newline at end of file
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/components/MultiStepFormComponent.java b/bundle/src/main/java/com/adobe/acs/commons/forms/components/MultiStepFormComponent.java
index c97ea8f488..a89fdfedb4 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/components/MultiStepFormComponent.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/components/MultiStepFormComponent.java
@@ -1,81 +1,82 @@
-/*
- * #%L
- * ACS AEM Commons Bundle
- * %%
- * Copyright (C) 2013 Adobe
- * %%
- * Licensed 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.
- * #L%
- */
+/*
+ * #%L
+ * ACS AEM Commons Bundle
+ * %%
+ * Copyright (C) 2013 Adobe
+ * %%
+ * Licensed 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.
+ * #L%
+ */
package com.adobe.acs.commons.forms.components;
-import aQute.bnd.annotation.ProviderType;
-
+import aQute.bnd.annotation.ProviderType;
+
import com.adobe.acs.commons.forms.Form;
-
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
-
+
@ProviderType
+@SuppressWarnings("squid:S00112")
public interface MultiStepFormComponent {
- /**
- * Get the data from the HTTP Request and move into the Map-based Form
- * abstraction
- *
- * @param request
- * @return
- */
- public Form getForm(SlingHttpServletRequest request, String step);
-
- /**
- * Validate the provided form data. Create any Error records on the form
- * itself.
- *
- * @param form
- * @return
- */
- public Form validate(Form form, String step);
+ /**
+ * Get the data from the HTTP Request and move into the Map-based Form
+ * abstraction
+ *
+ * @param request
+ * @return
+ */
+ Form getForm(SlingHttpServletRequest request, String step);
+
+ /**
+ * Validate the provided form data. Create any Error records on the form
+ * itself.
+ *
+ * @param form
+ * @return
+ */
+ Form validate(Form form, String step);
- /**
- * Save the data to the underlying data store; implementation specific. This
- * could be CRX or external data store.
- *
- * @param form
- * @return
- */
- public boolean save(Form form, String step);
+ /**
+ * Save the data to the underlying data store; implementation specific. This
+ * could be CRX or external data store.
+ *
+ * @param form
+ * @return
+ */
+ boolean save(Form form, String step);
- /**
- * Handle successful form submission. Typically includes a 302 redirect to a
- * Success page.
- *
- * @param form
- * @param request
- * @param response
- */
- public void onSuccess(Form form, String step,
+ /**
+ * Handle successful form submission. Typically includes a 302 redirect to a
+ * Success page.
+ *
+ * @param form
+ * @param request
+ * @param response
+ */
+ void onSuccess(Form form, String step,
SlingHttpServletRequest request, SlingHttpServletResponse response)
- throws Exception;
+ throws Exception;
- /**
- * Handle unsuccessful form submission. Typically includes a 302 redirect
- * back to self.
- *
- * @param form
- * @param request
- * @param response
- */
- public void onFailure(Form form, String step, SlingHttpServletRequest request,
+ /**
+ * Handle unsuccessful form submission. Typically includes a 302 redirect
+ * back to self.
+ *
+ * @param form
+ * @param request
+ * @param response
+ */
+ void onFailure(Form form, String step, SlingHttpServletRequest request,
SlingHttpServletResponse response) throws Exception;
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/FormHelper.java b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/FormHelper.java
index fe6264cdef..49111ced54 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/FormHelper.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/FormHelper.java
@@ -34,6 +34,7 @@
import java.io.IOException;
@ProviderType
+@SuppressWarnings("squid:S1214")
public interface FormHelper {
String EXTENSION = ".html";
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/ForwardAsGetFormHelper.java b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/ForwardAsGetFormHelper.java
index 28686a3490..efb853ae76 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/ForwardAsGetFormHelper.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/ForwardAsGetFormHelper.java
@@ -1,42 +1,43 @@
-/*
- * #%L
- * ACS AEM Commons Bundle
- * %%
- * Copyright (C) 2013 Adobe
- * %%
- * Licensed 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.
- * #L%
- */
+/*
+ * #%L
+ * ACS AEM Commons Bundle
+ * %%
+ * Copyright (C) 2013 Adobe
+ * %%
+ * Licensed 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.
+ * #L%
+ */
package com.adobe.acs.commons.forms.helpers;
-import aQute.bnd.annotation.ProviderType;
-
+import aQute.bnd.annotation.ProviderType;
+
import com.adobe.acs.commons.forms.Form;
import com.day.cq.wcm.api.Page;
-
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestDispatcherOptions;
import org.apache.sling.api.resource.Resource;
-
+
import javax.servlet.ServletException;
-
+
import java.io.IOException;
/**
* Interface used for working with ACS-AEM-Commons forms.
- */
-@ProviderType
+ */
+@ProviderType
+@SuppressWarnings("squid:S1214")
public interface ForwardAsGetFormHelper extends FormHelper {
public final String REQUEST_ATTR_FORM_KEY = ForwardAsGetFormHelper.class.getName() + "__Form_";
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/PostRedirectGetFormHelper.java b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/PostRedirectGetFormHelper.java
index 90e05d4c02..eb337cb04f 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/PostRedirectGetFormHelper.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/PostRedirectGetFormHelper.java
@@ -1,42 +1,43 @@
-/*
- * #%L
- * ACS AEM Commons Bundle
- * %%
- * Copyright (C) 2013 Adobe
- * %%
- * Licensed 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.
- * #L%
- */
+/*
+ * #%L
+ * ACS AEM Commons Bundle
+ * %%
+ * Copyright (C) 2013 Adobe
+ * %%
+ * Licensed 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.
+ * #L%
+ */
package com.adobe.acs.commons.forms.helpers;
-import aQute.bnd.annotation.ProviderType;
-
+import aQute.bnd.annotation.ProviderType;
+
import com.adobe.acs.commons.forms.Form;
import com.day.cq.wcm.api.Page;
-
+
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.commons.json.JSONException;
-
+
import java.io.IOException;
-
+
@ProviderType
+@SuppressWarnings("squid:S1214")
public interface PostRedirectGetFormHelper extends FormHelper {
- public final static String KEY_FORM_NAME = "n";
- public final static String KEY_FORM = "f";
- public final static String KEY_ERRORS = "e";
- public final static String KEY_PREFIX_FORM_NAME = "f_";
- public final static String QUERY_PARAM_FORM_SELECTOR = "f_selector";
+ String KEY_FORM_NAME = "n";
+ String KEY_FORM = "f";
+ String KEY_ERRORS = "e";
+ String KEY_PREFIX_FORM_NAME = "f_";
+ String QUERY_PARAM_FORM_SELECTOR = "f_selector";
/**
* Issues a 302 redirect with the form serialized into a JSON object that can be
@@ -50,7 +51,7 @@ public interface PostRedirectGetFormHelper extends FormHelper {
* @throws IOException
* @throws JSONException
*/
- public void sendRedirect(Form form, String path, SlingHttpServletResponse response) throws IOException, JSONException;
+ void sendRedirect(Form form, String path, SlingHttpServletResponse response) throws IOException, JSONException;
/**
* Issues a 302 redirect with the form serialized into a JSON object that can be
@@ -64,7 +65,7 @@ public interface PostRedirectGetFormHelper extends FormHelper {
* @throws IOException
* @throws JSONException
*/
- public void sendRedirect(Form form, Page page, SlingHttpServletResponse response) throws IOException, JSONException;
+ void sendRedirect(Form form, Page page, SlingHttpServletResponse response) throws IOException, JSONException;
/**
/**
@@ -79,7 +80,7 @@ public interface PostRedirectGetFormHelper extends FormHelper {
* @throws IOException
* @throws JSONException
*/
- public void sendRedirect(Form form, Resource resource, SlingHttpServletResponse response) throws IOException, JSONException;
+ void sendRedirect(Form form, Resource resource, SlingHttpServletResponse response) throws IOException, JSONException;
/**
@@ -96,7 +97,7 @@ public interface PostRedirectGetFormHelper extends FormHelper {
* @throws IOException
* @throws JSONException
*/
- public void sendRedirect(Form form, String path, String formSelector, SlingHttpServletResponse response) throws IOException, JSONException;
+ void sendRedirect(Form form, String path, String formSelector, SlingHttpServletResponse response) throws IOException, JSONException;
/**
* Same as:
@@ -112,7 +113,7 @@ public interface PostRedirectGetFormHelper extends FormHelper {
* @throws IOException
* @throws JSONException
*/
- public void sendRedirect(Form form, Page page, String formSelector, SlingHttpServletResponse response) throws IOException, JSONException;
+ void sendRedirect(Form form, Page page, String formSelector, SlingHttpServletResponse response) throws IOException, JSONException;
/**
* Same as:
@@ -128,5 +129,5 @@ public interface PostRedirectGetFormHelper extends FormHelper {
* @throws IOException
* @throws JSONException
*/
- public void sendRedirect(Form form, Resource resource, String formSelector, SlingHttpServletResponse response) throws IOException, JSONException;
+ void sendRedirect(Form form, Resource resource, String formSelector, SlingHttpServletResponse response) throws IOException, JSONException;
}
\ No newline at end of file
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/AbstractFormHelperImpl.java b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/AbstractFormHelperImpl.java
index 667ce3dc0c..57f455efcf 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/AbstractFormHelperImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/AbstractFormHelperImpl.java
@@ -60,6 +60,7 @@ public abstract class AbstractFormHelperImpl {
private static final String SERVICE_NAME = "form-helper";
private static final Map AUTH_INFO;
+
static {
AUTH_INFO = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object) SERVICE_NAME);
}
@@ -75,25 +76,27 @@ public abstract class AbstractFormHelperImpl {
public final String getFormInputsHTML(final Form form, final String... keys) {
// The form objects data and errors should be xssProtected before being passed into this method
- StringBuffer html = new StringBuffer();
+ StringBuilder html = new StringBuilder();
- html.append("\n");
+ appendHiddenTag(html, FormHelper.FORM_NAME_INPUT, form.getName());
final String resourcePath = form.getResourcePath();
- html.append("\n");
+ appendHiddenTag(html, FormHelper.FORM_RESOURCE_INPUT, resourcePath);
for (final String key : keys) {
if (form.has(key)) {
- html.append("\n");
+ appendHiddenTag(html, key, form.get(key));
}
}
return html.toString();
}
+ private void appendHiddenTag(StringBuilder html, String name, String value) {
+ html.append("\n");
+ }
+
public final String getAction(final Page page) {
return this.getAction(page.getPath());
}
@@ -208,6 +211,7 @@ protected final Form getPostForm(final String formName,
* @param formName
* @return
*/
+ @SuppressWarnings("squid:S1172")
protected final String getPostLookupKey(final String formName) {
// This may change; keeping as method call to ease future refactoring
return FormHelper.FORM_NAME_INPUT;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/synthetics/SyntheticSlingHttpServletGetRequest.java b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/synthetics/SyntheticSlingHttpServletGetRequest.java
index c427d477d1..acce441152 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/synthetics/SyntheticSlingHttpServletGetRequest.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/synthetics/SyntheticSlingHttpServletGetRequest.java
@@ -1,22 +1,22 @@
-/*
- * #%L
- * ACS AEM Commons Bundle
- * %%
- * Copyright (C) 2013 Adobe
- * %%
- * Licensed 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.
- * #L%
- */
+/*
+ * #%L
+ * ACS AEM Commons Bundle
+ * %%
+ * Copyright (C) 2013 Adobe
+ * %%
+ * Licensed 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.
+ * #L%
+ */
package com.adobe.acs.commons.forms.helpers.impl.synthetics;
import org.apache.sling.api.SlingHttpServletRequest;
@@ -26,14 +26,14 @@
* Used to turn a POST request into a GET request for Internal Forwarding
*/
public class SyntheticSlingHttpServletGetRequest extends SlingHttpServletRequestWrapper {
- private static final String METHOD_GET = "GET";
+ private static final String METHOD_GET = "GET";
- public SyntheticSlingHttpServletGetRequest(final SlingHttpServletRequest request) {
- super(request);
- }
+ public SyntheticSlingHttpServletGetRequest(final SlingHttpServletRequest request) {
+ super(request);
+ }
- @Override
- public String getMethod() {
- return METHOD_GET;
- }
+ @Override
+ public String getMethod() {
+ return METHOD_GET;
+ }
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostFilterImpl.java b/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostFilterImpl.java
index 759a3a0b68..e1f8dda80d 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostFilterImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostFilterImpl.java
@@ -66,6 +66,7 @@ public class FormsPostFilterImpl implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
+ // no-op
}
@Override
@@ -123,6 +124,7 @@ public final void doFilter(ServletRequest servletRequest, ServletResponse servle
@Override
public void destroy() {
+ // no-op
}
private String getParameter(SlingHttpServletRequest slingRequest, String param) {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostRedirectGetFilterImpl.java b/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostRedirectGetFilterImpl.java
index 2c2d1c2f34..e431e17509 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostRedirectGetFilterImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/forms/impl/FormsPostRedirectGetFilterImpl.java
@@ -68,6 +68,7 @@ public class FormsPostRedirectGetFilterImpl implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
+ // no-op
}
@Override
@@ -136,5 +137,6 @@ public final void doFilter(ServletRequest servletRequest, ServletResponse servle
@Override
public void destroy() {
+ // no-op
}
}
\ No newline at end of file
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/BiConsumer.java b/bundle/src/main/java/com/adobe/acs/commons/functions/BiConsumer.java
index cc9408de6d..5517794584 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/BiConsumer.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/BiConsumer.java
@@ -28,6 +28,7 @@
* @param the type of the second argument to the operation
*
* @see Consumer
+ * @deprecated Use CheckedBiConsumer instead
*/
@ConsumerType
@Deprecated
@@ -54,7 +55,7 @@ public BiConsumer andThen(final BiConsumer super T, ? super U> after) {
private static class Adapter extends BiConsumer {
- final private CheckedBiConsumer delegate;
+ private final CheckedBiConsumer delegate;
public Adapter(CheckedBiConsumer delegate) {
this.delegate = delegate;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/BiFunction.java b/bundle/src/main/java/com/adobe/acs/commons/functions/BiFunction.java
index 10b11d8c38..b06f4763a1 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/BiFunction.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/BiFunction.java
@@ -27,6 +27,7 @@
* @param the type of the result of the function
*
* @see Function
+ * @deprecated Use CheckedBiFunction instead
*/
@ConsumerType
@Deprecated
@@ -54,7 +55,7 @@ public static BiFunction adapt(CheckedBiFunction del
private static class Adapter extends BiFunction {
- final private CheckedBiFunction delegate;
+ private final CheckedBiFunction delegate;
public Adapter(CheckedBiFunction delegate) {
this.delegate = delegate;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiConsumer.java b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiConsumer.java
index f0064d5d0b..22b028ba12 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiConsumer.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiConsumer.java
@@ -31,6 +31,7 @@
*/
@ConsumerType
@FunctionalInterface
+@SuppressWarnings("squid:S00112")
public interface CheckedBiConsumer {
/**
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiFunction.java b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiFunction.java
index 4ea3893b33..8dae8c68d2 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiFunction.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedBiFunction.java
@@ -30,6 +30,7 @@
*/
@ConsumerType
@FunctionalInterface
+@SuppressWarnings("squid:S00112")
public interface CheckedBiFunction {
/**
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedConsumer.java b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedConsumer.java
index 7e5ef5cb91..12235c5af2 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedConsumer.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedConsumer.java
@@ -27,6 +27,7 @@
*/
@ConsumerType
@FunctionalInterface
+@SuppressWarnings("squid:S00112")
public interface CheckedConsumer {
void accept(T t) throws Exception;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedFunction.java b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedFunction.java
index e8731967ce..d5db0ab2c7 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedFunction.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/CheckedFunction.java
@@ -26,6 +26,7 @@
*/
@ConsumerType
@FunctionalInterface
+@SuppressWarnings("squid:S00112")
public interface CheckedFunction {
/**
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/Consumer.java b/bundle/src/main/java/com/adobe/acs/commons/functions/Consumer.java
index 63b5115e9a..7d9c6ff50b 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/Consumer.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/Consumer.java
@@ -24,6 +24,7 @@
* to operate via side-effects.
*
* @param the type of the input to the operation
+ * @deprecated Use CheckedConsumer instead
*/
@ConsumerType
@Deprecated
@@ -50,7 +51,7 @@ public static Consumer adapt(CheckedConsumer delegate) {
private static class Adapter extends Consumer {
- final private CheckedConsumer delegate;
+ private final CheckedConsumer delegate;
public Adapter(CheckedConsumer delegate) {
this.delegate = delegate;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/functions/Function.java b/bundle/src/main/java/com/adobe/acs/commons/functions/Function.java
index de674065ca..02c009d445 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/functions/Function.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/functions/Function.java
@@ -23,6 +23,7 @@
*
* @param the type of the input to the function
* @param the type of the result of the function
+ * @deprecated Use CheckedFunction instead
*/
@ConsumerType
@Deprecated
@@ -81,7 +82,7 @@ public static Function adapt(CheckedFunction delegate) {
private static class Adapter extends Function {
- final private CheckedFunction delegate;
+ private final CheckedFunction delegate;
public Adapter(CheckedFunction delegate) {
this.delegate = delegate;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/genericlists/impl/GenericListImpl.java b/bundle/src/main/java/com/adobe/acs/commons/genericlists/impl/GenericListImpl.java
index 1a4259d945..77d38e6d41 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/genericlists/impl/GenericListImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/genericlists/impl/GenericListImpl.java
@@ -51,14 +51,11 @@ public ItemImpl(String t, String v, ValueMap props) {
this.props = props;
}
+ @Override
public String getTitle() {
return title;
}
- public String getValue() {
- return value;
- }
-
@Override
public String getTitle(Locale locale) {
// no locale - return default title
@@ -72,20 +69,20 @@ public String getTitle(Locale locale) {
return getTitle();
}
- String title = null;
+ String localizedTitle = null;
// try property name like jcr:title.de_ch
if (locale.getCountry().length() > 0) {
- title = getLocalizedTitle(locale);
+ localizedTitle = getLocalizedTitle(locale);
}
// then just jcr:title.de
- if (title == null) {
- title = getLocalizedTitle(new Locale(language));
+ if (localizedTitle == null) {
+ localizedTitle = getLocalizedTitle(new Locale(language));
}
- if (title == null) {
+ if (localizedTitle == null) {
return getTitle();
} else {
- return title;
+ return localizedTitle;
}
}
@@ -93,6 +90,11 @@ private String getLocalizedTitle(Locale locale) {
return props.get(TITLE_PREFIX + locale.toString().toLowerCase(), String.class);
}
+ @Override
+ public String getValue() {
+ return value;
+ }
+
}
private final List- items;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/hc/impl/HealthCheckStatusEmailer.java b/bundle/src/main/java/com/adobe/acs/commons/hc/impl/HealthCheckStatusEmailer.java
index 799ac6b022..a72a086884 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/hc/impl/HealthCheckStatusEmailer.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/hc/impl/HealthCheckStatusEmailer.java
@@ -81,6 +81,8 @@ public class HealthCheckStatusEmailer implements Runnable {
private static final int HEALTH_CHECK_STATUS_PADDING = 20;
private static final int NUM_DASHES = 100;
+ private static final Object LOCK = new Object();
+
private Calendar nextEmailTime = Calendar.getInstance();
/* OSGi Properties */
@@ -196,10 +198,10 @@ public final void run() {
final long timeTaken = System.currentTimeMillis() - start;
log.info("Executed ACS Commons Health Check E-mailer scheduled service in [ {} ms ]", timeTaken);
- if (!sendEmailOnlyOnFailure || (sendEmailOnlyOnFailure && failure.size() > 0)) {
+ if (!sendEmailOnlyOnFailure || failure.size() > 0) {
if (nextEmailTime == null || Calendar.getInstance().after(nextEmailTime)) {
sendEmail(success, failure, timeTaken);
- synchronized (nextEmailTime) {
+ synchronized (LOCK) {
nextEmailTime = Calendar.getInstance();
nextEmailTime.add(Calendar.MINUTE, throttleInMins);
}
@@ -218,6 +220,7 @@ public final void run() {
* @param failure the list of unsuccessful Health Check Execution Results
* @param timeTaken the time taken to execute all Health Checks
*/
+ @SuppressWarnings("squid:S1192")
protected final void sendEmail(final List success, final List failure, final long timeTaken) {
final ProductInfo[] productInfos = productInfoService.getInfos();
final String hostname = getHostname();
@@ -316,13 +319,14 @@ protected final void activate(final Map config) {
*
* @return the AEM Instance's hostname.
*/
+ @SuppressWarnings({"squid:S3776", "squid:S1192"})
private String getHostname() {
String hostname = null;
- final String OS = System.getProperty("os.name").toLowerCase();
+ final String os = System.getProperty("os.name").toLowerCase();
// Unpleasant 'if structure' to avoid making unnecessary Runtime calls; only call Runtime.
- if (OS.indexOf("win") >= 0) {
+ if (os.indexOf("win") >= 0) {
hostname = System.getenv("COMPUTERNAME");
if (StringUtils.isBlank(hostname)) {
try {
@@ -331,7 +335,7 @@ private String getHostname() {
log.warn("Unable to collect hostname from Windows via 'hostname' command.", ex);
}
}
- } else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("mac") >= 0) {
+ } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("mac") >= 0) {
hostname = System.getenv("HOSTNAME");
if (StringUtils.isBlank(hostname)) {
@@ -350,7 +354,7 @@ private String getHostname() {
}
}
} else {
- log.warn("Unidentifiable OS [ {} ]. Could not collect hostname.", OS);
+ log.warn("Unidentifiable OS [ {} ]. Could not collect hostname.", os);
}
hostname = StringUtils.trimToNull(hostname);
diff --git a/bundle/src/main/java/com/adobe/acs/commons/hc/impl/SMTPMailServiceHealthCheck.java b/bundle/src/main/java/com/adobe/acs/commons/hc/impl/SMTPMailServiceHealthCheck.java
index 1d37dfb213..a8012baaad 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/hc/impl/SMTPMailServiceHealthCheck.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/hc/impl/SMTPMailServiceHealthCheck.java
@@ -26,8 +26,15 @@
import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.text.StrLookup;
import org.apache.commons.mail.SimpleEmail;
-import org.apache.felix.scr.annotations.*;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Properties;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.PropertyUnbounded;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.hc.api.HealthCheck;
import org.apache.sling.hc.api.Result;
@@ -36,7 +43,10 @@
import org.slf4j.LoggerFactory;
import javax.mail.internet.InternetAddress;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
@Component(metatype = true,
label = "ACS AEM Commons - Health Check - SMTP E-Mail Service",
@@ -59,6 +69,7 @@
value = "smtpMailService",
propertyPrivate = true)})
@Service
+@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class SMTPMailServiceHealthCheck implements HealthCheck {
private static final Logger log = LoggerFactory.getLogger(SMTPMailServiceHealthCheck.class);
@@ -66,8 +77,8 @@ public class SMTPMailServiceHealthCheck implements HealthCheck {
private static final int TIMEOUT = 1000 * 10;
private static String MAIL_TEMPLATE =
- System.getProperty("line.separator") +
- "Sling Health Check for AEM E-mail Service connectivity";
+ System.getProperty("line.separator")
+ + "Sling Health Check for AEM E-mail Service connectivity";
private static final String DEFAULT_EMAIL = "healthcheck@example.com";
@Property(
@@ -75,17 +86,18 @@ public class SMTPMailServiceHealthCheck implements HealthCheck {
description = "E-mail address to send test message to.",
value = DEFAULT_EMAIL)
private static final String PROP_EMAIL = "email";
- private String email;
+ private String toEmail;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
private MessageGatewayService messageGatewayService;
@Activate
protected void activate(Map properties) {
- this.email = PropertiesUtil.toString(properties.get(PROP_EMAIL), DEFAULT_EMAIL);
+ this.toEmail = PropertiesUtil.toString(properties.get(PROP_EMAIL), DEFAULT_EMAIL);
}
@Override
+ @SuppressWarnings("squid:S1141")
public Result execute() {
final FormattingResultLog resultLog = new FormattingResultLog();
@@ -102,7 +114,7 @@ public Result execute() {
} else {
try {
List emailAddresses = new ArrayList();
- emailAddresses.add(new InternetAddress(this.email));
+ emailAddresses.add(new InternetAddress(this.toEmail));
MailTemplate mailTemplate = new MailTemplate(IOUtils.toInputStream(MAIL_TEMPLATE), CharEncoding.UTF_8);
SimpleEmail email = mailTemplate.getEmail(StrLookup.mapLookup(Collections.emptyMap()), SimpleEmail.class);
@@ -113,15 +125,15 @@ public Result execute() {
email.setSocketTimeout(TIMEOUT);
try {
messageGateway.send(email);
- resultLog.info("The E-mail Service appears to be working properly. Verify the health check e-mail was sent to [ {} ]", this.email);
+ resultLog.info("The E-mail Service appears to be working properly. Verify the health check e-mail was sent to [ {} ]", this.toEmail);
} catch (Exception e) {
- resultLog.critical("Failed sending e-mail. Unable to send a test email via the configured E-mail server: " + e.getMessage(), e);
+ resultLog.critical("Failed sending e-mail. Unable to send a test toEmail via the configured E-mail server: " + e.getMessage(), e);
log.warn("Failed to send E-mail for E-mail Service health check", e);
}
logMailServiceConfig(resultLog, email);
} catch (Exception e) {
- resultLog.healthCheckError("Sling Health check could not formulate a test email: " + e.getMessage(), e);
+ resultLog.healthCheckError("Sling Health check could not formulate a test toEmail: " + e.getMessage(), e);
log.error("Unable to execute E-mail health check", e);
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/http/headers/impl/AbstractDispatcherCacheHeaderFilter.java b/bundle/src/main/java/com/adobe/acs/commons/http/headers/impl/AbstractDispatcherCacheHeaderFilter.java
index bfb384374b..b483b701cb 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/http/headers/impl/AbstractDispatcherCacheHeaderFilter.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/http/headers/impl/AbstractDispatcherCacheHeaderFilter.java
@@ -123,9 +123,9 @@ protected boolean accepts(final HttpServletRequest request) {
// - GET request
// - No Params
// - From Dispatcher
- if (StringUtils.equalsIgnoreCase("get", request.getMethod()) &&
- request.getParameterMap().isEmpty() &&
- serverAgents.contains(DISPATCHER_AGENT_HEADER_VALUE)) {
+ if (StringUtils.equalsIgnoreCase("get", request.getMethod())
+ && request.getParameterMap().isEmpty()
+ && serverAgents.contains(DISPATCHER_AGENT_HEADER_VALUE)) {
return true;
}
@@ -133,6 +133,7 @@ protected boolean accepts(final HttpServletRequest request) {
}
@Activate
+ @SuppressWarnings("squid:S1149")
protected final void activate(ComponentContext context) throws Exception {
Dictionary, ?> properties = context.getProperties();
diff --git a/bundle/src/main/java/com/adobe/acs/commons/http/impl/HttpClientFactoryImpl.java b/bundle/src/main/java/com/adobe/acs/commons/http/impl/HttpClientFactoryImpl.java
index 0097edf904..ecd93b2939 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/http/impl/HttpClientFactoryImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/http/impl/HttpClientFactoryImpl.java
@@ -20,7 +20,13 @@
package com.adobe.acs.commons.http.impl;
import com.adobe.acs.commons.http.HttpClientFactory;
-import org.apache.felix.scr.annotations.*;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.ConfigurationPolicy;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.Service;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.fluent.Executor;
@@ -73,6 +79,7 @@ public class HttpClientFactoryImpl implements HttpClientFactory {
private static final String PROP_USERNAME = "username";
@Property(label = "Password", description = "Password for requests (using basic authentication)")
+ @SuppressWarnings("squid:S2068")
private static final String PROP_PASSWORD = "password";
@Property(label = "Socket Timeout", description = "Socket timeout in milliseconds", intValue = DEFAULT_SOCKET_TIMEOUT)
@@ -91,7 +98,6 @@ public class HttpClientFactoryImpl implements HttpClientFactory {
@Activate
protected void activate(Map config) throws Exception {
boolean useSSL = PropertiesUtil.toBoolean(config.get(PROP_USE_SSL), DEFAULT_USE_SSL);
- boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK), DEFAULT_DISABLE_CERT_CHECK);
String scheme = useSSL ? "https" : "http";
String hostname = PropertiesUtil.toString(config.get(PROP_HOST_DOMAIN), null);
@@ -114,6 +120,8 @@ protected void activate(Map config) throws Exception {
.build();
builder.setDefaultRequestConfig(requestConfig);
+ boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK), DEFAULT_DISABLE_CERT_CHECK);
+
if (useSSL && disableCertCheck) {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/http/injectors/AbstractHtmlRequestInjector.java b/bundle/src/main/java/com/adobe/acs/commons/http/injectors/AbstractHtmlRequestInjector.java
index f6072f9a1b..8be08d6502 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/http/injectors/AbstractHtmlRequestInjector.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/http/injectors/AbstractHtmlRequestInjector.java
@@ -108,6 +108,7 @@ public void destroy() {
}
+ @SuppressWarnings("squid:S3923")
protected boolean accepts(final ServletRequest servletRequest,
final ServletResponse servletResponse) {
@@ -143,6 +144,7 @@ protected boolean accepts(final ServletRequest servletRequest,
return true;
}
+ @SuppressWarnings("squid:S1149")
protected final void registerAsFilter(ComponentContext ctx, int ranking, String pattern) {
Dictionary filterProps = new Hashtable();
@@ -152,6 +154,7 @@ protected final void registerAsFilter(ComponentContext ctx, int ranking, String
filterRegistration = ctx.getBundleContext().registerService(Filter.class.getName(), this, filterProps);
}
+ @SuppressWarnings("squid:S1149")
protected final void registerAsSlingFilter(ComponentContext ctx, int ranking, String pattern) {
Dictionary filterProps = new Hashtable();
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/AuthenticationStatusConfigConstants.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/AuthenticationStatusConfigConstants.java
index 2678aa7827..fe469227c1 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/AuthenticationStatusConfigConstants.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/AuthenticationStatusConfigConstants.java
@@ -24,7 +24,6 @@
*/
public final class AuthenticationStatusConfigConstants {
private AuthenticationStatusConfigConstants() {
- throw new Error(AuthenticationStatusConfigConstants.class.getName() + " is not meant to be instantiated.");
}
/** Unauthenticated public requests */
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/GroupHttpCacheConfigExtension.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/GroupHttpCacheConfigExtension.java
index 4ec9b719f4..3f48d8d7d3 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/GroupHttpCacheConfigExtension.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/GroupHttpCacheConfigExtension.java
@@ -58,8 +58,8 @@
* user's group membership list. Made it as config factory as it could move along 1-1 with HttpCacheConfig.
*/
@Component(label = "ACS AEM Commons - HTTP Cache - Group based extension for HttpCacheConfig and CacheKeyFactory.",
- description = "HttpCacheConfig custom extension for group based configuration and associated cache key " +
- "creation.",
+ description = "HttpCacheConfig custom extension for group based configuration and associated cache key "
+ + "creation.",
metatype = true,
configurationFactory = true,
policy = ConfigurationPolicy.REQUIRE
@@ -171,6 +171,10 @@ public boolean equals(Object o) {
return false;
}
+ if (o == null) {
+ return false;
+ }
+
GroupCacheKey that = (GroupCacheKey) o;
return new EqualsBuilder()
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/HttpCacheConfigImpl.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/HttpCacheConfigImpl.java
index bdbea1e2e4..5f4948c982 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/HttpCacheConfigImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/HttpCacheConfigImpl.java
@@ -66,12 +66,12 @@
)
@Properties({
@Property(name = "webconsole.configurationFactory.nameHint",
- value = "Order: {httpcache.config.order}, " +
- "Request URIs: {httpcache.config.requesturi.patterns}, " +
- "Request URIs blacklist: {httpcache.config.requesturi.patterns.blacklisted}, " +
- "Authentication: {httpcache.config.request.authentication}, " +
- "Invalidation paths: {httpcache.config.invalidation.oak.paths}, " +
- "Cache type: {httpcache.config.cachestore}",
+ value = "Order: {httpcache.config.order}, "
+ + "Request URIs: {httpcache.config.requesturi.patterns}, "
+ + "Request URIs blacklist: {httpcache.config.requesturi.patterns.blacklisted}, "
+ + "Authentication: {httpcache.config.request.authentication}, "
+ + "Invalidation paths: {httpcache.config.invalidation.oak.paths}, "
+ + "Cache type: {httpcache.config.cachestore}",
propertyPrivate = true)
})
@Service
@@ -84,16 +84,16 @@ public class HttpCacheConfigImpl implements HttpCacheConfig {
public static final int DEFAULT_ORDER = 1000;
private int order = DEFAULT_ORDER;
@Property(label = "Priority order",
- description = "Order in which the HttpCacheEngine should evaluate the HttpCacheConfigs against the " +
- "request. Evaluates smallest to largest (Integer.MIN_VALUE -> Integer.MAX_VALUE). Defaults to " +
- "1000 ",
+ description = "Order in which the HttpCacheEngine should evaluate the HttpCacheConfigs against the "
+ + "request. Evaluates smallest to largest (Integer.MIN_VALUE -> Integer.MAX_VALUE). Defaults to "
+ + "1000 ",
intValue = DEFAULT_ORDER)
public static final String PROP_ORDER = "httpcache.config.order";
// Request URIs - Whitelisted.
@Property(label = "Request URI patterns",
- description = "Request URI patterns (REGEX) to be cached. Example - /content/mysite(.*).product-data" +
- ".json. Mandatory parameter.",
+ description = "Request URI patterns (REGEX) to be cached. Example - /content/mysite(.*).product-data"
+ + ".json. Mandatory parameter.",
cardinality = Integer.MAX_VALUE)
private static final String PROP_REQUEST_URI_PATTERNS = "httpcache.config.requesturi.patterns";
private List requestUriPatterns;
@@ -101,8 +101,8 @@ public class HttpCacheConfigImpl implements HttpCacheConfig {
// Request URIs - Blacklisted.
@Property(label = "Blacklisted request URI patterns",
- description = "Blacklisted request URI patterns (REGEX). Evaluated post applying the above request uri " +
- "" + "patterns (httpcache.config.requesturi.patterns). Optional parameter.",
+ description = "Blacklisted request URI patterns (REGEX). Evaluated post applying the above request uri "
+ + "patterns (httpcache.config.requesturi.patterns). Optional parameter.",
cardinality = Integer.MAX_VALUE)
private static final String PROP_BLACKLISTED_REQUEST_URI_PATTERNS =
"httpcache.config.requesturi.patterns.blacklisted";
@@ -119,8 +119,7 @@ public class HttpCacheConfigImpl implements HttpCacheConfig {
@PropertyOption(name = AuthenticationStatusConfigConstants.AUTHENTICATED_REQUEST,
value = AuthenticationStatusConfigConstants.AUTHENTICATED_REQUEST),
@PropertyOption(name = AuthenticationStatusConfigConstants.BOTH_ANONYMOUS_AUTHENTICATED_REQUESTS,
- value = AuthenticationStatusConfigConstants
- .BOTH_ANONYMOUS_AUTHENTICATED_REQUESTS)
+ value = AuthenticationStatusConfigConstants.BOTH_ANONYMOUS_AUTHENTICATED_REQUESTS)
},
value = AuthenticationStatusConfigConstants.ANONYMOUS_REQUEST)
// @formatter:on
@@ -131,8 +130,8 @@ public class HttpCacheConfigImpl implements HttpCacheConfig {
// Invalidation paths
@Property(label = "JCR path pattern (REGEX) for cache invalidation ",
- description = "Optional set of paths in JCR (Oak) repository for which this cache has to be invalidated" +
- ". This accepts " + "REGEX. Example - /etc/my-products(.*)",
+ description = "Optional set of paths in JCR (Oak) repository for which this cache has to be invalidated"
+ + ". This accepts " + "REGEX. Example - /etc/my-products(.*)",
cardinality = Integer.MAX_VALUE)
private static final String PROP_CACHE_INVALIDATION_PATH_PATTERNS = "httpcache.config.invalidation.oak.paths";
private List cacheInvalidationPathPatterns;
@@ -179,9 +178,9 @@ public class HttpCacheConfigImpl implements HttpCacheConfig {
// Making the cache config extension configurable.
@Property(name = "cacheConfigExtension.target",
label = "HttpCacheConfigExtension service pid",
- description = "Service pid of target implementation of HttpCacheConfigExtension to be used. Example - " +
- "(service.pid=com.adobe.acs.commons.httpcache.config.impl.GroupHttpCacheConfigExtension)." +
- " Optional parameter.",
+ description = "Service pid of target implementation of HttpCacheConfigExtension to be used. Example - "
+ + "(service.pid=com.adobe.acs.commons.httpcache.config.impl.GroupHttpCacheConfigExtension)."
+ + " Optional parameter.",
value = "(service.pid=com.adobe.acs.commons.httpcache.config.impl.GroupHttpCacheConfigExtension)")
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
policy = ReferencePolicy.DYNAMIC,
@@ -191,9 +190,9 @@ public class HttpCacheConfigImpl implements HttpCacheConfig {
// Making the cache key factory configurable.
@Property(name = "cacheKeyFactory.target",
label = "CacheKeyFactory service pid",
- description = "Service pid of target implementation of CacheKeyFactory to be used. Example - " +
- "(service.pid=com.adobe.acs.commons.httpcac`he.config.impl.GroupHttpCacheConfigExtension)." +
- " Mandatory parameter.",
+ description = "Service pid of target implementation of CacheKeyFactory to be used. Example - "
+ + "(service.pid=com.adobe.acs.commons.httpcac`he.config.impl.GroupHttpCacheConfigExtension)."
+ + " Mandatory parameter.",
value = "(service.pid=com.adobe.acs.commons.httpcache.config.impl.GroupHttpCacheConfigExtension)")
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY,
@@ -203,8 +202,8 @@ public class HttpCacheConfigImpl implements HttpCacheConfig {
@Property(label = "Config-specific HttpCacheHandlingRules",
- description = "List of Service pid of HttpCacheHandlingRule applicable for this cache config. Optional " +
- "parameter",
+ description = "List of Service pid of HttpCacheHandlingRule applicable for this cache config. Optional "
+ + "parameter",
unbounded = PropertyUnbounded.ARRAY)
private static final String PROP_CACHE_HANDLING_RULES_PID = "httpcache.config.cache-handling-rules.pid";
private List cacheHandlingRulesPid;
@@ -218,8 +217,8 @@ protected void activate(Map configs) {
requestUriPatternsAsRegEx = compileToPatterns(requestUriPatterns);
// Request URIs - Blacklisted.
- blacklistedRequestUriPatterns = Arrays.asList(PropertiesUtil.toStringArray(configs.get
- (PROP_BLACKLISTED_REQUEST_URI_PATTERNS), new String[]{}));
+ blacklistedRequestUriPatterns = Arrays.asList(PropertiesUtil.toStringArray(configs
+ .get(PROP_BLACKLISTED_REQUEST_URI_PATTERNS), new String[]{}));
blacklistedRequestUriPatternsAsRegEx = compileToPatterns(blacklistedRequestUriPatterns);
// Authentication requirement.
@@ -230,8 +229,8 @@ protected void activate(Map configs) {
cacheStore = PropertiesUtil.toString(configs.get(PROP_CACHE_STORE), DEFAULT_CACHE_STORE);
// Cache invalidation paths.
- cacheInvalidationPathPatterns = Arrays.asList(PropertiesUtil.toStringArray(configs.get
- (PROP_CACHE_INVALIDATION_PATH_PATTERNS), new String[]{}));
+ cacheInvalidationPathPatterns = Arrays.asList(PropertiesUtil.toStringArray(configs
+ .get(PROP_CACHE_INVALIDATION_PATH_PATTERNS), new String[]{}));
cacheInvalidationPathPatternsAsRegEx = compileToPatterns(cacheInvalidationPathPatterns);
order = PropertiesUtil.toInteger(configs.get(PROP_ORDER), DEFAULT_ORDER);
@@ -239,8 +238,8 @@ protected void activate(Map configs) {
filterScope = FilterScope.valueOf(PropertiesUtil.toString(configs.get(PROP_FILTER_SCOPE), DEFAULT_FILTER_SCOPE).toUpperCase());
// PIDs of cache handling rules.
- cacheHandlingRulesPid = new ArrayList(Arrays.asList(PropertiesUtil.toStringArray(configs.get
- (PROP_CACHE_HANDLING_RULES_PID), new String[]{})));
+ cacheHandlingRulesPid = new ArrayList(Arrays.asList(PropertiesUtil.toStringArray(configs
+ .get(PROP_CACHE_HANDLING_RULES_PID), new String[]{})));
ListIterator listIterator = cacheHandlingRulesPid.listIterator();
while (listIterator.hasNext()) {
String value = listIterator.next();
@@ -288,8 +287,8 @@ public boolean accepts(SlingHttpServletRequest request) throws HttpCacheReposito
// Match authentication requirement.
if (UserUtils.isAnonymous(request.getResourceResolver().getUserID())) {
if (AuthenticationStatusConfigConstants.AUTHENTICATED_REQUEST.equals(this.authenticationRequirement)) {
- log.trace("Rejected: Request is anonymous but the config accepts only authenticated request and hence" +
- " reject");
+ log.trace("Rejected: Request is anonymous but the config accepts only authenticated request and hence"
+ + " reject");
return false;
}
} else {
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/ResourceTypeHttpCacheConfigExtension.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/ResourceTypeHttpCacheConfigExtension.java
index add3382087..b44b54e96d 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/ResourceTypeHttpCacheConfigExtension.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/ResourceTypeHttpCacheConfigExtension.java
@@ -171,6 +171,10 @@ public boolean equals(Object o) {
return false;
}
+ if (o == null) {
+ return false;
+ }
+
ResourceTypeCacheKey that = (ResourceTypeCacheKey) o;
return new EqualsBuilder()
.append(getUri(), that.getUri())
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/CacheContent.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/CacheContent.java
index 9810939e48..4003fa0071 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/CacheContent.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/CacheContent.java
@@ -21,8 +21,6 @@
import com.adobe.acs.commons.httpcache.exception.HttpCacheDataStreamException;
import com.adobe.acs.commons.httpcache.store.TempSink;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
@@ -35,7 +33,6 @@
* Represents response content to be cached.
*/
public class CacheContent {
- private static final Logger log = LoggerFactory.getLogger(CacheContent.class);
/** Response status **/
private int status;
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/HttpCacheServletResponseWrapper.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/HttpCacheServletResponseWrapper.java
index a60bf501d6..34670d5f31 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/HttpCacheServletResponseWrapper.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/HttpCacheServletResponseWrapper.java
@@ -69,6 +69,7 @@ public ServletOutputStream getOutputStream() throws IOException {
}
@Override
+ @SuppressWarnings("squid:S2095")
public PrintWriter getWriter() throws IOException {
if (this.servletOutputStream != null) {
throw new IllegalStateException("Cannot invoke getWriter() once getOutputStream() has been called.");
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/HttpCacheEngineImpl.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/HttpCacheEngineImpl.java
index bbbf0b3a55..c83dc03c43 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/HttpCacheEngineImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/HttpCacheEngineImpl.java
@@ -275,8 +275,8 @@ protected void unbindHttpCacheHandlingRule(final HttpCacheHandlingRule cacheHand
protected void activate(Map configs) {
// PIDs of global cache handling rules.
- globalCacheHandlingRulesPid = new ArrayList(Arrays.asList(PropertiesUtil.toStringArray(configs.get
- (PROP_GLOBAL_CACHE_HANDLING_RULES_PID), new String[]{})));
+ globalCacheHandlingRulesPid = new ArrayList(Arrays.asList(PropertiesUtil.toStringArray(configs
+ .get(PROP_GLOBAL_CACHE_HANDLING_RULES_PID), new String[]{})));
ListIterator listIterator = globalCacheHandlingRulesPid.listIterator();
while (listIterator.hasNext()) {
String value = listIterator.next();
@@ -362,6 +362,7 @@ public boolean isCacheHit(SlingHttpServletRequest request, HttpCacheConfig cache
}
@Override
+ @SuppressWarnings("squid:S3776")
public boolean deliverCacheContent(SlingHttpServletRequest request, SlingHttpServletResponse response,
HttpCacheConfig cacheConfig) throws HttpCacheKeyCreationException,
HttpCacheDataStreamException, HttpCachePersistenceException {
@@ -486,6 +487,7 @@ public boolean isPathPotentialToInvalidate(String path) {
}
@Override
+ @SuppressWarnings("squid:S3776")
public void invalidateCache(String path) throws HttpCachePersistenceException, HttpCacheKeyCreationException {
// Find out all the cache config which has this path applicable for invalidation.
@@ -533,6 +535,7 @@ public HttpCacheEngineImpl() throws NotCompliantMBeanException {
}
@Override
+ @SuppressWarnings("squid:S1192")
public TabularData getRegisteredHttpCacheRules() throws OpenDataException {
// @formatter:off
final CompositeType cacheEntryType = new CompositeType(
@@ -561,6 +564,7 @@ public TabularData getRegisteredHttpCacheRules() throws OpenDataException {
}
@Override
+ @SuppressWarnings("squid:S1192")
public TabularData getRegisteredHttpCacheConfigs() throws OpenDataException {
// @formatter:off
// Exposing all google guava stats.
@@ -595,6 +599,7 @@ public TabularData getRegisteredHttpCacheConfigs() throws OpenDataException {
}
@Override
+ @SuppressWarnings("squid:S1192")
public TabularData getRegisteredPersistenceStores() throws OpenDataException {
// @formatter:off
final CompositeType cacheEntryType = new CompositeType(
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeePrintWriter.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeePrintWriter.java
index 1d3a667f8b..b9e6672931 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeePrintWriter.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeePrintWriter.java
@@ -34,27 +34,31 @@ public TeePrintWriter(PrintWriter main, PrintWriter branch) {
this.branch = branch;
}
- public void write(char buf[], int off, int len) {
+ @Override
+ public void write(char[] buf, int off, int len) {
super.write(buf, off, len);
super.flush();
branch.write(buf, off, len);
branch.flush();
}
- public void write(String s, int off, int len) {
- super.write(s, off, len);
+ @Override
+ public void write(String string, int off, int len) {
+ super.write(string, off, len);
super.flush();
- branch.write(s, off, len);
+ branch.write(string, off, len);
branch.flush();
}
- public void write(int c) {
- super.write(c);
+ @Override
+ public void write(int character) {
+ super.write(character);
super.flush();
- branch.write(c);
+ branch.write(character);
branch.flush();
}
+ @Override
public void flush() {
super.flush();
branch.flush();
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeeServletOutputStream.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeeServletOutputStream.java
index b52e835c06..8135ce8c86 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeeServletOutputStream.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/engine/impl/TeeServletOutputStream.java
@@ -37,18 +37,18 @@ public TeeServletOutputStream(OutputStream one, OutputStream two) {
}
@Override
- public void write(int arg0) throws IOException {
- this.teeOutputStream.write(arg0);
+ public void write(int character) throws IOException {
+ this.teeOutputStream.write(character);
}
@Override
- public void write(byte b[], int off, int len) throws IOException {
- this.teeOutputStream.write(b, off, len);
+ public void write(byte[] oneByte, int off, int len) throws IOException {
+ this.teeOutputStream.write(oneByte, off, len);
}
@Override
- public void write(byte b[]) throws IOException {
- this.teeOutputStream.write(b);
+ public void write(byte[] oneByte) throws IOException {
+ this.teeOutputStream.write(oneByte);
}
@Override
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheConfigConflictException.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheConfigConflictException.java
index 9b3c8edf28..39b78bdf0c 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheConfigConflictException.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheConfigConflictException.java
@@ -22,6 +22,7 @@
/**
* Custom exception representing a conflict in resolving cache config.
*/
+@SuppressWarnings({"serial", "squid:S2166"})
public class HttpCacheConfigConflictException extends HttpCacheException {
public HttpCacheConfigConflictException() {
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheDataStreamException.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheDataStreamException.java
index 9bfa9dfaff..fea265dd51 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheDataStreamException.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheDataStreamException.java
@@ -22,6 +22,7 @@
/**
* Custom exception representing failure conditions in accessing data streams.
*/
+@SuppressWarnings({"serial", "squid:S2166"})
public class HttpCacheDataStreamException extends HttpCacheException {
public HttpCacheDataStreamException() {
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheKeyCreationException.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheKeyCreationException.java
index 701a6e23df..92dcc822ee 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheKeyCreationException.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheKeyCreationException.java
@@ -22,6 +22,7 @@
/**
* Custom exception representing failure conditions in creating a cache key.
*/
+@SuppressWarnings({"serial", "squid:S2166"})
public class HttpCacheKeyCreationException extends HttpCacheException {
public HttpCacheKeyCreationException() {
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCachePersistenceException.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCachePersistenceException.java
index 84ba1a9a55..eb2e1e4b1d 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCachePersistenceException.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCachePersistenceException.java
@@ -22,6 +22,7 @@
/**
* Custom exception representing failure conditions in persistence of cached items.
*/
+@SuppressWarnings({"serial", "squid:S2166"})
public class HttpCachePersistenceException extends HttpCacheException {
public HttpCachePersistenceException() {
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheRepositoryAccessException.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheRepositoryAccessException.java
index 8b85983f17..0946900328 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheRepositoryAccessException.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/exception/HttpCacheRepositoryAccessException.java
@@ -22,6 +22,7 @@
/**
* Custom exception representing failure condition in accessing JCR repository.
*/
+@SuppressWarnings({"serial", "squid:S2166"})
public class HttpCacheRepositoryAccessException extends HttpCacheException {
public HttpCacheRepositoryAccessException() {
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/AbstractHttpCacheFilter.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/AbstractHttpCacheFilter.java
index 5e050a6f81..7861958018 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/AbstractHttpCacheFilter.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/AbstractHttpCacheFilter.java
@@ -43,6 +43,7 @@ public abstract class AbstractHttpCacheFilter implements Filter {
public abstract void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException;
+ @SuppressWarnings("squid:S3776")
protected void doFilter(ServletRequest request, ServletResponse response, FilterChain chain,
HttpCacheEngine cacheEngine, HttpCacheConfig.FilterScope filterScope) throws IOException, ServletException {
log.trace("In HttpCache filter.");
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheIncludeFilter.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheIncludeFilter.java
index 8ec4657a8b..6f385dcc9e 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheIncludeFilter.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheIncludeFilter.java
@@ -70,9 +70,11 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
//---------------
@Override
public void init(FilterConfig filterConfig) throws ServletException {
+ // no-op
}
@Override
public void destroy() {
+ // no-op
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheRequestFilter.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheRequestFilter.java
index 4d7d5abbad..fedb2a54d4 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheRequestFilter.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/filter/impl/HttpCacheRequestFilter.java
@@ -70,9 +70,11 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
//---------------
@Override
public void init(FilterConfig filterConfig) throws ServletException {
+ // no-op
}
@Override
public void destroy() {
+ // no-op
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/CacheInvalidationJobConstants.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/CacheInvalidationJobConstants.java
index ac4b86a70c..087c00a347 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/CacheInvalidationJobConstants.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/CacheInvalidationJobConstants.java
@@ -35,6 +35,5 @@ public final class CacheInvalidationJobConstants {
public static final String PAYLOAD_KEY_DATA_CHANGE_PATH = "path";
private CacheInvalidationJobConstants() {
- throw new Error(CacheInvalidationJobConstants.class.getName() + " is not meant to be instantiated.");
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/HttpCacheInvalidationJobConsumer.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/HttpCacheInvalidationJobConsumer.java
index c4b1f6a9f9..c90884c7f2 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/HttpCacheInvalidationJobConsumer.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/HttpCacheInvalidationJobConsumer.java
@@ -123,7 +123,7 @@ void invalidate(String path){
*
* @param path the path to search for
*/
- void invalidateReferences(String path){
+ void invalidateReferences(String path) {
ResourceResolver adminResolver = null;
try {
adminResolver = resolverFactory.getServiceResourceResolver(null);
@@ -137,7 +137,9 @@ void invalidateReferences(String path){
} catch (Exception e){
log.debug("failed to invalidate references of {}", path);
} finally {
- if(adminResolver != null) adminResolver.close();
+ if (adminResolver != null) {
+ adminResolver.close();
+ }
}
}
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/event/JCRNodeChangeEventHandler.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/event/JCRNodeChangeEventHandler.java
index 73db3106fc..3e30a3e6c1 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/event/JCRNodeChangeEventHandler.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/invalidator/event/JCRNodeChangeEventHandler.java
@@ -59,10 +59,10 @@
name = EventConstants.EVENT_TOPIC,
propertyPrivate = true),
@Property(label = "JCR paths to watch for changes.",
- value = "(|(" + SlingConstants.PROPERTY_PATH + "=" +
- "/content*)(" + SlingConstants.PROPERTY_PATH + "=" + "/etc*))",
- description = "Paths expressed in LDAP syntax. Example: (|(path=/content*)(path=/etc*))" +
- " - Watches for changes under /content or /etc. ",
+ value = "(|(" + SlingConstants.PROPERTY_PATH + "="
+ + "/content*)(" + SlingConstants.PROPERTY_PATH + "=" + "/etc*))",
+ description = "Paths expressed in LDAP syntax. Example: (|(path=/content*)(path=/etc*))"
+ + " - Watches for changes under /content or /etc. ",
name = EventConstants.EVENT_FILTER),
@Property(name = "webconsole.configurationFactory.nameHint",
value = "JCR paths to watch for changes: {" + EventConstants.EVENT_FILTER + "}",
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/HttpCacheStore.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/HttpCacheStore.java
index 2fd0da4eb6..df07cd4f5b 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/HttpCacheStore.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/HttpCacheStore.java
@@ -28,6 +28,7 @@
* Data store for persisting cache items. Data store implementation could be in-memory, disk or even JCR repository.
* Multiple implementation of this cache store can be present at any time and they can work in conjunction.
*/
+@SuppressWarnings("squid:S1214")
public interface HttpCacheStore {
/** Represents the key to find out the type of cache data store. Type could be MEM, DISK, JCR, etc. */
String KEY_CACHE_STORE_TYPE = "httpcache.cachestore.type";
@@ -78,11 +79,6 @@ public interface HttpCacheStore {
*/
void invalidate(CacheKey key);
- /**
- * Invalidate all entries in the cache.
- */
- void invalidateAll();
-
/**
* Invalidate all the cached items applicable for the given cache config.
*
@@ -90,6 +86,11 @@ public interface HttpCacheStore {
*/
void invalidate(HttpCacheConfig cacheConfig);
+ /**
+ * Invalidate all entries in the cache.
+ */
+ void invalidateAll();
+
/**
* Create a temp sink for stashing response stream.
* @return
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/disk/impl/DiskHttpCacheStoreImpl.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/disk/impl/DiskHttpCacheStoreImpl.java
index 0d9fd8b90b..a1f59ed9e9 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/disk/impl/DiskHttpCacheStoreImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/disk/impl/DiskHttpCacheStoreImpl.java
@@ -67,12 +67,12 @@ public void invalidate(CacheKey key) {
}
@Override
- public void invalidateAll() {
+ public void invalidate(HttpCacheConfig cacheConfig) {
throw new NotImplementedException();
}
@Override
- public void invalidate(HttpCacheConfig cacheConfig) {
+ public void invalidateAll() {
throw new NotImplementedException();
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/jcr/impl/JCRHttpCacheStoreImpl.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/jcr/impl/JCRHttpCacheStoreImpl.java
index 150f725eb5..0d6c5ee8c3 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/jcr/impl/JCRHttpCacheStoreImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/jcr/impl/JCRHttpCacheStoreImpl.java
@@ -69,12 +69,12 @@ public void invalidate(CacheKey key) {
}
@Override
- public void invalidateAll() {
+ public void invalidate(HttpCacheConfig cacheConfig) {
throw new NotImplementedException();
}
@Override
- public void invalidate(HttpCacheConfig cacheConfig) {
+ public void invalidateAll() {
throw new NotImplementedException();
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemCachePersistenceObject.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemCachePersistenceObject.java
index 1d3e04d66f..63ba86ef6c 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemCachePersistenceObject.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemCachePersistenceObject.java
@@ -101,6 +101,7 @@ public MemCachePersistenceObject buildForCaching(int status, String charEncoding
public int getStatus() {
return status;
}
+
/**
* Get char encoding.
*
@@ -157,5 +158,7 @@ public void incrementHitCount() {
/**
* @return the number of times this cache entry has been requested
*/
- public int getHitCount() { return count.get(); }
+ public int getHitCount() {
+ return count.get();
+ }
}
diff --git a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemHttpCacheStoreImpl.java b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemHttpCacheStoreImpl.java
index 8bb7787c2c..6b5c8b61d7 100644
--- a/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemHttpCacheStoreImpl.java
+++ b/bundle/src/main/java/com/adobe/acs/commons/httpcache/store/mem/impl/MemHttpCacheStoreImpl.java
@@ -69,8 +69,8 @@
value = "com.adobe.acs.httpcache:type=In Memory HTTP Cache Store",
propertyPrivate = true),
@Property(name = "webconsole.configurationFactory.nameHint",
- value = "TTL: {httpcache.cachestore.memcache.ttl}, " +
- "Max size in MB: {httpcache.cachestore.memcache.maxsize}",
+ value = "TTL: {httpcache.cachestore.memcache.ttl}, "
+ + "Max size in MB: {httpcache.cachestore.memcache.maxsize}",
propertyPrivate = true)
})
@Service(value = {DynamicMBean.class, HttpCacheStore.class})
@@ -88,8 +88,8 @@ public class MemHttpCacheStoreImpl extends AbstractGuavaCacheMBean cacheAsMap = cache.asMap();
@@ -232,6 +227,11 @@ public void invalidate(HttpCacheConfig cacheConfig) {
}
}
+ @Override
+ public void invalidateAll() {
+ cache.invalidateAll();
+ }
+
@Override
public TempSink createTempSink() {
return new MemTempSinkImpl();
@@ -260,6 +260,7 @@ protected long getBytesLength(MemCachePersistenceObject cacheObj) {
}
@Override
+ @SuppressWarnings("squid:S1192")
protected void addCacheData(Map