Improved: General refactoring and code improvements, package
org.apache.ofbiz.base.util. (OFBIZ-9944) Thanks Dennis Balkir for reporting and providing the patches. git-svn-id: https://svn.apache.org/repos/asf/ofbiz/ofbiz-framework/trunk@1818495 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 <code>
|
||||
* IllegalArgumentException</code> 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.
|
||||
* <p><code>Assert.isAssignableTo("foo", foo, Foo.class);</code></p>
|
||||
*
|
||||
*
|
||||
* @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.
|
||||
* <p><code>Assert.isInstanceOf("foo", foo, Foo.class);</code></p>
|
||||
*
|
||||
*
|
||||
* @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.
|
||||
* <p><code>Assert.isInstanceOf("foo", foo, Foo.class, Bar.class, ...);</code></p>
|
||||
*
|
||||
*
|
||||
* @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.
|
||||
* <p><code>Assert.isNotInstanceOf("foo", foo, Foo.class);</code></p>
|
||||
*
|
||||
*
|
||||
* @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.
|
||||
* <p><code>Assert.isNotInstanceOf("foo", foo, Foo.class, Bar.class, ...);</code></p>
|
||||
*
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @param targetClasses
|
||||
@@ -127,7 +127,7 @@ public class Assert {
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
@@ -142,7 +142,7 @@ public class Assert {
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
@@ -157,7 +157,7 @@ public class Assert {
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
@@ -172,7 +172,7 @@ public class Assert {
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
@@ -187,7 +187,7 @@ public class Assert {
|
||||
/**
|
||||
* Tests a list of arguments for <code>null</code>.
|
||||
* <p><code>Assert.notNull("foo", foo, "bar", bar, ...);</code></p>
|
||||
*
|
||||
*
|
||||
* @param arguments
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
@@ -200,7 +200,7 @@ public class Assert {
|
||||
/**
|
||||
* Tests an argument for <code>null</code>.
|
||||
* <p><code>Assert.notNull("foo", foo);</code></p>
|
||||
*
|
||||
*
|
||||
* @param argumentName
|
||||
* @param objectToTest
|
||||
* @throws IllegalArgumentException
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<String, Integer> levelStringMap = new HashMap<String, Integer>();
|
||||
private static final Map<String, Integer> 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()));
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String> stringsToFindInFile = new HashSet<String>();
|
||||
Set<String> stringsToFindInPath = new HashSet<String>();
|
||||
Set<String> stringsToFindInFile = new HashSet<>();
|
||||
Set<String> stringsToFindInPath = new HashSet<>();
|
||||
|
||||
public SearchTextFilesFilter(String fileExtension, Set<String> stringsToFindInPath, Set<String> 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<String> stringsToFindInPath = new HashSet<String>();
|
||||
Set<String> stringsToFindInFile = new HashSet<String>();
|
||||
Set<String> stringsToFindInPath = new HashSet<>();
|
||||
Set<String> stringsToFindInFile = new HashSet<>();
|
||||
|
||||
if (partialPath != null) {
|
||||
stringsToFindInPath.add(partialPath);
|
||||
@@ -307,7 +302,7 @@ public final class FileUtil {
|
||||
stringsToFindInFile.add(stringToFind);
|
||||
}
|
||||
|
||||
List<File> fileList = new LinkedList<File>();
|
||||
List<File> 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<String> stringsToFindInPath = new HashSet<String>();
|
||||
Set<String> stringsToFindInFile = new HashSet<String>();
|
||||
Set<String> stringsToFindInPath = new HashSet<>();
|
||||
Set<String> 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<File> fileList = new LinkedList<File>();
|
||||
List<File> 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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -34,9 +34,15 @@ public class GeneralException extends Exception {
|
||||
}
|
||||
|
||||
public static <T> 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<String> getMessageList() {
|
||||
|
||||
+12
-6
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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" <code>Map</code>.</p>
|
||||
*
|
||||
*
|
||||
* @param context A <code>Map</code> containing initial variables
|
||||
* @return A <code>Binding</code> instance
|
||||
*/
|
||||
public static Binding getBinding(Map<String, Object> context, String expression) {
|
||||
Map<String, Object> vars = new HashMap<String, Object>();
|
||||
Map<String, Object> 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) {
|
||||
|
||||
@@ -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<String, Object>();
|
||||
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<String, String>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+19
-11
@@ -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<String, String>();
|
||||
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());
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,17 +55,20 @@ public class JNDIContextFactory {
|
||||
if (UtilValidate.isEmpty(jndiServerInfo.contextProviderUrl)) {
|
||||
ic = new InitialContext();
|
||||
} else {
|
||||
Hashtable<String, Object> h = new Hashtable<String, Object>();
|
||||
Hashtable<String, Object> 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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<String, String> getX500Map(Principal x500) {
|
||||
Map<String, String> x500Map = new HashMap<String, String>();
|
||||
Map<String, String> x500Map = new HashMap<>();
|
||||
|
||||
String name = x500.getName().replaceAll("\\\\,", "&com;");
|
||||
String[] x500Opts = name.split("\\,");
|
||||
|
||||
@@ -48,23 +48,31 @@ public class MessageString implements Serializable {
|
||||
if (fieldName == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
Set<String> fieldSet = new TreeSet<String>();
|
||||
Set<String> fieldSet = new TreeSet<>();
|
||||
fieldSet.add(fieldName);
|
||||
return getMessagesForField(fieldSet, convertToStrings, messageStringList);
|
||||
}
|
||||
public static List<Object> getMessagesForField(String fieldName1, String fieldName2, String fieldName3, String fieldName4, boolean convertToStrings, List<Object> messageStringList) {
|
||||
Set<String> fieldSet = new TreeSet<String>();
|
||||
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<String> 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<Object> getMessagesForField(Set<String> fieldNameSet, boolean convertToStrings, List<Object> messageStringList) {
|
||||
if (messageStringList == null || UtilValidate.isEmpty(fieldNameSet)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<Object> outList = new ArrayList<Object>(messageStringList.size());
|
||||
List<Object> 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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -45,7 +45,7 @@ public class MultiTrustManager implements X509TrustManager {
|
||||
}
|
||||
|
||||
public MultiTrustManager() {
|
||||
keystores = new LinkedList<KeyStore>();
|
||||
keystores = new LinkedList<>();
|
||||
}
|
||||
|
||||
public void add(KeyStore ks) {
|
||||
@@ -77,7 +77,7 @@ public class MultiTrustManager implements X509TrustManager {
|
||||
}
|
||||
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
List<X509Certificate> issuers = new LinkedList<X509Certificate>();
|
||||
List<X509Certificate> issuers = new LinkedList<>();
|
||||
for (KeyStore store: keystores) {
|
||||
try {
|
||||
Enumeration<String> 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<String, String> classAlias = new HashMap<String, String>();
|
||||
private static final Map<String, Class<?>> primitives = new HashMap<String, Class<?>>();
|
||||
private static final Map<String, String> classAlias = new HashMap<>();
|
||||
private static final Map<String, Class<?>> 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<Object> 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<? extends Object>) value).size() == 0;
|
||||
if (value instanceof Map) return ((Map<? extends Object, ? extends Object>) 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<? extends Object>) value).size() == 0;
|
||||
}
|
||||
if (value instanceof Map) {
|
||||
return ((Map<? extends Object, ? extends Object>) 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
public final class Observable {
|
||||
|
||||
private final AtomicBoolean changed = new AtomicBoolean();
|
||||
private final CopyOnWriteArrayList<Observer> observers = new CopyOnWriteArrayList<Observer>();
|
||||
private final CopyOnWriteArrayList<Observer> 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 <code>null</code> 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 <code>true</code> if this object has changed.
|
||||
* Returns <code>true</code> 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.
|
||||
* <p>Each <code>Observer</code> has its <code>update</code> method called with two
|
||||
* arguments: this observable object and <code>null</code>. In other
|
||||
* arguments: this observable object and <code>null</code>. In other
|
||||
* words, this method is equivalent to:
|
||||
* </p>
|
||||
* <blockquote>
|
||||
@@ -103,7 +103,7 @@ public final class Observable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all of the observers.
|
||||
* Notify all of the observers.
|
||||
* <p>Each observer has its <code>update</code> method called with two
|
||||
* arguments: this observable object and the <code>arg</code> argument.</p>
|
||||
*
|
||||
@@ -115,7 +115,7 @@ public final class Observable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the changed flag to <code>true</code>.
|
||||
* Sets the changed flag to <code>true</code>.
|
||||
*/
|
||||
public void setChanged() {
|
||||
changed.set(true);
|
||||
|
||||
@@ -25,7 +25,7 @@ package org.apache.ofbiz.base.util;
|
||||
public interface Observer {
|
||||
/**
|
||||
* Called when <code>Observable.notifyObservers</code> is invoked.
|
||||
*
|
||||
*
|
||||
* @param observable
|
||||
* @param arg
|
||||
*/
|
||||
|
||||
+11
-12
@@ -26,8 +26,8 @@ import java.net.UnknownHostException;
|
||||
import java.rmi.server.RMISocketFactory;
|
||||
|
||||
/**
|
||||
* A <code>RMISocketFactory</code> implementation that creates <code>ServerSocket</code>s bound
|
||||
* on a specified network interface.
|
||||
* A <code>RMISocketFactory</code> implementation that creates <code>ServerSocket</code>s bound
|
||||
* on a specified network interface.
|
||||
*/
|
||||
public class RMIExtendedSocketFactory extends RMISocketFactory {
|
||||
|
||||
@@ -44,21 +44,21 @@ public class RMIExtendedSocketFactory extends RMISocketFactory {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s
|
||||
* bound on the specified network interface.
|
||||
*
|
||||
* @param inetAddress The <code>InetAddress</code> of the network interface.
|
||||
* Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s
|
||||
* bound on the specified network interface.
|
||||
*
|
||||
* @param inetAddress The <code>InetAddress</code> of the network interface.
|
||||
*/
|
||||
public RMIExtendedSocketFactory( InetAddress inetAddress ) {
|
||||
this.hostInetAddress = inetAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s
|
||||
* bound on the specified network interface.
|
||||
*
|
||||
* Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s
|
||||
* 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
|
||||
|
||||
@@ -63,7 +63,7 @@ public final class ReferenceCleaner {
|
||||
private ReferenceCleaner() {
|
||||
}
|
||||
|
||||
private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<Object>();
|
||||
private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<>();
|
||||
|
||||
public interface Removable {
|
||||
void remove() throws Exception;
|
||||
|
||||
@@ -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<KeyManager> keyMgrs = new LinkedList<KeyManager>();
|
||||
List<KeyManager> 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<String, String> subjectMap = KeyStoreUtil.getX500Map(x500s);
|
||||
|
||||
if (Debug.infoOn())
|
||||
if (Debug.infoOn()) {
|
||||
Debug.logInfo(peerCert.getSerialNumber().toString(16) + " :: " + subjectMap.get("CN"), module);
|
||||
}
|
||||
|
||||
try {
|
||||
peerCert.checkValidity();
|
||||
|
||||
@@ -37,7 +37,7 @@ public interface ScriptHelper {
|
||||
|
||||
/**
|
||||
* Extracts service IN parameters from <code>inputMap</code> and returns them in a new <code>Map</code>.
|
||||
*
|
||||
*
|
||||
* @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 <code>String</code> 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 <code>GenericValue</code>.
|
||||
*
|
||||
*
|
||||
* @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);
|
||||
|
||||
@@ -75,7 +75,7 @@ public final class ScriptUtil {
|
||||
public static final Set<String> SCRIPT_NAMES;
|
||||
|
||||
static {
|
||||
Set<String> writableScriptNames = new HashSet<String>();
|
||||
Set<String> writableScriptNames = new HashSet<>();
|
||||
ScriptEngineManager manager = new ScriptEngineManager();
|
||||
List<ScriptEngineFactory> 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 <code>null</code> 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 <code>null</code> if the script engine does not support compilation.
|
||||
@@ -196,13 +196,13 @@ public final class ScriptUtil {
|
||||
* <p>If a <code>CompiledScript</code> instance is to be shared by multiple threads, then
|
||||
* each thread must create its own <code>ScriptContext</code> and pass it to the
|
||||
* <code>CompiledScript</code> eval method.</p>
|
||||
*
|
||||
*
|
||||
* @param context
|
||||
* @return
|
||||
*/
|
||||
public static ScriptContext createScriptContext(Map<String, Object> context) {
|
||||
Assert.notNull("context", context);
|
||||
Map<String, Object> localContext = new HashMap<String, Object>(context);
|
||||
Map<String, Object> 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 {
|
||||
* <p>If a <code>CompiledScript</code> instance is to be shared by multiple threads, then
|
||||
* each thread must create its own <code>ScriptContext</code> and pass it to the
|
||||
* <code>CompiledScript</code> eval method.</p>
|
||||
*
|
||||
*
|
||||
* @param context
|
||||
* @param protectedKeys
|
||||
* @return
|
||||
*/
|
||||
public static ScriptContext createScriptContext(Map<String, Object> context, Set<String> protectedKeys) {
|
||||
Assert.notNull("context", context, "protectedKeys", protectedKeys);
|
||||
Map<String, Object> localContext = new HashMap<String, Object>(context);
|
||||
Map<String, Object> 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 <code>String</code> 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -49,7 +49,7 @@ public class StringUtil {
|
||||
private static final Map<String, Pattern> substitutionPatternMap = createSubstitutionPatternMap();
|
||||
|
||||
private static Map<String, Pattern> createSubstitutionPatternMap() {
|
||||
Map<String, Pattern> substitutionPatternMap = new LinkedHashMap<String, Pattern>(); // Preserve insertion order
|
||||
Map<String, Pattern> 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<String> 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<String> 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<String>();
|
||||
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<String> quoteStrList(List<String> list) {
|
||||
List<String> tmpList = list;
|
||||
|
||||
list = new LinkedList<String>();
|
||||
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<String, String> strToMap(String str, String delim, boolean trim, String pairsSeparator) {
|
||||
if (str == null) return null;
|
||||
Map<String, String> decodedMap = new HashMap<String, String>();
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> decodedMap = new HashMap<>();
|
||||
List<String> 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<? extends Object, ? extends Object> 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<String, String> toMap(String s) {
|
||||
Map<String, String> newMap = new HashMap<String, String>();
|
||||
Map<String, String> 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<String> toList(String s) {
|
||||
List<String> newList = new LinkedList<String>();
|
||||
List<String> 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<String> toSet(String s) {
|
||||
Set<String> newSet = new LinkedHashSet<String>();
|
||||
Set<String> 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<K, V> newMap = new HashMap<K, V>();
|
||||
Map<K, V> 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<? extends Appender<StringBuilder>> iterable, String prefix, String suffix, String sepPrefix, String sep, String sepSuffix) {
|
||||
Iterator<? extends Appender<StringBuilder>> 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<? extends Object> iterable, String prefix, String suffix, String sepPrefix, String sep, String sepSuffix) {
|
||||
Iterator<? extends Object> 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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ public class UtilCodec {
|
||||
private static final UrlCodec urlCodec = new UrlCodec();
|
||||
private static final List<Codec> codecs;
|
||||
static {
|
||||
List<Codec> tmpCodecs = new ArrayList<Codec>();
|
||||
List<Codec> 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 </html> and </body>. I guess because <html> and <body> 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.
|
||||
* <p>
|
||||
* 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<String> 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<K> implements Map<K, Object> {
|
||||
public static <K> HtmlEncodingMapWrapper<K> getHtmlEncodingMapWrapper(Map<K, Object> mapToWrap, SimpleEncoder encoder) {
|
||||
if (mapToWrap == null) return null;
|
||||
if (mapToWrap == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HtmlEncodingMapWrapper<K> mapWrapper = new HtmlEncodingMapWrapper<K>();
|
||||
HtmlEncodingMapWrapper<K> 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.<K, Object>checkMap(theObject), this.encoder);
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ public final class UtilDateTime {
|
||||
}
|
||||
|
||||
public static String formatInterval(double interval, int count, Locale locale) {
|
||||
List<Double> parts = new ArrayList<Double>(timevals.length);
|
||||
List<Double> 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<String> resultList = new ArrayList<String>();
|
||||
List<String> 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<String> resultList = new ArrayList<String>();
|
||||
List<String> 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<TimeZone> availableTimeZoneList = getTimeZones();
|
||||
|
||||
private static List<TimeZone> getTimeZones() {
|
||||
ArrayList<TimeZone> availableTimeZoneList = new ArrayList<TimeZone>();
|
||||
ArrayList<TimeZone> availableTimeZoneList = new ArrayList<>();
|
||||
List<String> 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 <code>date</code> that cannot be modified.
|
||||
* Attempts to modify the returned date will result in an
|
||||
* <tt>UnsupportedOperationException</tt>.
|
||||
*
|
||||
*
|
||||
* @param date
|
||||
*/
|
||||
public static Date unmodifiableDate(Date date) {
|
||||
|
||||
@@ -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 <code>String</code> with the formatted date/time, or an empty <code>String</code> if <code>timestamp</code> is <code>null</code>
|
||||
*/
|
||||
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 <code>pre + base + post</code> if base String is not null or empty, otherwise an empty but non-null String.
|
||||
@@ -436,10 +451,10 @@ public final class UtilFormatOut {
|
||||
* @return <code>pre + base + post</code> 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++) {
|
||||
|
||||
@@ -42,7 +42,9 @@ public final class UtilGenerics {
|
||||
|
||||
public static <C extends Collection<?>> void checkCollectionContainment(Object object, Class<C> 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 <T> Collection<T> checkCollection(Object object) {
|
||||
return (Collection<T>) checkCollectionCast(object, Collection.class);
|
||||
return checkCollectionCast(object, Collection.class);
|
||||
}
|
||||
|
||||
public static <T> Collection<T> checkCollection(Object object, Class<T> type) {
|
||||
@@ -65,7 +67,7 @@ public final class UtilGenerics {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> List<T> checkList(Object object) {
|
||||
return (List<T>) checkCollectionCast(object, List.class);
|
||||
return checkCollectionCast(object, List.class);
|
||||
}
|
||||
|
||||
public static <T> List<T> checkList(Object object, Class<T> type) {
|
||||
@@ -75,13 +77,17 @@ public final class UtilGenerics {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <K, V> Map<K, V> 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<K, V>) object;
|
||||
}
|
||||
|
||||
public static <K, V> Map<K, V> checkMap(Object object, Class<K> keyType, Class<V> 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 <T> Stack<T> checkStack(Object object) {
|
||||
return (Stack<T>) checkCollectionCast(object, Stack.class);
|
||||
return checkCollectionCast(object, Stack.class);
|
||||
}
|
||||
|
||||
public static <T> Stack<T> checkStack(Object object, Class<T> type) {
|
||||
@@ -109,7 +115,7 @@ public final class UtilGenerics {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Set<T> checkSet(Object object) {
|
||||
return (Set<T>) checkCollectionCast(object, Set.class);
|
||||
return checkCollectionCast(object, Set.class);
|
||||
}
|
||||
|
||||
public static <T> Set<T> checkSet(Object object, Class<T> type) {
|
||||
@@ -122,7 +128,9 @@ public final class UtilGenerics {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> List<T> toList(Object object) {
|
||||
if (object != null && !(object instanceof List)) return null;
|
||||
if (object != null && !(object instanceof List)) {
|
||||
return null;
|
||||
}
|
||||
return (List<T>) object;
|
||||
}
|
||||
|
||||
@@ -131,7 +139,9 @@ public final class UtilGenerics {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <K, V> Map<K, V> toMap(Object object) {
|
||||
if (object != null && !(object instanceof Map)) return null;
|
||||
if (object != null && !(object instanceof Map)) {
|
||||
return null;
|
||||
}
|
||||
return (Map<K, V>) 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<K, V> map = new LinkedHashMap<K, V>();
|
||||
Map<K, V> 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<K, Object> map = new LinkedHashMap<K, Object>();
|
||||
Map<K, Object> 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);
|
||||
|
||||
@@ -97,7 +97,7 @@ public final class UtilHttp {
|
||||
* @return The resulting Map
|
||||
*/
|
||||
public static Map<String, Object> getCombinedMap(HttpServletRequest request, Set<? extends String> namesToSkip) {
|
||||
Map<String, Object> combinedMap = new HashMap<String, Object>();
|
||||
Map<String, Object> 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<String, Object> getParameterMap(HttpServletRequest request, Set<? extends String> nameSet, Boolean onlyIncludeOrSkip) {
|
||||
boolean onlyIncludeOrSkipPrim = onlyIncludeOrSkip == null ? true : onlyIncludeOrSkip.booleanValue();
|
||||
Map<String, Object> paramMap = new HashMap<String, Object>();
|
||||
Map<String, Object> paramMap = new HashMap<>();
|
||||
|
||||
// add all the actual HTTP request parameters
|
||||
Enumeration<String> 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<String, Object> getQueryStringOnlyParameterMap(String queryString) {
|
||||
Map<String, Object> paramMap = new HashMap<String, Object>();
|
||||
Map<String, Object> 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<String, Object> getPathInfoOnlyParameterMap(String pathInfoStr, Set<? extends String> nameSet, Boolean onlyIncludeOrSkip) {
|
||||
boolean onlyIncludeOrSkipPrim = onlyIncludeOrSkip == null ? true : onlyIncludeOrSkip.booleanValue();
|
||||
Map<String, Object> paramMap = new HashMap<String, Object>();
|
||||
Map<String, Object> 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<String>();
|
||||
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<String> newList = new LinkedList<String>();
|
||||
List<String> newList = new LinkedList<>();
|
||||
for (String listEntry: UtilGenerics.<String>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<String, Object> getJSONAttributeMap(HttpServletRequest request) {
|
||||
Map<String, Object> returnMap = new HashMap<String, Object>();
|
||||
Map<String, Object> returnMap = new HashMap<>();
|
||||
Map<String, Object> attrMap = getAttributeMap(request);
|
||||
for (Map.Entry<String, Object> 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<String, Object> getAttributeMap(HttpServletRequest request, Set<? extends String> namesToSkip) {
|
||||
Map<String, Object> attributeMap = new HashMap<String, Object>();
|
||||
Map<String, Object> attributeMap = new HashMap<>();
|
||||
|
||||
// look at all request attributes
|
||||
Enumeration<String> 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<String, Object> getSessionMap(HttpServletRequest request, Set<? extends String> namesToSkip) {
|
||||
Map<String, Object> sessionMap = new HashMap<String, Object>();
|
||||
Map<String, Object> sessionMap = new HashMap<>();
|
||||
HttpSession session = request.getSession();
|
||||
|
||||
// look at all the session attributes
|
||||
Enumeration<String> 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<String, Object> getServletContextMap(HttpServletRequest request, Set<? extends String> namesToSkip) {
|
||||
Map<String, Object> servletCtxMap = new HashMap<String, Object>();
|
||||
Map<String, Object> servletCtxMap = new HashMap<>();
|
||||
|
||||
// look at all servlet context attributes
|
||||
ServletContext servletContext = (ServletContext) request.getAttribute("servletContext");
|
||||
Enumeration<String> 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<String, Object> makeParamMapWithPrefix(Map<String, ? extends Object> context, Map<String, ? extends Object> additionalFields, String prefix, String suffix) {
|
||||
Map<String, Object> paramMap = new HashMap<String, Object>();
|
||||
Map<String, Object> paramMap = new HashMap<>();
|
||||
for (Map.Entry<String, ? extends Object> entry: context.entrySet()) {
|
||||
String parameterName = entry.getKey();
|
||||
if (parameterName.startsWith(prefix)) {
|
||||
@@ -500,7 +508,7 @@ public final class UtilHttp {
|
||||
}
|
||||
|
||||
public static List<Object> makeParamListWithSuffix(HttpServletRequest request, Map<String, ? extends Object> additionalFields, String suffix, String prefix) {
|
||||
List<Object> paramList = new ArrayList<Object>();
|
||||
List<Object> paramList = new ArrayList<>();
|
||||
Enumeration<String> 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<String, Object> 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<String> paramNames = new HashSet<String>();
|
||||
Set<String> paramNames = new HashSet<>();
|
||||
if (UtilValidate.isNotEmpty(paginatorNumber)) {
|
||||
paginatorNumber = "_" + paginatorNumber;
|
||||
}
|
||||
@@ -1148,21 +1171,28 @@ public final class UtilHttp {
|
||||
* index of the row.
|
||||
*/
|
||||
public static Collection<Map<String, Object>> parseMultiFormData(Map<String, Object> parameters) {
|
||||
Map<Integer, Map<String, Object>> rows = new HashMap<Integer, Map<String, Object>>(); // stores the rows keyed by row number
|
||||
Map<Integer, Map<String, Object>> 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<String, Object> 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<String, Object> m = new HashMap<String, Object>();
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> map = rows.get(n);
|
||||
if (map == null) continue;
|
||||
if (map == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// get the key without the <DELIMITER>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 <V> Map<String, V> removeMultiFormParameters(Map<String, V> parameters) {
|
||||
Map<String, V> filteredParameters = new HashMap<String, V>();
|
||||
Map<String, V> filteredParameters = new HashMap<>();
|
||||
for (Map.Entry<String, V> 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<String, String> data = new HashMap<String, String>();
|
||||
Map<String, String> data = new HashMap<>();
|
||||
for (Enumeration<String> 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<String> 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<String> 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<String, Map<String, Object>> paramMapStore = UtilGenerics.checkMap(session.getAttribute("_PARAM_MAP_STORE_"));
|
||||
if (paramMapStore == null) {
|
||||
paramMapStore = new HashMap<String, Map<String, Object>>();
|
||||
paramMapStore = new HashMap<>();
|
||||
session.setAttribute("_PARAM_MAP_STORE_", paramMapStore);
|
||||
}
|
||||
Map<String, Object> parameters = getParameterMap(request);
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -37,8 +37,8 @@ public final class UtilJavaParse {
|
||||
public static final String module = UtilJavaParse.class.getName();
|
||||
|
||||
// FIXME: Not thread safe
|
||||
private static Set<String> serviceMethodNames = new HashSet<String>();
|
||||
private static Set<String> entityMethodNames = new HashSet<String>();
|
||||
private static Set<String> serviceMethodNames = new HashSet<>();
|
||||
private static Set<String> 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<ComponentConfig> 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<String> findServiceCallsInBlock(int blockStart, int blockEnd, String javaFile) {
|
||||
Set<String> serviceNameSet = new HashSet<String>();
|
||||
Set<String> 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<String> findEntityUseInBlock(int blockStart, int blockEnd, String javaFile) {
|
||||
Set<String> entityNameSet = new HashSet<String>();
|
||||
Set<String> entityNameSet = new HashSet<>();
|
||||
|
||||
int delegatorIndex = javaFile.indexOf("delegator.", blockStart+1);
|
||||
while (delegatorIndex > 0 && delegatorIndex < blockEnd) {
|
||||
|
||||
@@ -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 <E> int compare(List<E> obj1, List<E> obj2) {
|
||||
@@ -103,10 +101,10 @@ public final class UtilMisc {
|
||||
* @return The resulting Iterator
|
||||
*/
|
||||
public static <T> Iterator<T> toIterator(Collection<T> 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<String, V> map = new HashMap<String, V>();
|
||||
Map<String, V> 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 <T> List<T> makeListWritable(Collection<? extends T> col) {
|
||||
List<T> result = new LinkedList<T>();
|
||||
if (col != null) result.addAll(col);
|
||||
List<T> result = new LinkedList<>();
|
||||
if (col != null) {
|
||||
result.addAll(col);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static <K, V> Map<K, V> makeMapWritable(Map<K, ? extends V> map) {
|
||||
if (map == null) {
|
||||
return new HashMap<K, V>();
|
||||
return new HashMap<>();
|
||||
}
|
||||
Map<K, V> result = new HashMap<K, V>(map.size());
|
||||
Map<K, V> result = new HashMap<>(map.size());
|
||||
result.putAll(map);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static <T> Set<T> makeSetWritable(Collection<? extends T> col) {
|
||||
Set<T> result = new LinkedHashSet<T>();
|
||||
if (col != null) result.addAll(col);
|
||||
Set<T> result = new LinkedHashSet<>();
|
||||
if (col != null) {
|
||||
result.addAll(col);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -170,12 +172,11 @@ public final class UtilMisc {
|
||||
*/
|
||||
public static <V> void makeMapSerializable(Map<String, V> map) {
|
||||
// now filter out all non-serializable values
|
||||
Set<String> keysToRemove = new LinkedHashSet<String>();
|
||||
Set<String> keysToRemove = new LinkedHashSet<>();
|
||||
for (Map.Entry<String, V> 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<Map<Object, Object>> sortMaps(List<Map<Object, Object>> listOfMaps, List<? extends String> sortKeys) {
|
||||
if (listOfMaps == null || sortKeys == null)
|
||||
if (listOfMaps == null || sortKeys == null) {
|
||||
return null;
|
||||
List<Map<Object, Object>> toSort = new ArrayList<Map<Object, Object>>(listOfMaps.size());
|
||||
}
|
||||
List<Map<Object, Object>> toSort = new ArrayList<>(listOfMaps.size());
|
||||
toSort.addAll(listOfMaps);
|
||||
try {
|
||||
MapComparator mc = new MapComparator(sortKeys);
|
||||
@@ -208,7 +210,7 @@ public final class UtilMisc {
|
||||
public static <K, IK, V> Map<IK, V> getMapFromMap(Map<K, Object> outerMap, K key) {
|
||||
Map<IK, V> innerMap = UtilGenerics.<IK, V>checkMap(outerMap.get(key));
|
||||
if (innerMap == null) {
|
||||
innerMap = new HashMap<IK, V>();
|
||||
innerMap = new HashMap<>();
|
||||
outerMap.put(key, innerMap);
|
||||
}
|
||||
return innerMap;
|
||||
@@ -220,7 +222,7 @@ public final class UtilMisc {
|
||||
public static <K, V> List<V> getListFromMap(Map<K, Object> outerMap, K key) {
|
||||
List<V> innerList = UtilGenerics.<V>checkList(outerMap.get(key));
|
||||
if (innerList == null) {
|
||||
innerList = new LinkedList<V>();
|
||||
innerList = new LinkedList<>();
|
||||
outerMap.put(key, innerList);
|
||||
}
|
||||
return innerList;
|
||||
@@ -257,21 +259,23 @@ public final class UtilMisc {
|
||||
}
|
||||
|
||||
public static <T> Set<T> collectionToSet(Collection<T> c) {
|
||||
if (c == null) return null;
|
||||
if (c == null) {
|
||||
return null;
|
||||
}
|
||||
Set<T> theSet = null;
|
||||
if (c instanceof Set<?>) {
|
||||
theSet = (Set<T>) c;
|
||||
} else {
|
||||
theSet = new LinkedHashSet<T>();
|
||||
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<T> theSet = new LinkedHashSet<T>();
|
||||
Set<T> theSet = new LinkedHashSet<>();
|
||||
for (T elem : data) {
|
||||
theSet.add(elem);
|
||||
}
|
||||
@@ -309,27 +313,28 @@ public final class UtilMisc {
|
||||
}
|
||||
|
||||
public static <T> Set<T> toSet(Collection<T> collection) {
|
||||
if (collection == null) return null;
|
||||
if (collection == null) {
|
||||
return null;
|
||||
}
|
||||
if (collection instanceof Set<?>) {
|
||||
return (Set<T>) collection;
|
||||
} else {
|
||||
Set<T> theSet = new LinkedHashSet<T>();
|
||||
theSet.addAll(collection);
|
||||
return theSet;
|
||||
}
|
||||
Set<T> theSet = new LinkedHashSet<>();
|
||||
theSet.addAll(collection);
|
||||
return theSet;
|
||||
}
|
||||
|
||||
public static <T> Set<T> toSetArray(T[] data) {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
Set<T> set = new LinkedHashSet<T>();
|
||||
Set<T> 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<T> list = new LinkedList<T>();
|
||||
|
||||
List<T> list = new LinkedList<>();
|
||||
|
||||
for(T t : data){
|
||||
list.add(t);
|
||||
@@ -351,21 +356,22 @@ public final class UtilMisc {
|
||||
}
|
||||
|
||||
public static <T> List<T> toList(Collection<T> collection) {
|
||||
if (collection == null) return null;
|
||||
if (collection == null) {
|
||||
return null;
|
||||
}
|
||||
if (collection instanceof List<?>) {
|
||||
return (List<T>) collection;
|
||||
} else {
|
||||
List<T> list = new LinkedList<T>();
|
||||
list.addAll(collection);
|
||||
return list;
|
||||
}
|
||||
List<T> list = new LinkedList<>();
|
||||
list.addAll(collection);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static <T> List<T> toListArray(T[] data) {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
List<T> list = new LinkedList<T>();
|
||||
List<T> list = new LinkedList<>();
|
||||
for (T value: data) {
|
||||
list.add(value);
|
||||
}
|
||||
@@ -375,7 +381,7 @@ public final class UtilMisc {
|
||||
public static <K, V> void addToListInMap(V element, Map<K, Object> theMap, K listKey) {
|
||||
List<V> theList = UtilGenerics.checkList(theMap.get(listKey));
|
||||
if (theList == null) {
|
||||
theList = new LinkedList<V>();
|
||||
theList = new LinkedList<>();
|
||||
theMap.put(listKey, theList);
|
||||
}
|
||||
theList.add(element);
|
||||
@@ -384,7 +390,7 @@ public final class UtilMisc {
|
||||
public static <K, V> void addToSetInMap(V element, Map<K, Set<V>> theMap, K setKey) {
|
||||
Set<V> theSet = UtilGenerics.checkSet(theMap.get(setKey));
|
||||
if (theSet == null) {
|
||||
theSet = new LinkedHashSet<V>();
|
||||
theSet = new LinkedHashSet<>();
|
||||
theMap.put(setKey, theSet);
|
||||
}
|
||||
theSet.add(element);
|
||||
@@ -393,7 +399,7 @@ public final class UtilMisc {
|
||||
public static <K, V> void addToSortedSetInMap(V element, Map<K, Set<V>> theMap, K setKey) {
|
||||
Set<V> theSet = UtilGenerics.checkSet(theMap.get(setKey));
|
||||
if (theSet == null) {
|
||||
theSet = new TreeSet<V>();
|
||||
theSet = new TreeSet<>();
|
||||
theMap.put(setKey, theSet);
|
||||
}
|
||||
theSet.add(element);
|
||||
@@ -562,7 +568,7 @@ public final class UtilMisc {
|
||||
private static final List<Locale> availableLocaleList = getAvailableLocaleList();
|
||||
|
||||
private static List<Locale> getAvailableLocaleList() {
|
||||
TreeMap<String, Locale> localeMap = new TreeMap<String, Locale>();
|
||||
TreeMap<String, Locale> localeMap = new TreeMap<>();
|
||||
String localesString = UtilProperties.getPropertyValue("general", "locales.available");
|
||||
if (UtilValidate.isNotEmpty(localesString)) {
|
||||
List<String> idList = StringUtil.split(localesString, ",");
|
||||
@@ -579,7 +585,7 @@ public final class UtilMisc {
|
||||
}
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableList(new ArrayList<Locale>(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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -168,7 +168,7 @@ public final class UtilNumber {
|
||||
// hash map to store ICU4J rule sets keyed to Locale
|
||||
private static HashMap<Locale, String> rbnfRuleSets;
|
||||
static {
|
||||
rbnfRuleSets = new HashMap<Locale, String>();
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String, Object> 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<String, Object> 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<Object> 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<Object> 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("<key>");
|
||||
writer.print(name);
|
||||
writer.println("</key>");
|
||||
@@ -106,23 +120,31 @@ public final class UtilPlist {
|
||||
List<Object> 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("<string>");
|
||||
writer.print(value);
|
||||
writer.println("</string>");
|
||||
}
|
||||
}
|
||||
public static void writePlistPropertyMapXml(Map<String, Object> 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("<dict>");
|
||||
for (Map.Entry<String, Object> 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("</dict>");
|
||||
}
|
||||
public static void writePlistPropertyValueListXml(List<Object> 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("<array>");
|
||||
|
||||
indentLevel++;
|
||||
@@ -133,7 +155,9 @@ public final class UtilPlist {
|
||||
Map<String, Object> 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("<string>");
|
||||
writer.print(propertyValue);
|
||||
writer.println("</string>");
|
||||
@@ -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("</array>");
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ public final class UtilProperties implements Serializable {
|
||||
*/
|
||||
private static final UtilCache<String, Properties> urlCache = UtilCache.createUtilCache("properties.UtilPropertiesUrlCache");
|
||||
|
||||
private static final Set<String> propertiesNotFound = new HashSet<String>();
|
||||
private static final Set<String> 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 <code>Properties</code> instance created from <code>fileName</code>.
|
||||
* <p>This method is intended for low-level framework classes that need to read
|
||||
* properties files before OFBiz has been fully initialized.</p>
|
||||
*
|
||||
*
|
||||
* @param fileName The full name of the properties file ("foo.properties")
|
||||
* @return A new <code>Properties</code> instance created from <code>fileName</code>, or
|
||||
* <code>null</code> 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<String> resourceNotFoundMessagesShown = new HashSet<String>();
|
||||
private static Set<String> 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<Locale> localeToCandidateList(Locale locale) {
|
||||
List<Locale> localeList = new LinkedList<Locale>();
|
||||
List<Locale> 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<Locale> defaultCandidateLocales = getDefaultCandidateLocales();
|
||||
|
||||
private static Set<Locale> getDefaultCandidateLocales() {
|
||||
Set<Locale> defaultCandidateLocales = new LinkedHashSet<Locale>();
|
||||
Set<Locale> 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<Locale> localeSet = new LinkedHashSet<Locale>();
|
||||
Set<Locale> localeSet = new LinkedHashSet<>();
|
||||
localeSet.addAll(localeToCandidateList(locale));
|
||||
localeSet.addAll(getDefaultCandidateLocales());
|
||||
List<Locale> localeList = new ArrayList<Locale>(localeSet);
|
||||
List<Locale> 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.
|
||||
* <p>This method uses the following strategy:</p>
|
||||
* <ul>
|
||||
@@ -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<Locale> candidateLocales = (List<Locale>) getCandidateLocales(locale);
|
||||
List<Locale> candidateLocales = getCandidateLocales(locale);
|
||||
UtilResourceBundle parentBundle = null;
|
||||
int numProperties = 0;
|
||||
while (candidateLocales.size() > 0) {
|
||||
|
||||
@@ -30,7 +30,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
public class UtilTimer {
|
||||
|
||||
public static final String module = UtilTimer.class.getName();
|
||||
protected static final ConcurrentHashMap<String, UtilTimer> staticTimers = new ConcurrentHashMap<String, UtilTimer>();
|
||||
protected static final ConcurrentHashMap<String, UtilTimer> 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String, URL> urlMap = new ConcurrentHashMap<String, URL>();
|
||||
private static final Map<String, URL> 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 {
|
||||
* <p>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.</p>
|
||||
*
|
||||
*
|
||||
* @param resourceName
|
||||
* @return
|
||||
*/
|
||||
@@ -60,10 +62,10 @@ public final class UtilURL {
|
||||
}
|
||||
|
||||
public static <C> URL fromResource(Class<C> 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 {
|
||||
* <p>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.</p>
|
||||
*
|
||||
*
|
||||
* @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;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 <code>InputStream</code>.
|
||||
*
|
||||
*
|
||||
* @param input The <code>InputStream</code>
|
||||
* @return The deserialized <code>Object</code>
|
||||
*/
|
||||
@@ -257,7 +256,7 @@ public final class UtilXml {
|
||||
}
|
||||
|
||||
/** Deserialize an object from a <code>Reader</code>.
|
||||
*
|
||||
*
|
||||
* @param reader The <code>Reader</code>
|
||||
* @return The deserialized <code>Object</code>
|
||||
*/
|
||||
@@ -266,7 +265,7 @@ public final class UtilXml {
|
||||
}
|
||||
|
||||
/** Deserialize an object from a <code>String</code>.
|
||||
*
|
||||
*
|
||||
* @param str The <code>String</code>
|
||||
* @return The deserialized <code>Object</code>
|
||||
*/
|
||||
@@ -275,7 +274,7 @@ public final class UtilXml {
|
||||
}
|
||||
|
||||
/** Serialize an object to an XML <code>String</code>.
|
||||
*
|
||||
*
|
||||
* @param obj The object to serialize
|
||||
* @return An XML <code>String</code>
|
||||
*/
|
||||
@@ -284,7 +283,7 @@ public final class UtilXml {
|
||||
}
|
||||
|
||||
/** Serialize an object to an <code>OutputStream</code>.
|
||||
*
|
||||
*
|
||||
* @param obj The object to serialize
|
||||
* @param output The <code>OutputStream</code>
|
||||
*/
|
||||
@@ -293,7 +292,7 @@ public final class UtilXml {
|
||||
}
|
||||
|
||||
/** Serialize an object to a <code>Writer</code>.
|
||||
*
|
||||
*
|
||||
* @param obj The object to serialize
|
||||
* @param writer The <code>Writer</code>
|
||||
*/
|
||||
@@ -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<? extends Element> childElementList(Element element) {
|
||||
if (element == null) return null;
|
||||
if (element == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Element> elements = new LinkedList<Element>();
|
||||
List<Element> 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<? extends Element> childElementList(Element element, String childElementName) {
|
||||
if (element == null) return null;
|
||||
if (element == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Element> elements = new LinkedList<Element>();
|
||||
List<Element> 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<? extends Element> childElementList(Element element, Set<String> childElementNames) {
|
||||
if (element == null) return null;
|
||||
if (element == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Element> elements = new LinkedList<Element>();
|
||||
if (childElementNames == null) return elements;
|
||||
List<Element> 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<? extends Element> childElementList(DocumentFragment fragment) {
|
||||
if (fragment == null) return null;
|
||||
List<Element> elements = new LinkedList<Element>();
|
||||
if (fragment == null) {
|
||||
return null;
|
||||
}
|
||||
List<Element> 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<? extends Node> childNodeList(Node node) {
|
||||
if (node == null) return null;
|
||||
if (node == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Node> nodes = new LinkedList<Node>();
|
||||
List<Node> 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<String> 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++)
|
||||
|
||||
Reference in New Issue
Block a user