diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/AliasKeyManager.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/AliasKeyManager.java index 9660244ce8..05bdabe2dd 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/AliasKeyManager.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/AliasKeyManager.java @@ -49,7 +49,9 @@ public class AliasKeyManager implements X509KeyManager { if (aliases != null && aliases.length > 0) { for (String alias: aliases) { if (this.alias.equals(alias)) { - if (Debug.verboseOn()) Debug.logVerbose("chooseClientAlias for keyType [" + keyType + "] got alias " + this.alias, module); + if (Debug.verboseOn()) { + Debug.logVerbose("chooseClientAlias for keyType [" + keyType + "] got alias " + this.alias, module); + } return this.alias; } } @@ -70,7 +72,9 @@ public class AliasKeyManager implements X509KeyManager { public X509Certificate[] getCertificateChain(String alias) { X509Certificate[] certArray = keyManager.getCertificateChain(alias); - if (Debug.verboseOn()) Debug.logVerbose("getCertificateChain for alias [" + alias + "] got " + certArray.length + " results", module); + if (Debug.verboseOn()) { + Debug.logVerbose("getCertificateChain for alias [" + alias + "] got " + certArray.length + " results", module); + } return certArray; } @@ -80,7 +84,9 @@ public class AliasKeyManager implements X509KeyManager { public PrivateKey getPrivateKey(String alias) { PrivateKey pk = keyManager.getPrivateKey(alias); - if (Debug.verboseOn()) Debug.logVerbose("getPrivateKey for alias [" + alias + "] got " + (pk == null ? "[Not Found!]" : "[alg:" + pk.getAlgorithm() + ";format:" + pk.getFormat() + "]"), module); + if (Debug.verboseOn()) { + Debug.logVerbose("getPrivateKey for alias [" + alias + "] got " + (pk == null ? "[Not Found!]" : "[alg:" + pk.getAlgorithm() + ";format:" + pk.getFormat() + "]"), module); + } return pk; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/Assert.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/Assert.java index 308626d634..1cea0d8293 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/Assert.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/Assert.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import org.apache.ofbiz.base.lang.ThreadSafe; /** Basic assertions. The static methods in this class provide a convenient way * to test method arguments. All of the methods in this class throw * IllegalArgumentException if the method arguments are invalid. - * + * */ @ThreadSafe public class Assert { @@ -33,7 +33,7 @@ public class Assert { /** * Tests if an argument is not null and can be cast to a specified class. *

Assert.isAssignableTo("foo", foo, Foo.class);

- * + * * @param argumentName * @param argumentObject * @param targetClass @@ -49,7 +49,7 @@ public class Assert { /** * Tests if an argument is not null and is an instance of a specified class. *

Assert.isInstanceOf("foo", foo, Foo.class);

- * + * * @param argumentName * @param argumentObject * @param targetClass @@ -65,7 +65,7 @@ public class Assert { /** * Tests if an argument is not null and is an instance of one of the specified classes. *

Assert.isInstanceOf("foo", foo, Foo.class, Bar.class, ...);

- * + * * @param argumentName * @param argumentObject * @param targetClasses @@ -92,7 +92,7 @@ public class Assert { /** * Tests if an argument is not null and is not an instance of a specified class. *

Assert.isNotInstanceOf("foo", foo, Foo.class);

- * + * * @param argumentName * @param argumentObject * @param targetClass @@ -108,7 +108,7 @@ public class Assert { /** * Tests if an argument is not null and is not an instance of one of the specified classes. *

Assert.isNotInstanceOf("foo", foo, Foo.class, Bar.class, ...);

- * + * * @param argumentName * @param argumentObject * @param targetClasses @@ -127,7 +127,7 @@ public class Assert { /** * Tests if an argument is not null and is not empty. *

Assert.notEmpty("foo", foo);

- * + * * @param argumentName * @param argumentObject * @throws IllegalArgumentException @@ -142,7 +142,7 @@ public class Assert { /** * Tests if an argument is not null and is not empty. *

Assert.notEmpty("foo", foo);

- * + * * @param argumentName * @param argumentObject * @throws IllegalArgumentException @@ -157,7 +157,7 @@ public class Assert { /** * Tests if an argument is not null and is not empty. *

Assert.notEmpty("foo", foo);

- * + * * @param argumentName * @param argumentObject * @throws IllegalArgumentException @@ -172,7 +172,7 @@ public class Assert { /** * Tests if an argument is not null and is not empty. *

Assert.notEmpty("foo", foo);

- * + * * @param argumentName * @param argumentObject * @throws IllegalArgumentException @@ -187,7 +187,7 @@ public class Assert { /** * Tests a list of arguments for null. *

Assert.notNull("foo", foo, "bar", bar, ...);

- * + * * @param arguments * @throws IllegalArgumentException */ @@ -200,7 +200,7 @@ public class Assert { /** * Tests an argument for null. *

Assert.notNull("foo", foo);

- * + * * @param argumentName * @param objectToTest * @throws IllegalArgumentException diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/Base64.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/Base64.java index 777cca1b97..da944a6b97 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/Base64.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/Base64.java @@ -150,7 +150,9 @@ public class Base64 { * @return the decoded str. */ public final static String base64Decode(String str) { - if (str == null) return null; + if (str == null) { + return null; + } return new String(base64Decode(str.getBytes(UtilIO.getUtf8()))); } @@ -182,8 +184,9 @@ public class Base64 { if (sidx < data.length - 1) { dest[didx++] = base64EncMap[(data[sidx + 1] >>> 4) & 017 | (data[sidx] << 4) & 077]; dest[didx++] = base64EncMap[(data[sidx + 1] << 2) & 077]; - } else + } else { dest[didx++] = base64EncMap[(data[sidx] << 4) & 077]; + } } // add padding diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/Debug.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/Debug.java index 7bc01dd66a..cb04a9920e 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/Debug.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/Debug.java @@ -49,7 +49,7 @@ public final class Debug { private static final String[] levelProps = {"", "print.verbose", "print.timing", "print.info", "print.important", "print.warning", "print.error", "print.fatal"}; private static final Level[] levelObjs = {Level.FATAL, Level.DEBUG, Level.TRACE, Level.INFO, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL}; - private static final Map levelStringMap = new HashMap(); + private static final Map levelStringMap = new HashMap<>(); private static final boolean levelOnCache[] = new boolean[8]; // this field is not thread safe @@ -79,14 +79,15 @@ public final class Debug { public static Logger getLogger(String module) { if (UtilValidate.isNotEmpty(module)) { return LogManager.getLogger(module); - } else { - return root; } + return root; } /** Gets an Integer representing the level number from a String representing the level name; will return null if not found */ public static Integer getLevelFromString(String levelName) { - if (levelName == null) return null; + if (levelName == null) { + return null; + } return levelStringMap.get(levelName.toLowerCase(Locale.getDefault())); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java index 45f9426277..3193bdb8c9 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/FileUtil.java @@ -25,8 +25,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; @@ -55,8 +53,8 @@ public final class FileUtil { private static class SearchTextFilesFilter implements FilenameFilter { String fileExtension; - Set stringsToFindInFile = new HashSet(); - Set stringsToFindInPath = new HashSet(); + Set stringsToFindInFile = new HashSet<>(); + Set stringsToFindInPath = new HashSet<>(); public SearchTextFilesFilter(String fileExtension, Set stringsToFindInPath, Set stringsToFindInFile) { this.fileExtension = fileExtension; @@ -94,9 +92,6 @@ public final class FileUtil { StringBuffer xmlFileBuffer = null; try { xmlFileBuffer = FileUtil.readTextFile(file, true); - } catch (FileNotFoundException e) { - Debug.logWarning("Error reading xml file [" + file + "] for file search: " + e.toString(), module); - return false; } catch (IOException e) { Debug.logWarning("Error reading xml file [" + file + "] for file search: " + e.toString(), module); return false; @@ -149,7 +144,7 @@ public final class FileUtil { writeString(null, fileName, s); } - public static void writeString(String path, String name, String s) throws IOException { + public static void writeString(String path, String name, String s) { try ( Writer out = getBufferedWriter(path, name); @@ -297,8 +292,8 @@ public final class FileUtil { basePath = System.getProperty("ofbiz.home"); } - Set stringsToFindInPath = new HashSet(); - Set stringsToFindInFile = new HashSet(); + Set stringsToFindInPath = new HashSet<>(); + Set stringsToFindInFile = new HashSet<>(); if (partialPath != null) { stringsToFindInPath.add(partialPath); @@ -307,7 +302,7 @@ public final class FileUtil { stringsToFindInFile.add(stringToFind); } - List fileList = new LinkedList(); + List fileList = new LinkedList<>(); FileUtil.searchFiles(fileList, new File(basePath), new SearchTextFilesFilter(fileExt, stringsToFindInPath, stringsToFindInFile), true); return fileList; @@ -318,14 +313,20 @@ public final class FileUtil { basePath = System.getProperty("ofbiz.home"); } - Set stringsToFindInPath = new HashSet(); - Set stringsToFindInFile = new HashSet(); + Set stringsToFindInPath = new HashSet<>(); + Set stringsToFindInFile = new HashSet<>(); - if (partialPath != null) stringsToFindInPath.add(partialPath); - if (rootElementName != null) stringsToFindInFile.add("<" + rootElementName + " "); - if (xsdOrDtdName != null) stringsToFindInFile.add(xsdOrDtdName); + if (partialPath != null) { + stringsToFindInPath.add(partialPath); + } + if (rootElementName != null) { + stringsToFindInFile.add("<" + rootElementName + " "); + } + if (xsdOrDtdName != null) { + stringsToFindInFile.add(xsdOrDtdName); + } - List fileList = new LinkedList(); + List fileList = new LinkedList<>(); FileUtil.searchFiles(fileList, new File(basePath), new SearchTextFilesFilter("xml", stringsToFindInPath, stringsToFindInFile), true); return fileList; } @@ -348,9 +349,14 @@ public final class FileUtil { int count = 0; while((numCharsRead = reader.read(buffer)) > 0) { for (int c = 0; c < numCharsRead; ++c) { - if (buffer[c] == searchString.charAt(count)) count++; - else count = 0; - if (count == searchString.length()) return true; + if (buffer[c] == searchString.charAt(count)) { + count++; + } else { + count = 0; + } + if (count == searchString.length()) { + return true; + } } } return false; @@ -377,9 +383,8 @@ public final class FileUtil { ) { return containsString(in, searchString); } - } else { - return false; } + return false; } /** @@ -396,5 +401,4 @@ public final class FileUtil { File f = new File(fileName); return f.isFile(); } - } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralException.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralException.java index 7d94b4acbf..dd575da26c 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralException.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralException.java @@ -34,9 +34,15 @@ public class GeneralException extends Exception { } public static T checkException(String message, Throwable t) throws GeneralException { - if (t instanceof Error) throw (Error) t; - if (t instanceof RuntimeException) throw (RuntimeException) t; - if (t instanceof GeneralException) throw (GeneralException) t; + if (t instanceof Error) { + throw (Error) t; + } + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + if (t instanceof GeneralException) { + throw (GeneralException) t; + } throw (GeneralException) new GeneralException(message).initCause(t); } @@ -117,12 +123,10 @@ public class GeneralException extends Exception { if (nested != null) { if (super.getMessage() == null) { return nested.getMessage(); - } else { - return super.getMessage() + " (" + nested.getMessage() + ")"; } - } else { - return super.getMessage(); + return super.getMessage() + " (" + nested.getMessage() + ")"; } + return super.getMessage(); } public List getMessageList() { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralRuntimeException.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralRuntimeException.java index 7cc862737c..01cd20406b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralRuntimeException.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/GeneralRuntimeException.java @@ -66,10 +66,10 @@ public class GeneralRuntimeException extends RuntimeException { /** Returns the detail message, including the message from the nested exception if there is one. */ @Override public String getMessage() { - if (nested != null) + if (nested != null) { return super.getMessage() + " (" + nested.getMessage() + ")"; - else - return super.getMessage(); + } + return super.getMessage(); } /** Returns the detail message, NOT including the message from the nested exception. */ @@ -86,20 +86,26 @@ public class GeneralRuntimeException extends RuntimeException { @Override public void printStackTrace() { super.printStackTrace(); - if (nested != null) nested.printStackTrace(); + if (nested != null) { + nested.printStackTrace(); + } } /** Prints the composite message and the embedded stack trace to the specified stream ps. */ @Override public void printStackTrace(PrintStream ps) { super.printStackTrace(ps); - if (nested != null) nested.printStackTrace(ps); + if (nested != null) { + nested.printStackTrace(ps); + } } /** Prints the composite message and the embedded stack trace to the specified print writer pw. */ @Override public void printStackTrace(PrintWriter pw) { super.printStackTrace(pw); - if (nested != null) nested.printStackTrace(pw); + if (nested != null) { + nested.printStackTrace(pw); + } } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/GroovyUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/GroovyUtil.java index 108d00060e..672a684dec 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/GroovyUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/GroovyUtil.java @@ -64,7 +64,7 @@ public class GroovyUtil { */ try { GroovyUtil.runScriptAtLocation("component://base/config/GroovyInit.groovy", null, null); - } catch(Exception e) { + } catch (Exception e) { Debug.logWarning("The following error occurred during the initialization of Groovy: " + e.getMessage(), module); } } @@ -114,19 +114,22 @@ public class GroovyUtil { * back to the caller. Any variables that are created in the script * are lost when the script ends unless they are copied to the * "context" Map.

- * + * * @param context A Map containing initial variables * @return A Binding instance */ public static Binding getBinding(Map context, String expression) { - Map vars = new HashMap(); + Map vars = new HashMap<>(); if (context != null) { vars.putAll(context); if (UtilValidate.isNotEmpty(expression)) { //analyse expression to find variables by split non alpha, ignoring "_" to allow my_variable usage String [] variables = expression.split("[\\P{Alpha}&&[^_]]+"); - for (String variable: variables) - if(!vars.containsKey(variable)) vars.put(variable, null); + for (String variable: variables) { + if(!vars.containsKey(variable)) { + vars.put(variable, null); + } + } } vars.put("context", context); if (vars.get(ScriptUtil.SCRIPT_HELPER_KEY) == null) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpClient.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpClient.java index 354269b4a6..7ad0154eea 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpClient.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpClient.java @@ -144,8 +144,9 @@ public class HttpClient { /** Set an individual parameter for this request. */ public void setParameter(String name, String value) { - if (parameters == null) - parameters = new HashMap(); + if (parameters == null) { + parameters = new HashMap<>(); + } parameters.put(name, value); } @@ -156,8 +157,9 @@ public class HttpClient { /** Set an individual header for this request. */ public void setHeader(String name, String value) { - if (headers == null) - headers = new HashMap(); + if (headers == null) { + headers = new HashMap<>(); + } headers.put(name, value); } @@ -185,12 +187,12 @@ public class HttpClient { public String getContentType() { return this.contentType; } - + /** Sets the scream charset */ public void setStreamCharset(String streamCharset) { this.streamCharset = streamCharset; } - + /** Returns the stream charset */ public String getStreamCharset() { return this.streamCharset; @@ -340,13 +342,15 @@ public class HttpClient { public String sendHttpRequest(String method) throws HttpClientException { InputStream in = sendHttpRequestStream(method); - if (in == null) return null; + if (in == null) { + return null; + } StringBuilder buf = new StringBuilder(); try { if (Debug.verboseOn() || debug) { try { - Debug.logInfo("ContentEncoding: " + con.getContentEncoding() + "; ContentType: " + + Debug.logVerbose("ContentEncoding: " + con.getContentEncoding() + "; ContentType: " + con.getContentType() + " or: " + URLConnection.guessContentTypeFromStream(in), module); } catch (IOException ioe) { Debug.logWarning(ioe, "Caught exception printing content debugging information", module); @@ -359,11 +363,15 @@ public class HttpClient { try { contentType = URLConnection.guessContentTypeFromStream(in); } catch (IOException ioe) { - Debug.logWarning(ioe, "Problems guessing content type from steam", module); + if (Debug.warningOn()) { + Debug.logWarning(ioe, "Problems guessing content type from stream", module); + } } } - if (Debug.verboseOn() || debug) Debug.logVerbose("Content-Type: " + contentType, module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Content-Type: " + contentType, module); + } if (contentType != null) { contentType = contentType.toUpperCase(Locale.getDefault()); @@ -375,8 +383,12 @@ public class HttpClient { charset = contentType.substring(charsetEqualsLoc + 1); } - if (charset != null) charset = charset.trim().replaceAll("\"", ""); - if (Debug.verboseOn() || debug) Debug.logVerbose("Getting text from HttpClient with charset: " + charset, module); + if (charset != null) { + charset = charset.trim().replaceAll("\"", ""); + } + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Getting text from HttpClient with charset: " + charset, module); + } } try ( @@ -384,9 +396,13 @@ public class HttpClient { : new InputStreamReader(in, charset))) { String line = ""; - if (Debug.verboseOn() || debug) Debug.logVerbose("---- HttpClient Response Content ----", module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("---- HttpClient Response Content ----", module); + } while ((line = post.readLine()) != null) { - if (Debug.verboseOn() || debug) Debug.logVerbose("[HttpClient] : " + line, module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("[HttpClient] : " + line, module); + } buf.append(line); if (lineFeed) { buf.append("\n"); @@ -439,11 +455,15 @@ public class HttpClient { } else { con = URLConnector.openConnection(requestUrl, timeout, clientCertAlias, hostVerification); } - if (Debug.verboseOn() || debug) Debug.logVerbose("Connection opened to : " + requestUrl.toExternalForm(), module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Connection opened to : " + requestUrl.toExternalForm(), module); + } if ((con instanceof HttpURLConnection)) { ((HttpURLConnection) con).setInstanceFollowRedirects(followRedirects); - if (Debug.verboseOn() || debug) Debug.logVerbose("Connection is of type HttpURLConnection, more specifically: " + con.getClass().getName(), module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Connection is of type HttpURLConnection, more specifically: " + con.getClass().getName(), module); + } } // set the content type @@ -469,7 +489,9 @@ public class HttpClient { if (basicAuthUsername != null) { String basicAuthString = "Basic " + Base64.base64Encode(basicAuthUsername + ":" + (basicAuthPassword == null ? "" : basicAuthPassword)); con.setRequestProperty("Authorization", basicAuthString); - if (Debug.verboseOn() || debug) Debug.logVerbose("Header - Authorization: " + basicAuthString, module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Header - Authorization: " + basicAuthString, module); + } } if (UtilValidate.isNotEmpty(headers)) { @@ -477,7 +499,9 @@ public class HttpClient { String headerName = entry.getKey(); String headerValue = entry.getValue(); con.setRequestProperty(headerName, headerValue); - if (Debug.verboseOn() || debug) Debug.logVerbose("Header - " + headerName + ": " + headerValue, module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Header - " + headerName + ": " + headerValue, module); + } } } @@ -485,17 +509,20 @@ public class HttpClient { try ( OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), this.streamCharset != null ? this.streamCharset : "UTF-8")) { - if (Debug.verboseOn() || debug) - if (Debug.verboseOn()) Debug.logVerbose("Opened output stream", module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Opened output stream", module); + } if (arguments != null) { out.write(arguments); - if (Debug.verboseOn() || debug) - if (Debug.verboseOn()) Debug.logVerbose("Wrote arguements (parameters) : " + arguments, module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Wrote arguements (parameters) : " + arguments, module); + } } - if (Debug.verboseOn() || debug) - if (Debug.verboseOn()) Debug.logVerbose("Flushed and closed buffer", module); + if (Debug.verboseOn() || debug) { + Debug.logVerbose("Flushed and closed buffer", module); + } } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java index 3d0db7eed9..9af96d06da 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/HttpRequestFileUpload.java @@ -73,14 +73,16 @@ public class HttpRequestFileUpload { } public String getFieldValue(String fieldName) { - if (fields == null || fieldName == null) + if (fields == null || fieldName == null) { return null; + } return fields.get(fieldName); } private void setFilename(String s) { - if (s == null) + if (s == null) { return; + } int pos = s.indexOf("filename=\""); @@ -90,21 +92,24 @@ public class HttpRequestFileUpload { // But Linux/Unix and Mac browsers only send the filename // test if this is from a Windows browser pos = filepath.lastIndexOf("\\"); - if (pos != -1) + if (pos != -1) { filename = filepath.substring(pos + 1); - else + } else { filename = filepath; + } } } private void setContentType(String s) { - if (s == null) + if (s == null) { return; + } int pos = s.indexOf(": "); - if (pos != -1) + if (pos != -1) { contentType = s.substring(pos + 2, s.length()); + } } public void doUpload(HttpServletRequest request) throws IOException { @@ -127,14 +132,15 @@ public class HttpRequestFileUpload { i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength); requestLength -= i; - if (i < 3) + if (i < 3) { return; + } int boundaryLength = i - 2; String boundary = new String(line, 0, boundaryLength, UtilIO.getUtf8()); // -2 discards the newline character System.out.println("boundary=[" + boundary + "] length is " + boundaryLength); - fields = new HashMap(); + fields = new HashMap<>(); while (requestLength > 0/* i != -1*/) { String newLine = ""; @@ -145,8 +151,9 @@ public class HttpRequestFileUpload { if (newLine.startsWith("Content-Disposition: form-data; name=\"")) { if (newLine.indexOf("filename=\"") != -1) { setFilename(new String(line, 0, i - 2, UtilIO.getUtf8())); - if (filename == null) + if (filename == null) { return; + } // this is the file content i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength); requestLength -= i; @@ -252,10 +259,11 @@ public class HttpRequestFileUpload { i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength); requestLength -= i; if ((i == boundaryLength + 2 || i == boundaryLength + 4) // + 4 is eof - && (new String(line, 0, i).startsWith(boundary))) + && (new String(line, 0, i).startsWith(boundary))) { fieldValue.append(newLine.substring(0, newLine.length() - 2)); - else + } else { fieldValue.append(newLine); + } newLine = new String(line, 0, i, UtilIO.getUtf8()); } fields.put(fieldName, fieldValue.toString()); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java index 5e938f9e75..d5d714f9ea 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/IndentingWriter.java @@ -47,7 +47,9 @@ public class IndentingWriter extends FilterWriter { public IndentingWriter newline() throws IOException { lastWasNewline = true; - if (doNewline) super.write('\n'); + if (doNewline) { + super.write('\n'); + } return this; } @@ -76,7 +78,9 @@ public class IndentingWriter extends FilterWriter { public IndentingWriter space() throws IOException { checkAfterNewline(); - if (doSpace) super.write(' '); + if (doSpace) { + super.write(' '); + } return this; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/JNDIContextFactory.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/JNDIContextFactory.java index 76b697f6a0..f3a292f6c0 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/JNDIContextFactory.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/JNDIContextFactory.java @@ -55,17 +55,20 @@ public class JNDIContextFactory { if (UtilValidate.isEmpty(jndiServerInfo.contextProviderUrl)) { ic = new InitialContext(); } else { - Hashtable h = new Hashtable(); + Hashtable h = new Hashtable<>(); h.put(Context.INITIAL_CONTEXT_FACTORY, jndiServerInfo.initialContextFactory); h.put(Context.PROVIDER_URL, jndiServerInfo.contextProviderUrl); - if (UtilValidate.isNotEmpty(jndiServerInfo.urlPkgPrefixes)) + if (UtilValidate.isNotEmpty(jndiServerInfo.urlPkgPrefixes)) { h.put(Context.URL_PKG_PREFIXES, jndiServerInfo.urlPkgPrefixes); + } - if (UtilValidate.isNotEmpty(jndiServerInfo.securityPrincipal)) + if (UtilValidate.isNotEmpty(jndiServerInfo.securityPrincipal)) { h.put(Context.SECURITY_PRINCIPAL, jndiServerInfo.securityPrincipal); - if (UtilValidate.isNotEmpty(jndiServerInfo.securityCredentials)) + } + if (UtilValidate.isNotEmpty(jndiServerInfo.securityCredentials)) { h.put(Context.SECURITY_CREDENTIALS, jndiServerInfo.securityCredentials); + } ic = new InitialContext(h); } @@ -88,5 +91,4 @@ public class JNDIContextFactory { public static void clearInitialContext(String jndiServerName) { contexts.remove(jndiServerName); } - } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java index e20fff0c89..4e91f76154 100755 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java @@ -31,7 +31,6 @@ import java.io.PrintStream; import java.io.Reader; import java.io.StringReader; import java.net.URL; -import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyStore; @@ -145,7 +144,7 @@ public final class KeyStoreUtil { } public static Map getX500Map(Principal x500) { - Map x500Map = new HashMap(); + Map x500Map = new HashMap<>(); String name = x500.getName().replaceAll("\\\\,", "&com;"); String[] x500Opts = name.split("\\,"); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java index 22c609ebb1..ad0b1d5a08 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/MessageString.java @@ -48,23 +48,31 @@ public class MessageString implements Serializable { if (fieldName == null) { return Collections.emptyList(); } - Set fieldSet = new TreeSet(); + Set fieldSet = new TreeSet<>(); fieldSet.add(fieldName); return getMessagesForField(fieldSet, convertToStrings, messageStringList); } public static List getMessagesForField(String fieldName1, String fieldName2, String fieldName3, String fieldName4, boolean convertToStrings, List messageStringList) { - Set fieldSet = new TreeSet(); - if (UtilValidate.isNotEmpty(fieldName1)) fieldSet.add(fieldName1); - if (UtilValidate.isNotEmpty(fieldName2)) fieldSet.add(fieldName2); - if (UtilValidate.isNotEmpty(fieldName3)) fieldSet.add(fieldName3); - if (UtilValidate.isNotEmpty(fieldName4)) fieldSet.add(fieldName4); + Set fieldSet = new TreeSet<>(); + if (UtilValidate.isNotEmpty(fieldName1)) { + fieldSet.add(fieldName1); + } + if (UtilValidate.isNotEmpty(fieldName2)) { + fieldSet.add(fieldName2); + } + if (UtilValidate.isNotEmpty(fieldName3)) { + fieldSet.add(fieldName3); + } + if (UtilValidate.isNotEmpty(fieldName4)) { + fieldSet.add(fieldName4); + } return getMessagesForField(fieldSet, convertToStrings, messageStringList); } public static List getMessagesForField(Set fieldNameSet, boolean convertToStrings, List messageStringList) { if (messageStringList == null || UtilValidate.isEmpty(fieldNameSet)) { return Collections.emptyList(); } - List outList = new ArrayList(messageStringList.size()); + List outList = new ArrayList<>(messageStringList.size()); for (Object messageStringCur: messageStringList) { if (messageStringCur instanceof MessageString) { MessageString messageString = (MessageString) messageStringCur; @@ -152,12 +160,10 @@ public class MessageString implements Serializable { if (this.fieldName == null) { if (fieldName == null) { return true; - } else { - return false; } - } else { - return this.fieldName.equals(fieldName); + return false; } + return this.fieldName.equals(fieldName); } /** diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/MultiTrustManager.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/MultiTrustManager.java index a19de3ea86..122502b309 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/MultiTrustManager.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/MultiTrustManager.java @@ -45,7 +45,7 @@ public class MultiTrustManager implements X509TrustManager { } public MultiTrustManager() { - keystores = new LinkedList(); + keystores = new LinkedList<>(); } public void add(KeyStore ks) { @@ -77,7 +77,7 @@ public class MultiTrustManager implements X509TrustManager { } public X509Certificate[] getAcceptedIssuers() { - List issuers = new LinkedList(); + List issuers = new LinkedList<>(); for (KeyStore store: keystores) { try { Enumeration e = store.aliases(); @@ -87,16 +87,18 @@ public class MultiTrustManager implements X509TrustManager { if (chain != null) { for (Certificate cert: chain) { if (cert instanceof X509Certificate) { - if (Debug.verboseOn()) - Debug.logInfo("Read certificate (chain) : " + ((X509Certificate) cert).getSubjectX500Principal().getName(), module); + if (Debug.verboseOn()) { + Debug.logVerbose("Read certificate (chain) : " + ((X509Certificate) cert).getSubjectX500Principal().getName(), module); + } issuers.add((X509Certificate) cert); } } } else { Certificate cert = store.getCertificate(alias); if (cert != null && cert instanceof X509Certificate) { - if (Debug.verboseOn()) - Debug.logInfo("Read certificate : " + ((X509Certificate) cert).getSubjectX500Principal().getName(), module); + if (Debug.verboseOn()) { + Debug.logVerbose("Read certificate : " + ((X509Certificate) cert).getSubjectX500Principal().getName(), module); + } issuers.add((X509Certificate) cert); } } @@ -114,11 +116,13 @@ public class MultiTrustManager implements X509TrustManager { X509Certificate[] issuers = this.getAcceptedIssuers(); for (X509Certificate issuer: issuers) { for (X509Certificate c: cert) { - if (Debug.verboseOn()) - Debug.logInfo("--- Checking cert: " + issuer.getSubjectX500Principal() + " vs " + c.getSubjectX500Principal(), module); + if (Debug.verboseOn()) { + Debug.logVerbose("--- Checking cert: " + issuer.getSubjectX500Principal() + " vs " + c.getSubjectX500Principal(), module); + } if (issuer.equals(c)) { - if (Debug.verboseOn()) - Debug.logInfo("--- Found trusted cert: " + issuer.getSerialNumber().toString(16) + " : " + issuer.getSubjectX500Principal(), module); + if (Debug.verboseOn()) { + Debug.logVerbose("--- Found trusted cert: " + issuer.getSerialNumber().toString(16) + " : " + issuer.getSubjectX500Principal(), module); + } return true; } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectInputStream.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectInputStream.java index 38d0405399..af018ef37f 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectInputStream.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectInputStream.java @@ -50,8 +50,9 @@ public class ObjectInputStream extends java.io.ObjectInputStream { @Override protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class[] cinterfaces = new Class[interfaces.length]; - for (int i = 0; i < interfaces.length; i++) + for (int i = 0; i < interfaces.length; i++) { cinterfaces[i] = classloader.loadClass(interfaces[i]); + } try { return Proxy.getProxyClass(classloader, cinterfaces); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java index e79812ba05..f67948d9ab 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/ObjectType.java @@ -21,7 +21,6 @@ package org.apache.ofbiz.base.util; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.HashMap; import java.util.List; @@ -50,8 +49,8 @@ public class ObjectType { public static final String LANG_PACKAGE = "java.lang."; // We will test both the raw value and this + raw value public static final String SQL_PACKAGE = "java.sql."; // We will test both the raw value and this + raw value - private static final Map classAlias = new HashMap(); - private static final Map> primitives = new HashMap>(); + private static final Map classAlias = new HashMap<>(); + private static final Map> primitives = new HashMap<>(); static { classAlias.put("Object", "java.lang.Object"); @@ -114,7 +113,9 @@ public class ObjectType { } int genericsStart = className.indexOf("<"); - if (genericsStart != -1) className = className.substring(0, genericsStart); + if (genericsStart != -1) { + className = className.substring(0, genericsStart); + } // Handle array classes. Details in http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/types.html#wp16437 if (className.endsWith("[]")) { @@ -138,7 +139,9 @@ public class ObjectType { className = classAlias.get(className); } - if (loader == null) loader = Thread.currentThread().getContextClassLoader(); + if (loader == null) { + loader = Thread.currentThread().getContextClassLoader(); + } theClass = Class.forName(className, true, loader); @@ -159,7 +162,9 @@ public class ObjectType { Class c = loadClass(className); Object o = c.newInstance(); - if (Debug.verboseOn()) Debug.logVerbose("Instantiated object: " + o.toString(), module); + if (Debug.verboseOn()) { + Debug.logVerbose("Instantiated object: " + o.toString(), module); + } return o; } @@ -207,7 +212,9 @@ public class ObjectType { Constructor con = c.getConstructor(sig); Object o = con.newInstance(parameters); - if (Debug.verboseOn()) Debug.logVerbose("Instantiated object: " + o.toString(), module); + if (Debug.verboseOn()) { + Debug.logVerbose("Instantiated object: " + o.toString(), module); + } return o; } @@ -259,7 +266,9 @@ public class ObjectType { Class[] ifaces = objectClass.getInterfaces(); for (Class iface: ifaces) { - if (iface == interfaceClass) return true; + if (iface == interfaceClass) { + return true; + } } objectClass = objectClass.getSuperclass(); } @@ -336,7 +345,9 @@ public class ObjectType { */ public static boolean isOrSubOf(Class objectClass, Class parentClass) { while (objectClass != null) { - if (objectClass == parentClass) return true; + if (objectClass == parentClass) { + return true; + } objectClass = objectClass.getSuperclass(); } return false; @@ -396,8 +407,9 @@ public class ObjectType { public static boolean instanceOf(Class objectClass, String typeName, ClassLoader loader) { Class infoClass = loadInfoClass(typeName, loader); - if (infoClass == null) + if (infoClass == null) { throw new IllegalArgumentException("Illegal type found in info map (could not load class for specified type)"); + } return instanceOf(objectClass, infoClass); } @@ -453,7 +465,9 @@ public class ObjectType { * @return true if obj is an instance of a sub-class of typeClass */ public static boolean instanceOf(Object obj, Class typeClass) { - if (obj == null) return true; + if (obj == null) { + return true; + } Class objectClass = obj.getClass(); return instanceOf(objectClass, typeClass); } @@ -467,9 +481,8 @@ public class ObjectType { public static boolean instanceOf(Class objectClass, Class typeClass) { if (typeClass.isInterface() && !objectClass.isInterface()) { return interfaceOf(objectClass, typeClass); - } else { - return isOrSubOf(objectClass, typeClass); } + return isOrSubOf(objectClass, typeClass); } public static Object simpleTypeConvert(Object obj, String type, String format, Locale locale, boolean noTypeFail) throws GeneralException { @@ -503,9 +516,8 @@ public class ObjectType { String nodeValue = node.getTextContent(); if ("String".equals(type) || "java.lang.String".equals(type)) { return nodeValue; - } else { - return simpleTypeConvert(nodeValue, type, format, timeZone, locale, noTypeFail); } + return simpleTypeConvert(nodeValue, type, format, timeZone, locale, noTypeFail); } int genericsStart = type.indexOf("<"); if (genericsStart != -1) { @@ -562,10 +574,11 @@ public class ObjectType { } if (noTypeFail) { throw new GeneralException("Conversion from " + obj.getClass().getName() + " to " + type + " not currently supported"); - } else { - if (Debug.infoOn()) Debug.logInfo("No type conversion available for " + obj.getClass().getName() + " to " + targetClass.getName() + ", returning original object.", module); - return obj; } + if (Debug.infoOn()) { + Debug.logInfo("No type conversion available for " + obj.getClass().getName() + " to " + targetClass.getName() + ", returning original object.", module); + } + return obj; } public static Object simpleTypeConvert(Object obj, String type, String format, Locale locale) throws GeneralException { @@ -576,7 +589,9 @@ public class ObjectType { List messages, Locale locale, ClassLoader loader, boolean value2InlineConstant) { boolean verboseOn = Debug.verboseOn(); - if (verboseOn) Debug.logVerbose("Comparing value1: \"" + value1 + "\" " + operator + " value2:\"" + value2 + "\"", module); + if (verboseOn) { + Debug.logVerbose("Comparing value1: \"" + value1 + "\" " + operator + " value2:\"" + value2 + "\"", module); + } try { if (!"PlainString".equals(type)) { @@ -660,29 +675,36 @@ public class ObjectType { String str2 = (String) convertedValue2; return str1.indexOf(str2) < 0 ? Boolean.FALSE : Boolean.TRUE; - } else { - messages.add("Error in XML file: cannot do a contains compare between a String and a non-String type"); - return null; } + messages.add("Error in XML file: cannot do a contains compare between a String and a non-String type"); + return null; } else if ("is-empty".equals(operator)) { - if (convertedValue1 == null) + if (convertedValue1 == null) { return Boolean.TRUE; - if (convertedValue1 instanceof String && ((String) convertedValue1).length() == 0) + } + if (convertedValue1 instanceof String && ((String) convertedValue1).length() == 0) { return Boolean.TRUE; - if (convertedValue1 instanceof List && ((List) convertedValue1).size() == 0) + } + if (convertedValue1 instanceof List && ((List) convertedValue1).size() == 0) { return Boolean.TRUE; - if (convertedValue1 instanceof Map && ((Map) convertedValue1).size() == 0) + } + if (convertedValue1 instanceof Map && ((Map) convertedValue1).size() == 0) { return Boolean.TRUE; + } return Boolean.FALSE; } else if ("is-not-empty".equals(operator)) { - if (convertedValue1 == null) + if (convertedValue1 == null) { return Boolean.FALSE; - if (convertedValue1 instanceof String && ((String) convertedValue1).length() == 0) + } + if (convertedValue1 instanceof String && ((String) convertedValue1).length() == 0) { return Boolean.FALSE; - if (convertedValue1 instanceof List && ((List) convertedValue1).size() == 0) + } + if (convertedValue1 instanceof List && ((List) convertedValue1).size() == 0) { return Boolean.FALSE; - if (convertedValue1 instanceof Map && ((Map) convertedValue1).size() == 0) + } + if (convertedValue1 instanceof Map && ((Map) convertedValue1).size() == 0) { return Boolean.FALSE; + } return Boolean.TRUE; } @@ -708,12 +730,13 @@ public class ObjectType { tempNum = (Number) convertedValue2; double value2Double = tempNum.doubleValue(); - if (value1Double < value2Double) + if (value1Double < value2Double) { result = -1; - else if (value1Double > value2Double) + } else if (value1Double > value2Double) { result = 1; - else + } else { result = 0; + } } else if ("java.sql.Date".equals(type)) { java.sql.Date value1Date = (java.sql.Date) convertedValue1; java.sql.Date value2Date = (java.sql.Date) convertedValue2; @@ -730,15 +753,17 @@ public class ObjectType { Boolean value1Boolean = (Boolean) convertedValue1; Boolean value2Boolean = (Boolean) convertedValue2; if ("equals".equals(operator)) { - if ((value1Boolean.booleanValue() && value2Boolean.booleanValue()) || (!value1Boolean.booleanValue() && !value2Boolean.booleanValue())) + if ((value1Boolean.booleanValue() && value2Boolean.booleanValue()) || (!value1Boolean.booleanValue() && !value2Boolean.booleanValue())) { result = 0; - else + } else { result = 1; + } } else if ("not-equals".equals(operator)) { - if ((!value1Boolean.booleanValue() && value2Boolean.booleanValue()) || (value1Boolean.booleanValue() && !value2Boolean.booleanValue())) + if ((!value1Boolean.booleanValue() && value2Boolean.booleanValue()) || (value1Boolean.booleanValue() && !value2Boolean.booleanValue())) { result = 0; - else + } else { result = 1; + } } else { messages.add("Can only compare Booleans using the operators 'equals' or 'not-equals'"); return null; @@ -754,50 +779,80 @@ public class ObjectType { return null; } - if (verboseOn) Debug.logVerbose("Got Compare result: " + result + ", operator: " + operator, module); + if (verboseOn) { + Debug.logVerbose("Got Compare result: " + result + ", operator: " + operator, module); + } if ("less".equals(operator)) { - if (result >= 0) + if (result >= 0) { return Boolean.FALSE; + } } else if ("greater".equals(operator)) { - if (result <= 0) + if (result <= 0) { return Boolean.FALSE; + } } else if ("less-equals".equals(operator)) { - if (result > 0) + if (result > 0) { return Boolean.FALSE; + } } else if ("greater-equals".equals(operator)) { - if (result < 0) + if (result < 0) { return Boolean.FALSE; + } } else if ("equals".equals(operator)) { - if (result != 0) + if (result != 0) { return Boolean.FALSE; + } } else if ("not-equals".equals(operator)) { - if (result == 0) + if (result == 0) { return Boolean.FALSE; + } } else { messages.add("Specified compare operator \"" + operator + "\" not known."); return null; } - if (verboseOn) Debug.logVerbose("Returning true", module); + if (verboseOn) { + Debug.logVerbose("Returning true", module); + } return Boolean.TRUE; } @SuppressWarnings("unchecked") public static boolean isEmpty(Object value) { - if (value == null) return true; + if (value == null) { + return true; + } - if (value instanceof String) return ((String) value).length() == 0; - if (value instanceof Collection) return ((Collection) value).size() == 0; - if (value instanceof Map) return ((Map) value).size() == 0; - if (value instanceof CharSequence) return ((CharSequence) value).length() == 0; - if (value instanceof IsEmpty) return ((IsEmpty) value).isEmpty(); + if (value instanceof String) { + return ((String) value).length() == 0; + } + if (value instanceof Collection) { + return ((Collection) value).size() == 0; + } + if (value instanceof Map) { + return ((Map) value).size() == 0; + } + if (value instanceof CharSequence) { + return ((CharSequence) value).length() == 0; + } + if (value instanceof IsEmpty) { + return ((IsEmpty) value).isEmpty(); + } // These types would flood the log // Number covers: BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short - if (value instanceof Boolean) return false; - if (value instanceof Number) return false; - if (value instanceof Character) return false; - if (value instanceof java.util.Date) return false; + if (value instanceof Boolean) { + return false; + } + if (value instanceof Number) { + return false; + } + if (value instanceof Character) { + return false; + } + if (value instanceof java.util.Date) { + return false; + } if (Debug.verboseOn()) { Debug.logVerbose("In ObjectType.isEmpty(Object value) returning false for " + value.getClass() + " Object.", module); @@ -824,9 +879,8 @@ public class ObjectType { if (other instanceof NullObject) { // should do equality of object? don't think so, just same type return true; - } else { - return false; } + return false; } } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/Observable.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/Observable.java index bb1e7b72dd..4e0babffcf 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/Observable.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/Observable.java @@ -35,7 +35,7 @@ import java.util.concurrent.atomic.AtomicBoolean; public final class Observable { private final AtomicBoolean changed = new AtomicBoolean(); - private final CopyOnWriteArrayList observers = new CopyOnWriteArrayList(); + private final CopyOnWriteArrayList observers = new CopyOnWriteArrayList<>(); public Observable() {} @@ -46,7 +46,7 @@ public final class Observable { } /** - * Adds an observer to the set of observers for this object. + * Adds an observer to the set of observers for this object. * * @param observer the observer to be added. */ @@ -56,16 +56,16 @@ public final class Observable { } /** - * Clears the changed flag. + * Clears the changed flag. */ public void clearChanged() { changed.set(false); } /** - * Deletes an observer from the set of observers of this object. + * Deletes an observer from the set of observers of this object. * Passing null to this method will have no effect. - * + * * @param observer the observer to be deleted. */ public void deleteObserver(Observer observer) { @@ -80,7 +80,7 @@ public final class Observable { } /** - * Returns true if this object has changed. + * Returns true if this object has changed. * */ public boolean hasChanged() { @@ -88,9 +88,9 @@ public final class Observable { } /** - * Notify all of the observers. + * Notify all of the observers. *

Each Observer has its update method called with two - * arguments: this observable object and null. In other + * arguments: this observable object and null. In other * words, this method is equivalent to: *

*
@@ -103,7 +103,7 @@ public final class Observable { } /** - * Notify all of the observers. + * Notify all of the observers. *

Each observer has its update method called with two * arguments: this observable object and the arg argument.

* @@ -115,7 +115,7 @@ public final class Observable { } /** - * Sets the changed flag to true. + * Sets the changed flag to true. */ public void setChanged() { changed.set(true); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/Observer.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/Observer.java index c86936f60a..f3301e07a4 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/Observer.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/Observer.java @@ -25,7 +25,7 @@ package org.apache.ofbiz.base.util; public interface Observer { /** * Called when Observable.notifyObservers is invoked. - * + * * @param observable * @param arg */ diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/RMIExtendedSocketFactory.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/RMIExtendedSocketFactory.java index f7fba18141..2cfdb8c3cb 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/RMIExtendedSocketFactory.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/RMIExtendedSocketFactory.java @@ -26,8 +26,8 @@ import java.net.UnknownHostException; import java.rmi.server.RMISocketFactory; /** - * A RMISocketFactory implementation that creates ServerSockets bound - * on a specified network interface. + * A RMISocketFactory implementation that creates ServerSockets bound + * on a specified network interface. */ public class RMIExtendedSocketFactory extends RMISocketFactory { @@ -44,21 +44,21 @@ public class RMIExtendedSocketFactory extends RMISocketFactory { } /** - * Creates a new RMIExtendedSocketFactory which will create ServerSockets - * bound on the specified network interface. - * - * @param inetAddress The InetAddress of the network interface. + * Creates a new RMIExtendedSocketFactory which will create ServerSockets + * bound on the specified network interface. + * + * @param inetAddress The InetAddress of the network interface. */ public RMIExtendedSocketFactory( InetAddress inetAddress ) { this.hostInetAddress = inetAddress; } /** - * Creates a new RMIExtendedSocketFactory which will create ServerSockets - * bound on the specified network interface. - * + * Creates a new RMIExtendedSocketFactory which will create ServerSockets + * bound on the specified network interface. + * * @param hostIpAddress The IP address of the interface to bind the server sockets to. - * @throws UnknownHostException If an invalid IP address is provided. + * @throws UnknownHostException If an invalid IP address is provided. */ public RMIExtendedSocketFactory( String hostIpAddress ) throws UnknownHostException { @@ -89,9 +89,8 @@ public class RMIExtendedSocketFactory extends RMISocketFactory { public ServerSocket createServerSocket(int port) throws IOException { if ( hostInetAddress != null ) { return new ServerSocket( port, 0, hostInetAddress ); - } else { - return new ServerSocket( port ); } + return new ServerSocket( port ); } @Override diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/ReferenceCleaner.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/ReferenceCleaner.java index 280652601b..69773948a4 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/ReferenceCleaner.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/ReferenceCleaner.java @@ -63,7 +63,7 @@ public final class ReferenceCleaner { private ReferenceCleaner() { } - private static final ReferenceQueue QUEUE = new ReferenceQueue(); + private static final ReferenceQueue QUEUE = new ReferenceQueue<>(); public interface Removable { void remove() throws Exception; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java index a5c7c9dfa8..618f425d9a 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java @@ -104,11 +104,7 @@ public final class SSLUtil { TrustManager[] mgrs = new TrustManager[0]; try { mgrs = SSLUtil.getTrustManagers(); - } catch (IOException e) { - Debug.logError(e, module); - } catch (GeneralSecurityException e) { - Debug.logError(e, module); - } catch (GenericConfigException e) { + } catch (IOException | GeneralSecurityException | GenericConfigException e) { Debug.logError(e, module); } @@ -126,7 +122,7 @@ public final class SSLUtil { } public static KeyManager[] getKeyManagers(String alias) throws IOException, GeneralSecurityException, GenericConfigException { - List keyMgrs = new LinkedList(); + List keyMgrs = new LinkedList<>(); for (ComponentConfig.KeystoreInfo ksi: ComponentConfig.getAllKeystoreInfos()) { if (ksi.isCertStore()) { KeyStore ks = ksi.getKeyStore(); @@ -190,7 +186,7 @@ public final class SSLUtil { return keyManagers; } - public static TrustManager[] getTrustManagers(KeyStore ks) throws GeneralSecurityException { + public static TrustManager[] getTrustManagers(KeyStore ks) { return new TrustManager[] { new MultiTrustManager(ks) }; } @@ -263,8 +259,9 @@ public final class SSLUtil { Principal x500s = peerCert.getSubjectDN(); Map subjectMap = KeyStoreUtil.getX500Map(x500s); - if (Debug.infoOn()) + if (Debug.infoOn()) { Debug.logInfo(peerCert.getSerialNumber().toString(16) + " :: " + subjectMap.get("CN"), module); + } try { peerCert.checkValidity(); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptHelper.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptHelper.java index 859761574c..22ebdf6d95 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptHelper.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptHelper.java @@ -37,7 +37,7 @@ public interface ScriptHelper { /** * Extracts service IN parameters from inputMap and returns them in a new Map. - * + * * @param serviceName * @param inputMap * @return The matching service parameters @@ -47,14 +47,14 @@ public interface ScriptHelper { /** * Sets the event/service status to error status. - * + * * @param message */ void error(String message); /** * Evaluates a String and returns the result. - * + * * @param original * @return */ @@ -62,7 +62,7 @@ public interface ScriptHelper { /** * Sets the event/service status to failure status. - * + * * @param message */ void failure(String message); @@ -97,21 +97,21 @@ public interface ScriptHelper { /** * Logs an error message. - * + * * @param message */ void logError(String message); /** * Logs an info message. - * + * * @param message */ void logInfo(String message); /** * Logs a warning message. - * + * * @param message */ void logWarning(String message); @@ -126,7 +126,7 @@ public interface ScriptHelper { /** * Creates a new, empty GenericValue. - * + * * @param entityName * @param fields * @return @@ -136,7 +136,7 @@ public interface ScriptHelper { /** * Runs a service synchronously. - * + * * @param serviceName * @param inputMap * @return @@ -146,7 +146,7 @@ public interface ScriptHelper { /** * Runs a service synchronously. - * + * * @param serviceName * @param inputMap * @param args @@ -162,7 +162,7 @@ public interface ScriptHelper { /** * Sets the event/service status to success status. - * + * * @param message */ void success(String message); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptUtil.java index 6f21d8aa06..44ba579d3b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/ScriptUtil.java @@ -75,7 +75,7 @@ public final class ScriptUtil { public static final Set SCRIPT_NAMES; static { - Set writableScriptNames = new HashSet(); + Set writableScriptNames = new HashSet<>(); ScriptEngineManager manager = new ScriptEngineManager(); List engines = manager.getEngineFactories(); if (engines.isEmpty()) { @@ -117,7 +117,7 @@ public final class ScriptUtil { /** * Returns a compiled script. - * + * * @param filePath Script path and file name. * @return The compiled script, or null if the script engine does not support compilation. * @throws IllegalArgumentException @@ -156,7 +156,7 @@ public final class ScriptUtil { /** * Returns a compiled script. - * + * * @param language * @param script * @return The compiled script, or null if the script engine does not support compilation. @@ -196,13 +196,13 @@ public final class ScriptUtil { *

If a CompiledScript instance is to be shared by multiple threads, then * each thread must create its own ScriptContext and pass it to the * CompiledScript eval method.

- * + * * @param context * @return */ public static ScriptContext createScriptContext(Map context) { Assert.notNull("context", context); - Map localContext = new HashMap(context); + Map localContext = new HashMap<>(context); localContext.put(WIDGET_CONTEXT_KEY, context); localContext.put("context", context); ScriptContext scriptContext = new SimpleScriptContext(); @@ -220,14 +220,14 @@ public final class ScriptUtil { *

If a CompiledScript instance is to be shared by multiple threads, then * each thread must create its own ScriptContext and pass it to the * CompiledScript eval method.

- * + * * @param context * @param protectedKeys * @return */ public static ScriptContext createScriptContext(Map context, Set protectedKeys) { Assert.notNull("context", context, "protectedKeys", protectedKeys); - Map localContext = new HashMap(context); + Map localContext = new HashMap<>(context); localContext.put(WIDGET_CONTEXT_KEY, context); localContext.put("context", context); ScriptContext scriptContext = new SimpleScriptContext(); @@ -249,7 +249,7 @@ public final class ScriptUtil { /** * Executes a script String and returns the result. - * + * * @param language * @param script * @param scriptClass @@ -286,7 +286,7 @@ public final class ScriptUtil { /** * Executes a compiled script and returns the result. - * + * * @param script Compiled script. * @param functionName Optional function or method to invoke. * @param scriptContext Script execution context. @@ -313,7 +313,7 @@ public final class ScriptUtil { /** * Executes the script at the specified location and returns the result. - * + * * @param filePath Script path and file name. * @param functionName Optional function or method to invoke. * @param context Script execution context. @@ -326,7 +326,7 @@ public final class ScriptUtil { /** * Executes the script at the specified location and returns the result. - * + * * @param filePath Script path and file name. * @param functionName Optional function or method to invoke. * @param context Script execution context. @@ -351,7 +351,7 @@ public final class ScriptUtil { /** * Executes the script at the specified location and returns the result. - * + * * @param filePath Script path and file name. * @param functionName Optional function or method to invoke. * @param scriptContext Script execution context. diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/Scriptlet.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/Scriptlet.java index 5f554c8b69..032e58b325 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/Scriptlet.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/Scriptlet.java @@ -44,7 +44,7 @@ public final class Scriptlet { /** * Executes the scriptlet and returns the result. - * + * * @param context The script bindings * @return The scriptlet result * @throws Exception diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/StringUtil.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/StringUtil.java index 757543290f..798b4ba98c 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/StringUtil.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/StringUtil.java @@ -49,7 +49,7 @@ public class StringUtil { private static final Map substitutionPatternMap = createSubstitutionPatternMap(); private static Map createSubstitutionPatternMap() { - Map substitutionPatternMap = new LinkedHashMap(); // Preserve insertion order + Map substitutionPatternMap = new LinkedHashMap<>(); // Preserve insertion order substitutionPatternMap.put("&&", Pattern.compile("@and", Pattern.LITERAL)); substitutionPatternMap.put("||", Pattern.compile("@or", Pattern.LITERAL)); substitutionPatternMap.put("<=", Pattern.compile("@lteq", Pattern.LITERAL)); @@ -86,7 +86,9 @@ public class StringUtil { int i = mainString.lastIndexOf(oldString); - if (i < 0) return mainString; + if (i < 0) { + return mainString; + } StringBuilder mainSb = new StringBuilder(mainString); @@ -114,15 +116,17 @@ public class StringUtil { * @return a String of all values in the collection seperated by the delimiter */ public static String join(Collection col, String delim) { - if (UtilValidate.isEmpty(col)) + if (UtilValidate.isEmpty(col)) { return null; + } StringBuilder buf = new StringBuilder(); Iterator i = col.iterator(); while (i.hasNext()) { buf.append(i.next()); - if (i.hasNext()) + if (i.hasNext()) { buf.append(delim); + } } return buf.toString(); } @@ -137,15 +141,18 @@ public class StringUtil { List splitList = null; StringTokenizer st; - if (str == null) return null; + if (str == null) { + return null; + } st = (delim != null? new StringTokenizer(str, delim): new StringTokenizer(str)); if (st.hasMoreTokens()) { splitList = new LinkedList<>(); - while (st.hasMoreTokens()) + while (st.hasMoreTokens()) { splitList.add(st.nextToken()); + } } return splitList; } @@ -161,15 +168,22 @@ public class StringUtil { List splitList = null; String[] st = null; - if (str == null) return splitList; + if (str == null) { + return splitList; + } - if (delim != null) st = Pattern.compile(delim).split(str, limit); - else st = str.split("\\s"); + if (delim != null) { + st = Pattern.compile(delim).split(str, limit); + } else { + st = str.split("\\s"); + } if (st != null && st.length > 0) { - splitList = new LinkedList(); - for (int i=0; i < st.length; i++) splitList.add(st[i]); + splitList = new LinkedList<>(); + for (String element : st) { + splitList.add(element); + } } return splitList; @@ -182,7 +196,7 @@ public class StringUtil { public static List quoteStrList(List list) { List tmpList = list; - list = new LinkedList(); + list = new LinkedList<>(); for (String str: tmpList) { str = "'" + str + "'"; list.add(str); @@ -212,8 +226,10 @@ public class StringUtil { * @return a Map of name/value pairs */ public static Map strToMap(String str, String delim, boolean trim, String pairsSeparator) { - if (str == null) return null; - Map decodedMap = new HashMap(); + if (str == null) { + return null; + } + Map decodedMap = new HashMap<>(); List elements = split(str, delim); pairsSeparator = pairsSeparator == null ? "=" : pairsSeparator; @@ -281,7 +297,9 @@ public class StringUtil { * @return String The encoded String */ public static String mapToStr(Map map) { - if (map == null) return null; + if (map == null) { + return null; + } StringBuilder buf = new StringBuilder(); boolean first = true; @@ -289,8 +307,9 @@ public class StringUtil { Object key = entry.getKey(); Object value = entry.getValue(); - if (!(key instanceof String) || !(value instanceof String)) + if (!(key instanceof String) || !(value instanceof String)) { continue; + } String encodedName = null; try { encodedName = URLEncoder.encode((String) key, "UTF-8"); @@ -304,10 +323,11 @@ public class StringUtil { Debug.logError(e, module); } - if (first) + if (first) { first = false; - else + } else { buf.append("|"); + } buf.append(encodedName); buf.append("="); @@ -325,7 +345,7 @@ public class StringUtil { * @return new Map */ public static Map toMap(String s) { - Map newMap = new HashMap(); + Map newMap = new HashMap<>(); if (s.startsWith("{") && s.endsWith("}")) { s = s.substring(1, s.length() - 1); String[] entries = s.split("\\,\\s"); @@ -349,7 +369,7 @@ public class StringUtil { * @return new List */ public static List toList(String s) { - List newList = new LinkedList(); + List newList = new LinkedList<>(); if (s.startsWith("[") && s.endsWith("]")) { s = s.substring(1, s.length() - 1); String[] entries = s.split("\\,\\s"); @@ -370,7 +390,7 @@ public class StringUtil { * @return new List */ public static Set toSet(String s) { - Set newSet = new LinkedHashSet(); + Set newSet = new LinkedHashSet<>(); if (s.startsWith("[") && s.endsWith("]")) { s = s.substring(1, s.length() - 1); String[] entries = s.split("\\,\\s"); @@ -395,7 +415,7 @@ public class StringUtil { if (keys == null || values == null || keys.size() != values.size()) { throw new IllegalArgumentException("Keys and Values cannot be null and must be the same size"); } - Map newMap = new HashMap(); + Map newMap = new HashMap<>(); for (int i = 0; i < keys.size(); i++) { newMap.put(keys.get(i), values.get(i)); } @@ -404,7 +424,9 @@ public class StringUtil { /** Make sure the string starts with a forward slash but does not end with one; converts back-slashes to forward-slashes; if in String is null or empty, returns zero length string. */ public static String cleanUpPathPrefix(String prefix) { - if (UtilValidate.isEmpty(prefix)) return ""; + if (UtilValidate.isEmpty(prefix)) { + return ""; + } StringBuilder cppBuff = new StringBuilder(prefix.replace('\\', '/')); @@ -495,7 +517,9 @@ public class StringUtil { * @return the new value */ public static String addToNumberString(String numberString, long addAmount) { - if (numberString == null) return null; + if (numberString == null) { + return null; + } int origLength = numberString.length(); long number = Long.parseLong(numberString); return padNumberString(Long.toString(number + addAmount), origLength); @@ -585,8 +609,12 @@ public class StringUtil { return makeStringWrapper(theString); } public static StringWrapper makeStringWrapper(String theString) { - if (theString == null) return null; - if (theString.length() == 0) return StringWrapper.EMPTY_STRING_WRAPPER; + if (theString == null) { + return null; + } + if (theString.length() == 0) { + return StringWrapper.EMPTY_STRING_WRAPPER; + } return new StringWrapper(theString); } @@ -597,13 +625,21 @@ public class StringUtil { public static StringBuilder appendTo(StringBuilder sb, Iterable> iterable, String prefix, String suffix, String sepPrefix, String sep, String sepSuffix) { Iterator> it = iterable.iterator(); while (it.hasNext()) { - if (prefix != null) sb.append(prefix); + if (prefix != null) { + sb.append(prefix); + } it.next().appendTo(sb); - if (suffix != null) sb.append(suffix); + if (suffix != null) { + sb.append(suffix); + } if (it.hasNext() && sep != null) { - if (sepPrefix != null) sb.append(sepPrefix); + if (sepPrefix != null) { + sb.append(sepPrefix); + } sb.append(sep); - if (sepSuffix != null) sb.append(sepSuffix); + if (sepSuffix != null) { + sb.append(sepSuffix); + } } } return sb; @@ -616,13 +652,21 @@ public class StringUtil { public static StringBuilder append(StringBuilder sb, Iterable iterable, String prefix, String suffix, String sepPrefix, String sep, String sepSuffix) { Iterator it = iterable.iterator(); while (it.hasNext()) { - if (prefix != null) sb.append(prefix); + if (prefix != null) { + sb.append(prefix); + } sb.append(it.next()); - if (suffix != null) sb.append(suffix); + if (suffix != null) { + sb.append(suffix); + } if (it.hasNext() && sep != null) { - if (sepPrefix != null) sb.append(sepPrefix); + if (sepPrefix != null) { + sb.append(sepPrefix); + } sb.append(sep); - if (sepSuffix != null) sb.append(sepSuffix); + if (sepSuffix != null) { + sb.append(sepSuffix); + } } } return sb; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/URLConnector.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/URLConnector.java index 1eb3250aa0..3f07d2c7b9 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/URLConnector.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/URLConnector.java @@ -69,10 +69,9 @@ public class URLConnector { if (connection != null) { return connection; - } else { - timedOut = true; - throw new IOException("Connection timed out"); } + timedOut = true; + throw new IOException("Connection timed out"); } // trusted certs only @@ -126,9 +125,7 @@ public class URLConnector { if (hv != null) { scon.setHostnameVerifier(hv); } - } catch (GeneralSecurityException e) { - Debug.logError(e, module); - } catch (GenericConfigException e) { + } catch (GeneralSecurityException | GenericConfigException e) { Debug.logError(e, module); } } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java index 15a0db7314..9dfaa878ce 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilCodec.java @@ -45,7 +45,7 @@ public class UtilCodec { private static final UrlCodec urlCodec = new UrlCodec(); private static final List codecs; static { - List tmpCodecs = new ArrayList(); + List tmpCodecs = new ArrayList<>(); tmpCodecs.add(new HTMLEntityCodec()); tmpCodecs.add(new PercentCodec()); codecs = Collections.unmodifiableList(tmpCodecs); @@ -63,8 +63,8 @@ public class UtilCodec { /** * @deprecated Use {@link #sanitize(String,String)} instead */ - public String sanitize(String outString); // Only really useful with HTML, else it simply calls encode() method - public String sanitize(String outString, String contentTypeId); // Only really useful with HTML, else it simply calls encode() method + public String sanitize(String outString); // Only really useful with HTML, else it simply calls encode() method + public String sanitize(String outString, String contentTypeId); // Only really useful with HTML, else it simply calls encode() method } public static interface SimpleDecoder { @@ -93,7 +93,7 @@ public class UtilCodec { PolicyFactory sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS).and(Sanitizers.IMAGES).and(Sanitizers.LINKS).and(Sanitizers.STYLES); // TODO to be improved to use a (or several) contentTypeId/s when necessary. Below is an example with BIRT_FLEXIBLE_REPORT_POLICY - if (UtilProperties.getPropertyAsBoolean("owasp", "sanitizer.permissive.policy", false)) { + if (UtilProperties.getPropertyAsBoolean("owasp", "sanitizer.permissive.policy", false)) { sanitizer = sanitizer.and(PERMISSIVE_POLICY); } if ("FLEXIBLE_REPORT".equals(contentTypeId)) { @@ -101,9 +101,9 @@ public class UtilCodec { } return sanitizer.sanitize(original); } - + // Given as an example based on rendering cmssite as it was before using the sanitizer. - // To use the PERMISSIVE_POLICY set sanitizer.permissive.policy to true. + // To use the PERMISSIVE_POLICY set sanitizer.permissive.policy to true. // Note that I was unable to render and . I guess because and are not sanitized in 1st place (else the sanitizer makes some damages I found) // You might even want to adapt the PERMISSIVE_POLICY to your needs... Be sure to check https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet before... // And https://github.com/OWASP/java-html-sanitizer/blob/master/docs/getting_started.md for examples. @@ -115,7 +115,7 @@ public class UtilCodec { .allowWithoutAttributes("html", "body", "div", "span", "table", "td") .allowAttributes("width").onElements("table") .toFactory(); - + // This is the PolicyFactory used for the Birt Report Builder usage feature. ("FLEXIBLE_REPORT" contentTypeId) // It allows to use the OOTB Birt Report Builder example. // You might need to enhance it for your needs (when using a new REPORT_MASTER) but normally you should not. See PERMISSIVE_POLICY above for documentation and examples @@ -219,9 +219,8 @@ public class UtilCodec { public static SimpleDecoder getDecoder(String type) { if ("url".equals(type)) { return urlCodec; - } else { - return null; } + return null; } public static String canonicalize(String value) throws IntrusionException { @@ -268,21 +267,18 @@ public class UtilCodec { if (foundCount >= 2 && mixedCount > 1) { if (restrictMultiple || restrictMixed) { throw new IntrusionException("Input validation failure"); - } else { - Debug.logWarning("Multiple (" + foundCount + "x) and mixed encoding (" + mixedCount + "x) detected in " + input, module); } + Debug.logWarning("Multiple (" + foundCount + "x) and mixed encoding (" + mixedCount + "x) detected in " + input, module); } else if (foundCount >= 2) { if (restrictMultiple) { throw new IntrusionException("Input validation failure"); - } else { - Debug.logWarning("Multiple (" + foundCount + "x) encoding detected in " + input, module); } + Debug.logWarning("Multiple (" + foundCount + "x) encoding detected in " + input, module); } else if (mixedCount > 1) { if (restrictMixed) { throw new IntrusionException("Input validation failure"); - } else { - Debug.logWarning("Mixed encoding (" + mixedCount + "x) detected in " + input, module); } + Debug.logWarning("Mixed encoding (" + mixedCount + "x) detected in " + input, module); } return working; } @@ -291,14 +287,16 @@ public class UtilCodec { * Uses a black-list approach for necessary characters for HTML. *

* Does not allow various characters (after canonicalization), including - * "<", ">", "&" (if not followed by a space), and "%" (if not + * "<", ">", "&" (if not followed by a space), and "%" (if not * followed by a space). * * @param value * @param errorMessageList */ public static String checkStringForHtmlStrictNone(String valueName, String value, List errorMessageList) { - if (UtilValidate.isEmpty(value)) return value; + if (UtilValidate.isEmpty(value)) { + return value; + } // canonicalize, strict (error on double-encoding) try { @@ -324,9 +322,11 @@ public class UtilCodec { */ public static class HtmlEncodingMapWrapper implements Map { public static HtmlEncodingMapWrapper getHtmlEncodingMapWrapper(Map mapToWrap, SimpleEncoder encoder) { - if (mapToWrap == null) return null; + if (mapToWrap == null) { + return null; + } - HtmlEncodingMapWrapper mapWrapper = new HtmlEncodingMapWrapper(); + HtmlEncodingMapWrapper mapWrapper = new HtmlEncodingMapWrapper<>(); mapWrapper.setup(mapToWrap, encoder); return mapWrapper; } @@ -353,9 +353,8 @@ public class UtilCodec { if (theObject instanceof String) { if (this.encoder != null) { return encoder.encode((String) theObject); - } else { - return UtilCodec.getEncoder("html").encode((String) theObject); } + return UtilCodec.getEncoder("html").encode((String) theObject); } else if (theObject instanceof Map) { return HtmlEncodingMapWrapper.getHtmlEncodingMapWrapper(UtilGenerics.checkMap(theObject), this.encoder); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilDateTime.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilDateTime.java index 8fd378a507..d841be6add 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilDateTime.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilDateTime.java @@ -114,7 +114,7 @@ public final class UtilDateTime { } public static String formatInterval(double interval, int count, Locale locale) { - List parts = new ArrayList(timevals.length); + List parts = new ArrayList<>(timevals.length); for (String[] timeval: timevals) { int value = Integer.parseInt(timeval[0]); double remainder = interval % value; @@ -128,8 +128,12 @@ public final class UtilDateTime { for (int i = parts.size() - 1; i >= 0 && count > 0; i--) { Double D = parts.get(i); double d = D.doubleValue(); - if (d < 1) continue; - if (sb.length() > 0) sb.append(", "); + if (d < 1) { + continue; + } + if (sb.length() > 0) { + sb.append(", "); + } count--; sb.append(count == 0 ? df.format(d) : Integer.toString(D.intValue())); sb.append(' '); @@ -312,9 +316,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Date(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -330,9 +333,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Date(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -348,9 +350,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Date(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -364,9 +365,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Time(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -382,9 +382,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Time(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -400,9 +399,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Time(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -416,9 +414,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Timestamp(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -433,9 +430,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Timestamp(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -455,9 +451,8 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Timestamp(newDate.getTime()); - } else { - return null; } + return null; } /** @@ -476,13 +471,14 @@ public final class UtilDateTime { if (newDate != null) { return new java.sql.Timestamp(newDate.getTime()); - } else { - return null; } + return null; } public static java.sql.Timestamp toTimestamp(Date date) { - if (date == null) return null; + if (date == null) { + return null; + } return new Timestamp(date.getTime()); } @@ -511,7 +507,9 @@ public final class UtilDateTime { * @return A Date made from the date and time Strings */ public static java.util.Date toDate(String date, String time) { - if (date == null || time == null) return null; + if (date == null || time == null) { + return null; + } String month; String day; String year; @@ -522,11 +520,15 @@ public final class UtilDateTime { int dateSlash1 = date.indexOf("/"); int dateSlash2 = date.lastIndexOf("/"); - if (dateSlash1 <= 0 || dateSlash1 == dateSlash2) return null; + if (dateSlash1 <= 0 || dateSlash1 == dateSlash2) { + return null; + } int timeColon1 = time.indexOf(":"); int timeColon2 = time.lastIndexOf(":"); - if (timeColon1 <= 0) return null; + if (timeColon1 <= 0) { + return null; + } month = date.substring(0, dateSlash1); day = date.substring(dateSlash1 + 1, dateSlash2); year = date.substring(dateSlash2 + 1); @@ -603,7 +605,9 @@ public final class UtilDateTime { * @return A date String in the given format */ public static String toDateString(java.util.Date date, String format) { - if (date == null) return ""; + if (date == null) { + return ""; + } SimpleDateFormat dateFormat = null; if (format != null) { dateFormat = new SimpleDateFormat(format); @@ -634,7 +638,9 @@ public final class UtilDateTime { * @return A time String in the format HH:MM:SS or HH:MM */ public static String toTimeString(java.util.Date date) { - if (date == null) return ""; + if (date == null) { + return ""; + } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); @@ -671,9 +677,8 @@ public final class UtilDateTime { } if (second == 0) { return hourStr + ":" + minuteStr; - } else { - return hourStr + ":" + minuteStr + ":" + secondStr; } + return hourStr + ":" + minuteStr + ":" + secondStr; } /** @@ -683,15 +688,16 @@ public final class UtilDateTime { * @return A combined data and time string in the format "MM/DD/YYYY HH:MM:SS" where the seconds are left off if they are 0. */ public static String toDateTimeString(java.util.Date date) { - if (date == null) return ""; + if (date == null) { + return ""; + } String dateString = toDateString(date); String timeString = toTimeString(date); if (!dateString.isEmpty() && !timeString.isEmpty()) { return dateString + " " + timeString; - } else { - return ""; } + return ""; } public static String toGmtTimestampString(Timestamp timestamp) { @@ -926,7 +932,7 @@ public final class UtilDateTime { Calendar tempCal = Calendar.getInstance(locale); tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek()); SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE", locale); - List resultList = new ArrayList(); + List resultList = new ArrayList<>(); for (int i = 0; i < 7; i++) { resultList.add(dateFormat.format(tempCal.getTime())); tempCal.roll(Calendar.DAY_OF_WEEK, 1); @@ -944,7 +950,7 @@ public final class UtilDateTime { Calendar tempCal = Calendar.getInstance(locale); tempCal.set(Calendar.MONTH, Calendar.JANUARY); SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM", locale); - List resultList = new ArrayList(); + List resultList = new ArrayList<>(); for (int i = Calendar.JANUARY; i <= tempCal.getActualMaximum(Calendar.MONTH); i++) { resultList.add(dateFormat.format(tempCal.getTime())); tempCal.roll(Calendar.MONTH, 1); @@ -1040,12 +1046,12 @@ public final class UtilDateTime { return dateFormat.format(stamp); } - // Private lazy-initializer class + // Private lazy-initializer class private static class TimeZoneHolder { private static final List availableTimeZoneList = getTimeZones(); private static List getTimeZones() { - ArrayList availableTimeZoneList = new ArrayList(); + ArrayList availableTimeZoneList = new ArrayList<>(); List idList = null; String tzString = UtilProperties.getPropertyValue("general", "timeZones.available"); if (UtilValidate.isNotEmpty(tzString)) { @@ -1077,9 +1083,8 @@ public final class UtilDateTime { public static TimeZone toTimeZone(String tzId) { if (UtilValidate.isEmpty(tzId)) { return TimeZone.getDefault(); - } else { - return TimeZone.getTimeZone(tzId); } + return TimeZone.getTimeZone(tzId); } /** Returns a TimeZone object based upon an hour offset from GMT. @@ -1166,7 +1171,7 @@ public final class UtilDateTime { * Returns a copy of date that cannot be modified. * Attempts to modify the returned date will result in an * UnsupportedOperationException. - * + * * @param date */ public static Date unmodifiableDate(Date date) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java index fb54b04c7b..52f966255e 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilFormatOut.java @@ -32,7 +32,7 @@ import java.util.TimeZone; public final class UtilFormatOut { public static final String module = UtilFormatOut.class.getName(); - + // ------------------- price format handlers ------------------- // FIXME: This is not thread-safe! DecimalFormat is not synchronized. private static final DecimalFormat priceDecimalFormat = new DecimalFormat(UtilProperties.getPropertyValue("general", "currency.decimal.format", "#,##0.00")); @@ -48,9 +48,8 @@ public final class UtilFormatOut { public static String safeToString(Object obj) { if (obj != null) { return obj.toString(); - } else { - return ""; } + return ""; } /** Formats a Double representing a price into a string @@ -58,7 +57,9 @@ public final class UtilFormatOut { * @return A String with the formatted price */ public static String formatPrice(Double price) { - if (price == null) return ""; + if (price == null) { + return ""; + } return formatPrice(price.doubleValue()); } @@ -67,7 +68,9 @@ public final class UtilFormatOut { * @return A String with the formatted price */ public static String formatPrice(BigDecimal price) { - if (price == null) return ""; + if (price == null) { + return ""; + } return priceDecimalFormat.format(price); } @@ -100,7 +103,9 @@ public final class UtilFormatOut { if (isoCode != null && isoCode.length() > 1) { nf.setCurrency(com.ibm.icu.util.Currency.getInstance(isoCode)); } else { - if (Debug.verboseOn()) Debug.logVerbose("No isoCode specified to format currency value:" + price, module); + if (Debug.verboseOn()) { + Debug.logVerbose("No isoCode specified to format currency value:" + price, module); + } } if (maximumFractionDigits >= 0) { nf.setMaximumFractionDigits(maximumFractionDigits); @@ -180,7 +185,9 @@ public final class UtilFormatOut { * @return A String with the formatted percentage */ public static String formatPercentage(Double percentage) { - if (percentage == null) return ""; + if (percentage == null) { + return ""; + } return formatPercentage(percentage.doubleValue()); } @@ -189,7 +196,9 @@ public final class UtilFormatOut { * @return A String with the formatted percentage */ public static String formatPercentage(BigDecimal percentage) { - if (percentage == null) return ""; + if (percentage == null) { + return ""; + } return percentageDecimalFormat.format(percentage); } @@ -206,10 +215,10 @@ public final class UtilFormatOut { * @return A String with the formatted quantity */ public static String formatQuantity(Long quantity) { - if (quantity == null) + if (quantity == null) { return ""; - else - return formatQuantity(quantity.doubleValue()); + } + return formatQuantity(quantity.doubleValue()); } /** Formats an int representing a quantity into a string @@ -225,10 +234,10 @@ public final class UtilFormatOut { * @return A String with the formatted quantity */ public static String formatQuantity(Integer quantity) { - if (quantity == null) + if (quantity == null) { return ""; - else - return formatQuantity(quantity.doubleValue()); + } + return formatQuantity(quantity.doubleValue()); } /** Formats an int representing a quantity into a string @@ -244,10 +253,10 @@ public final class UtilFormatOut { * @return A String with the formatted quantity */ public static String formatQuantity(Float quantity) { - if (quantity == null) + if (quantity == null) { return ""; - else - return formatQuantity(quantity.doubleValue()); + } + return formatQuantity(quantity.doubleValue()); } /** Formats a float representing a quantity into a string @@ -263,10 +272,10 @@ public final class UtilFormatOut { * @return A String with the formatted quantity */ public static String formatQuantity(Double quantity) { - if (quantity == null) + if (quantity == null) { return ""; - else - return formatQuantity(quantity.doubleValue()); + } + return formatQuantity(quantity.doubleValue()); } /** Formats an BigDecimal representing a quantity into a string @@ -274,10 +283,10 @@ public final class UtilFormatOut { * @return A String with the formatted quantity */ public static String formatQuantity(BigDecimal quantity) { - if (quantity == null) + if (quantity == null) { return ""; - else - return quantityDecimalFormat.format(quantity); + } + return quantityDecimalFormat.format(quantity); } /** Formats an double representing a quantity into a string @@ -297,7 +306,9 @@ public final class UtilFormatOut { } public static String formatPaddingRemove(String original) { - if (original == null) return null; + if (original == null) { + return null; + } StringBuilder orgBuf = new StringBuilder(original); while (orgBuf.length() > 0 && orgBuf.charAt(0) == '0') { orgBuf.deleteCharAt(0); @@ -313,8 +324,9 @@ public final class UtilFormatOut { * @return A String with the formatted date/time, or an empty String if timestamp is null */ public static String formatDate(java.sql.Timestamp timestamp) { - if (timestamp == null) + if (timestamp == null) { return ""; + } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL); java.util.Date date = timestamp; return df.format(date); @@ -372,10 +384,10 @@ public final class UtilFormatOut { * @return The passed String if not null, otherwise an empty non-null String */ public static String checkNull(String string1) { - if (string1 != null) + if (string1 != null) { return string1; - else - return ""; + } + return ""; } /** Returns the first passed String if not null, otherwise the second if not null, otherwise an empty but non-null String. @@ -384,12 +396,13 @@ public final class UtilFormatOut { * @return The first passed String if not null, otherwise the second if not null, otherwise an empty but non-null String */ public static String checkNull(String string1, String string2) { - if (string1 != null) + if (string1 != null) { return string1; - else if (string2 != null) + } else if (string2 != null) { return string2; - else + } else { return ""; + } } /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise an empty but non-null String. @@ -399,14 +412,15 @@ public final class UtilFormatOut { * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise an empty but non-null String */ public static String checkNull(String string1, String string2, String string3) { - if (string1 != null) + if (string1 != null) { return string1; - else if (string2 != null) + } else if (string2 != null) { return string2; - else if (string3 != null) + } else if (string3 != null) { return string3; - else + } else { return ""; + } } /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise the fourth if not null, otherwise an empty but non-null String. @@ -417,16 +431,17 @@ public final class UtilFormatOut { * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise the fourth if not null, otherwise an empty but non-null String */ public static String checkNull(String string1, String string2, String string3, String string4) { - if (string1 != null) + if (string1 != null) { return string1; - else if (string2 != null) + } else if (string2 != null) { return string2; - else if (string3 != null) + } else if (string3 != null) { return string3; - else if (string4 != null) + } else if (string4 != null) { return string4; - else + } else { return ""; + } } /** Returns pre + base + post if base String is not null or empty, otherwise an empty but non-null String. @@ -436,10 +451,10 @@ public final class UtilFormatOut { * @return pre + base + post if base String is not null or empty, otherwise an empty but non-null String. */ public static String ifNotEmpty(String base, String pre, String post) { - if (UtilValidate.isNotEmpty(base)) + if (UtilValidate.isNotEmpty(base)) { return pre + base + post; - else - return ""; + } + return ""; } /** Returns the first passed String if not empty, otherwise the second if not empty, otherwise an empty but non-null String. @@ -448,12 +463,13 @@ public final class UtilFormatOut { * @return The first passed String if not empty, otherwise the second if not empty, otherwise an empty but non-null String */ public static String checkEmpty(String string1, String string2) { - if (UtilValidate.isNotEmpty(string1)) + if (UtilValidate.isNotEmpty(string1)) { return string1; - else if (UtilValidate.isNotEmpty(string2)) + } else if (UtilValidate.isNotEmpty(string2)) { return string2; - else + } else { return ""; + } } /** Returns the first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, otherwise an empty but non-null String. @@ -463,18 +479,19 @@ public final class UtilFormatOut { * @return The first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, otherwise an empty but non-null String */ public static String checkEmpty(String string1, String string2, String string3) { - if (UtilValidate.isNotEmpty(string1)) + if (UtilValidate.isNotEmpty(string1)) { return string1; - else if (UtilValidate.isNotEmpty(string2)) + } else if (UtilValidate.isNotEmpty(string2)) { return string2; - else if (UtilValidate.isNotEmpty(string3)) + } else if (UtilValidate.isNotEmpty(string3)) { return string3; - else + } else { return ""; + } } // ------------------- web encode handlers ------------------- - /** + /** * Encodes an HTTP URL query String, replacing characters used for other * things in HTTP URL query strings, but not touching the separator * characters '?', '=', and '&' @@ -530,7 +547,7 @@ public final class UtilFormatOut { } // ------------------- web encode handlers ------------------- - /** + /** * Encodes an XML string replacing the characters '<', '>', '"', ''', '&' * @param inString The plain value String * @return The encoded String @@ -557,27 +574,30 @@ public final class UtilFormatOut { int diff = setLen - stringLen; if (diff < 0) { return str.substring(0, setLen); - } else { - StringBuilder newString = new StringBuilder(); - if (padEnd) { - newString.append(str); - } - for (int i = 0; i < diff; i++) { - newString.append(padChar); - } - if (!padEnd) { - newString.append(str); - } - return newString.toString(); } + StringBuilder newString = new StringBuilder(); + if (padEnd) { + newString.append(str); + } + for (int i = 0; i < diff; i++) { + newString.append(padChar); + } + if (!padEnd) { + newString.append(str); + } + return newString.toString(); } public static String makeSqlSafe(String unsafeString) { return unsafeString.replaceAll("'","''"); } public static String formatPrintableCreditCard(String original) { - if (original == null) return null; - if (original.length() <= 4) return original; + if (original == null) { + return null; + } + if (original.length() <= 4) { + return original; + } StringBuilder buffer = new StringBuilder(); for (int i=0; i < original.length()-4 ; i++) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilGenerics.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilGenerics.java index ab8ce670d6..9cd3c9294b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilGenerics.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilGenerics.java @@ -42,7 +42,9 @@ public final class UtilGenerics { public static > void checkCollectionContainment(Object object, Class clz, Class type) { if (object != null) { - if (!(clz.isInstance(object))) throw new ClassCastException("Not a " + clz.getName()); + if (!(clz.isInstance(object))) { + throw new ClassCastException("Not a " + clz.getName()); + } int i = 0; for (Object value: (Collection) object) { if (value != null && !type.isInstance(value)) { @@ -55,7 +57,7 @@ public final class UtilGenerics { @SuppressWarnings("unchecked") public static Collection checkCollection(Object object) { - return (Collection) checkCollectionCast(object, Collection.class); + return checkCollectionCast(object, Collection.class); } public static Collection checkCollection(Object object, Class type) { @@ -65,7 +67,7 @@ public final class UtilGenerics { @SuppressWarnings("unchecked") public static List checkList(Object object) { - return (List) checkCollectionCast(object, List.class); + return checkCollectionCast(object, List.class); } public static List checkList(Object object, Class type) { @@ -75,13 +77,17 @@ public final class UtilGenerics { @SuppressWarnings("unchecked") public static Map checkMap(Object object) { - if (object != null && !(object instanceof Map)) throw new ClassCastException("Not a map"); + if (object != null && !(object instanceof Map)) { + throw new ClassCastException("Not a map"); + } return (Map) object; } public static Map checkMap(Object object, Class keyType, Class valueType) { if (object != null) { - if (!(object instanceof Map)) throw new ClassCastException("Not a map"); + if (!(object instanceof Map)) { + throw new ClassCastException("Not a map"); + } Map map = (Map) object; int i = 0; for (Map.Entry entry: map.entrySet()) { @@ -99,7 +105,7 @@ public final class UtilGenerics { @SuppressWarnings("unchecked") public static Stack checkStack(Object object) { - return (Stack) checkCollectionCast(object, Stack.class); + return checkCollectionCast(object, Stack.class); } public static Stack checkStack(Object object, Class type) { @@ -109,7 +115,7 @@ public final class UtilGenerics { @SuppressWarnings("unchecked") public static Set checkSet(Object object) { - return (Set) checkCollectionCast(object, Set.class); + return checkCollectionCast(object, Set.class); } public static Set checkSet(Object object, Class type) { @@ -122,7 +128,9 @@ public final class UtilGenerics { */ @SuppressWarnings("unchecked") public static List toList(Object object) { - if (object != null && !(object instanceof List)) return null; + if (object != null && !(object instanceof List)) { + return null; + } return (List) object; } @@ -131,7 +139,9 @@ public final class UtilGenerics { */ @SuppressWarnings("unchecked") public static Map toMap(Object object) { - if (object != null && !(object instanceof Map)) return null; + if (object != null && !(object instanceof Map)) { + return null; + } return (Map) object; } @@ -142,13 +152,17 @@ public final class UtilGenerics { if (data.length % 2 == 1) { throw new IllegalArgumentException("You must pass an even sized array to the toMap method"); } - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); for (int i = 0; i < data.length;) { Object key = data[i]; - if (key != null && !(keyType.isInstance(key))) throw new IllegalArgumentException("Key(" + i + ") is not a " + keyType.getName() + ", was(" + key.getClass().getName() + ")"); + if (key != null && !(keyType.isInstance(key))) { + throw new IllegalArgumentException("Key(" + i + ") is not a " + keyType.getName() + ", was(" + key.getClass().getName() + ")"); + } i++; Object value = data[i]; - if (value != null && !(valueType.isInstance(value))) throw new IllegalArgumentException("Value(" + i + ") is not a " + keyType.getName() + ", was(" + key.getClass().getName() + ")"); + if (value != null && !(valueType.isInstance(value))) { + throw new IllegalArgumentException("Value(" + i + ") is not a " + keyType.getName() + ", was(" + key.getClass().getName() + ")"); + } i++; map.put(keyType.cast(key), valueType.cast(value)); } @@ -163,10 +177,12 @@ public final class UtilGenerics { if (data.length % 2 == 1) { throw new IllegalArgumentException("You must pass an even sized array to the toMap method"); } - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); for (int i = 0; i < data.length;) { Object key = data[i]; - if (key != null && !(keyType.isInstance(key))) throw new IllegalArgumentException("Key(" + i + ") is not a " + keyType.getName() + ", was(" + key.getClass().getName() + ")"); + if (key != null && !(keyType.isInstance(key))) { + throw new IllegalArgumentException("Key(" + i + ") is not a " + keyType.getName() + ", was(" + key.getClass().getName() + ")"); + } i++; Object value = data[i]; map.put(keyType.cast(key), value); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java index 293077acb1..28b80c59e5 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilHttp.java @@ -97,7 +97,7 @@ public final class UtilHttp { * @return The resulting Map */ public static Map getCombinedMap(HttpServletRequest request, Set namesToSkip) { - Map combinedMap = new HashMap(); + Map combinedMap = new HashMap<>(); combinedMap.putAll(getParameterMap(request)); // parameters override nothing combinedMap.putAll(getServletContextMap(request, namesToSkip)); // bottom level application attributes combinedMap.putAll(getSessionMap(request, namesToSkip)); // session overrides application @@ -125,7 +125,7 @@ public final class UtilHttp { */ public static Map getParameterMap(HttpServletRequest request, Set nameSet, Boolean onlyIncludeOrSkip) { boolean onlyIncludeOrSkipPrim = onlyIncludeOrSkip == null ? true : onlyIncludeOrSkip.booleanValue(); - Map paramMap = new HashMap(); + Map paramMap = new HashMap<>(); // add all the actual HTTP request parameters Enumeration e = UtilGenerics.cast(request.getParameterNames()); @@ -160,14 +160,13 @@ public final class UtilHttp { if (Debug.verboseOn()) { Debug.logVerbose("Made Request Parameter Map with [" + paramMap.size() + "] Entries", module); - //Debug.logVerbose("Request Parameter Map Entries: " + System.getProperty("line.separator") + UtilMisc.printMap(paramMap), module); see OFBIZ-9310 } return canonicalizeParameterMap(paramMap); } public static Map getQueryStringOnlyParameterMap(String queryString) { - Map paramMap = new HashMap(); + Map paramMap = new HashMap<>(); if (UtilValidate.isNotEmpty(queryString)) { StringTokenizer queryTokens = new StringTokenizer(queryString, "&"); while (queryTokens.hasMoreTokens()) { @@ -192,14 +191,16 @@ public final class UtilHttp { public static Map getPathInfoOnlyParameterMap(String pathInfoStr, Set nameSet, Boolean onlyIncludeOrSkip) { boolean onlyIncludeOrSkipPrim = onlyIncludeOrSkip == null ? true : onlyIncludeOrSkip.booleanValue(); - Map paramMap = new HashMap(); + Map paramMap = new HashMap<>(); // now add in all path info parameters /~name1=value1/~name2=value2/ // note that if a parameter with a given name already exists it will be put into a list with all values if (UtilValidate.isNotEmpty(pathInfoStr)) { // make sure string ends with a trailing '/' so we get all values - if (!pathInfoStr.endsWith("/")) pathInfoStr += "/"; + if (!pathInfoStr.endsWith("/")) { + pathInfoStr += "/"; + } int current = pathInfoStr.indexOf('/'); int last = current; @@ -221,7 +222,7 @@ public final class UtilHttp { paramList.add(value); } else { String paramString = (String) curValue; - paramList = new LinkedList(); + paramList = new LinkedList<>(); paramList.add(paramString); paramList.add(value); } @@ -248,7 +249,7 @@ public final class UtilHttp { if (paramEntry.getValue() instanceof String) { paramEntry.setValue(canonicalizeParameter((String) paramEntry.getValue())); } else if (paramEntry.getValue() instanceof Collection) { - List newList = new LinkedList(); + List newList = new LinkedList<>(); for (String listEntry: UtilGenerics.checkCollection(paramEntry.getValue())) { newList.add(canonicalizeParameter(listEntry)); } @@ -262,7 +263,9 @@ public final class UtilHttp { try { /** calling canonicalize with strict flag set to false so we only get warnings about double encoding, etc; can be set to true for exceptions and more security */ String cannedStr = UtilCodec.canonicalize(paramValue, false); - if (Debug.verboseOn()) Debug.logVerbose("Canonicalized parameter with " + (cannedStr.equals(paramValue) ? "no " : "") + "change: original [" + paramValue + "] canned [" + cannedStr + "]", module); + if (Debug.verboseOn()) { + Debug.logVerbose("Canonicalized parameter with " + (cannedStr.equals(paramValue) ? "no " : "") + "change: original [" + paramValue + "] canned [" + cannedStr + "]", module); + } return cannedStr; } catch (Exception e) { Debug.logError(e, "Error in canonicalize parameter value [" + paramValue + "]: " + e.toString(), module); @@ -275,7 +278,7 @@ public final class UtilHttp { * @return The resulting Map */ public static Map getJSONAttributeMap(HttpServletRequest request) { - Map returnMap = new HashMap(); + Map returnMap = new HashMap<>(); Map attrMap = getAttributeMap(request); for (Map.Entry entry : attrMap.entrySet()) { String key = entry.getKey(); @@ -284,7 +287,9 @@ public final class UtilHttp { val = val.toString(); } if (val instanceof String || val instanceof Number || val instanceof Map || val instanceof List || val instanceof Boolean) { - if (Debug.verboseOn()) Debug.logVerbose("Adding attribute to JSON output: " + key, module); + if (Debug.verboseOn()) { + Debug.logVerbose("Adding attribute to JSON output: " + key, module); + } returnMap.put(key, val); } } @@ -305,14 +310,15 @@ public final class UtilHttp { * @return The resulting Map */ public static Map getAttributeMap(HttpServletRequest request, Set namesToSkip) { - Map attributeMap = new HashMap(); + Map attributeMap = new HashMap<>(); // look at all request attributes Enumeration requestAttrNames = UtilGenerics.cast(request.getAttributeNames()); while (requestAttrNames.hasMoreElements()) { String attrName = requestAttrNames.nextElement(); - if (namesToSkip != null && namesToSkip.contains(attrName)) + if (namesToSkip != null && namesToSkip.contains(attrName)) { continue; + } Object attrValue = request.getAttribute(attrName); attributeMap.put(attrName, attrValue); @@ -339,15 +345,16 @@ public final class UtilHttp { * @return The resulting Map */ public static Map getSessionMap(HttpServletRequest request, Set namesToSkip) { - Map sessionMap = new HashMap(); + Map sessionMap = new HashMap<>(); HttpSession session = request.getSession(); // look at all the session attributes Enumeration sessionAttrNames = UtilGenerics.cast(session.getAttributeNames()); while (sessionAttrNames.hasMoreElements()) { String attrName = sessionAttrNames.nextElement(); - if (namesToSkip != null && namesToSkip.contains(attrName)) + if (namesToSkip != null && namesToSkip.contains(attrName)) { continue; + } Object attrValue = session.getAttribute(attrName); sessionMap.put(attrName, attrValue); @@ -374,15 +381,16 @@ public final class UtilHttp { * @return The resulting Map */ public static Map getServletContextMap(HttpServletRequest request, Set namesToSkip) { - Map servletCtxMap = new HashMap(); + Map servletCtxMap = new HashMap<>(); // look at all servlet context attributes ServletContext servletContext = (ServletContext) request.getAttribute("servletContext"); Enumeration applicationAttrNames = UtilGenerics.cast(servletContext.getAttributeNames()); while (applicationAttrNames.hasMoreElements()) { String attrName = applicationAttrNames.nextElement(); - if (namesToSkip != null && namesToSkip.contains(attrName)) + if (namesToSkip != null && namesToSkip.contains(attrName)) { continue; + } Object attrValue = servletContext.getAttribute(attrName); servletCtxMap.put(attrName, attrValue); @@ -405,7 +413,7 @@ public final class UtilHttp { } public static Map makeParamMapWithPrefix(Map context, Map additionalFields, String prefix, String suffix) { - Map paramMap = new HashMap(); + Map paramMap = new HashMap<>(); for (Map.Entry entry: context.entrySet()) { String parameterName = entry.getKey(); if (parameterName.startsWith(prefix)) { @@ -500,7 +508,7 @@ public final class UtilHttp { } public static List makeParamListWithSuffix(HttpServletRequest request, Map additionalFields, String suffix, String prefix) { - List paramList = new ArrayList(); + List paramList = new ArrayList<>(); Enumeration parameterNames = UtilGenerics.cast(request.getParameterNames()); while (parameterNames.hasMoreElements()) { String parameterName = parameterNames.nextElement(); @@ -584,8 +592,9 @@ public final class UtilHttp { StringBuilder requestUrl = new StringBuilder(); requestUrl.append(request.getScheme()); requestUrl.append("://" + request.getServerName()); - if (request.getServerPort() != 80 && request.getServerPort() != 443) + if (request.getServerPort() != 80 && request.getServerPort() != 443) { requestUrl.append(":" + request.getServerPort()); + } return requestUrl; } @@ -637,7 +646,9 @@ public final class UtilHttp { * @return Locale The current Locale to use */ public static Locale getLocale(HttpServletRequest request) { - if (request == null) return Locale.getDefault(); + if (request == null) { + return Locale.getDefault(); + } return getLocale(request, request.getSession(), null); } @@ -648,7 +659,9 @@ public final class UtilHttp { * @return Locale The current Locale to use */ public static Locale getLocale(HttpSession session) { - if (session == null) return Locale.getDefault(); + if (session == null) { + return Locale.getDefault(); + } return getLocale(null, session, null); } @@ -700,7 +713,7 @@ public final class UtilHttp { public static TimeZone getTimeZone(HttpServletRequest request, HttpSession session, String appDefaultTimeZoneString) { // check session first, should override all if anything set there TimeZone timeZone = session != null ? (TimeZone) session.getAttribute(SESSION_KEY_TIMEZONE) : null; - + // next see if the userLogin has a value if (timeZone == null) { Map userLogin = UtilGenerics.checkMap(session.getAttribute("userLogin"), String.class, Object.class); @@ -861,7 +874,9 @@ public final class UtilHttp { } public static String getRequestUriFromTarget(String target) { - if (UtilValidate.isEmpty(target)) return null; + if (UtilValidate.isEmpty(target)) { + return null; + } int endOfRequestUri = target.length(); if (target.indexOf('?') > 0) { endOfRequestUri = target.indexOf('?'); @@ -882,7 +897,9 @@ public final class UtilHttp { * @return The query string */ public static String getQueryStringFromTarget(String target) { - if (UtilValidate.isEmpty(target)) return ""; + if (UtilValidate.isEmpty(target)) { + return ""; + } int queryStart = target.indexOf('?'); if (queryStart != -1) { return target.substring(queryStart); @@ -896,7 +913,9 @@ public final class UtilHttp { * @return The request target string */ public static String removeQueryStringFromTarget(String target) { - if (UtilValidate.isEmpty(target)) return null; + if (UtilValidate.isEmpty(target)) { + return null; + } int queryStart = target.indexOf('?'); if (queryStart < 0) { return target; @@ -906,8 +925,12 @@ public final class UtilHttp { public static String getWebappMountPointFromTarget(String target) { int firstChar = 0; - if (UtilValidate.isEmpty(target)) return null; - if (target.charAt(0) == '/') firstChar = 1; + if (UtilValidate.isEmpty(target)) { + return null; + } + if (target.charAt(0) == '/') { + firstChar = 1; + } int pathSep = target.indexOf('/', 1); String webappMountPoint = null; if (pathSep > 0) { @@ -1102,7 +1125,7 @@ public final class UtilHttp { } public static String stripViewParamsFromQueryString(String queryString, String paginatorNumber) { - Set paramNames = new HashSet(); + Set paramNames = new HashSet<>(); if (UtilValidate.isNotEmpty(paginatorNumber)) { paginatorNumber = "_" + paginatorNumber; } @@ -1148,21 +1171,28 @@ public final class UtilHttp { * index of the row. */ public static Collection> parseMultiFormData(Map parameters) { - Map> rows = new HashMap>(); // stores the rows keyed by row number + Map> rows = new HashMap<>(); // stores the rows keyed by row number // first loop through all the keys and create a hashmap for each ${ROW_SUBMIT_PREFIX}${N} = Y for (Map.Entry entry : parameters.entrySet()) { String key = entry.getKey(); // skip everything that is not ${ROW_SUBMIT_PREFIX}N - if (key == null || key.length() <= ROW_SUBMIT_PREFIX_LENGTH) continue; - if (key.indexOf(MULTI_ROW_DELIMITER) <= 0) continue; - if (!key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) continue; - if (!"Y".equals(entry.getValue())) + if (key == null || key.length() <= ROW_SUBMIT_PREFIX_LENGTH) { continue; + } + if (key.indexOf(MULTI_ROW_DELIMITER) <= 0) { + continue; + } + if (!key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) { + continue; + } + if (!"Y".equals(entry.getValue())) { + continue; + } // decode the value of N and create a new map for it Integer n = Integer.decode(key.substring(ROW_SUBMIT_PREFIX_LENGTH, key.length())); - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("row", n); // special "row" = N tuple rows.put(n, m); // key it to N } @@ -1171,15 +1201,23 @@ public final class UtilHttp { for (Map.Entry entry : parameters.entrySet()) { String key = entry.getKey(); // skip keys without DELIMITER and skip ROW_SUBMIT_PREFIX - if (key == null) continue; + if (key == null) { + continue; + } int index = key.indexOf(MULTI_ROW_DELIMITER); - if (index <= 0) continue; - if (key.length() > ROW_SUBMIT_PREFIX_LENGTH && key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) continue; + if (index <= 0) { + continue; + } + if (key.length() > ROW_SUBMIT_PREFIX_LENGTH && key.substring(0, ROW_SUBMIT_PREFIX_LENGTH).equals(ROW_SUBMIT_PREFIX)) { + continue; + } // get the map with index N Integer n = Integer.decode(key.substring(index + MULTI_ROW_DELIMITER_LENGTH, key.length())); // N from ${param}${DELIMITER}${N} Map map = rows.get(n); - if (map == null) continue; + if (map == null) { + continue; + } // get the key without the N suffix and store it and its value String newKey = key.substring(0, index); @@ -1194,7 +1232,7 @@ public final class UtilHttp { * multi form parameters (usually named according to the ${param}_o_N notation). */ public static Map removeMultiFormParameters(Map parameters) { - Map filteredParameters = new HashMap(); + Map filteredParameters = new HashMap<>(); for (Map.Entry entry : parameters.entrySet()) { String key = entry.getKey(); if (key != null && (key.indexOf(MULTI_ROW_DELIMITER) != -1 || key.indexOf("_useRowSubmit") != -1 || key.indexOf("_rowCount") != -1)) { @@ -1245,13 +1283,17 @@ public final class UtilHttp { */ public static Object makeParamValueFromComposite(HttpServletRequest request, String prefix, Locale locale) { String compositeType = request.getParameter(makeCompositeParam(prefix, "compositeType")); - if (UtilValidate.isEmpty(compositeType)) return null; + if (UtilValidate.isEmpty(compositeType)) { + return null; + } // collect the composite fields into a map - Map data = new HashMap(); + Map data = new HashMap<>(); for (Enumeration names = UtilGenerics.cast(request.getParameterNames()); names.hasMoreElements();) { String name = names.nextElement(); - if (!name.startsWith(prefix + COMPOSITE_DELIMITER)) continue; + if (!name.startsWith(prefix + COMPOSITE_DELIMITER)) { + continue; + } // extract the suffix of the composite name String suffix = name.substring(name.indexOf(COMPOSITE_DELIMITER) + COMPOSITE_DELIMITER_LENGTH); @@ -1270,9 +1312,15 @@ public final class UtilHttp { String hour = data.get("hour"); String minutes = data.get("minutes"); String ampm = data.get("ampm"); - if (date == null || date.length() < 10) return null; - if (UtilValidate.isEmpty(hour)) return null; - if (UtilValidate.isEmpty(minutes)) return null; + if (date == null || date.length() < 10) { + return null; + } + if (UtilValidate.isEmpty(hour)) { + return null; + } + if (UtilValidate.isEmpty(minutes)) { + return null; + } boolean isTwelveHour = UtilValidate.isNotEmpty(ampm); // create the timestamp from the data @@ -1283,8 +1331,12 @@ public final class UtilHttp { cal.setTime(timestamp); if (isTwelveHour) { boolean isAM = ("AM".equals(ampm) ? true : false); - if (isAM && h == 12) h = 0; - if (!isAM && h < 12) h += 12; + if (isAM && h == 12) { + h = 0; + } + if (!isAM && h < 12) { + h += 12; + } } cal.set(Calendar.HOUR_OF_DAY, h); cal.set(Calendar.MINUTE, Integer.parseInt(minutes)); @@ -1317,27 +1369,25 @@ public final class UtilHttp { if (UtilValidate.isNotEmpty(spiderRequest)) { if ("Y".equals(spiderRequest)) { return true; - } else { - return false; } - } else { - String initialUserAgent = request.getHeader("User-Agent") != null ? request.getHeader("User-Agent") : ""; - List spiderList = StringUtil.split(UtilProperties.getPropertyValue("url", "link.remove_lsessionid.user_agent_list"), ","); + return false; + } + String initialUserAgent = request.getHeader("User-Agent") != null ? request.getHeader("User-Agent") : ""; + List spiderList = StringUtil.split(UtilProperties.getPropertyValue("url", "link.remove_lsessionid.user_agent_list"), ","); - if (UtilValidate.isNotEmpty(spiderList)) { - for (String spiderNameElement : spiderList) { - Pattern pattern = null; - try { - pattern = PatternFactory.createOrGetPerl5CompiledPattern(spiderNameElement, false); - } catch (MalformedPatternException e) { - Debug.logError(e, module); - } - PatternMatcher matcher = new Perl5Matcher(); - if (matcher.contains(initialUserAgent, pattern)) { - request.setAttribute("_REQUEST_FROM_SPIDER_", "Y"); - result = true; - break; - } + if (UtilValidate.isNotEmpty(spiderList)) { + for (String spiderNameElement : spiderList) { + Pattern pattern = null; + try { + pattern = PatternFactory.createOrGetPerl5CompiledPattern(spiderNameElement, false); + } catch (MalformedPatternException e) { + Debug.logError(e, module); + } + PatternMatcher matcher = new Perl5Matcher(); + if (matcher.contains(initialUserAgent, pattern)) { + request.setAttribute("_REQUEST_FROM_SPIDER_", "Y"); + result = true; + break; } } } @@ -1403,7 +1453,7 @@ public final class UtilHttp { HttpSession session = request.getSession(); Map> paramMapStore = UtilGenerics.checkMap(session.getAttribute("_PARAM_MAP_STORE_")); if (paramMapStore == null) { - paramMapStore = new HashMap>(); + paramMapStore = new HashMap<>(); session.setAttribute("_PARAM_MAP_STORE_", paramMapStore); } Map parameters = getParameterMap(request); diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilIO.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilIO.java index 5a386f517b..aa4e3dd281 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilIO.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilIO.java @@ -53,10 +53,14 @@ public final class UtilIO { try { IOUtils.copy(in, out); } finally { - if (closeIn) IOUtils.closeQuietly(in); + if (closeIn) { + IOUtils.closeQuietly(in); + } } } finally { - if (closeOut) IOUtils.closeQuietly(out); + if (closeOut) { + IOUtils.closeQuietly(out); + } } } @@ -74,10 +78,14 @@ public final class UtilIO { try { IOUtils.copy(reader, writer); } finally { - if (closeIn) IOUtils.closeQuietly(reader); + if (closeIn) { + IOUtils.closeQuietly(reader); + } } } finally { - if (closeOut) IOUtils.closeQuietly(writer); + if (closeOut) { + IOUtils.closeQuietly(writer); + } } } @@ -97,7 +105,9 @@ public final class UtilIO { out.append(buffer); } } finally { - if (closeIn) IOUtils.closeQuietly(reader); + if (closeIn) { + IOUtils.closeQuietly(reader); + } } } @@ -108,7 +118,7 @@ public final class UtilIO { * @return the converted string, with platform line endings converted * to \n */ - public static final String readString(byte[] bytes) throws IOException { + public static final String readString(byte[] bytes) { return readString(bytes, 0, bytes.length, UTF8); } @@ -122,7 +132,7 @@ public final class UtilIO { * @return the converted string, with platform line endings converted * to \n */ - public static final String readString(byte[] bytes, int offset, int length) throws IOException { + public static final String readString(byte[] bytes, int offset, int length) { return readString(bytes, offset, length, UTF8); } @@ -135,7 +145,7 @@ public final class UtilIO { * @return the converted string, with platform line endings converted * to \n */ - public static final String readString(byte[] bytes, String charset) throws IOException { + public static final String readString(byte[] bytes, String charset) { return readString(bytes, 0, bytes.length, Charset.forName(charset)); } @@ -151,7 +161,7 @@ public final class UtilIO { * @return the converted string, with platform line endings converted * to \n */ - public static final String readString(byte[] bytes, int offset, int length, String charset) throws IOException { + public static final String readString(byte[] bytes, int offset, int length, String charset) { return readString(bytes, 0, bytes.length, Charset.forName(charset)); } @@ -163,7 +173,7 @@ public final class UtilIO { * @return the converted string, with platform line endings converted * to \n */ - public static final String readString(byte[] bytes, Charset charset) throws IOException { + public static final String readString(byte[] bytes, Charset charset) { return readString(bytes, 0, bytes.length, charset); } @@ -179,7 +189,7 @@ public final class UtilIO { * @return the converted string, with platform line endings converted * to \n */ - public static final String readString(byte[] bytes, int offset, int length, Charset charset) throws IOException { + public static final String readString(byte[] bytes, int offset, int length, Charset charset) { ByteBuffer buf = ByteBuffer.allocate(length); buf.put(bytes, offset, length); buf.flip(); @@ -299,7 +309,7 @@ public final class UtilIO { * @param out where to write the converted bytes to * @param charset the charset to use to convert the raw bytes * @param value the value to write - * @throws IOException + * @throws IOException */ public static void writeString(OutputStream out, Charset charset, String value) throws IOException { try (Writer writer = new OutputStreamWriter(out, charset)) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilJavaParse.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilJavaParse.java index f5f56283e6..2fb378fa0f 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilJavaParse.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilJavaParse.java @@ -37,8 +37,8 @@ public final class UtilJavaParse { public static final String module = UtilJavaParse.class.getName(); // FIXME: Not thread safe - private static Set serviceMethodNames = new HashSet(); - private static Set entityMethodNames = new HashSet(); + private static Set serviceMethodNames = new HashSet<>(); + private static Set entityMethodNames = new HashSet<>(); static { serviceMethodNames.add("runSync"); serviceMethodNames.add("runSyncIgnore"); @@ -48,7 +48,7 @@ public final class UtilJavaParse { serviceMethodNames.add("schedule"); // NOTE: the service name may be the 1st, 2nd or 3rd param for variations on this serviceMethodNames.add("addRollbackService"); serviceMethodNames.add("addCommitService"); - + entityMethodNames.add("getModelEntity"); entityMethodNames.add("getEntityGroupName"); entityMethodNames.add("getModelEntityMapByGroup"); @@ -101,7 +101,9 @@ public final class UtilJavaParse { Collection allComponentConfigs = ComponentConfig.getAllComponents(); for (ComponentConfig cc: allComponentConfigs) { String rootDirectory = cc.getRootLocation(); - if (!rootDirectory.endsWith(File.separatorChar + "")) rootDirectory += File.separatorChar; + if (!rootDirectory.endsWith(File.separatorChar + "")) { + rootDirectory += File.separatorChar; + } rootDirectory += "src" + File.separatorChar; File rootDirFile = new File(rootDirectory); @@ -120,7 +122,9 @@ public final class UtilJavaParse { String fullPathAndFile = classDir + File.separatorChar + classFileName; File classFile = new File(fullPathAndFile); if (classFile.exists()) { - if (Debug.verboseOn()) Debug.logVerbose("In findRealPathAndFileForClass for [" + fullyQualifiedClassName + "]: [" + fullPathAndFile + "]", module); + if (Debug.verboseOn()) { + Debug.logVerbose("In findRealPathAndFileForClass for [" + fullyQualifiedClassName + "]: [" + fullPathAndFile + "]", module); + } return fullPathAndFile; } } @@ -129,28 +133,41 @@ public final class UtilJavaParse { } public static int findServiceMethodBlockStart(String methodName, String javaFile) { - if (Debug.verboseOn()) Debug.logVerbose("In findServiceMethodBlockStart for " + methodName, module); + if (Debug.verboseOn()) { + Debug.logVerbose("In findServiceMethodBlockStart for " + methodName, module); + } // starts with something like this: public static Map exportServiceEoModelBundle(DispatchContext dctx, Map context) { // start with the main pattern int methodNameIndex = javaFile.indexOf("public static Map " + methodName + "(DispatchContext dctx, Map context) {"); // try a little less... and some nice messy variations... - if (methodNameIndex < 0) methodNameIndex = javaFile.indexOf(" Map " + methodName + "(DispatchContext "); - if (methodNameIndex < 0) methodNameIndex = javaFile.indexOf(" Map " + methodName + "(DispatchContext "); - if (methodNameIndex < 0) methodNameIndex = javaFile.indexOf(" Map " + methodName + " (DispatchContext "); - if (methodNameIndex < 0) methodNameIndex = javaFile.indexOf(" Map " + methodName + "(DispatchContext "); - if (methodNameIndex < 0) methodNameIndex = javaFile.indexOf(" Map " + methodName + " (DispatchContext "); + if (methodNameIndex < 0) { + methodNameIndex = javaFile.indexOf(" Map " + methodName + "(DispatchContext "); + } + if (methodNameIndex < 0) { + methodNameIndex = javaFile.indexOf(" Map " + methodName + "(DispatchContext "); + } + if (methodNameIndex < 0) { + methodNameIndex = javaFile.indexOf(" Map " + methodName + " (DispatchContext "); + } + if (methodNameIndex < 0) { + methodNameIndex = javaFile.indexOf(" Map " + methodName + "(DispatchContext "); + } + if (methodNameIndex < 0) { + methodNameIndex = javaFile.indexOf(" Map " + methodName + " (DispatchContext "); + } // not found! - if (methodNameIndex < 0) return -1; + if (methodNameIndex < 0) { + return -1; + } // find the open brace and return its position return javaFile.indexOf("{", methodNameIndex); } public static int findEndOfBlock(int blockStart, String javaFile) { - //Debug.logInfo("In findEndOfBlock for blockStart " + blockStart, module); int nextOpen = javaFile.indexOf("{", blockStart+1); int nextClose = javaFile.indexOf("}", blockStart+1); @@ -158,11 +175,15 @@ public final class UtilJavaParse { javaFile = javaFile.substring(nextOpen, nextClose); } // if no close, end with couldn't find - if (nextClose < 0) return -1; + if (nextClose < 0) { + return -1; + } // while nextOpen is found and is before the next close, then recurse (list while (nextOpen > -1 && nextOpen < nextClose) { int endOfSubBlock = findEndOfBlock(nextOpen, javaFile); - if (endOfSubBlock < 0) return -1; + if (endOfSubBlock < 0) { + return -1; + } nextOpen = javaFile.indexOf("{", endOfSubBlock+1); nextClose = javaFile.indexOf("}", endOfSubBlock+1); } @@ -172,7 +193,7 @@ public final class UtilJavaParse { } public static Set findServiceCallsInBlock(int blockStart, int blockEnd, String javaFile) { - Set serviceNameSet = new HashSet(); + Set serviceNameSet = new HashSet<>(); int dispatcherIndex = javaFile.indexOf("dispatcher.", blockStart+1); while (dispatcherIndex > 0 && dispatcherIndex < blockEnd) { @@ -197,7 +218,7 @@ public final class UtilJavaParse { } public static Set findEntityUseInBlock(int blockStart, int blockEnd, String javaFile) { - Set entityNameSet = new HashSet(); + Set entityNameSet = new HashSet<>(); int delegatorIndex = javaFile.indexOf("delegator.", blockStart+1); while (delegatorIndex > 0 && delegatorIndex < blockEnd) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java index 4650e39595..6939450a5a 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilMisc.java @@ -72,12 +72,10 @@ public final class UtilMisc { if (obj1 == null) { if (obj2 == null) { return 0; - } else { - return 1; } - } else { - return obj1.compareTo(obj2); + return 1; } + return obj1.compareTo(obj2); } public static int compare(List obj1, List obj2) { @@ -103,10 +101,10 @@ public final class UtilMisc { * @return The resulting Iterator */ public static Iterator toIterator(Collection col) { - if (col == null) + if (col == null) { return null; - else - return col.iterator(); + } + return col.iterator(); } /** @@ -123,7 +121,7 @@ public final class UtilMisc { Debug.logInfo(e, module); throw e; } - Map map = new HashMap(); + Map map = new HashMap<>(); for (int i = 0; i < data.length;) { map.put((String) data[i++], (V) data[i++]); } @@ -142,23 +140,27 @@ public final class UtilMisc { } public static List makeListWritable(Collection col) { - List result = new LinkedList(); - if (col != null) result.addAll(col); + List result = new LinkedList<>(); + if (col != null) { + result.addAll(col); + } return result; } public static Map makeMapWritable(Map map) { if (map == null) { - return new HashMap(); + return new HashMap<>(); } - Map result = new HashMap(map.size()); + Map result = new HashMap<>(map.size()); result.putAll(map); return result; } public static Set makeSetWritable(Collection col) { - Set result = new LinkedHashSet(); - if (col != null) result.addAll(col); + Set result = new LinkedHashSet<>(); + if (col != null) { + result.addAll(col); + } return result; } @@ -170,12 +172,11 @@ public final class UtilMisc { */ public static void makeMapSerializable(Map map) { // now filter out all non-serializable values - Set keysToRemove = new LinkedHashSet(); + Set keysToRemove = new LinkedHashSet<>(); for (Map.Entry mapEntry: map.entrySet()) { Object entryValue = mapEntry.getValue(); if (entryValue != null && !(entryValue instanceof Serializable)) { keysToRemove.add(mapEntry.getKey()); - //Debug.logInfo("Found Map value that is not Serializable: " + mapEntry.getKey() + "=" + mapEntry.getValue(), module); } } for (String keyToRemove: keysToRemove) { map.remove(keyToRemove); } @@ -188,9 +189,10 @@ public final class UtilMisc { * @return a new List of sorted Maps. */ public static List> sortMaps(List> listOfMaps, List sortKeys) { - if (listOfMaps == null || sortKeys == null) + if (listOfMaps == null || sortKeys == null) { return null; - List> toSort = new ArrayList>(listOfMaps.size()); + } + List> toSort = new ArrayList<>(listOfMaps.size()); toSort.addAll(listOfMaps); try { MapComparator mc = new MapComparator(sortKeys); @@ -208,7 +210,7 @@ public final class UtilMisc { public static Map getMapFromMap(Map outerMap, K key) { Map innerMap = UtilGenerics.checkMap(outerMap.get(key)); if (innerMap == null) { - innerMap = new HashMap(); + innerMap = new HashMap<>(); outerMap.put(key, innerMap); } return innerMap; @@ -220,7 +222,7 @@ public final class UtilMisc { public static List getListFromMap(Map outerMap, K key) { List innerList = UtilGenerics.checkList(outerMap.get(key)); if (innerList == null) { - innerList = new LinkedList(); + innerList = new LinkedList<>(); outerMap.put(key, innerList); } return innerList; @@ -257,21 +259,23 @@ public final class UtilMisc { } public static Set collectionToSet(Collection c) { - if (c == null) return null; + if (c == null) { + return null; + } Set theSet = null; if (c instanceof Set) { theSet = (Set) c; } else { - theSet = new LinkedHashSet(); + theSet = new LinkedHashSet<>(); c.remove(null); theSet.addAll(c); } return theSet; } - + /** * Generates a String from given values delimited by delimiter. - * + * * @param values * @param delimiter * @return String @@ -301,7 +305,7 @@ public final class UtilMisc { if (data == null) { return null; } - Set theSet = new LinkedHashSet(); + Set theSet = new LinkedHashSet<>(); for (T elem : data) { theSet.add(elem); } @@ -309,27 +313,28 @@ public final class UtilMisc { } public static Set toSet(Collection collection) { - if (collection == null) return null; + if (collection == null) { + return null; + } if (collection instanceof Set) { return (Set) collection; - } else { - Set theSet = new LinkedHashSet(); - theSet.addAll(collection); - return theSet; } + Set theSet = new LinkedHashSet<>(); + theSet.addAll(collection); + return theSet; } public static Set toSetArray(T[] data) { if (data == null) { return null; } - Set set = new LinkedHashSet(); + Set set = new LinkedHashSet<>(); for (T value: data) { set.add(value); } return set; } - + /** * Creates a list from passed objects. * @param data @@ -340,8 +345,8 @@ public final class UtilMisc { if(data == null){ return null; } - - List list = new LinkedList(); + + List list = new LinkedList<>(); for(T t : data){ list.add(t); @@ -351,21 +356,22 @@ public final class UtilMisc { } public static List toList(Collection collection) { - if (collection == null) return null; + if (collection == null) { + return null; + } if (collection instanceof List) { return (List) collection; - } else { - List list = new LinkedList(); - list.addAll(collection); - return list; } + List list = new LinkedList<>(); + list.addAll(collection); + return list; } public static List toListArray(T[] data) { if (data == null) { return null; } - List list = new LinkedList(); + List list = new LinkedList<>(); for (T value: data) { list.add(value); } @@ -375,7 +381,7 @@ public final class UtilMisc { public static void addToListInMap(V element, Map theMap, K listKey) { List theList = UtilGenerics.checkList(theMap.get(listKey)); if (theList == null) { - theList = new LinkedList(); + theList = new LinkedList<>(); theMap.put(listKey, theList); } theList.add(element); @@ -384,7 +390,7 @@ public final class UtilMisc { public static void addToSetInMap(V element, Map> theMap, K setKey) { Set theSet = UtilGenerics.checkSet(theMap.get(setKey)); if (theSet == null) { - theSet = new LinkedHashSet(); + theSet = new LinkedHashSet<>(); theMap.put(setKey, theSet); } theSet.add(element); @@ -393,7 +399,7 @@ public final class UtilMisc { public static void addToSortedSetInMap(V element, Map> theMap, K setKey) { Set theSet = UtilGenerics.checkSet(theMap.get(setKey)); if (theSet == null) { - theSet = new TreeSet(); + theSet = new TreeSet<>(); theMap.put(setKey, theSet); } theSet.add(element); @@ -562,7 +568,7 @@ public final class UtilMisc { private static final List availableLocaleList = getAvailableLocaleList(); private static List getAvailableLocaleList() { - TreeMap localeMap = new TreeMap(); + TreeMap localeMap = new TreeMap<>(); String localesString = UtilProperties.getPropertyValue("general", "locales.available"); if (UtilValidate.isNotEmpty(localesString)) { List idList = StringUtil.split(localesString, ","); @@ -579,7 +585,7 @@ public final class UtilMisc { } } } - return Collections.unmodifiableList(new ArrayList(localeMap.values())); + return Collections.unmodifiableList(new ArrayList<>(localeMap.values())); } } @@ -597,18 +603,16 @@ public final class UtilMisc { public static void copyFile(File sourceLocation , File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { throw new IOException("File is a directory, not a file, cannot copy") ; - } else { - - try ( - InputStream in = new FileInputStream(sourceLocation); - OutputStream out = new FileOutputStream(targetLocation); - ) { - // Copy the bits from instream to outstream - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } + } + try ( + InputStream in = new FileInputStream(sourceLocation); + OutputStream out = new FileOutputStream(targetLocation); + ) { + // Copy the bits from instream to outstream + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); } } } @@ -646,5 +650,5 @@ public final class UtilMisc { } return result; } - + } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilNumber.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilNumber.java index b8d1551b4d..c3eefecaaf 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilNumber.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilNumber.java @@ -168,7 +168,7 @@ public final class UtilNumber { // hash map to store ICU4J rule sets keyed to Locale private static HashMap rbnfRuleSets; static { - rbnfRuleSets = new HashMap(); + rbnfRuleSets = new HashMap<>(); rbnfRuleSets.put(Locale.US, ruleSet_en_US); rbnfRuleSets.put(new Locale("th"), ruleSet_th_TH); rbnfRuleSets.put(new Locale("en", "IN"), ruleSet_en_IN); @@ -183,8 +183,12 @@ public final class UtilNumber { * @return int - Scale factor to pass to BigDecimal's methods. Defaults to DEFAULT_BD_SCALE (2) */ public static int getBigDecimalScale(String file, String property) { - if (UtilValidate.isEmpty(file)) return DEFAULT_BD_SCALE; - if (UtilValidate.isEmpty(property)) return DEFAULT_BD_SCALE; + if (UtilValidate.isEmpty(file)) { + return DEFAULT_BD_SCALE; + } + if (UtilValidate.isEmpty(property)) { + return DEFAULT_BD_SCALE; + } int scale = -1; String value = UtilProperties.getPropertyValue(file, property); @@ -213,8 +217,12 @@ public final class UtilNumber { * @return int - Rounding mode to pass to BigDecimal's methods. Defaults to DEFAULT_BD_ROUNDING_MODE (BigDecimal.ROUND_HALF_UP) */ public static int getBigDecimalRoundingMode(String file, String property) { - if (UtilValidate.isEmpty(file)) return DEFAULT_BD_SCALE; - if (UtilValidate.isEmpty(property)) return DEFAULT_BD_ROUNDING_MODE; + if (UtilValidate.isEmpty(file)) { + return DEFAULT_BD_SCALE; + } + if (UtilValidate.isEmpty(property)) { + return DEFAULT_BD_ROUNDING_MODE; + } String value = UtilProperties.getPropertyValue(file, property); int mode = roundingModeFromString(value); @@ -238,16 +246,27 @@ public final class UtilNumber { * @return int - The int value of the mode (e.g, BigDecimal.ROUND_HALF_UP) or -1 if the input was bad. */ public static int roundingModeFromString(String value) { - if (value == null) return -1; + if (value == null) { + return -1; + } value = value.trim(); - if ("ROUND_HALF_UP".equals(value)) return BigDecimal.ROUND_HALF_UP; - else if ("ROUND_HALF_DOWN".equals(value)) return BigDecimal.ROUND_HALF_DOWN; - else if ("ROUND_HALF_EVEN".equals(value)) return BigDecimal.ROUND_HALF_EVEN; - else if ("ROUND_UP".equals(value)) return BigDecimal.ROUND_UP; - else if ("ROUND_DOWN".equals(value)) return BigDecimal.ROUND_DOWN; - else if ("ROUND_CEILING".equals(value)) return BigDecimal.ROUND_CEILING; - else if ("ROUND_FLOOR".equals(value)) return BigDecimal.ROUND_FLOOR; - else if ("ROUND_UNNECCESSARY".equals(value)) return BigDecimal.ROUND_UNNECESSARY; + if ("ROUND_HALF_UP".equals(value)) { + return BigDecimal.ROUND_HALF_UP; + } else if ("ROUND_HALF_DOWN".equals(value)) { + return BigDecimal.ROUND_HALF_DOWN; + } else if ("ROUND_HALF_EVEN".equals(value)) { + return BigDecimal.ROUND_HALF_EVEN; + } else if ("ROUND_UP".equals(value)) { + return BigDecimal.ROUND_UP; + } else if ("ROUND_DOWN".equals(value)) { + return BigDecimal.ROUND_DOWN; + } else if ("ROUND_CEILING".equals(value)) { + return BigDecimal.ROUND_CEILING; + } else if ("ROUND_FLOOR".equals(value)) { + return BigDecimal.ROUND_FLOOR; + } else if ("ROUND_UNNECCESSARY".equals(value)) { + return BigDecimal.ROUND_UNNECESSARY; + } return -1; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java index 2272aedeeb..39ecfa11c8 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java @@ -131,9 +131,7 @@ public final class UtilObject { Object obj = null; try { obj = getObjectException(bytes); - } catch (ClassNotFoundException e) { - Debug.logError(e, module); - } catch (IOException e) { + } catch (ClassNotFoundException | IOException e) { Debug.logError(e, module); } return obj; @@ -181,7 +179,9 @@ public final class UtilObject { } public static int doHashCode(Object o1) { - if (o1 == null) return 0; + if (o1 == null) { + return 0; + } if (o1.getClass().isArray()) { int length = Array.getLength(o1); int result = 0; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java index 9dcfb6ba86..5a90a6c0c3 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilPlist.java @@ -41,12 +41,14 @@ public final class UtilPlist { public static final String module = UtilPlist.class.getName(); private UtilPlist() {} - + /** simple 4 char indentation */ private static final String indentFourString = " "; public static void writePlistProperty(String name, Object value, int indentLevel, PrintWriter writer) { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.print(name); writer.print(" = "); if (value instanceof Map) { @@ -62,12 +64,16 @@ public final class UtilPlist { } } public static void writePlistPropertyMap(Map propertyMap, int indentLevel, PrintWriter writer, boolean appendComma) { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.println("{"); for (Map.Entry property: propertyMap.entrySet()) { writePlistProperty(property.getKey(), property.getValue(), indentLevel + 1, writer); } - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } if (appendComma) { writer.println("},"); } else { @@ -75,7 +81,9 @@ public final class UtilPlist { } } public static void writePlistPropertyValueList(List propertyValueList, int indentLevel, PrintWriter writer) { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.print("("); Iterator propertyValueIter = propertyValueList.iterator(); @@ -86,16 +94,22 @@ public final class UtilPlist { writePlistPropertyMap(propertyMap, indentLevel + 1, writer, propertyValueIter.hasNext()); } else { writer.print(propertyValue); - if (propertyValueIter.hasNext()) writer.print(", "); + if (propertyValueIter.hasNext()) { + writer.print(", "); + } } } - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.println(");"); } public static void writePlistPropertyXml(String name, Object value, int indentLevel, PrintWriter writer) { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.print(""); writer.print(name); writer.println(""); @@ -106,23 +120,31 @@ public final class UtilPlist { List list = checkList(value); writePlistPropertyValueListXml(list, indentLevel, writer); } else { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.print(""); writer.print(value); writer.println(""); } } public static void writePlistPropertyMapXml(Map propertyMap, int indentLevel, PrintWriter writer) { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.println(""); for (Map.Entry property: propertyMap.entrySet()) { writePlistPropertyXml(property.getKey(), property.getValue(), indentLevel + 1, writer); } - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.println(""); } public static void writePlistPropertyValueListXml(List propertyValueList, int indentLevel, PrintWriter writer) { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.println(""); indentLevel++; @@ -133,7 +155,9 @@ public final class UtilPlist { Map propertyMap = checkMap(propertyValue); writePlistPropertyMapXml(propertyMap, indentLevel, writer); } else { - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.print(""); writer.print(propertyValue); writer.println(""); @@ -141,7 +165,9 @@ public final class UtilPlist { } indentLevel--; - for (int i = 0; i < indentLevel; i++) writer.print(indentFourString); + for (int i = 0; i < indentLevel; i++) { + writer.print(indentFourString); + } writer.println(""); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java index 0b6c57ecca..36fe056c8b 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java @@ -74,7 +74,7 @@ public final class UtilProperties implements Serializable { */ private static final UtilCache urlCache = UtilCache.createUtilCache("properties.UtilPropertiesUrlCache"); - private static final Set propertiesNotFound = new HashSet(); + private static final Set propertiesNotFound = new HashSet<>(); /** Compares the specified property to the compareString, returns true if they are the same, false otherwise * @param resource The name of the resource - if the properties file is 'webevent.properties', the resource name is 'webevent' @@ -110,10 +110,10 @@ public final class UtilProperties implements Serializable { public static String getPropertyValue(String resource, String name, String defaultValue) { String value = getPropertyValue(resource, name); - if (UtilValidate.isEmpty(value)) + if (UtilValidate.isEmpty(value)) { return defaultValue; - else - return value; + } + return value; } public static double getPropertyNumber(String resource, String name, double defaultValue) { @@ -144,12 +144,12 @@ public final class UtilProperties implements Serializable { if (UtilValidate.isEmpty(str)) { Debug.logWarning("Error converting String \"" + str + "\" to " + type + "; using defaultNumber " + defaultNumber + ".", module); return defaultNumber; - } else - try { - return (Number)(ObjectType.simpleTypeConvert(str, type, null, null)); - } catch (GeneralException e) { - Debug.logWarning("Error converting String \"" + str + "\" to " + type + "; using defaultNumber " + defaultNumber + ".", module); - } + } + try { + return (Number)(ObjectType.simpleTypeConvert(str, type, null, null)); + } catch (GeneralException e) { + Debug.logWarning("Error converting String \"" + str + "\" to " + type + "; using defaultNumber " + defaultNumber + ".", module); + } return defaultNumber; } @@ -163,9 +163,13 @@ public final class UtilProperties implements Serializable { */ public static Boolean getPropertyAsBoolean(String resource, String name, boolean defaultValue) { String str = getPropertyValue(resource, name); - if ("true".equalsIgnoreCase(str)) return Boolean.TRUE; - else if ("false".equalsIgnoreCase(str)) return Boolean.FALSE; - else return defaultValue; + if ("true".equalsIgnoreCase(str)) { + return Boolean.TRUE; + } else if ("false".equalsIgnoreCase(str)) { + return Boolean.FALSE; + } else { + return defaultValue; + } } /** @@ -260,8 +264,12 @@ public final class UtilProperties implements Serializable { * @return The value of the property in the properties file */ public static String getPropertyValue(String resource, String name) { - if (UtilValidate.isEmpty(resource)) return ""; - if (UtilValidate.isEmpty(name)) return ""; + if (UtilValidate.isEmpty(resource)) { + return ""; + } + if (UtilValidate.isEmpty(name)) { + return ""; + } Properties properties = getProperties(resource); if (properties == null) { @@ -282,7 +290,7 @@ public final class UtilProperties implements Serializable { * Returns a new Properties instance created from fileName. *

This method is intended for low-level framework classes that need to read * properties files before OFBiz has been fully initialized.

- * + * * @param fileName The full name of the properties file ("foo.properties") * @return A new Properties instance created from fileName, or * null if the file was not found @@ -363,7 +371,9 @@ public final class UtilProperties implements Serializable { public static boolean propertyValueEquals(URL url, String name, String compareString) { String value = getPropertyValue(url, name); - if (value == null) return false; + if (value == null) { + return false; + } return value.trim().equals(compareString); } @@ -376,7 +386,9 @@ public final class UtilProperties implements Serializable { public static boolean propertyValueEqualsIgnoreCase(URL url, String name, String compareString) { String value = getPropertyValue(url, name); - if (value == null) return false; + if (value == null) { + return false; + } return value.trim().equalsIgnoreCase(compareString); } @@ -390,10 +402,10 @@ public final class UtilProperties implements Serializable { public static String getPropertyValue(URL url, String name, String defaultValue) { String value = getPropertyValue(url, name); - if (UtilValidate.isEmpty(value)) + if (UtilValidate.isEmpty(value)) { return defaultValue; - else - return value; + } + return value; } public static double getPropertyNumber(URL url, String name, double defaultValue) { @@ -419,8 +431,12 @@ public final class UtilProperties implements Serializable { * @return The value of the property in the properties file */ public static String getPropertyValue(URL url, String name) { - if (url == null) return ""; - if (UtilValidate.isEmpty(name)) return ""; + if (url == null) { + return ""; + } + if (UtilValidate.isEmpty(name)) { + return ""; + } Properties properties = getProperties(url); if (properties == null) { @@ -446,8 +462,12 @@ public final class UtilProperties implements Serializable { * @return The value of the split property from the properties file */ public static String getSplitPropertyValue(URL url, String name) { - if (url == null) return ""; - if (UtilValidate.isEmpty(name)) return ""; + if (url == null) { + return ""; + } + if (UtilValidate.isEmpty(name)) { + return ""; + } Properties properties = getProperties(url); @@ -479,8 +499,12 @@ public final class UtilProperties implements Serializable { * @param name The name of the property in the properties file * @param value The value of the property in the properties file */ public static void setPropertyValue(String resource, String name, String value) { - if (UtilValidate.isEmpty(resource)) return; - if (UtilValidate.isEmpty(name)) return; + if (UtilValidate.isEmpty(resource)) { + return; + } + if (UtilValidate.isEmpty(name)) { + return; + } Properties properties = getProperties(resource); if (properties == null) { @@ -556,8 +580,12 @@ public final class UtilProperties implements Serializable { * @param name The name of the property in the resource * @param value The value of the property to set in memory */ public static void setPropertyValueInMemory(String resource, String name, String value) { - if (UtilValidate.isEmpty(resource)) return; - if (UtilValidate.isEmpty(name)) return; + if (UtilValidate.isEmpty(resource)) { + return; + } + if (UtilValidate.isEmpty(name)) { + return; + } Properties properties = getProperties(resource); if (properties == null) { @@ -576,12 +604,18 @@ public final class UtilProperties implements Serializable { * @return The value of the property in the properties file */ public static String getMessage(String resource, String name, Locale locale) { - if (UtilValidate.isEmpty(resource)) return ""; - if (UtilValidate.isEmpty(name)) return ""; + if (UtilValidate.isEmpty(resource)) { + return ""; + } + if (UtilValidate.isEmpty(name)) { + return ""; + } ResourceBundle bundle = getResourceBundle(resource, locale); - if (bundle == null) return name; + if (bundle == null) { + return name; + } String value = null; if (bundle.containsKey(name)) { @@ -606,12 +640,11 @@ public final class UtilProperties implements Serializable { if (UtilValidate.isEmpty(value)) { return ""; - } else { - if (arguments != null && arguments.length > 0) { - value = MessageFormat.format(value, arguments); - } - return value; } + if (arguments != null && arguments.length > 0) { + value = MessageFormat.format(value, arguments); + } + return value; } /** Returns the value of the specified property name from the specified resource/properties file corresponding @@ -627,12 +660,11 @@ public final class UtilProperties implements Serializable { if (UtilValidate.isEmpty(value)) { return ""; - } else { - if (UtilValidate.isNotEmpty(arguments)) { - value = MessageFormat.format(value, arguments.toArray()); - } - return value; } + if (UtilValidate.isNotEmpty(arguments)) { + value = MessageFormat.format(value, arguments.toArray()); + } + return value; } public static String getMessageList(String resource, String name, Locale locale, Object... arguments) { @@ -652,19 +684,18 @@ public final class UtilProperties implements Serializable { if (UtilValidate.isEmpty(value)) { return ""; - } else { - if (UtilValidate.isNotEmpty(context)) { - value = FlexibleStringExpander.expandString(value, context, locale); - } - return value; } + if (UtilValidate.isNotEmpty(context)) { + value = FlexibleStringExpander.expandString(value, context, locale); + } + return value; } public static String getMessageMap(String resource, String name, Locale locale, Object... context) { return getMessage(resource, name, UtilGenerics.toMap(String.class, context), locale); } - private static Set resourceNotFoundMessagesShown = new HashSet(); + private static Set resourceNotFoundMessagesShown = new HashSet<>(); /** Returns the specified resource/properties file as a ResourceBundle * @param resource The name of the resource - can be a file, class, or URL * @param locale The locale that the given resource will correspond to @@ -744,7 +775,9 @@ public final class UtilProperties implements Serializable { } } if (UtilValidate.isNotEmpty(properties)) { - if (Debug.verboseOn()) Debug.logVerbose("Loaded " + properties.size() + " properties for: " + resource + " (" + locale + ")", module); + if (Debug.verboseOn()) { + Debug.logVerbose("Loaded " + properties.size() + " properties for: " + resource + " (" + locale + ")", module); + } } return properties; } @@ -785,7 +818,7 @@ public final class UtilProperties implements Serializable { * @return A list of candidate locales. */ public static List localeToCandidateList(Locale locale) { - List localeList = new LinkedList(); + List localeList = new LinkedList<>(); localeList.add(locale); String localeString = locale.toString(); int pos = localeString.lastIndexOf("_", localeString.length()); @@ -802,7 +835,7 @@ public final class UtilProperties implements Serializable { private static Set defaultCandidateLocales = getDefaultCandidateLocales(); private static Set getDefaultCandidateLocales() { - Set defaultCandidateLocales = new LinkedHashSet(); + Set defaultCandidateLocales = new LinkedHashSet<>(); defaultCandidateLocales.addAll(localeToCandidateList(Locale.getDefault())); defaultCandidateLocales.addAll(localeToCandidateList(getFallbackLocale())); defaultCandidateLocales.add(Locale.ROOT); @@ -831,10 +864,10 @@ public final class UtilProperties implements Serializable { if (Locale.ROOT.equals(locale)) { return UtilMisc.toList(locale); } - Set localeSet = new LinkedHashSet(); + Set localeSet = new LinkedHashSet<>(); localeSet.addAll(localeToCandidateList(locale)); localeSet.addAll(getDefaultCandidateLocales()); - List localeList = new ArrayList(localeSet); + List localeList = new ArrayList<>(localeSet); return localeList; } @@ -866,7 +899,7 @@ public final class UtilProperties implements Serializable { return propertiesNotFound.contains(createResourceName(resource, locale, removeExtension)); } - /** + /** * Resolve a properties file URL. *

This method uses the following strategy:

*
    @@ -959,7 +992,7 @@ public final class UtilProperties implements Serializable { return null; } - /** + /** * Convert XML property file to Properties instance. This method will convert * both the Java XML properties file format and the OFBiz custom XML * properties file format. @@ -1070,7 +1103,7 @@ public final class UtilProperties implements Serializable { UtilResourceBundle bundle = bundleCache.get(resourceName); if (bundle == null) { double startTime = System.currentTimeMillis(); - List candidateLocales = (List) getCandidateLocales(locale); + List candidateLocales = getCandidateLocales(locale); UtilResourceBundle parentBundle = null; int numProperties = 0; while (candidateLocales.size() > 0) { diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java index 19fa21f37c..30f49a8378 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilTimer.java @@ -30,7 +30,7 @@ import java.util.concurrent.ConcurrentHashMap; public class UtilTimer { public static final String module = UtilTimer.class.getName(); - protected static final ConcurrentHashMap staticTimers = new ConcurrentHashMap(); + protected static final ConcurrentHashMap staticTimers = new ConcurrentHashMap<>(); protected String timerName = null; protected String lastMessage = null; @@ -107,7 +107,9 @@ public class UtilTimer { lastMessage = message; String retString = retBuf.toString(); - if (log) Debug.log(Debug.TIMING, null, retString, module, "org.apache.ofbiz.base.util.UtilTimer"); + if (log) { + Debug.log(Debug.TIMING, null, retString, module, "org.apache.ofbiz.base.util.UtilTimer"); + } // have lastMessageTime come as late as possible to just time what happens between calls lastMessageTime = System.currentTimeMillis(); @@ -197,7 +199,9 @@ public class UtilTimer { lastMessageTime = System.currentTimeMillis(); String retString = retStringBuf.toString(); - if (log && Debug.timingOn()) Debug.logTiming(retString, module); + if (log && Debug.timingOn()) { + Debug.logTiming(retString, module); + } return retString; } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java index b4935dfb97..f938dc3951 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilURL.java @@ -31,7 +31,7 @@ import java.util.concurrent.ConcurrentHashMap; public final class UtilURL { public static final String module = UtilURL.class.getName(); - private static final Map urlMap = new ConcurrentHashMap(); + private static final Map urlMap = new ConcurrentHashMap<>(); private UtilURL() {} @@ -39,7 +39,9 @@ public final class UtilURL { String resourceName = contextClass.getName(); int dotIndex = resourceName.lastIndexOf('.'); - if (dotIndex != -1) resourceName = resourceName.substring(0, dotIndex); + if (dotIndex != -1) { + resourceName = resourceName.substring(0, dotIndex); + } resourceName += ".properties"; return fromResource(contextClass, resourceName); @@ -51,7 +53,7 @@ public final class UtilURL { *

    This method uses various ways to locate the resource, and in all * cases it tests to see if the resource exists - so it * is very inefficient.

    - * + * * @param resourceName * @return */ @@ -60,10 +62,10 @@ public final class UtilURL { } public static URL fromResource(Class contextClass, String resourceName) { - if (contextClass == null) + if (contextClass == null) { return fromResource(resourceName, null); - else - return fromResource(resourceName, contextClass.getClassLoader()); + } + return fromResource(resourceName, contextClass.getClassLoader()); } /** @@ -72,7 +74,7 @@ public final class UtilURL { *

    This method uses various ways to locate the resource, and in all * cases it tests to see if the resource exists - so it * is very inefficient.

    - * + * * @param resourceName * @param loader * @return @@ -122,12 +124,16 @@ public final class UtilURL { } public static URL fromFilename(String filename) { - if (filename == null) return null; + if (filename == null) { + return null; + } File file = new File(filename); URL url = null; try { - if (file.exists()) url = file.toURI().toURL(); + if (file.exists()) { + url = file.toURI().toURL(); + } } catch (java.net.MalformedURLException e) { Debug.logError(e, "unable to retrieve URL for file: " + filename, module); url = null; diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilValidate.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilValidate.java index 4840546ebe..b687618501 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilValidate.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilValidate.java @@ -157,9 +157,8 @@ public final class UtilValidate { public static boolean areEqual(Object obj, Object obj2) { if (obj == null) { return obj2 == null; - } else { - return obj.equals(obj2); } + return obj.equals(obj2); } /** Check whether an object is empty, will see if it is a String, Map, Collection, etc. */ @@ -224,7 +223,9 @@ public final class UtilValidate { /** Returns true if string s is empty or whitespace characters only. */ public static boolean isWhitespace(String s) { // Is s empty? - if (isEmpty(s)) return true; + if (isEmpty(s)) { + return true; + } // Search through string's characters one by one // until we find a non-whitespace character. @@ -233,7 +234,9 @@ public final class UtilValidate { // Check that current character isn't whitespace. char c = s.charAt(i); - if (whitespace.indexOf(c) == -1) return false; + if (whitespace.indexOf(c) == -1) { + return false; + } } // All characters are whitespace. return true; @@ -249,7 +252,9 @@ public final class UtilValidate { for (i = 0; i < s.length(); i++) { char c = s.charAt(i); - if (bag.indexOf(c) == -1) stringBuilder.append(c); + if (bag.indexOf(c) == -1) { + stringBuilder.append(c); + } } return stringBuilder.toString(); } @@ -264,7 +269,9 @@ public final class UtilValidate { for (i = 0; i < s.length(); i++) { char c = s.charAt(i); - if (bag.indexOf(c) != -1) stringBuilder.append(c); + if (bag.indexOf(c) != -1) { + stringBuilder.append(c); + } } return stringBuilder.toString(); } @@ -285,7 +292,9 @@ public final class UtilValidate { public static String stripInitialWhitespace(String s) { int i = 0; - while ((i < s.length()) && charInString(s.charAt(i), whitespace)) i++; + while ((i < s.length()) && charInString(s.charAt(i), whitespace)) { + i++; + } return s.substring(i); } @@ -319,7 +328,9 @@ public final class UtilValidate { * point, exponential notation, etc. */ public static boolean isInteger(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } // Search through string's characters one by one // until we find a non-numeric character. @@ -328,7 +339,9 @@ public final class UtilValidate { // Check that current character is number. char c = s.charAt(i); - if (!isDigit(c)) return false; + if (!isDigit(c)) { + return false; + } } // All characters are numbers. @@ -341,7 +354,9 @@ public final class UtilValidate { * Does not accept floating point, exponential notation, etc. */ public static boolean isSignedInteger(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { Integer.parseInt(s); return true; @@ -356,7 +371,9 @@ public final class UtilValidate { * Does not accept floating point, exponential notation, etc. */ public static boolean isSignedLong(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { Long.parseLong(s); return true; @@ -370,12 +387,16 @@ public final class UtilValidate { * NOTE: using the Java Long object for greatest precision */ public static boolean isPositiveInteger(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { long temp = Long.parseLong(s); - if (temp > 0) return true; + if (temp > 0) { + return true; + } return false; } catch (Exception e) { return false; @@ -386,12 +407,16 @@ public final class UtilValidate { * Returns true if string s is an integer >= 0 */ public static boolean isNonnegativeInteger(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { int temp = Integer.parseInt(s); - if (temp >= 0) return true; + if (temp >= 0) { + return true; + } return false; } catch (Exception e) { return false; @@ -402,28 +427,36 @@ public final class UtilValidate { * Returns true if string s is an integer < 0 */ public static boolean isNegativeInteger(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { int temp = Integer.parseInt(s); - if (temp < 0) return true; + if (temp < 0) { + return true; + } return false; } catch (Exception e) { return false; } } - /** + /** * Returns true if string s is an integer <= 0 */ public static boolean isNonpositiveInteger(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { int temp = Integer.parseInt(s); - if (temp <= 0) return true; + if (temp <= 0) { + return true; + } return false; } catch (Exception e) { return false; @@ -439,11 +472,15 @@ public final class UtilValidate { * Does not accept exponential notation. */ public static boolean isFloat(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } boolean seenDecimalPoint = false; - if (s.startsWith(decimalPointDelimiter)) return false; + if (s.startsWith(decimalPointDelimiter)) { + return false; + } // Search through string's characters one by one // until we find a non-numeric character. @@ -459,7 +496,9 @@ public final class UtilValidate { return false; } } else { - if (!isDigit(c)) return false; + if (!isDigit(c)) { + return false; + } } } // All characters are numbers. @@ -469,21 +508,33 @@ public final class UtilValidate { /** General routine for testing whether a string is a float. */ public static boolean isFloat(String s, boolean allowNegative, boolean allowPositive, int minDecimal, int maxDecimal) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { float temp = Float.parseFloat(s); - if (!allowNegative && temp < 0) return false; - if (!allowPositive && temp > 0) return false; + if (!allowNegative && temp < 0) { + return false; + } + if (!allowPositive && temp > 0) { + return false; + } int decimalPoint = s.indexOf("."); if (decimalPoint == -1) { - if (minDecimal > 0) return false; + if (minDecimal > 0) { + return false; + } return true; } // 1.2345; length=6; point=1; num=4 int numDecimals = s.length() - decimalPoint - 1; - if (minDecimal >= 0 && numDecimals < minDecimal) return false; - if (maxDecimal >= 0 && numDecimals > maxDecimal) return false; + if (minDecimal >= 0 && numDecimals < minDecimal) { + return false; + } + if (maxDecimal >= 0 && numDecimals > maxDecimal) { + return false; + } return true; } catch (Exception e) { return false; @@ -493,21 +544,33 @@ public final class UtilValidate { /** General routine for testing whether a string is a double. */ public static boolean isDouble(String s, boolean allowNegative, boolean allowPositive, int minDecimal, int maxDecimal) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { double temp = Double.parseDouble(s); - if (!allowNegative && temp < 0) return false; - if (!allowPositive && temp > 0) return false; + if (!allowNegative && temp < 0) { + return false; + } + if (!allowPositive && temp > 0) { + return false; + } int decimalPoint = s.indexOf("."); if (decimalPoint == -1) { - if (minDecimal > 0) return false; + if (minDecimal > 0) { + return false; + } return true; } // 1.2345; length=6; point=1; num=4 int numDecimals = s.length() - decimalPoint - 1; - if (minDecimal >= 0 && numDecimals < minDecimal) return false; - if (maxDecimal >= 0 && numDecimals > maxDecimal) return false; + if (minDecimal >= 0 && numDecimals < minDecimal) { + return false; + } + if (maxDecimal >= 0 && numDecimals > maxDecimal) { + return false; + } return true; } catch (Exception e) { return false; @@ -522,7 +585,9 @@ public final class UtilValidate { * first call isSignedInteger, then call isSignedFloat. */ public static boolean isSignedFloat(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { Float.parseFloat(s); return true; @@ -539,7 +604,9 @@ public final class UtilValidate { * first call isSignedInteger, then call isSignedFloat. */ public static boolean isSignedDouble(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } try { Double.parseDouble(s); return true; @@ -554,7 +621,9 @@ public final class UtilValidate { * since it now uses Character.isLetter() */ public static boolean isAlphabetic(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } // Search through string's characters one by one // until we find a non-alphabetic character. @@ -563,8 +632,9 @@ public final class UtilValidate { // Check that current character is letter. char c = s.charAt(i); - if (!isLetter(c)) + if (!isLetter(c)) { return false; + } } // All characters are letters. @@ -578,7 +648,9 @@ public final class UtilValidate { * sets and orderings for various languages and platforms. */ public static boolean isAlphanumeric(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } // Search through string's characters one by one // until we find a non-alphanumeric character. @@ -587,7 +659,9 @@ public final class UtilValidate { // Check that current character is number or letter. char c = s.charAt(i); - if (!isLetterOrDigit(c)) return false; + if (!isLetterOrDigit(c)) { + return false; + } } // All characters are numbers or letters. @@ -598,7 +672,9 @@ public final class UtilValidate { /** isSSN returns true if string s is a valid U.S. Social Security Number. Must be 9 digits. */ public static boolean isSSN(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } String normalizedSSN = stripCharsInBag(s, SSNDelimiters); @@ -610,7 +686,9 @@ public final class UtilValidate { **/ @Deprecated public static boolean isUSPhoneNumber(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } String normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters); return (isInteger(normalizedPhone) && normalizedPhone.length() == digitsInUSPhoneNumber); @@ -621,7 +699,9 @@ public final class UtilValidate { * */ @Deprecated public static boolean isUSPhoneAreaCode(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } String normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters); return (isInteger(normalizedPhone) && normalizedPhone.length() == digitsInUSPhoneAreaCode); @@ -632,7 +712,9 @@ public final class UtilValidate { * */ @Deprecated public static boolean isUSPhoneMainNumber(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } String normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters); return (isInteger(normalizedPhone) && normalizedPhone.length() == digitsInUSPhoneMainNumber); @@ -645,7 +727,9 @@ public final class UtilValidate { */ @Deprecated public static boolean isInternationalPhoneNumber(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } String normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters); @@ -654,7 +738,9 @@ public final class UtilValidate { /** isZIPCode returns true if string s is a valid U.S. ZIP code. Must be 5 or 9 digits only. */ public static boolean isZipCode(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } String normalizedZip = stripCharsInBag(s, ZipCodeDelimiters); @@ -665,12 +751,16 @@ public final class UtilValidate { public static boolean isContiguousZipCode(String s) { boolean retval = false; if (isZipCode(s)) { - if (isEmpty(s)) retval = defaultEmptyOK; - else { + if (isEmpty(s)) { + retval = defaultEmptyOK; + } else { String normalizedZip = s.substring(0,5); int iZip = Integer.parseInt(normalizedZip); - if ((iZip >= 96701 && iZip <= 96898) || (iZip >= 99501 && iZip <= 99950)) retval = false; - else retval = true; + if ((iZip >= 96701 && iZip <= 96898) || (iZip >= 99501 && iZip <= 99950)) { + retval = false; + } else { + retval = true; + } } } return retval; @@ -678,26 +768,34 @@ public final class UtilValidate { /** Return true if s is a valid U.S. Postal Code (abbreviation for state). */ public static boolean isStateCode(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return ((USStateCodes.indexOf(s) != -1) && (s.indexOf(USStateCodeDelimiter) == -1)); } /** Return true if s is a valid contiguous U.S. Postal Code (abbreviation for state). */ public static boolean isContiguousStateCode(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return ((ContiguousUSStateCodes.indexOf(s) != -1) && (s.indexOf(USStateCodeDelimiter) == -1)); } public static boolean isEmail(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return EmailValidator.getInstance().isValid(s); } - - /** + + /** * Checks a String for a valid Email-List seperated by ",". */ public static boolean isEmailList(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } String[] emails = s.split(","); for (String email : emails) { if (!EmailValidator.getInstance().isValid(email)) { @@ -712,9 +810,12 @@ public final class UtilValidate { * @return true if s contains :// */ public static boolean isUrl(String s) { - if (isEmpty(s)) return defaultEmptyOK; - if (s.indexOf("://") != -1) + if (isEmpty(s)) { + return defaultEmptyOK; + } + if (s.indexOf("://") != -1) { return true; + } return false; } @@ -725,9 +826,13 @@ public final class UtilValidate { * to use 4-digit year numbers everywhere. */ public static boolean isYear(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } - if (!isNonnegativeInteger(s)) return false; + if (!isNonnegativeInteger(s)) { + return false; + } return ((s.length() == 2) || (s.length() == 4)); } @@ -735,10 +840,14 @@ public final class UtilValidate { * within the range of integer arguments a and b, inclusive. */ public static boolean isIntegerInRange(String s, int a, int b) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } // Catch non-integer strings to avoid creating a NaN below, // which isn't available on JavaScript 1.0 for Windows. - if (!isSignedInteger(s)) return false; + if (!isSignedInteger(s)) { + return false; + } // Now, explicitly change the type to integer via parseInt // so that the comparison code below will work both on // JavaScript 1.2(which typechecks in equality comparisons) @@ -750,13 +859,17 @@ public final class UtilValidate { /** isMonth returns true if string s is a valid month number between 1 and 12. */ public static boolean isMonth(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return isIntegerInRange(s, 1, 12); } /** isDay returns true if string s is a valid day number between 1 and 31. */ public static boolean isDay(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return isIntegerInRange(s, 1, 31); } @@ -769,40 +882,54 @@ public final class UtilValidate { /** isHour returns true if string s is a valid number between 0 and 23. */ public static boolean isHour(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return isIntegerInRange(s, 0, 23); } /** isMinute returns true if string s is a valid number between 0 and 59. */ public static boolean isMinute(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return isIntegerInRange(s, 0, 59); } /** isSecond returns true if string s is a valid number between 0 and 59. */ public static boolean isSecond(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } return isIntegerInRange(s, 0, 59); } /** isDate returns true if string arguments year, month, and day form a valid date. */ public static boolean isDate(String year, String month, String day) { // catch invalid years(not 2- or 4-digit) and invalid months and days. - if (!(isYear(year) && isMonth(month) && isDay(day))) return false; + if (!(isYear(year) && isMonth(month) && isDay(day))) { + return false; + } int intYear = Integer.parseInt(year); int intMonth = Integer.parseInt(month); int intDay = Integer.parseInt(day); // catch invalid days, except for February - if (intDay > daysInMonth[intMonth - 1]) return false; - if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false; + if (intDay > daysInMonth[intMonth - 1]) { + return false; + } + if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) { + return false; + } return true; } /** isDate returns true if string argument date forms a valid date. */ public static boolean isDate(String date) { - if (isEmpty(date)) return defaultEmptyOK; + if (isEmpty(date)) { + return defaultEmptyOK; + } String month; String day; String year; @@ -810,7 +937,9 @@ public final class UtilValidate { int dateSlash1 = date.indexOf("/"); int dateSlash2 = date.lastIndexOf("/"); - if (dateSlash1 <= 0 || dateSlash1 == dateSlash2) return false; + if (dateSlash1 <= 0 || dateSlash1 == dateSlash2) { + return false; + } month = date.substring(0, dateSlash1); day = date.substring(dateSlash1 + 1, dateSlash2); year = date.substring(dateSlash2 + 1); @@ -820,11 +949,15 @@ public final class UtilValidate { /** isDate returns true if string argument date forms a valid date and is after today. */ public static boolean isDateAfterToday(String date) { - if (isEmpty(date)) return defaultEmptyOK; + if (isEmpty(date)) { + return defaultEmptyOK; + } int dateSlash1 = date.indexOf("/"); int dateSlash2 = date.lastIndexOf("/"); - if (dateSlash1 <= 0) return false; + if (dateSlash1 <= 0) { + return false; + } java.util.Date passed = null; if (dateSlash1 == dateSlash2) { @@ -832,7 +965,9 @@ public final class UtilValidate { String month = date.substring(0, dateSlash1); String day = "28"; String year = date.substring(dateSlash1 + 1); - if (!isDate(year, month, day)) return false; + if (!isDate(year, month, day)) { + return false; + } try { int monthInt = Integer.parseInt(month); @@ -848,25 +983,31 @@ public final class UtilValidate { String month = date.substring(0, dateSlash1); String day = date.substring(dateSlash1 + 1, dateSlash2); String year = date.substring(dateSlash2 + 1); - if (!isDate(year, month, day)) return false; + if (!isDate(year, month, day)) { + return false; + } passed = UtilDateTime.toDate(month, day, year, "0", "0", "0"); } java.util.Date now = UtilDateTime.nowDate(); if (passed != null) { return passed.after(now); - } else { - return false; } + return false; } /** isDate returns true if string argument date forms a valid date and is before today. */ public static boolean isDateBeforeToday(String date) { - if (isEmpty(date)) return defaultEmptyOK; + if (isEmpty(date)) { + return defaultEmptyOK; + } int dateSlash1 = date.indexOf("/"); int dateSlash2 = date.lastIndexOf("/"); - if (dateSlash1 <= 0) return defaultEmptyOK; // In this case an issue number has been provided (requires a javascript check in template!) + if (dateSlash1 <= 0) + { + return defaultEmptyOK; // In this case an issue number has been provided (requires a javascript check in template!) + } java.util.Date passed = null; if (dateSlash1 == dateSlash2) { @@ -874,7 +1015,9 @@ public final class UtilValidate { String month = date.substring(0, dateSlash1); String day = "28"; String year = date.substring(dateSlash1 + 1); - if (!isDate(year, month, day)) return false; + if (!isDate(year, month, day)) { + return false; + } try { int monthInt = Integer.parseInt(month); @@ -890,47 +1033,48 @@ public final class UtilValidate { String month = date.substring(0, dateSlash1); String day = date.substring(dateSlash1 + 1, dateSlash2); String year = date.substring(dateSlash2 + 1); - if (!isDate(year, month, day)) return false; + if (!isDate(year, month, day)) { + return false; + } passed = UtilDateTime.toDate(month, day, year, "0", "0", "0"); } java.util.Date now = UtilDateTime.nowDate(); if (passed != null) { return passed.before(now); - } else { - return false; } + return false; } public static boolean isDateBeforeNow(Timestamp date) { Timestamp now = UtilDateTime.nowTimestamp(); if (date != null) { return date.before(now); - } else { - return false; } + return false; } public static boolean isDateAfterNow(Timestamp date) { Timestamp now = UtilDateTime.nowTimestamp(); if (date != null) { return date.after(now); - } else { - return false; } + return false; } /** isTime returns true if string arguments hour, minute, and second form a valid time. */ public static boolean isTime(String hour, String minute, String second) { // catch invalid years(not 2- or 4-digit) and invalid months and days. - if (isHour(hour) && isMinute(minute) && isSecond(second)) + if (isHour(hour) && isMinute(minute) && isSecond(second)) { return true; - else - return false; + } + return false; } /** isTime returns true if string argument time forms a valid time. */ public static boolean isTime(String time) { - if (isEmpty(time)) return defaultEmptyOK; + if (isEmpty(time)) { + return defaultEmptyOK; + } String hour; String minute; @@ -939,7 +1083,9 @@ public final class UtilValidate { int timeColon1 = time.indexOf(":"); int timeColon2 = time.lastIndexOf(":"); - if (timeColon1 <= 0) return false; + if (timeColon1 <= 0) { + return false; + } hour = time.substring(0, timeColon1); if (timeColon1 == timeColon2) { minute = time.substring(timeColon1 + 1); @@ -957,7 +1103,9 @@ public final class UtilValidate { * @return true, if the number passed simple checks */ public static boolean isValueLinkCard(String stPassed) { - if (isEmpty(stPassed)) return defaultEmptyOK; + if (isEmpty(stPassed)) { + return defaultEmptyOK; + } String st = stripCharsInBag(stPassed, creditCardDelimiters); if (st.length() == 16 && (st.startsWith("7") || st.startsWith("6"))) { return true; @@ -971,7 +1119,9 @@ public final class UtilValidate { * @return tru, if the number passed simple checks */ public static boolean isOFBGiftCard(String stPassed) { - if (isEmpty(stPassed)) return defaultEmptyOK; + if (isEmpty(stPassed)) { + return defaultEmptyOK; + } String st = stripCharsInBag(stPassed, creditCardDelimiters); if (st.length() == 15 && sumIsMod10(getLuhnSum(st))) { return true; @@ -1029,13 +1179,19 @@ public final class UtilValidate { * @return true, if the credit card number passes the Luhn Mod-10 test, false otherwise */ public static boolean isCreditCard(String stPassed) { - if (isEmpty(stPassed)) return defaultEmptyOK; + if (isEmpty(stPassed)) { + return defaultEmptyOK; + } String st = stripCharsInBag(stPassed, creditCardDelimiters); - - if (!isInteger(st)) return false; - + + if (!isInteger(st)) { + return false; + } + // encoding only works on cars with less the 19 digits - if (st.length() > 19) return false; + if (st.length() > 19) { + return false; + } return sumIsMod10(getLuhnSum(st)); } @@ -1045,8 +1201,9 @@ public final class UtilValidate { * @return true, if the credit card number is a valid VISA number, false otherwise */ public static boolean isVisa(String cc) { - if (((cc.length() == 16) || (cc.length() == 13)) && ("4".equals(cc.substring(0, 1)))) + if (((cc.length() == 16) || (cc.length() == 13)) && ("4".equals(cc.substring(0, 1)))) { return isCreditCard(cc); + } return false; } @@ -1059,8 +1216,9 @@ public final class UtilValidate { int firstdig = Integer.parseInt(cc.substring(0, 1)); int seconddig = Integer.parseInt(cc.substring(1, 2)); - if ((cc.length() == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5))) + if ((cc.length() == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5))) { return isCreditCard(cc); + } return false; } @@ -1073,8 +1231,9 @@ public final class UtilValidate { int firstdig = Integer.parseInt(cc.substring(0, 1)); int seconddig = Integer.parseInt(cc.substring(1, 2)); - if ((cc.length() == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7))) + if ((cc.length() == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7))) { return isCreditCard(cc); + } return false; } @@ -1087,8 +1246,9 @@ public final class UtilValidate { int firstdig = Integer.parseInt(cc.substring(0, 1)); int seconddig = Integer.parseInt(cc.substring(1, 2)); - if ((cc.length() == 14) && (firstdig == 3) && ((seconddig == 0) || (seconddig == 6) || (seconddig == 8))) + if ((cc.length() == 14) && (firstdig == 3) && ((seconddig == 0) || (seconddig == 6) || (seconddig == 8))) { return isCreditCard(cc); + } return false; } @@ -1107,8 +1267,9 @@ public final class UtilValidate { public static boolean isDiscover(String cc) { String first4digs = cc.substring(0, 4); - if ((cc.length() == 16) && ("6011".equals(first4digs))) + if ((cc.length() == 16) && ("6011".equals(first4digs))) { return isCreditCard(cc); + } return false; } @@ -1119,8 +1280,9 @@ public final class UtilValidate { public static boolean isEnRoute(String cc) { String first4digs = cc.substring(0, 4); - if ((cc.length() == 15) && ("2014".equals(first4digs) || "2149".equals(first4digs))) + if ((cc.length() == 15) && ("2014".equals(first4digs) || "2149".equals(first4digs))) { return isCreditCard(cc); + } return false; } @@ -1137,8 +1299,9 @@ public final class UtilValidate { "3112".equals(first4digs) || "3158".equals(first4digs) || "3337".equals(first4digs) || - "3528".equals(first4digs))) + "3528".equals(first4digs))) { return isCreditCard(cc); + } return false; } @@ -1158,8 +1321,9 @@ public final class UtilValidate { "564182".equals(first6digs) || "633110".equals(first6digs) || "6333".equals(first4digs) || - "6759".equals(first4digs))) + "6759".equals(first4digs))) { return isCreditCard(cc); + } return false; } @@ -1171,8 +1335,9 @@ public final class UtilValidate { String first4digs = cc.substring(0, 4); String first2digs = cc.substring(0, 2); if (((cc.length() == 16) || (cc.length() == 18) || (cc.length() == 19)) && - ("63".equals(first2digs) || "6767".equals(first4digs))) + ("63".equals(first2digs) || "6767".equals(first4digs))) { return isCreditCard(cc); + } return false; } @@ -1190,8 +1355,9 @@ public final class UtilValidate { "4913".equals(first4digs) || "4508".equals(first4digs) || "4844".equals(first4digs) || - "4027".equals(first4digs))) + "4027".equals(first4digs))) { return isCreditCard(cc); + } return false; } @@ -1201,14 +1367,19 @@ public final class UtilValidate { * @return true, if the credit card number is any valid credit card number for any of the accepted card types, false otherwise */ public static boolean isAnyCard(String ccPassed) { - if (isEmpty(ccPassed)) return defaultEmptyOK; + if (isEmpty(ccPassed)) { + return defaultEmptyOK; + } String cc = stripCharsInBag(ccPassed, creditCardDelimiters); - if (!isCreditCard(cc)) return false; + if (!isCreditCard(cc)) { + return false; + } if (isMasterCard(cc) || isVisa(cc) || isAmericanExpress(cc) || isDinersClub(cc) || - isDiscover(cc) || isEnRoute(cc) || isJCB(cc) || isSolo(cc)|| isSwitch (cc)|| isVisaElectron(cc)) + isDiscover(cc) || isEnRoute(cc) || isJCB(cc) || isSolo(cc)|| isSwitch (cc)|| isVisaElectron(cc)) { return true; + } return false; } @@ -1217,21 +1388,45 @@ public final class UtilValidate { * @return true, if the credit card number is any valid credit card number for any of the accepted card types, false otherwise */ public static String getCardType(String ccPassed) { - if (isEmpty(ccPassed)) return "Unknown"; + if (isEmpty(ccPassed)) { + return "Unknown"; + } String cc = stripCharsInBag(ccPassed, creditCardDelimiters); - if (!isCreditCard(cc)) return "Unknown"; + if (!isCreditCard(cc)) { + return "Unknown"; + } - if (isMasterCard(cc)) return "CCT_MASTERCARD"; - if (isVisa(cc)) return "CCT_VISA"; - if (isAmericanExpress(cc)) return "CCT_AMERICANEXPRESS"; - if (isDinersClub(cc)) return "CCT_DINERSCLUB"; - if (isDiscover(cc)) return "CCT_DISCOVER"; - if (isEnRoute(cc)) return "CCT_ENROUTE"; - if (isJCB(cc)) return "CCT_JCB"; - if (isSolo(cc)) return "CCT_SOLO"; - if (isSwitch (cc)) return "CCT_SWITCH"; - if (isVisaElectron(cc)) return "CCT_VISAELECTRON"; + if (isMasterCard(cc)) { + return "CCT_MASTERCARD"; + } + if (isVisa(cc)) { + return "CCT_VISA"; + } + if (isAmericanExpress(cc)) { + return "CCT_AMERICANEXPRESS"; + } + if (isDinersClub(cc)) { + return "CCT_DINERSCLUB"; + } + if (isDiscover(cc)) { + return "CCT_DISCOVER"; + } + if (isEnRoute(cc)) { + return "CCT_ENROUTE"; + } + if (isJCB(cc)) { + return "CCT_JCB"; + } + if (isSolo(cc)) { + return "CCT_SOLO"; + } + if (isSwitch (cc)) { + return "CCT_SWITCH"; + } + if (isVisaElectron(cc)) { + return "CCT_VISAELECTRON"; + } return "Unknown"; } @@ -1241,28 +1436,56 @@ public final class UtilValidate { * @return true, if the credit card number is valid for the particular credit card type given in "cardType", false otherwise */ public static boolean isCardMatch(String cardType, String cardNumberPassed) { - if (isEmpty(cardType)) return defaultEmptyOK; - if (isEmpty(cardNumberPassed)) return defaultEmptyOK; + if (isEmpty(cardType)) { + return defaultEmptyOK; + } + if (isEmpty(cardNumberPassed)) { + return defaultEmptyOK; + } String cardNumber = stripCharsInBag(cardNumberPassed, creditCardDelimiters); - if (("CCT_VISA".equalsIgnoreCase(cardType)) && (isVisa(cardNumber))) return true; - if (("CCT_MASTERCARD".equalsIgnoreCase(cardType)) && (isMasterCard(cardNumber))) return true; - if ((("CCT_AMERICANEXPRESS".equalsIgnoreCase(cardType)) || ("CCT_AMEX".equalsIgnoreCase(cardType))) && (isAmericanExpress(cardNumber))) return true; - if (("CCT_DISCOVER".equalsIgnoreCase(cardType)) && (isDiscover(cardNumber))) return true; - if (("CCT_JCB".equalsIgnoreCase(cardType)) && (isJCB(cardNumber))) return true; - if ((("CCT_DINERSCLUB".equalsIgnoreCase(cardType)) || ("CCT_DINERS".equalsIgnoreCase(cardType))) && (isDinersClub(cardNumber))) return true; - if (("CCT_CARTEBLANCHE".equalsIgnoreCase(cardType)) && (isCarteBlanche(cardNumber))) return true; - if (("CCT_ENROUTE".equalsIgnoreCase(cardType)) && (isEnRoute(cardNumber))) return true; - if (("CCT_SOLO".equalsIgnoreCase(cardType)) && (isSolo(cardNumber))) return true; - if (("CCT_SWITCH".equalsIgnoreCase(cardType)) && (isSwitch (cardNumber))) return true; - if (("CCT_VISAELECTRON".equalsIgnoreCase(cardType)) && (isVisaElectron(cardNumber))) return true; + if (("CCT_VISA".equalsIgnoreCase(cardType)) && (isVisa(cardNumber))) { + return true; + } + if (("CCT_MASTERCARD".equalsIgnoreCase(cardType)) && (isMasterCard(cardNumber))) { + return true; + } + if ((("CCT_AMERICANEXPRESS".equalsIgnoreCase(cardType)) || ("CCT_AMEX".equalsIgnoreCase(cardType))) && (isAmericanExpress(cardNumber))) { + return true; + } + if (("CCT_DISCOVER".equalsIgnoreCase(cardType)) && (isDiscover(cardNumber))) { + return true; + } + if (("CCT_JCB".equalsIgnoreCase(cardType)) && (isJCB(cardNumber))) { + return true; + } + if ((("CCT_DINERSCLUB".equalsIgnoreCase(cardType)) || ("CCT_DINERS".equalsIgnoreCase(cardType))) && (isDinersClub(cardNumber))) { + return true; + } + if (("CCT_CARTEBLANCHE".equalsIgnoreCase(cardType)) && (isCarteBlanche(cardNumber))) { + return true; + } + if (("CCT_ENROUTE".equalsIgnoreCase(cardType)) && (isEnRoute(cardNumber))) { + return true; + } + if (("CCT_SOLO".equalsIgnoreCase(cardType)) && (isSolo(cardNumber))) { + return true; + } + if (("CCT_SWITCH".equalsIgnoreCase(cardType)) && (isSwitch (cardNumber))) { + return true; + } + if (("CCT_VISAELECTRON".equalsIgnoreCase(cardType)) && (isVisaElectron(cardNumber))) { + return true; + } return false; } /** isNotPoBox returns true if address argument does not contain anything that looks like a a PO Box. */ public static boolean isNotPoBox(String s) { - if (isEmpty(s)) return defaultEmptyOK; + if (isEmpty(s)) { + return defaultEmptyOK; + } // strings to check from Greg's program // "P.O. B" @@ -1275,24 +1498,56 @@ public final class UtilValidate { // "P0 B" String sl = s.toLowerCase(Locale.getDefault()); - if (sl.indexOf("p.o. b") != -1) return false; - if (sl.indexOf("p.o.b") != -1) return false; - if (sl.indexOf("p.o b") != -1) return false; - if (sl.indexOf("p o b") != -1) return false; - if (sl.indexOf("po b") != -1) return false; - if (sl.indexOf("pobox") != -1) return false; - if (sl.indexOf("po#") != -1) return false; - if (sl.indexOf("po #") != -1) return false; + if (sl.indexOf("p.o. b") != -1) { + return false; + } + if (sl.indexOf("p.o.b") != -1) { + return false; + } + if (sl.indexOf("p.o b") != -1) { + return false; + } + if (sl.indexOf("p o b") != -1) { + return false; + } + if (sl.indexOf("po b") != -1) { + return false; + } + if (sl.indexOf("pobox") != -1) { + return false; + } + if (sl.indexOf("po#") != -1) { + return false; + } + if (sl.indexOf("po #") != -1) { + return false; + } // now with 0's for them sneaky folks - if (sl.indexOf("p.0. b") != -1) return false; - if (sl.indexOf("p.0.b") != -1) return false; - if (sl.indexOf("p.0 b") != -1) return false; - if (sl.indexOf("p 0 b") != -1) return false; - if (sl.indexOf("p0 b") != -1) return false; - if (sl.indexOf("p0box") != -1) return false; - if (sl.indexOf("p0#") != -1) return false; - if (sl.indexOf("p0 #") != -1) return false; + if (sl.indexOf("p.0. b") != -1) { + return false; + } + if (sl.indexOf("p.0.b") != -1) { + return false; + } + if (sl.indexOf("p.0 b") != -1) { + return false; + } + if (sl.indexOf("p 0 b") != -1) { + return false; + } + if (sl.indexOf("p0 b") != -1) { + return false; + } + if (sl.indexOf("p0box") != -1) { + return false; + } + if (sl.indexOf("p0#") != -1) { + return false; + } + if (sl.indexOf("p0 #") != -1) { + return false; + } return true; } @@ -1336,7 +1591,9 @@ public final class UtilValidate { } } int check = 10 - ((evensum + 3 * oddsum) % 10); - if (check >= 10) check = 0; + if (check >= 10) { + check = 0; + } return Character.forDigit(check, 10); } diff --git a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java index 18f2551488..6559784a51 100644 --- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java +++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java @@ -35,7 +35,6 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.jms.IllegalStateException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -248,7 +247,7 @@ public final class UtilXml { // ----- Java Object Marshalling/Unmarshalling ----- // /** Deserialize an object from an InputStream. - * + * * @param input The InputStream * @return The deserialized Object */ @@ -257,7 +256,7 @@ public final class UtilXml { } /** Deserialize an object from a Reader. - * + * * @param reader The Reader * @return The deserialized Object */ @@ -266,7 +265,7 @@ public final class UtilXml { } /** Deserialize an object from a String. - * + * * @param str The String * @return The deserialized Object */ @@ -275,7 +274,7 @@ public final class UtilXml { } /** Serialize an object to an XML String. - * + * * @param obj The object to serialize * @return An XML String */ @@ -284,7 +283,7 @@ public final class UtilXml { } /** Serialize an object to an OutputStream. - * + * * @param obj The object to serialize * @param output The OutputStream */ @@ -293,7 +292,7 @@ public final class UtilXml { } /** Serialize an object to a Writer. - * + * * @param obj The object to serialize * @param writer The Writer */ @@ -444,7 +443,9 @@ public final class UtilXml { document = builder.parse(is); double totalSeconds = (System.currentTimeMillis() - startTime)/1000.0; - if (Debug.verboseOn()) Debug.logVerbose("XML Read " + totalSeconds + "s: " + docDescription, module); + if (Debug.verboseOn()) { + Debug.logVerbose("XML Read " + totalSeconds + "s: " + docDescription, module); + } return document; } @@ -567,7 +568,9 @@ public final class UtilXml { document = parser.getDocument(); double totalSeconds = (System.currentTimeMillis() - startTime)/1000.0; - if (Debug.verboseOn()) Debug.logVerbose("XML Read " + totalSeconds + "s: " + docDescription, module); + if (Debug.verboseOn()) { + Debug.logVerbose("XML Read " + totalSeconds + "s: " + docDescription, module); + } return document; } @@ -588,7 +591,9 @@ public final class UtilXml { Debug.logError(e, module); } - if (document == null) return null; + if (document == null) { + return null; + } if (rootElementName != null) { Element rootElement = document.createElement(rootElementName); @@ -649,9 +654,11 @@ public final class UtilXml { /** Return a List of Element objects that are children of the given element */ public static List childElementList(Element element) { - if (element == null) return null; + if (element == null) { + return null; + } - List elements = new LinkedList(); + List elements = new LinkedList<>(); Node node = element.getFirstChild(); if (node != null) { @@ -669,9 +676,11 @@ public final class UtilXml { * immediate children of the given element; if name is null, all child * elements will be included. */ public static List childElementList(Element element, String childElementName) { - if (element == null) return null; + if (element == null) { + return null; + } - List elements = new LinkedList(); + List elements = new LinkedList<>(); Node node = element.getFirstChild(); if (node != null) { @@ -691,10 +700,14 @@ public final class UtilXml { * immediate children of the given element; if name is null, all child * elements will be included. */ public static List childElementList(Element element, Set childElementNames) { - if (element == null) return null; + if (element == null) { + return null; + } - List elements = new LinkedList(); - if (childElementNames == null) return elements; + List elements = new LinkedList<>(); + if (childElementNames == null) { + return elements; + } Node node = element.getFirstChild(); if (node != null) { @@ -717,8 +730,10 @@ public final class UtilXml { /** Return a List of Element objects that are children of the given DocumentFragment */ public static List childElementList(DocumentFragment fragment) { - if (fragment == null) return null; - List elements = new LinkedList(); + if (fragment == null) { + return null; + } + List elements = new LinkedList<>(); Node node = fragment.getFirstChild(); if (node != null) { do { @@ -734,9 +749,11 @@ public final class UtilXml { /** Return a List of Node objects that have the given name and are immediate children of the given element; * if name is null, all child elements will be included. */ public static List childNodeList(Node node) { - if (node == null) return null; + if (node == null) { + return null; + } - List nodes = new LinkedList(); + List nodes = new LinkedList<>(); do { if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.COMMENT_NODE) { @@ -749,7 +766,9 @@ public final class UtilXml { /** Return the first child Element * returns the first element. */ public static Element firstChildElement(Element element, Set childElementNames) { - if (element == null) return null; + if (element == null) { + return null; + } // get the first element with the given name Node node = element.getFirstChild(); @@ -774,7 +793,9 @@ public final class UtilXml { /** Return the first child Element * returns the first element. */ public static Element firstChildElement(Element element) { - if (element == null) return null; + if (element == null) { + return null; + } // get the first element with the given name Node node = element.getFirstChild(); @@ -793,8 +814,12 @@ public final class UtilXml { /** Return the first child Element with the given name; if name is null * returns the first element. */ public static Element firstChildElement(Element element, String childElementName) { - if (element == null) return null; - if (UtilValidate.isEmpty(childElementName)) return null; + if (element == null) { + return null; + } + if (UtilValidate.isEmpty(childElementName)) { + return null; + } // get the first element with the given name Node node = element.getFirstChild(); @@ -817,7 +842,9 @@ public final class UtilXml { /** Return the first child Element with the given name; if name is null * returns the first element. */ public static Element firstChildElement(Element element, String childElementName, String attrName, String attrValue) { - if (element == null) return null; + if (element == null) { + return null; + } // get the first element with the given name Node node = element.getFirstChild(); @@ -840,7 +867,9 @@ public final class UtilXml { /** Return the text (node value) contained by the named child node. */ public static String childElementValue(Element element, String childElementName) { - if (element == null) return null; + if (element == null) { + return null; + } // get the value of the first element with the given name Element childElement = firstChildElement(element, childElementName); @@ -849,39 +878,47 @@ public final class UtilXml { /** Return the text (node value) contained by the named child node or a default value if null. */ public static String childElementValue(Element element, String childElementName, String defaultValue) { - if (element == null) return defaultValue; + if (element == null) { + return defaultValue; + } // get the value of the first element with the given name Element childElement = firstChildElement(element, childElementName); String elementValue = elementValue(childElement); - if (UtilValidate.isEmpty(elementValue)) + if (UtilValidate.isEmpty(elementValue)) { return defaultValue; - else - return elementValue; + } + return elementValue; } /** Return a named attribute of a named child node or a default if null. */ public static String childElementAttribute(Element element, String childElementName, String attributeName, String defaultValue) { - if (element == null) return defaultValue; + if (element == null) { + return defaultValue; + } // get the value of the first element with the given name Element childElement = firstChildElement(element, childElementName); String elementAttribute = elementAttribute(childElement, attributeName, defaultValue); - if (UtilValidate.isEmpty(elementAttribute)) + if (UtilValidate.isEmpty(elementAttribute)) { return defaultValue; - else - return elementAttribute; + } + return elementAttribute; } /** Return the text (node value) of the first node under this, works best if normalized. */ public static String elementValue(Element element) { - if (element == null) return null; + if (element == null) { + return null; + } // make sure we get all the text there... element.normalize(); Node textNode = element.getFirstChild(); - if (textNode == null) return null; + if (textNode == null) { + return null; + } StringBuilder valueBuffer = new StringBuilder(); do { @@ -894,7 +931,9 @@ public final class UtilXml { /** Return the text (node value) of the first node under this */ public static String nodeValue(Node node) { - if (node == null) return null; + if (node == null) { + return null; + } StringBuilder valueBuffer = new StringBuilder(); do { @@ -906,36 +945,40 @@ public final class UtilXml { } public static String elementAttribute(Element element, String attrName, String defaultValue) { - if (element == null) return defaultValue; + if (element == null) { + return defaultValue; + } String attrValue = element.getAttribute(attrName); return UtilValidate.isNotEmpty(attrValue) ? attrValue : defaultValue; } public static String checkEmpty(String string) { - if (UtilValidate.isNotEmpty(string)) + if (UtilValidate.isNotEmpty(string)) { return string; - else - return ""; + } + return ""; } public static String checkEmpty(String string1, String string2) { - if (UtilValidate.isNotEmpty(string1)) + if (UtilValidate.isNotEmpty(string1)) { return string1; - else if (UtilValidate.isNotEmpty(string2)) + } else if (UtilValidate.isNotEmpty(string2)) { return string2; - else + } else { return ""; + } } public static String checkEmpty(String string1, String string2, String string3) { - if (UtilValidate.isNotEmpty(string1)) + if (UtilValidate.isNotEmpty(string1)) { return string1; - else if (UtilValidate.isNotEmpty(string2)) + } else if (UtilValidate.isNotEmpty(string2)) { return string2; - else if (UtilValidate.isNotEmpty(string3)) + } else if (UtilValidate.isNotEmpty(string3)) { return string3; - else + } else { return ""; + } } public static boolean checkBoolean(String str) { @@ -946,10 +989,9 @@ public final class UtilXml { if (defaultValue) { //default to true, ie anything but false is true return !"false".equals(str); - } else { - //default to false, ie anything but true is false - return "true".equals(str); } + //default to false, ie anything but true is false + return "true".equals(str); } public static String nodeNameToJavaName(String nodeName, boolean capitalizeFirst) { @@ -1001,8 +1043,10 @@ public final class UtilXml { hasDTD = false; String dtd = UtilProperties.getSplitPropertyValue(UtilURL.fromResource("localdtds.properties"), publicId); if (UtilValidate.isNotEmpty(dtd)) { - if (Debug.verboseOn()) Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] resolving DTD with publicId [" + publicId + - "], systemId [" + systemId + "] and the dtd file is [" + dtd + "]", module); + if (Debug.verboseOn()) { + Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] resolving DTD with publicId [" + publicId + + "], systemId [" + systemId + "] and the dtd file is [" + dtd + "]", module); + } try { URL dtdURL = UtilURL.fromResource(dtd); if (dtdURL == null) { @@ -1013,8 +1057,10 @@ public final class UtilXml { inputSource.setPublicId(publicId); hasDTD = true; - if (Debug.verboseOn()) Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD input source with publicId [" + - publicId + "] and the dtd file is [" + dtd + "]", module); + if (Debug.verboseOn()) { + Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD input source with publicId [" + + publicId + "] and the dtd file is [" + dtd + "]", module); + } return inputSource; } catch (GeneralException | IOException e) { Debug.logWarning(e, module); @@ -1039,14 +1085,15 @@ public final class UtilXml { inputSource.setPublicId(publicId); } hasDTD = true; - if (Debug.verboseOn()) Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD/Schema input source with publicId [" + - publicId + "] and the file/resource is [" + filename + "]", module); + if (Debug.verboseOn()) { + Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD/Schema input source with publicId [" + + publicId + "] and the file/resource is [" + filename + "]", module); + } return inputSource; - } else { - Debug.logWarning("[UtilXml.LocalResolver.resolveEntity] could not find LOCAL DTD/Schema with publicId [" + - publicId + "] and the file/resource is [" + filename + "]", module); - return null; } + Debug.logWarning("[UtilXml.LocalResolver.resolveEntity] could not find LOCAL DTD/Schema with publicId [" + + publicId + "] and the file/resource is [" + filename + "]", module); + return null; } return defaultResolver.resolveEntity(publicId, systemId); } @@ -1134,14 +1181,16 @@ public final class UtilXml { throw new UnsupportedOperationException(); } } - + /** * get node name without any prefix * @param node * @return */ public static String getNodeNameIgnorePrefix(Node node){ - if (node==null) return null; + if (node==null) { + return null; + } String nodeName = node.getNodeName(); if (nodeName.contains(":")){ // remove any possible prefix @@ -1149,14 +1198,16 @@ public final class UtilXml { } return nodeName; } - + /** * get tag name without any prefix * @param element * @return */ public static String getTagNameIgnorePrefix(Element element){ - if (element==null) return null; + if (element==null) { + return null; + } String tagName = element.getTagName(); if (tagName.contains(":")){ // remove any possible prefix @@ -1164,15 +1215,17 @@ public final class UtilXml { } return tagName; } - + /** * get attribute value ignoring prefix in attribute name * @param element * @return */ public static String getAttributeValueIgnorePrefix(Element element, String attributeName){ - if (element==null) return ""; - + if (element==null) { + return ""; + } + NamedNodeMap attributes = element.getAttributes(); if (attributes != null){ for (int i = 0, size = attributes.getLength(); i < size; i++)