Improved: Updated case indentation to 0 for all switch statements in framework component. Also done formatting changes as per checkstyle best practices.

(OFBIZ-11904)
This commit is contained in:
Suraj Khurana
2020-07-25 13:50:37 +05:30
parent 4739019732
commit f4f2722d36
67 changed files with 977 additions and 945 deletions
@@ -66,10 +66,8 @@ public class BlowFishCrypt {
* @param keyFile A file object containing the secret key as a String object.
*/
public BlowFishCrypt(File keyFile) {
try (
FileInputStream is = new FileInputStream(keyFile);
ObjectInputStream os = new ObjectInputStream(is);
) {
try (FileInputStream is = new FileInputStream(keyFile);
ObjectInputStream os = new ObjectInputStream(is);) {
String keyString = (String) os.readObject();
byte[] keyBytes = keyString.getBytes(StandardCharsets.UTF_8);
secretKeySpec = new SecretKeySpec(keyBytes, "Blowfish");
@@ -47,10 +47,10 @@ public class HashCrypt {
private static final String MODULE = HashCrypt.class.getName();
public static final String CRYPT_CHAR_SET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
private static final String PBKDF2_SHA1 ="PBKDF2-SHA1";
private static final String PBKDF2_SHA256 ="PBKDF2-SHA256";
private static final String PBKDF2_SHA384 ="PBKDF2-SHA384";
private static final String PBKDF2_SHA512 ="PBKDF2-SHA512";
private static final String PBKDF2_SHA1 = "PBKDF2-SHA1";
private static final String PBKDF2_SHA256 = "PBKDF2-SHA256";
private static final String PBKDF2_SHA384 = "PBKDF2-SHA384";
private static final String PBKDF2_SHA512 = "PBKDF2-SHA512";
private static final int PBKDF2_ITERATIONS = UtilProperties.getPropertyAsInteger("security.properties", "password.encrypt.pbkdf2.iterations", 10000);
public static MessageDigest getMessageDigest(String type) {
@@ -173,20 +173,20 @@ public class HashCrypt {
byte[] hash = Base64.encodeBase64(skf.generateSecret(spec).getEncoded());
String pbkdf2Type = null;
switch (hashType) {
case "PBKDF2WithHmacSHA1":
pbkdf2Type = PBKDF2_SHA1;
break;
case "PBKDF2WithHmacSHA256":
pbkdf2Type = PBKDF2_SHA256;
break;
case "PBKDF2WithHmacSHA384":
pbkdf2Type = PBKDF2_SHA384;
break;
case "PBKDF2WithHmacSHA512":
pbkdf2Type = PBKDF2_SHA512;
break;
default:
pbkdf2Type = PBKDF2_SHA1;
case "PBKDF2WithHmacSHA1":
pbkdf2Type = PBKDF2_SHA1;
break;
case "PBKDF2WithHmacSHA256":
pbkdf2Type = PBKDF2_SHA256;
break;
case "PBKDF2WithHmacSHA384":
pbkdf2Type = PBKDF2_SHA384;
break;
case "PBKDF2WithHmacSHA512":
pbkdf2Type = PBKDF2_SHA512;
break;
default:
pbkdf2Type = PBKDF2_SHA1;
}
StringBuilder sb = new StringBuilder();
sb.append("{").append(pbkdf2Type).append("}");
@@ -206,23 +206,23 @@ public class HashCrypt {
int typeEnd = crypted.indexOf("}");
String hashType = crypted.substring(1, typeEnd);
String[] parts = crypted.split("\\$");
int iterations = Integer.parseInt(parts[0].substring(typeEnd+1));
int iterations = Integer.parseInt(parts[0].substring(typeEnd + 1));
byte[] salt = Arrays.toString(java.util.Base64.getMimeDecoder().decode(parts[1].getBytes(StandardCharsets.UTF_8))).getBytes(StandardCharsets.UTF_8);
byte[] hash = Base64.decodeBase64(parts[2].getBytes(StandardCharsets.UTF_8));
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, hash.length * 8);
switch (hashType.substring(hashType.indexOf("-")+1)) {
case "SHA256":
hashType = "PBKDF2WithHmacSHA256";
break;
case "SHA384":
hashType = "PBKDF2WithHmacSHA384";
break;
case "SHA512":
hashType = "PBKDF2WithHmacSHA512";
break;
default:
hashType = "PBKDF2WithHmacSHA1";
switch (hashType.substring(hashType.indexOf("-") + 1)) {
case "SHA256":
hashType = "PBKDF2WithHmacSHA256";
break;
case "SHA384":
hashType = "PBKDF2WithHmacSHA384";
break;
case "SHA512":
hashType = "PBKDF2WithHmacSHA512";
break;
default:
hashType = "PBKDF2WithHmacSHA1";
}
SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType);
byte[] testHash = skf.generateSecret(spec).getEncoded();
@@ -28,4 +28,4 @@ import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface ThreadSafe {}
public @interface ThreadSafe { }
@@ -61,7 +61,7 @@ public interface Metrics {
/** Returns the total number of processed events. */
long getTotalEvents();
/**
/**
* Records the service time for <code>numEvents</code> taking
* <code>time</code> milliseconds to be processed.
*/
@@ -76,9 +76,9 @@ public final class Debug {
}
}
public static Logger getLogger(String MODULE) {
if (UtilValidate.isNotEmpty(MODULE)) {
return LogManager.getLogger(MODULE);
public static Logger getLogger(String module) {
if (UtilValidate.isNotEmpty(module)) {
return LogManager.getLogger(module);
}
return root;
}
@@ -91,19 +91,19 @@ public final class Debug {
return levelStringMap.get(levelName.toLowerCase(Locale.getDefault()));
}
public static void log(int level, Throwable t, String msg, String MODULE) {
log(level, t, msg, MODULE, "org.apache.ofbiz.base.util.Debug", emptyParams);
public static void log(int level, Throwable t, String msg, String module) {
log(level, t, msg, module, "org.apache.ofbiz.base.util.Debug", emptyParams);
}
public static void log(int level, Throwable t, String msg, String MODULE, Object... params) {
log(level, t, msg, MODULE, "org.apache.ofbiz.base.util.Debug", params);
public static void log(int level, Throwable t, String msg, String module, Object... params) {
log(level, t, msg, module, "org.apache.ofbiz.base.util.Debug", params);
}
public static void log(int level, Throwable t, String msg, String MODULE, String callingClass) {
log(level, t, msg, MODULE, callingClass, new Object[0]);
public static void log(int level, Throwable t, String msg, String module, String callingClass) {
log(level, t, msg, module, callingClass, new Object[0]);
}
public static void log(int level, Throwable t, String msg, String MODULE, String callingClass, Object... params) {
public static void log(int level, Throwable t, String msg, String module, String callingClass, Object... params) {
if (isOn(level)) {
if (msg != null && params.length > 0) {
StringBuilder sb = new StringBuilder();
@@ -114,7 +114,7 @@ public final class Debug {
}
// log
Logger logger = getLogger(MODULE);
Logger logger = getLogger(module);
logger.log(levelObjs[level], msg, t);
}
}
@@ -136,192 +136,192 @@ public final class Debug {
log(Debug.ALWAYS, t, null, noModuleModule, emptyParams);
}
public static void log(String msg, String MODULE) {
log(Debug.ALWAYS, null, msg, MODULE, emptyParams);
public static void log(String msg, String module) {
log(Debug.ALWAYS, null, msg, module, emptyParams);
}
public static void log(String msg, String MODULE, Object... params) {
log(Debug.ALWAYS, null, msg, MODULE, params);
public static void log(String msg, String module, Object... params) {
log(Debug.ALWAYS, null, msg, module, params);
}
public static void log(Throwable t, String MODULE) {
log(Debug.ALWAYS, t, null, MODULE, emptyParams);
public static void log(Throwable t, String module) {
log(Debug.ALWAYS, t, null, module, emptyParams);
}
public static void log(Throwable t, String msg, String MODULE) {
log(Debug.ALWAYS, t, msg, MODULE, emptyParams);
public static void log(Throwable t, String msg, String module) {
log(Debug.ALWAYS, t, msg, module, emptyParams);
}
public static void log(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.ALWAYS, t, msg, MODULE, params);
public static void log(Throwable t, String msg, String module, Object... params) {
log(Debug.ALWAYS, t, msg, module, params);
}
public static boolean verboseOn() {
return isOn(Debug.VERBOSE);
}
public static void logVerbose(String msg, String MODULE) {
log(Debug.VERBOSE, null, msg, MODULE, emptyParams);
public static void logVerbose(String msg, String module) {
log(Debug.VERBOSE, null, msg, module, emptyParams);
}
public static void logVerbose(String msg, String MODULE, Object... params) {
log(Debug.VERBOSE, null, msg, MODULE, params);
public static void logVerbose(String msg, String module, Object... params) {
log(Debug.VERBOSE, null, msg, module, params);
}
public static void logVerbose(Throwable t, String MODULE) {
log(Debug.VERBOSE, t, null, MODULE, emptyParams);
public static void logVerbose(Throwable t, String module) {
log(Debug.VERBOSE, t, null, module, emptyParams);
}
public static void logVerbose(Throwable t, String msg, String MODULE) {
log(Debug.VERBOSE, t, msg, MODULE, emptyParams);
public static void logVerbose(Throwable t, String msg, String module) {
log(Debug.VERBOSE, t, msg, module, emptyParams);
}
public static void logVerbose(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.VERBOSE, t, msg, MODULE, params);
public static void logVerbose(Throwable t, String msg, String module, Object... params) {
log(Debug.VERBOSE, t, msg, module, params);
}
public static boolean timingOn() {
return isOn(Debug.TIMING);
}
public static void logTiming(String msg, String MODULE) {
log(Debug.TIMING, null, msg, MODULE, emptyParams);
public static void logTiming(String msg, String module) {
log(Debug.TIMING, null, msg, module, emptyParams);
}
public static void logTiming(String msg, String MODULE, Object... params) {
log(Debug.TIMING, null, msg, MODULE, params);
public static void logTiming(String msg, String module, Object... params) {
log(Debug.TIMING, null, msg, module, params);
}
public static void logTiming(Throwable t, String MODULE) {
log(Debug.TIMING, t, null, MODULE, emptyParams);
public static void logTiming(Throwable t, String module) {
log(Debug.TIMING, t, null, module, emptyParams);
}
public static void logTiming(Throwable t, String msg, String MODULE) {
log(Debug.TIMING, t, msg, MODULE, emptyParams);
public static void logTiming(Throwable t, String msg, String module) {
log(Debug.TIMING, t, msg, module, emptyParams);
}
public static void logTiming(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.TIMING, t, msg, MODULE, params);
public static void logTiming(Throwable t, String msg, String module, Object... params) {
log(Debug.TIMING, t, msg, module, params);
}
public static boolean infoOn() {
return isOn(Debug.INFO);
}
public static void logInfo(String msg, String MODULE) {
log(Debug.INFO, null, msg, MODULE, emptyParams);
public static void logInfo(String msg, String module) {
log(Debug.INFO, null, msg, module, emptyParams);
}
public static void logInfo(String msg, String MODULE, Object... params) {
log(Debug.INFO, null, msg, MODULE, params);
public static void logInfo(String msg, String module, Object... params) {
log(Debug.INFO, null, msg, module, params);
}
public static void logInfo(Throwable t, String MODULE) {
log(Debug.INFO, t, null, MODULE, emptyParams);
public static void logInfo(Throwable t, String module) {
log(Debug.INFO, t, null, module, emptyParams);
}
public static void logInfo(Throwable t, String msg, String MODULE) {
log(Debug.INFO, t, msg, MODULE, emptyParams);
public static void logInfo(Throwable t, String msg, String module) {
log(Debug.INFO, t, msg, module, emptyParams);
}
public static void logInfo(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.INFO, t, msg, MODULE, params);
public static void logInfo(Throwable t, String msg, String module, Object... params) {
log(Debug.INFO, t, msg, module, params);
}
public static boolean importantOn() {
return isOn(Debug.IMPORTANT);
}
public static void logImportant(String msg, String MODULE) {
log(Debug.IMPORTANT, null, msg, MODULE, emptyParams);
public static void logImportant(String msg, String module) {
log(Debug.IMPORTANT, null, msg, module, emptyParams);
}
public static void logImportant(String msg, String MODULE, Object... params) {
log(Debug.IMPORTANT, null, msg, MODULE, params);
public static void logImportant(String msg, String module, Object... params) {
log(Debug.IMPORTANT, null, msg, module, params);
}
public static void logImportant(Throwable t, String MODULE) {
log(Debug.IMPORTANT, t, null, MODULE, emptyParams);
public static void logImportant(Throwable t, String module) {
log(Debug.IMPORTANT, t, null, module, emptyParams);
}
public static void logImportant(Throwable t, String msg, String MODULE) {
log(Debug.IMPORTANT, t, msg, MODULE, emptyParams);
public static void logImportant(Throwable t, String msg, String module) {
log(Debug.IMPORTANT, t, msg, module, emptyParams);
}
public static void logImportant(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.IMPORTANT, t, msg, MODULE, params);
public static void logImportant(Throwable t, String msg, String module, Object... params) {
log(Debug.IMPORTANT, t, msg, module, params);
}
public static boolean warningOn() {
return isOn(Debug.WARNING);
}
public static void logWarning(String msg, String MODULE) {
log(Debug.WARNING, null, msg, MODULE, emptyParams);
public static void logWarning(String msg, String module) {
log(Debug.WARNING, null, msg, module, emptyParams);
}
public static void logWarning(String msg, String MODULE, Object... params) {
log(Debug.WARNING, null, msg, MODULE, params);
public static void logWarning(String msg, String module, Object... params) {
log(Debug.WARNING, null, msg, module, params);
}
public static void logWarning(Throwable t, String MODULE) {
log(Debug.WARNING, t, null, MODULE, emptyParams);
public static void logWarning(Throwable t, String module) {
log(Debug.WARNING, t, null, module, emptyParams);
}
public static void logWarning(Throwable t, String msg, String MODULE) {
log(Debug.WARNING, t, msg, MODULE, emptyParams);
public static void logWarning(Throwable t, String msg, String module) {
log(Debug.WARNING, t, msg, module, emptyParams);
}
public static void logWarning(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.WARNING, t, msg, MODULE, params);
public static void logWarning(Throwable t, String msg, String module, Object... params) {
log(Debug.WARNING, t, msg, module, params);
}
public static boolean errorOn() {
return isOn(Debug.ERROR);
}
public static void logError(String msg, String MODULE) {
log(Debug.ERROR, null, msg, MODULE, emptyParams);
public static void logError(String msg, String module) {
log(Debug.ERROR, null, msg, module, emptyParams);
}
public static void logError(String msg, String MODULE, Object... params) {
log(Debug.ERROR, null, msg, MODULE, params);
public static void logError(String msg, String module, Object... params) {
log(Debug.ERROR, null, msg, module, params);
}
public static void logError(Throwable t, String MODULE) {
log(Debug.ERROR, t, null, MODULE, emptyParams);
public static void logError(Throwable t, String module) {
log(Debug.ERROR, t, null, module, emptyParams);
}
public static void logError(Throwable t, String msg, String MODULE) {
log(Debug.ERROR, t, msg, MODULE, emptyParams);
public static void logError(Throwable t, String msg, String module) {
log(Debug.ERROR, t, msg, module, emptyParams);
}
public static void logError(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.ERROR, t, msg, MODULE, params);
public static void logError(Throwable t, String msg, String module, Object... params) {
log(Debug.ERROR, t, msg, module, params);
}
public static boolean fatalOn() {
return isOn(Debug.FATAL);
}
public static void logFatal(String msg, String MODULE) {
log(Debug.FATAL, null, msg, MODULE, emptyParams);
public static void logFatal(String msg, String module) {
log(Debug.FATAL, null, msg, module, emptyParams);
}
public static void logFatal(String msg, String MODULE, Object... params) {
log(Debug.FATAL, null, msg, MODULE, params);
public static void logFatal(String msg, String module, Object... params) {
log(Debug.FATAL, null, msg, module, params);
}
public static void logFatal(Throwable t, String MODULE) {
log(Debug.FATAL, t, null, MODULE, emptyParams);
public static void logFatal(Throwable t, String module) {
log(Debug.FATAL, t, null, module, emptyParams);
}
public static void logFatal(Throwable t, String msg, String MODULE) {
log(Debug.FATAL, t, msg, MODULE, emptyParams);
public static void logFatal(Throwable t, String msg, String module) {
log(Debug.FATAL, t, msg, module, emptyParams);
}
public static void logFatal(Throwable t, String msg, String MODULE, Object... params) {
log(Debug.FATAL, t, msg, MODULE, params);
public static void logFatal(Throwable t, String msg, String module, Object... params) {
log(Debug.FATAL, t, msg, module, params);
}
public static void set(int level, boolean on) {
@@ -51,7 +51,6 @@ import org.apache.ofbiz.base.location.ComponentLocationResolver;
/**
* File Utilities
*
*/
public final class FileUtil {
@@ -59,68 +58,6 @@ public final class FileUtil {
private FileUtil() { }
private static class SearchTextFilesFilter implements FilenameFilter {
String fileExtension;
Set<String> stringsToFindInFile = new HashSet<>();
Set<String> stringsToFindInPath = new HashSet<>();
public SearchTextFilesFilter(String fileExtension, Set<String> stringsToFindInPath, Set<String> stringsToFindInFile) {
this.fileExtension = fileExtension;
if (stringsToFindInPath != null) {
this.stringsToFindInPath.addAll(stringsToFindInPath);
}
if (stringsToFindInFile != null) {
this.stringsToFindInFile.addAll(stringsToFindInFile);
}
}
@Override
public boolean accept(File dir, String name) {
File file = new File(dir, name);
if (file.getName().startsWith(".")) {
return false;
}
if (file.isDirectory()) {
return true;
}
boolean hasAllPathStrings = true;
String fullPath = dir.getPath().replace('\\', '/');
for (String pathString: stringsToFindInPath) {
if (fullPath.indexOf(pathString) < 0) {
hasAllPathStrings = false;
break;
}
}
if (hasAllPathStrings && name.endsWith("." + fileExtension)) {
if (stringsToFindInFile.size() == 0) {
return true;
}
StringBuffer xmlFileBuffer = null;
try {
xmlFileBuffer = FileUtil.readTextFile(file, true);
} catch (IOException e) {
Debug.logWarning("Error reading xml file [" + file + "] for file search: " + e.toString(), MODULE);
return false;
}
if (UtilValidate.isNotEmpty(xmlFileBuffer)) {
boolean hasAllStrings = true;
for (String stringToFile: stringsToFindInFile) {
if (xmlFileBuffer.indexOf(stringToFile) < 0) {
hasAllStrings = false;
break;
}
}
return hasAllStrings;
}
} else {
return false;
}
return false;
}
}
public static File getFile(String path) {
return getFile(null, path);
}
@@ -154,9 +91,7 @@ public final class FileUtil {
public static void writeString(String path, String name, String s) {
try (
Writer out = getBufferedWriter(path, name);
) {
try (Writer out = getBufferedWriter(path, name);) {
out.write(s + System.getProperty("line.separator"));
} catch (IOException e) {
Debug.logError(e, MODULE);
@@ -243,8 +178,7 @@ public final class FileUtil {
}
StringBuffer buf = new StringBuffer();
try (
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));) {
String str;
while ((str = in.readLine()) != null) {
@@ -259,6 +193,7 @@ public final class FileUtil {
return buf;
}
public static StringBuffer readTextFile(String fileName, boolean newline) throws FileNotFoundException, IOException {
File file = new File(fileName);
return readTextFile(file, newline);
@@ -303,10 +238,10 @@ public final class FileUtil {
Set<String> stringsToFindInFile = new HashSet<>();
if (partialPath != null) {
stringsToFindInPath.add(partialPath);
stringsToFindInPath.add(partialPath);
}
if (stringToFind != null) {
stringsToFindInFile.add(stringToFind);
stringsToFindInFile.add(stringToFind);
}
List<File> fileList = new LinkedList<>();
@@ -339,75 +274,67 @@ public final class FileUtil {
}
/**
*
*
* Search for the specified <code>searchString</code> in the given
* {@link Reader}.
*
* @param reader A Reader in which the String will be searched.
* @param searchString The String to search for
* @return <code>TRUE</code> if the <code>searchString</code> is found;
* <code>FALSE</code> otherwise.
* @throws IOException
*/
public static boolean containsString(Reader reader, final String searchString) throws IOException {
char[] buffer = new char[1024];
int numCharsRead;
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;
}
}
}
return false;
}
* Search for the specified <code>searchString</code> in the given
* {@link Reader}.
*
* @param reader A Reader in which the String will be searched.
* @param searchString The String to search for
* @return <code>TRUE</code> if the <code>searchString</code> is found;
* <code>FALSE</code> otherwise.
* @throws IOException
*/
public static boolean containsString(Reader reader, final String searchString) throws IOException {
char[] buffer = new char[1024];
int numCharsRead;
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;
}
}
}
return false;
}
/**
*
*
* Search for the specified <code>searchString</code> in the given
* filename. If the specified file doesn't exist, <code>FALSE</code>
* returns.
*
* @param fileName A full path to a file in which the String will be searched.
* @param searchString The String to search for
* @return <code>TRUE</code> if the <code>searchString</code> is found;
* <code>FALSE</code> otherwise.
* @throws IOException
*/
public static boolean containsString(final String fileName, final String searchString) throws IOException {
File inFile = new File(fileName);
if (inFile.exists()) {
try (
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), StandardCharsets.UTF_8));
) {
return containsString(in, searchString);
}
}
return false;
}
/**
* Search for the specified <code>searchString</code> in the given
* filename. If the specified file doesn't exist, <code>FALSE</code>
* returns.
*
* @param fileName A full path to a file in which the String will be searched.
* @param searchString The String to search for
* @return <code>TRUE</code> if the <code>searchString</code> is found;
* <code>FALSE</code> otherwise.
* @throws IOException
*/
public static boolean containsString(final String fileName, final String searchString) throws IOException {
File inFile = new File(fileName);
if (inFile.exists()) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), StandardCharsets.UTF_8));) {
return containsString(in, searchString);
}
}
return false;
}
/**
*
*
* Check if the specified <code>fileName</code> exists and is a file (not a directory)
* If the specified file doesn't exist or is a directory <code>FALSE</code> returns.
*
* @param fileName A full path to a file in which the String will be searched.
* @return <code>TRUE</code> if the <code>fileName</code> exists and is a file (not a directory)
* <code>FALSE</code> otherwise.
*/
public static boolean isFile(String fileName) {
File f = new File(fileName);
return f.isFile();
}
/**
* Check if the specified <code>fileName</code> exists and is a file (not a directory)
* If the specified file doesn't exist or is a directory <code>FALSE</code> returns.
*
* @param fileName A full path to a file in which the String will be searched.
* @return <code>TRUE</code> if the <code>fileName</code> exists and is a file (not a directory)
* <code>FALSE</code> otherwise.
*/
public static boolean isFile(String fileName) {
File f = new File(fileName);
return f.isFile();
}
/**
* For an inputStream and a file name, create a zip stream containing only one entry with the inputStream set to fileName
@@ -488,10 +415,11 @@ public final class FileUtil {
zis.closeEntry();
zis.close();
}
/**
* Creates a File with a normalized file path
* This useful to prevent path traversal security issues
* cf. OFBIZ-9973 for more details
* This useful to prevent path traversal security issues
* cf. OFBIZ-9973 for more details
*
* @param filePath The file path to normalize
* @return A File with a normalized file path
@@ -499,9 +427,10 @@ public final class FileUtil {
public static File createFileWithNormalizedPath(String filePath) {
return new File(filePath).toPath().normalize().toFile();
}
/**
* Normalizes a file path
* This useful to prevent path traversal security issues
* This useful to prevent path traversal security issues
*
* @param filePath The file path to normalize
* @return A normalized file path
@@ -510,4 +439,66 @@ public final class FileUtil {
return createFileWithNormalizedPath(filePath).toString();
}
private static class SearchTextFilesFilter implements FilenameFilter {
String fileExtension;
Set<String> stringsToFindInFile = new HashSet<>();
Set<String> stringsToFindInPath = new HashSet<>();
public SearchTextFilesFilter(String fileExtension, Set<String> stringsToFindInPath, Set<String> stringsToFindInFile) {
this.fileExtension = fileExtension;
if (stringsToFindInPath != null) {
this.stringsToFindInPath.addAll(stringsToFindInPath);
}
if (stringsToFindInFile != null) {
this.stringsToFindInFile.addAll(stringsToFindInFile);
}
}
@Override
public boolean accept(File dir, String name) {
File file = new File(dir, name);
if (file.getName().startsWith(".")) {
return false;
}
if (file.isDirectory()) {
return true;
}
boolean hasAllPathStrings = true;
String fullPath = dir.getPath().replace('\\', '/');
for (String pathString : stringsToFindInPath) {
if (fullPath.indexOf(pathString) < 0) {
hasAllPathStrings = false;
break;
}
}
if (hasAllPathStrings && name.endsWith("." + fileExtension)) {
if (stringsToFindInFile.size() == 0) {
return true;
}
StringBuffer xmlFileBuffer = null;
try {
xmlFileBuffer = FileUtil.readTextFile(file, true);
} catch (IOException e) {
Debug.logWarning("Error reading xml file [" + file + "] for file search: " + e.toString(), MODULE);
return false;
}
if (UtilValidate.isNotEmpty(xmlFileBuffer)) {
boolean hasAllStrings = true;
for (String stringToFile : stringsToFindInFile) {
if (xmlFileBuffer.indexOf(stringToFile) < 0) {
hasAllStrings = false;
break;
}
}
return hasAllStrings;
}
} else {
return false;
}
return false;
}
}
}
@@ -153,7 +153,8 @@ public final class GroovyUtil {
Debug.logVerbose("Cached Groovy script at: " + location, MODULE);
}
} else {
// the newly parsed script is discarded and the one found in the cache (that has been created by a concurrent thread in the meantime) is used
// the newly parsed script is discarded and the one found in the cache (that has been created by a concurrent thread in the
// meantime) is used
scriptClass = scriptClassCached;
}
}
@@ -213,6 +214,6 @@ public final class GroovyUtil {
Script script = InvokerHelper.createScript(getScriptClassFromLocation(location), getBinding(context));
return UtilValidate.isEmpty(methodName)
? script.run()
: script.invokeMethod(methodName, new Object[] { context });
: script.invokeMethod(methodName, new Object[] {context });
}
}
@@ -249,40 +249,40 @@ public final class SSLUtil {
public static HostnameVerifier getHostnameVerifier(int level) {
switch (level) {
case HOSTCERT_MIN_CHECK:
return (hostname, session) -> {
Certificate[] peerCerts;
case HOSTCERT_MIN_CHECK:
return (hostname, session) -> {
Certificate[] peerCerts;
try {
peerCerts = session.getPeerCertificates();
} catch (SSLPeerUnverifiedException e) {
// cert not verified
Debug.logWarning(e.getMessage(), MODULE);
return false;
}
for (Certificate peerCert : peerCerts) {
try {
peerCerts = session.getPeerCertificates();
} catch (SSLPeerUnverifiedException e) {
// cert not verified
Debug.logWarning(e.getMessage(), MODULE);
Principal x500s = session.getPeerPrincipal();
Map<String, String> subjectMap = KeyStoreUtil.getX500Map(x500s);
if (Debug.infoOn()) {
byte[] encodedCert = peerCert.getEncoded();
Debug.logInfo(new BigInteger(encodedCert).toString(16)
+ " :: " + subjectMap.get("CN"), MODULE);
}
peerCert.verify(peerCert.getPublicKey());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
// certificate not valid
Debug.logWarning("Certificate is not valid!", MODULE);
return false;
}
for (Certificate peerCert : peerCerts) {
try {
Principal x500s = session.getPeerPrincipal();
Map<String, String> subjectMap = KeyStoreUtil.getX500Map(x500s);
if (Debug.infoOn()) {
byte[] encodedCert = peerCert.getEncoded();
Debug.logInfo(new BigInteger(encodedCert).toString(16)
+ " :: " + subjectMap.get("CN"), MODULE);
}
peerCert.verify(peerCert.getPublicKey());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
// certificate not valid
Debug.logWarning("Certificate is not valid!", MODULE);
return false;
}
}
return true;
};
case HOSTCERT_NO_CHECK:
return (hostname, session) -> true;
default:
return null;
}
return true;
};
case HOSTCERT_NO_CHECK:
return (hostname, session) -> true;
default:
return null;
}
}
@@ -53,7 +53,7 @@ public final class UtilGenerics {
if (!(object instanceof Map<?, ?>)) {
throw new ClassCastException("Not a map");
}
Map<?, ?> map = (Map<?,?>) object;
Map<?, ?> map = (Map<?, ?>) object;
int i = 0;
for (Map.Entry<?, ?> entry: map.entrySet()) {
if (entry.getKey() != null && !keyType.isInstance(entry.getKey())) {
@@ -756,7 +756,7 @@ public final class UtilHttp {
if (localeObject == null) {
Map<?, ?> userLogin = (Map<?, ?>) session.getAttribute("userLogin");
if (userLogin == null) {
userLogin = (Map<?,?>) session.getAttribute("autoUserLogin");
userLogin = (Map<?, ?>) session.getAttribute("autoUserLogin");
}
if (userLogin != null) {
@@ -98,7 +98,7 @@ public final class UtilJavaParse {
// search through the component directories, in the src directory for each, using the class path as the path within it
String sourceSubPath = fullyQualifiedClassName.substring(0, fullyQualifiedClassName.lastIndexOf(".")).replace('.', File.separatorChar);
String classFileName = fullyQualifiedClassName.substring(fullyQualifiedClassName.lastIndexOf(".")+1) + ".java";
String classFileName = fullyQualifiedClassName.substring(fullyQualifiedClassName.lastIndexOf(".") + 1) + ".java";
Collection<ComponentConfig> allComponentConfigs = ComponentConfig.getAllComponents();
for (ComponentConfig cc: allComponentConfigs) {
@@ -163,8 +163,8 @@ public final class UtilJavaParse {
public static int findEndOfBlock(int blockStart, String javaFile) {
int nextOpen = javaFile.indexOf("{", blockStart+1);
int nextClose = javaFile.indexOf("}", blockStart+1);
int nextOpen = javaFile.indexOf("{", blockStart + 1);
int nextClose = javaFile.indexOf("}", blockStart + 1);
if (nextOpen > 0 && nextClose > 0 && nextClose > nextOpen) {
javaFile = javaFile.substring(nextOpen, nextClose);
}
@@ -178,8 +178,8 @@ public final class UtilJavaParse {
if (endOfSubBlock < 0) {
return -1;
}
nextOpen = javaFile.indexOf("{", endOfSubBlock+1);
nextClose = javaFile.indexOf("}", endOfSubBlock+1);
nextOpen = javaFile.indexOf("{", endOfSubBlock + 1);
nextClose = javaFile.indexOf("}", endOfSubBlock + 1);
}
// at this point there should be no nextOpen or nextOpen is after the nextClose, meaning we're at the end of the block
@@ -189,7 +189,7 @@ public final class UtilJavaParse {
public static Set<String> findServiceCallsInBlock(int blockStart, int blockEnd, String javaFile) {
Set<String> serviceNameSet = new HashSet<>();
int dispatcherIndex = javaFile.indexOf("dispatcher.", blockStart+1);
int dispatcherIndex = javaFile.indexOf("dispatcher.", blockStart + 1);
while (dispatcherIndex > 0 && dispatcherIndex < blockEnd) {
// verify it is a call we're looking for
int openParenIndex = javaFile.indexOf("(", dispatcherIndex);
@@ -197,10 +197,10 @@ public final class UtilJavaParse {
if (serviceMethodNames.contains(curMethodName)) {
// find the service name
int openQuoteIndex = javaFile.indexOf("\"", openParenIndex);
int closeQuoteIndex = javaFile.indexOf("\"", openQuoteIndex+1);
int closeQuoteIndex = javaFile.indexOf("\"", openQuoteIndex + 1);
if (openQuoteIndex - openParenIndex <= 3 && openQuoteIndex >= 0 && closeQuoteIndex >= 0) {
//more than two spaces/chars between quote and open paren... consider it something other than what we are looking for
String serviceName = javaFile.substring(openQuoteIndex+1, closeQuoteIndex).trim();
String serviceName = javaFile.substring(openQuoteIndex + 1, closeQuoteIndex).trim();
serviceNameSet.add(serviceName);
}
}
@@ -214,7 +214,7 @@ public final class UtilJavaParse {
public static Set<String> findEntityUseInBlock(int blockStart, int blockEnd, String javaFile) {
Set<String> entityNameSet = new HashSet<>();
int delegatorIndex = javaFile.indexOf("delegator.", blockStart+1);
int delegatorIndex = javaFile.indexOf("delegator.", blockStart + 1);
while (delegatorIndex > 0 && delegatorIndex < blockEnd) {
// verify it is a call we're looking for
int openParenIndex = javaFile.indexOf("(", delegatorIndex);
@@ -222,10 +222,10 @@ public final class UtilJavaParse {
if (entityMethodNames.contains(curMethodName)) {
// find the entity name
int openQuoteIndex = javaFile.indexOf("\"", openParenIndex);
int closeQuoteIndex = javaFile.indexOf("\"", openQuoteIndex+1);
int closeQuoteIndex = javaFile.indexOf("\"", openQuoteIndex + 1);
if (openQuoteIndex - openParenIndex <= 3 && openQuoteIndex >= 0 && closeQuoteIndex >= 0) {
//more than two spaces/chars between quote and open paren... consider it something other than what we are looking for
String entityName = javaFile.substring(openQuoteIndex+1, closeQuoteIndex).trim();
String entityName = javaFile.substring(openQuoteIndex + 1, closeQuoteIndex).trim();
entityNameSet.add(entityName);
}
}
@@ -98,6 +98,7 @@ public final class UtilMisc {
/**
* Get an iterator from a collection, returning null if collection is null
*
* @param col The collection to be turned in to an iterator
* @return The resulting Iterator
*/
@@ -111,7 +112,7 @@ public final class UtilMisc {
/**
* Creates a pseudo-literal map corresponding to key-values.
*
* @param kvs the key-value pairs
* @param kvs the key-value pairs
* @return the corresponding map.
* @throws IllegalArgumentException when the key-value list is not even.
*/
@@ -122,8 +123,8 @@ public final class UtilMisc {
/**
* Creates a pseudo-literal map corresponding to key-values.
*
* @param constructor the constructor used to instantiate the map
* @param kvs the key-value pairs
* @param constructor the constructor used to instantiate the map
* @param kvs the key-value pairs
* @return the corresponding map.
* @throws IllegalArgumentException when the key-value list is not even.
*/
@@ -134,12 +135,12 @@ public final class UtilMisc {
}
if (kvs.length % 2 == 1) {
IllegalArgumentException e = new IllegalArgumentException(
"You must pass an even sized array to the toMap method (size = " + kvs.length + ")");
"You must pass an even sized array to the toMap method (size = " + kvs.length + ")");
Debug.logInfo(e, MODULE);
throw e;
}
Map<K, V> map = constructor.get();
for (int i = 0; i < kvs.length;) {
for (int i = 0; i < kvs.length; ) {
map.put((K) kvs[i++], (V) kvs[i++]);
}
return map;
@@ -147,7 +148,7 @@ public final class UtilMisc {
public static <K, V> String printMap(Map<? extends K, ? extends V> theMap) {
StringBuilder theBuf = new StringBuilder();
for (Map.Entry<? extends K, ? extends V> entry: theMap.entrySet()) {
for (Map.Entry<? extends K, ? extends V> entry : theMap.entrySet()) {
theBuf.append(entry.getKey());
theBuf.append(" --> ");
theBuf.append(entry.getValue());
@@ -182,7 +183,7 @@ 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<>();
for (Map.Entry<String, V> mapEntry: map.entrySet()) {
for (Map.Entry<String, V> mapEntry : map.entrySet()) {
Object entryValue = mapEntry.getValue();
if (entryValue != null && !(entryValue instanceof Serializable)) {
keysToRemove.add(mapEntry.getKey());
@@ -192,13 +193,16 @@ public final class UtilMisc {
}
}
for (String keyToRemove: keysToRemove) { map.remove(keyToRemove); }
for (String keyToRemove : keysToRemove) {
map.remove(keyToRemove);
}
}
/**
* Sort a List of Maps by specified consistent keys.
*
* @param listOfMaps List of Map objects to sort.
* @param sortKeys List of Map keys to sort by.
* @param sortKeys List of Map keys to sort by.
* @return a new List of sorted Maps.
*/
public static List<Map<Object, Object>> sortMaps(List<Map<Object, Object>> listOfMaps, List<? extends String> sortKeys) {
@@ -310,6 +314,7 @@ public final class UtilMisc {
/**
* Create a set from the passed objects.
*
* @param data
* @return theSet
*/
@@ -342,7 +347,7 @@ public final class UtilMisc {
return null;
}
Set<T> set = new LinkedHashSet<>();
for (T value: data) {
for (T value : data) {
set.add(value);
}
return set;
@@ -350,6 +355,7 @@ public final class UtilMisc {
/**
* Creates a list from passed objects.
*
* @param data
* @return list
*/
@@ -373,7 +379,7 @@ public final class UtilMisc {
return null;
}
List<T> list = new LinkedList<>();
for (T value: data) {
for (T value : data) {
list.add(value);
}
return list;
@@ -406,8 +412,10 @@ public final class UtilMisc {
theSet.add(element);
}
/** Converts an <code>Object</code> to a <code>double</code>. Returns
/**
* Converts an <code>Object</code> to a <code>double</code>. Returns
* zero if conversion is not possible.
*
* @param obj Object to convert
* @return double value
*/
@@ -416,8 +424,10 @@ public final class UtilMisc {
return result == null ? 0.0 : result;
}
/** Converts an <code>Object</code> to a <code>Double</code>. Returns
/**
* Converts an <code>Object</code> to a <code>Double</code>. Returns
* <code>null</code> if conversion is not possible.
*
* @param obj Object to convert
* @return Double
*/
@@ -441,8 +451,10 @@ public final class UtilMisc {
return result;
}
/** Converts an <code>Object</code> to an <code>int</code>. Returns
/**
* Converts an <code>Object</code> to an <code>int</code>. Returns
* zero if conversion is not possible.
*
* @param obj Object to convert
* @return int value
*/
@@ -451,8 +463,10 @@ public final class UtilMisc {
return result == null ? 0 : result;
}
/** Converts an <code>Object</code> to an <code>Integer</code>. Returns
/**
* Converts an <code>Object</code> to an <code>Integer</code>. Returns
* <code>null</code> if conversion is not possible.
*
* @param obj Object to convert
* @return Integer
*/
@@ -476,8 +490,10 @@ public final class UtilMisc {
return result;
}
/** Converts an <code>Object</code> to a <code>long</code>. Returns
/**
* Converts an <code>Object</code> to a <code>long</code>. Returns
* zero if conversion is not possible.
*
* @param obj Object to convert
* @return long value
*/
@@ -486,8 +502,10 @@ public final class UtilMisc {
return result == null ? 0 : result;
}
/** Converts an <code>Object</code> to a <code>Long</code>. Returns
/**
* Converts an <code>Object</code> to a <code>Long</code>. Returns
* <code>null</code> if conversion is not possible.
*
* @param obj Object to convert
* @return Long
*/
@@ -513,6 +531,7 @@ public final class UtilMisc {
/**
* Adds value to the key entry in theMap, or creates a new one if not already there
*
* @param theMap
* @param key
* @param value
@@ -528,6 +547,7 @@ public final class UtilMisc {
/**
* Parse a locale string Locale object
*
* @param localeString The locale string (en_US)
* @return Locale The new Locale object or null if no valid locale can be interpreted
*/
@@ -552,19 +572,22 @@ public final class UtilMisc {
String extension = localeString.substring(6);
locale = new Locale(language, country, extension);
} else {
Debug.logWarning("Do not know what to do with the localeString [" + localeString + "], should be length 2, 5, or greater than 6, returning null", MODULE);
Debug.logWarning("Do not know what to do with the localeString [" + localeString + "], should be length 2, 5, or greater than 6, " +
"returning null", MODULE);
}
return locale;
}
/** The input can be a String, Locale, or even null and a valid Locale will always be returned; if nothing else works, returns the default locale.
/**
* The input can be a String, Locale, or even null and a valid Locale will always be returned; if nothing else works, returns the default locale.
*
* @param localeObject An Object representing the locale
*/
public static Locale ensureLocale(Object localeObject) {
if (localeObject instanceof String) {
Locale locale = parseLocale((String) localeObject);
if (locale != null) {
if (locale != null) {
return locale;
}
} else if (localeObject instanceof Locale) {
@@ -573,39 +596,17 @@ public final class UtilMisc {
return Locale.getDefault();
}
// Private lazy-initializer class
private static class LocaleHolder {
private static final List<Locale> availableLocaleList = getAvailableLocaleList();
private static List<Locale> getAvailableLocaleList() {
TreeMap<String, Locale> localeMap = new TreeMap<>();
String localesString = UtilProperties.getPropertyValue("general", "locales.available");
if (UtilValidate.isNotEmpty(localesString)) {
List<String> idList = StringUtil.split(localesString, ",");
for (String id : idList) {
Locale curLocale = parseLocale(id);
localeMap.put(curLocale.getDisplayName(), curLocale);
}
} else {
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < locales.length && locales[i] != null; i++) {
String displayName = locales[i].getDisplayName();
if (!displayName.isEmpty()) {
localeMap.put(displayName, locales[i]);
}
}
}
return Collections.unmodifiableList(new ArrayList<>(localeMap.values()));
}
}
/** Returns a List of available locales sorted by display name */
/**
* Returns a List of available locales sorted by display name
*/
public static List<Locale> availableLocales() {
return LocaleHolder.availableLocaleList;
return LocaleHolder.AVAIL_LOCALE_LIST;
}
/** List of domains or IP addresses to be checked to prevent Host Header Injection,
/**
* List of domains or IP addresses to be checked to prevent Host Header Injection,
* no spaces after commas, no wildcard, can be extended of course...
*
* @return List of domains or IP addresses to be checked to prevent Host Header Injection,
*/
public static List<String> getHostHeadersAllowed() {
@@ -617,7 +618,9 @@ public final class UtilMisc {
return Collections.unmodifiableList(hostHeadersAllowed);
}
/** @deprecated use Thread.sleep() */
/**
* @deprecated use Thread.sleep()
*/
@Deprecated
public static void staticWait(long timeout) throws InterruptedException {
Thread.sleep(timeout);
@@ -627,10 +630,8 @@ public final class UtilMisc {
if (sourceLocation.isDirectory()) {
throw new IOException("File is a directory, not a file, cannot copy");
}
try (
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
) {
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;
@@ -674,4 +675,30 @@ public final class UtilMisc {
return result;
}
// Private lazy-initializer class
private static class LocaleHolder {
private static final List<Locale> AVAIL_LOCALE_LIST = getAvailableLocaleList();
private static List<Locale> getAvailableLocaleList() {
TreeMap<String, Locale> localeMap = new TreeMap<>();
String localesString = UtilProperties.getPropertyValue("general", "locales.available");
if (UtilValidate.isNotEmpty(localesString)) {
List<String> idList = StringUtil.split(localesString, ",");
for (String id : idList) {
Locale curLocale = parseLocale(id);
localeMap.put(curLocale.getDisplayName(), curLocale);
}
} else {
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < locales.length && locales[i] != null; i++) {
String displayName = locales[i].getDisplayName();
if (!displayName.isEmpty()) {
localeMap.put(displayName, locales[i]);
}
}
}
return Collections.unmodifiableList(new ArrayList<>(localeMap.values()));
}
}
}
@@ -219,7 +219,7 @@ public final class UtilNumber {
* @deprecated Use {@link #getRoundingMode(String, String)} instead
*/
@Deprecated
public static int getBigDecimalRoundingMode(String file, String property) {
public static int getBigDecimalRoundingMode(String file, String property) {
return getRoundingMode(file, property).ordinal();
}
@@ -89,7 +89,7 @@ public class UtilTimer {
* @param MODULE The debug/log MODULE/thread to use, can be null for root MODULE
* @return A String with the timing information, the timer String
*/
public String timerString(String message, String MODULE) {
public String timerString(String message, String module) {
// time this call to avoid it interfering with the main timer
long tsStart = System.currentTimeMillis();
@@ -108,7 +108,7 @@ public class UtilTimer {
lastMessage = message;
String retString = retBuf.toString();
if (log) {
Debug.log(Debug.TIMING, null, retString, MODULE, "org.apache.ofbiz.base.util.UtilTimer");
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
@@ -222,17 +222,17 @@ public class UtilTimer {
return timer;
}
public static void timerLog(String timerName, String message, String MODULE) {
public static void timerLog(String timerName, String message, String module) {
UtilTimer timer = UtilTimer.getTimer(timerName);
if (!timer.isRunning()) {
timer.startTimer();
}
if (timer.getLog()) {
if (MODULE == null) {
MODULE = timer.getClass().getName();
if (module == null) {
module = timer.getClass().getName();
}
timer.timerString(message, MODULE);
timer.timerString(message, module);
}
}
@@ -244,9 +244,9 @@ public class UtilTimer {
UtilTimer.closeTimer(timerName, message, null);
}
public static void closeTimer(String timerName, String message, String MODULE) {
public static void closeTimer(String timerName, String message, String module) {
if (message != null) {
UtilTimer.timerLog(timerName, message, MODULE);
UtilTimer.timerLog(timerName, message, module);
}
staticTimers.remove(timerName);
}
@@ -169,7 +169,7 @@ public final class UtilURL {
String path = fileUrl.getPath();
if (path.startsWith(ofbizHome)) {
// note: the +1 is to remove the leading slash
path = path.substring(ofbizHome.length()+1);
path = path.substring(ofbizHome.length() + 1);
}
return path;
}
@@ -1097,14 +1097,14 @@ public final class UtilValidate {
String first6digs = cc.substring(0, 6);
if (((cc.length() == 16) || (cc.length() == 18) || (cc.length() == 19))
&& ("4903".equals(first4digs)
|| "4905".equals(first4digs)
|| "4911".equals(first4digs)
|| "4936".equals(first4digs)
|| "564182".equals(first6digs)
|| "633110".equals(first6digs)
|| "6333".equals(first4digs)
|| "6759".equals(first4digs))) {
&& ("4903".equals(first4digs)
|| "4905".equals(first4digs)
|| "4911".equals(first4digs)
|| "4936".equals(first4digs)
|| "564182".equals(first6digs)
|| "633110".equals(first6digs)
|| "6333".equals(first4digs)
|| "6759".equals(first4digs))) {
return isCreditCard(cc);
}
return false;
@@ -1117,8 +1117,7 @@ public final class UtilValidate {
private static boolean isSolo(String cc) {
String first4digs = cc.substring(0, 4);
String first2digs = cc.substring(0, 2);
if (((cc.length() == 16) || (cc.length() == 18) || (cc.length() == 19)) &&
("63".equals(first2digs) || "6767".equals(first4digs))) {
if (((cc.length() == 16) || (cc.length() == 18) || (cc.length() == 19)) && ("63".equals(first2digs) || "6767".equals(first4digs))) {
return isCreditCard(cc);
}
return false;
@@ -1241,7 +1240,7 @@ public final class UtilValidate {
if (("CCT_SOLO".equalsIgnoreCase(cardType)) && (isSolo(cardNumber))) {
return true;
}
if (("CCT_SWITCH".equalsIgnoreCase(cardType)) && (isSwitch (cardNumber))) {
if (("CCT_SWITCH".equalsIgnoreCase(cardType)) && (isSwitch(cardNumber))) {
return true;
}
if (("CCT_VISAELECTRON".equalsIgnoreCase(cardType)) && (isVisaElectron(cardNumber))) {
@@ -81,7 +81,7 @@ import com.thoughtworks.xstream.XStream;
public final class UtilXml {
private static final String MODULE = UtilXml.class.getName();
private static final XStream xstream = createXStream();
private static final XStream X_STREAM = createXStream();
private UtilXml() { }
private static XStream createXStream() {
@@ -255,7 +255,7 @@ public final class UtilXml {
* @return The deserialized <code>Object</code>
*/
public static Object fromXml(InputStream input) {
return xstream.fromXML(input);
return X_STREAM.fromXML(input);
}
/** Deserialize an object from a <code>Reader</code>.
@@ -264,7 +264,7 @@ public final class UtilXml {
* @return The deserialized <code>Object</code>
*/
public static Object fromXml(Reader reader) {
return xstream.fromXML(reader);
return X_STREAM.fromXML(reader);
}
/** Deserialize an object from a <code>String</code>.
@@ -273,7 +273,7 @@ public final class UtilXml {
* @return The deserialized <code>Object</code>
*/
public static Object fromXml(String str) {
return xstream.fromXML(str);
return X_STREAM.fromXML(str);
}
/** Serialize an object to an XML <code>String</code>.
@@ -282,7 +282,7 @@ public final class UtilXml {
* @return An XML <code>String</code>
*/
public static String toXml(Object obj) {
return xstream.toXML(obj);
return X_STREAM.toXML(obj);
}
/** Serialize an object to an <code>OutputStream</code>.
@@ -291,7 +291,7 @@ public final class UtilXml {
* @param output The <code>OutputStream</code>
*/
public static void toXml(Object obj, OutputStream output) {
xstream.toXML(obj, output);
X_STREAM.toXML(obj, output);
}
/** Serialize an object to a <code>Writer</code>.
@@ -300,7 +300,7 @@ public final class UtilXml {
* @param writer The <code>Writer</code>
*/
public static void toXml(Object obj, Writer writer) {
xstream.toXML(obj, writer);
X_STREAM.toXML(obj, writer);
}
// ------------------------------------------------- //
@@ -1045,8 +1045,8 @@ public final class UtilXml {
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);
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);
@@ -1059,8 +1059,8 @@ 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);
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) {
@@ -1087,13 +1087,13 @@ public final class UtilXml {
}
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);
Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD/Schema input source with publicId ["
+ publicId + "] and the file/resource is [" + filename + "]", MODULE);
}
return inputSource;
}
Debug.logWarning("[UtilXml.LocalResolver.resolveEntity] could not find LOCAL DTD/Schema with publicId [" +
publicId + "] and the file/resource is [" + filename + "]", MODULE);
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);
@@ -1129,12 +1129,11 @@ public final class UtilXml {
Matcher matcher = valueFlexExpr.matcher(exceptionMessage.toLowerCase());
if (localResolver.hasDTD() && !matcher.find()) {
Debug.logError("XmlFileLoader: File "
+ docDescription
+ " process error. Line: "
+ String.valueOf(exception.getLineNumber())
+ ". Error message: "
+ exceptionMessage, MODULE
);
+ docDescription
+ " process error. Line: "
+ String.valueOf(exception.getLineNumber())
+ ". Error message: "
+ exceptionMessage, MODULE);
}
}
@@ -1142,12 +1141,11 @@ public final class UtilXml {
public void fatalError(SAXParseException exception) {
if (localResolver.hasDTD()) {
Debug.logError("XmlFileLoader: File "
+ docDescription
+ " process fatal error. Line: "
+ String.valueOf(exception.getLineNumber())
+ ". Error message: "
+ exception.getMessage(), MODULE
);
+ docDescription
+ " process fatal error. Line: "
+ String.valueOf(exception.getLineNumber())
+ ". Error message: "
+ exception.getMessage(), MODULE);
}
}
@@ -1155,12 +1153,11 @@ public final class UtilXml {
public void warning(SAXParseException exception) {
if (localResolver.hasDTD()) {
Debug.logError("XmlFileLoader: File "
+ docDescription
+ " process warning. Line: "
+ String.valueOf(exception.getLineNumber())
+ ". Error message: "
+ exception.getMessage(), MODULE
);
+ docDescription
+ " process warning. Line: "
+ String.valueOf(exception.getLineNumber())
+ ". Error message: "
+ exception.getMessage(), MODULE);
}
}
}
@@ -463,7 +463,7 @@ public class UtilCache<K, V> implements Serializable, EvictionListener<Object, C
/** Removes all elements from this cache */
public static void clearAllCaches() {
// We make a copy since clear may take time
for (UtilCache<?,?> cache : utilCacheTable.values()) {
for (UtilCache<?, ?> cache : utilCacheTable.values()) {
cache.clear();
}
}
@@ -74,7 +74,7 @@ public class FlexibleServletAccessor<T> implements Serializable {
int dotIndex = name.indexOf('.');
if (dotIndex != -1) {
attributeName = name.substring(0, dotIndex);
fma = FlexibleMapAccessor.getInstance(name.substring(dotIndex+1));
fma = FlexibleMapAccessor.getInstance(name.substring(dotIndex + 1));
} else {
attributeName = name;
fma = null;
@@ -215,7 +215,7 @@ public class FlexibleServletAccessor<T> implements Serializable {
int dotIndex = name.indexOf('.');
if (dotIndex != -1) {
attributeName = name.substring(0, dotIndex);
fma = FlexibleMapAccessor.getInstance(name.substring(dotIndex+1));
fma = FlexibleMapAccessor.getInstance(name.substring(dotIndex + 1));
} else {
attributeName = name;
fma = null;
@@ -229,7 +229,7 @@ public class FlexibleServletAccessor<T> implements Serializable {
openBrace = attributeName.indexOf('[');
closeBrace = (openBrace == -1 ? -1 : attributeName.indexOf(']', openBrace));
if (openBrace != -1 && closeBrace != -1) {
String liStr = attributeName.substring(openBrace+1, closeBrace);
String liStr = attributeName.substring(openBrace + 1, closeBrace);
//if brackets are empty, append to list
if (liStr.length() == 0) {
isAddAtEnd = true;
@@ -452,8 +452,7 @@ public class UelFunctions {
} else {
Debug.logError("Unable to locate XML document " + str, MODULE);
}
}
catch (IOException e) {
} catch (IOException e) {
Debug.logError(e, "Error while reading XML document " + str, MODULE);
}
return document;
@@ -483,7 +483,7 @@ public final class UelUtil {
int closeBrace = (openBrace == -1 ? -1 : result.indexOf(']', openBrace));
if (closeBrace != -1) {
String base = result.substring(0, openBrace);
String property = result.substring(openBrace+2, closeBrace).trim();
String property = result.substring(openBrace + 2, closeBrace).trim();
String end = result.substring(closeBrace + 1);
result = base + "['insert@" + property + "']" + end;
}
@@ -129,18 +129,18 @@ public final class FreeMarkerWorker {
String templateClassResolver = UtilProperties.getPropertyValue("security", "templateClassResolver",
"SAFER_RESOLVER");
switch (templateClassResolver) {
case "UNRESTRICTED_RESOLVER":
newConfig.setNewBuiltinClassResolver(TemplateClassResolver.UNRESTRICTED_RESOLVER);
break;
case "SAFER_RESOLVER":
newConfig.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
break;
case "ALLOWS_NOTHING_RESOLVER":
newConfig.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
break;
default:
Debug.logError("Not a TemplateClassResolver.", MODULE);
break;
case "UNRESTRICTED_RESOLVER":
newConfig.setNewBuiltinClassResolver(TemplateClassResolver.UNRESTRICTED_RESOLVER);
break;
case "SAFER_RESOLVER":
newConfig.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
break;
case "ALLOWS_NOTHING_RESOLVER":
newConfig.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
break;
default:
Debug.logError("Not a TemplateClassResolver.", MODULE);
break;
}
// Transforms properties file set up as key=transform name, property=transform class name
ClassLoader loader = Thread.currentThread().getContextClassLoader();
@@ -147,15 +147,13 @@ public final class CommonWorkers {
EntityCondition stateProvinceFindCond = EntityCondition.makeCondition(
EntityCondition.makeCondition("geoIdFrom", country),
EntityCondition.makeCondition("geoAssocTypeId", "REGIONS"),
EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("geoTypeId", "STATE"), EntityCondition.makeCondition("geoTypeId", "PROVINCE"), EntityCondition.makeCondition("geoTypeId", "MUNICIPALITY"),
EntityCondition.makeCondition("geoTypeId", "TERRITORY"), EntityCondition.makeCondition("geoTypeId", "COUNTY")));
EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("geoTypeId", "STATE"), EntityCondition.makeCondition("geoTypeId", "PROVINCE"), EntityCondition.makeCondition("geoTypeId", "MUNICIPALITY"), EntityCondition.makeCondition("geoTypeId", "TERRITORY"), EntityCondition.makeCondition("geoTypeId", "COUNTY")));
geoList.addAll(EntityQuery.use(delegator)
.from("GeoAssocAndGeoToWithState")
.where(stateProvinceFindCond)
.orderBy(sortList)
.cache(true)
.queryList()
);
.queryList());
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot lookup Geo", MODULE);
}
@@ -222,8 +222,7 @@ public class JsLanguageFileMappingCreator {
// write it as a Java file
File file = new File(output);
FileUtils.writeStringToFile(file, writer.toString(), encoding);
}
catch (IOException | TemplateException e) {
} catch (IOException | TemplateException e) {
Debug.logError(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage("CommonUiLabels", "CommonOutputFileCouldNotBeCreated", UtilMisc.toMap("errorString", e.getMessage()), (Locale) context.get("locale")));
}
@@ -161,7 +161,7 @@ public final class KeywordSearchUtil {
// replace all %% with %
int dblPercIdx = -1;
while ((dblPercIdx = strSb.indexOf("%%")) >= 0) {
strSb.replace(dblPercIdx, dblPercIdx+2, "%");
strSb.replace(dblPercIdx, dblPercIdx + 2, "%");
}
token = strSb.toString();
}
@@ -87,7 +87,7 @@ public class PreferenceServices {
}
} catch (GeneralException e) {
Debug.logWarning(e.getMessage(), MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "getPreference.readFailure", new Object[] { e.getMessage() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "getPreference.readFailure", new Object[] {e.getMessage() }, locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
@@ -134,7 +134,7 @@ public class PreferenceServices {
}
} catch (GeneralException e) {
Debug.logWarning(e.getMessage(), MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "getPreference.readFailure", new Object[] { e.getMessage() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "getPreference.readFailure", new Object[] {e.getMessage() }, locale));
}
// for the 'DEFAULT' values find the related values in general properties and if found use those.
Properties generalProperties = UtilProperties.getProperties("general");
@@ -181,7 +181,7 @@ public class PreferenceServices {
delegator.createOrStore(rec);
} catch (GeneralException e) {
Debug.logWarning(e.getMessage(), MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "setPreference.writeFailure", new Object[] {e.getMessage() }, locale));
}
return ServiceUtil.returnSuccess();
@@ -207,7 +207,7 @@ public class PreferenceServices {
}
} catch (GenericEntityException e) {
Debug.logWarning(e.getMessage(), MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "setPreference.writeFailure", new Object[] {e.getMessage() }, locale));
}
return ServiceUtil.returnSuccess();
@@ -240,7 +240,7 @@ public class PreferenceServices {
}
} catch (GeneralException e) {
Debug.logWarning(e.getMessage(), MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "setPreference.writeFailure", new Object[] {e.getMessage() }, locale));
}
return ServiceUtil.returnSuccess();
@@ -279,7 +279,7 @@ public class PreferenceServices {
}
} catch (GenericEntityException e) {
Debug.logWarning(e.getMessage(), MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "copyPreference.writeFailure", new Object[] { e.getMessage() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "copyPreference.writeFailure", new Object[] {e.getMessage() }, locale));
}
return ServiceUtil.returnSuccess();
@@ -143,7 +143,7 @@ public class QRCodeEvents {
return "error";
}
} catch (IOException | GenericServiceException e) {
String errMsg = UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] { e.getMessage() }, locale);
String errMsg = UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] {e.getMessage() }, locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
@@ -205,9 +205,9 @@ public class QRCodeServices {
result.put("bufferedImage", bufferedImage);
return result;
} catch (WriterException e) {
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] { e.toString() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] {e.toString() }, locale));
} catch (ChecksumException | FormatException | NotFoundException e) {
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] { e.toString() }, locale));
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] {e.toString() }, locale));
}
}
@@ -44,12 +44,12 @@ public class PerformFindTests extends OFBizTestCase {
private static List<GenericValue> getCompleteList(Map<String, Object> context) {
List<GenericValue> foundElements = new LinkedList<>();
try (EntityListIterator listIt = (EntityListIterator) context.get("listIt")) {
if (listIt != null) {
foundElements = listIt.getCompleteList();
}
} catch (GenericEntityException e) {
Debug.logError(" Failed to extract values from EntityListIterator after a performFind service", MODULE);
try (EntityListIterator listIt = (EntityListIterator) context.get("listIt")) {
if (listIt != null) {
foundElements = listIt.getCompleteList();
}
} catch (GenericEntityException e) {
Debug.logError(" Failed to extract values from EntityListIterator after a performFind service", MODULE);
}
return foundElements;
}
@@ -104,11 +104,11 @@ public class PerformFindTests extends OFBizTestCase {
* @throws Exception
*/
public void testPerformFind() throws Exception {
performFindConditionFieldEquals();
performFindConditionFieldLike();
performFindConditionDistinct();
performFindFilterByDate();
performFindFilterByDateWithDedicateDateField();
performFindConditionFieldEquals();
performFindConditionFieldLike();
performFindConditionDistinct();
performFindFilterByDate();
performFindFilterByDateWithDedicateDateField();
}
private void performFindConditionFieldEquals() throws Exception {
@@ -42,29 +42,29 @@ public class UomWorker {
public static int[] uomTimeToCalTime(String uomId) {
if ("TF_ms".equals(uomId)) {
return new int[] { Calendar.MILLISECOND, 1 };
return new int[] {Calendar.MILLISECOND, 1 };
} else if ("TF_s".equals(uomId)) {
return new int[] { Calendar.SECOND, 1 };
return new int[] {Calendar.SECOND, 1 };
} else if ("TF_min".equals(uomId)) {
return new int[] { Calendar.MINUTE, 1 };
return new int[] {Calendar.MINUTE, 1 };
} else if ("TF_hr".equals(uomId)) {
return new int[] { Calendar.HOUR, 1 };
return new int[] {Calendar.HOUR, 1 };
} else if ("TF_day".equals(uomId)) {
return new int[] { Calendar.DAY_OF_YEAR, 1 };
return new int[] {Calendar.DAY_OF_YEAR, 1 };
} else if ("TF_wk".equals(uomId)) {
return new int[] { Calendar.WEEK_OF_YEAR, 1 };
return new int[] {Calendar.WEEK_OF_YEAR, 1 };
} else if ("TF_mon".equals(uomId)) {
return new int[] { Calendar.MONTH, 1 };
return new int[] {Calendar.MONTH, 1 };
} else if ("TF_yr".equals(uomId)) {
return new int[] { Calendar.YEAR, 1 };
return new int[] {Calendar.YEAR, 1 };
} else if ("TF_decade".equals(uomId)) {
return new int[] { Calendar.YEAR, 10 };
return new int[] {Calendar.YEAR, 10 };
} else if ("TF_score".equals(uomId)) {
return new int[] { Calendar.YEAR, 20 };
return new int[] {Calendar.YEAR, 20 };
} else if ("TF_century".equals(uomId)) {
return new int[] { Calendar.YEAR, 100 };
return new int[] {Calendar.YEAR, 100 };
} else if ("TF_millenium".equals(uomId)) {
return new int[] { Calendar.YEAR, 1000 };
return new int[] {Calendar.YEAR, 1000 };
}
return null;
@@ -183,8 +183,7 @@ public class DataFile {
try (FileOutputStream fos = new FileOutputStream(outFile);) {
writeDataFile(fos);
}
catch (IOException e) {
} catch (IOException e) {
throw new DataFileException("Error occured while writing data to file" + filename, e);
}
}
@@ -199,8 +198,7 @@ public class DataFile {
writeDataFile(bos);
outString = bos.toString("UTF-8");
}
catch (IOException e) {
} catch (IOException e) {
Debug.logWarning(e, MODULE);
}
return outString;
@@ -83,8 +83,7 @@ public class DataFile2EntityXml {
outFile.newLine();
}
outFile.write("</entity-engine-xml>");
}
catch (IOException e) {
} catch (IOException e) {
throw new DataFileException("Error writing to file " + fileName, e);
}
@@ -127,8 +126,7 @@ public class DataFile2EntityXml {
outFile.newLine();
}
}
}
catch (IOException e) {
} catch (IOException e) {
Debug.logError(e, MODULE);
}
}
@@ -54,8 +54,7 @@ public class RecordIterator {
InputStream urlStream = null;
try {
urlStream = fileUrl.openStream();
}
catch (IOException e) {
} catch (IOException e) {
throw new DataFileException("Error open URL: " + fileUrl.toString(), e);
}
this.setupStream(urlStream, fileUrl.toString());
@@ -72,8 +71,7 @@ public class RecordIterator {
String charsetStr = modelDataFile.getEncodingType();
try {
this.br = new BufferedReader(new InputStreamReader(dataFileStream, Charset.forName(charsetStr)));
}
catch (Exception e) {
} catch (Exception e) {
throw new DataFileException(charsetStr + " is not supported");
}
//move the cursor to the good start line
@@ -211,8 +209,7 @@ public class RecordIterator {
try {
this.br.close(); // this should also close the stream
this.closed = true;
}
catch (IOException e) {
} catch (IOException e) {
throw new DataFileException("Error closing data file input stream", e);
}
}
@@ -820,25 +820,25 @@ public class GenericEntity implements Map<String, Object>, LocalizedMap<Object>,
ModelEntity modelEntityToUse = this.getModelEntity();
Object resourceValue = get(this.getModelEntity(), modelEntityToUse, name, resource, locale);
if (resourceValue == null) {
if (modelEntityToUse instanceof ModelViewEntity) {
// now try to retrieve with the field heading from the real entity linked to the view
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntityToUse;
Iterator<ModelAlias> it = modelViewEntity.getAliasesIterator();
while (it.hasNext()) {
ModelAlias modelAlias = it.next();
if (modelAlias.getName().equalsIgnoreCase(name)) {
modelEntityToUse = modelViewEntity.getMemberModelEntity(modelAlias.getEntityAlias());
name = modelAlias.getField();
break;
}
}
resourceValue = get(this.getModelEntity(), modelEntityToUse, name, resource, locale);
if (resourceValue == null) {
return fieldValue;
}
return resourceValue;
}
return fieldValue;
if (modelEntityToUse instanceof ModelViewEntity) {
// now try to retrieve with the field heading from the real entity linked to the view
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntityToUse;
Iterator<ModelAlias> it = modelViewEntity.getAliasesIterator();
while (it.hasNext()) {
ModelAlias modelAlias = it.next();
if (modelAlias.getName().equalsIgnoreCase(name)) {
modelEntityToUse = modelViewEntity.getMemberModelEntity(modelAlias.getEntityAlias());
name = modelAlias.getField();
break;
}
}
resourceValue = get(this.getModelEntity(), modelEntityToUse, name, resource, locale);
if (resourceValue == null) {
return fieldValue;
}
return resourceValue;
}
return fieldValue;
}
return resourceValue;
}
@@ -1217,19 +1217,19 @@ public class GenericEntity implements Map<String, Object>, LocalizedMap<Object>,
switch (curChar) {
case '\'':
value.replace(i, i+1, "&apos;");
value.replace(i, i + 1, "&apos;");
break;
case '"':
value.replace(i, i+1, "&quot;");
value.replace(i, i + 1, "&quot;");
break;
case '&':
value.replace(i, i+1, "&amp;");
value.replace(i, i + 1, "&amp;");
break;
case '<':
value.replace(i, i+1, "&lt;");
value.replace(i, i + 1, "&lt;");
break;
case '>':
value.replace(i, i+1, "&gt;");
value.replace(i, i + 1, "&gt;");
break;
case 0xA: // newline, \n
needsCdata = true;
@@ -1241,25 +1241,25 @@ public class GenericEntity implements Map<String, Object>, LocalizedMap<Object>,
// do nothing, just catch here so it doesn't get into the default
break;
case 0x5: // elipses (...)
value.replace(i, i+1, "...");
value.replace(i, i + 1, "...");
break;
case 0x12: // apostrophe
value.replace(i, i+1, "&apos;");
value.replace(i, i + 1, "&apos;");
break;
case 0x13: // left quote
value.replace(i, i+1, "&quot;");
value.replace(i, i + 1, "&quot;");
break;
case 0x14: // right quote
value.replace(i, i+1, "&quot;");
value.replace(i, i + 1, "&quot;");
break;
case 0x16: // big(?) dash -
value.replace(i, i+1, "-");
value.replace(i, i + 1, "-");
break;
case 0x17: // dash -
value.replace(i, i+1, "-");
value.replace(i, i + 1, "-");
break;
case 0x19: // tm
value.replace(i, i+1, "tm");
value.replace(i, i + 1, "tm");
break;
default:
if (curChar < 0x20) {
@@ -1272,7 +1272,7 @@ public class GenericEntity implements Map<String, Object>, LocalizedMap<Object>,
if (Debug.verboseOn()) {
Debug.logVerbose("Entity: " + this.getEntityName() + ", PK: " + this.getPrimaryKey().toString() + " -> char [" + curChar + "] replaced with [" + replacement + "]", MODULE);
}
value.replace(i, i+1, replacement);
value.replace(i, i + 1, replacement);
}
}
}
@@ -37,8 +37,8 @@ public class EntityClause {
private String secondField = "";
private ModelEntity firstModelEntity = null;
private ModelEntity secondModelEntity = null;
private EntityOperator<?,?> interFieldOperation = null;
private EntityOperator<?,?> intraFieldOperation = null;
private EntityOperator<?, ?> interFieldOperation = null;
private EntityOperator<?, ?> intraFieldOperation = null;
private Object value = null;
public EntityClause() { }
@@ -69,7 +69,7 @@ public final class EntityFieldMap extends EntityConditionListBase<EntityExpr> {
* @param <V> The type of values that are compared.
*/
@SafeVarargs
public <V> EntityFieldMap(EntityComparisonOperator<?,?> compOp, EntityJoinOperator joinOp, V... keysValues) {
public <V> EntityFieldMap(EntityComparisonOperator<?, ?> compOp, EntityJoinOperator joinOp, V... keysValues) {
this(EntityUtil.makeFields(keysValues), UtilGenerics.cast(compOp), joinOp);
}
@@ -81,7 +81,7 @@ public final class EntityFieldMap extends EntityConditionListBase<EntityExpr> {
* @param joinOp the operator to join entries in the field map
* @param <V> the type of values contained in {@code fieldMap}
*/
public <V> EntityFieldMap(Map<String, V> fieldMap, EntityComparisonOperator<?,?> compOp,
public <V> EntityFieldMap(Map<String, V> fieldMap, EntityComparisonOperator<?, ?> compOp,
EntityJoinOperator joinOp) {
super(makeConditionList(fieldMap, UtilGenerics.cast(compOp)), joinOp);
this.fieldMap = (fieldMap == null) ? Collections.emptyMap() : fieldMap;
@@ -59,7 +59,7 @@ public abstract class EntityOperator<L, R> implements Serializable {
public static final int ID_NOT_IN = 13;
public static final int ID_NOT_LIKE = 14;
private static HashMap<String, EntityOperator<?,?>> registry = new HashMap<>();
private static HashMap<String, EntityOperator<?, ?>> registry = new HashMap<>();
private static <L, R> void registerCase(String name, EntityOperator<L, R> operator) {
registry.put(name.toLowerCase(Locale.getDefault()), operator);
@@ -77,24 +77,25 @@ public abstract class EntityOperator<L, R> implements Serializable {
}
public static <L, R> EntityComparisonOperator<L, R> lookupComparison(String name) {
EntityOperator<?,?> operator = lookup(name);
if (!(operator instanceof EntityComparisonOperator<?,?>)) {
EntityOperator<?, ?> operator = lookup(name);
if (!(operator instanceof EntityComparisonOperator<?, ?>)) {
throw new IllegalArgumentException(name + " is not a comparison operator");
}
return UtilGenerics.cast(operator);
}
public static EntityJoinOperator lookupJoin(String name) {
EntityOperator<?,?> operator = lookup(name);
EntityOperator<?, ?> operator = lookup(name);
if (!(operator instanceof EntityJoinOperator)) {
throw new IllegalArgumentException(name + " is not a join operator");
}
return UtilGenerics.cast(operator);
}
public static final EntityComparisonOperator<?,?> EQUALS = new ComparableEntityComparisonOperator<Object>(ID_EQUALS, "=") {
public static final EntityComparisonOperator<?, ?> EQUALS = new ComparableEntityComparisonOperator<Object>(ID_EQUALS, "=") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareEqual(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return EntityComparisonOperator.compareEqual(lhs, rhs); }
@Override
protected void makeRHSWhereString(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Object rhs, Datasource datasourceInfo) {
if (rhs == null || rhs == GenericEntity.NULL_FIELD) {
@@ -104,11 +105,14 @@ public abstract class EntityOperator<L, R> implements Serializable {
}
}
};
static { register("equals", EQUALS); }
static { register("=", EQUALS); }
public static final EntityComparisonOperator<?,?> NOT_EQUAL = new ComparableEntityComparisonOperator<Object>(ID_NOT_EQUAL, "<>") {
static {
register("equals", EQUALS); }
static {
register("=", EQUALS); }
public static final EntityComparisonOperator<?, ?> NOT_EQUAL = new ComparableEntityComparisonOperator<Object>(ID_NOT_EQUAL, "<>") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareNotEqual(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return EntityComparisonOperator.compareNotEqual(lhs, rhs); }
@Override
protected void makeRHSWhereString(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Object rhs, Datasource datasourceInfo) {
if (rhs == null || rhs == GenericEntity.NULL_FIELD) {
@@ -118,83 +122,126 @@ public abstract class EntityOperator<L, R> implements Serializable {
}
}
};
static { register("not-equal", NOT_EQUAL); }
static { register("not-equals", NOT_EQUAL); }
static { register("notEqual", NOT_EQUAL); }
static { register("!=", NOT_EQUAL); }
static { register("<>", NOT_EQUAL); }
public static final EntityComparisonOperator<?,?> LESS_THAN = new ComparableEntityComparisonOperator<Object>(ID_LESS_THAN, "<") {
static {
register("not-equal", NOT_EQUAL); }
static {
register("not-equals", NOT_EQUAL); }
static {
register("notEqual", NOT_EQUAL); }
static {
register("!=", NOT_EQUAL); }
static {
register("<>", NOT_EQUAL); }
public static final EntityComparisonOperator<?, ?> LESS_THAN = new ComparableEntityComparisonOperator<Object>(ID_LESS_THAN, "<") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareLessThan(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return EntityComparisonOperator.compareLessThan(lhs, rhs); }
};
static { register("less", LESS_THAN); }
static { register("less-than", LESS_THAN); }
static { register("lessThan", LESS_THAN); }
static { register("<", LESS_THAN); }
public static final EntityComparisonOperator<?,?> GREATER_THAN = new ComparableEntityComparisonOperator<Object>(ID_GREATER_THAN, ">") {
static {
register("less", LESS_THAN); }
static {
register("less-than", LESS_THAN); }
static {
register("lessThan", LESS_THAN); }
static {
register("<", LESS_THAN); }
public static final EntityComparisonOperator<?, ?> GREATER_THAN = new ComparableEntityComparisonOperator<Object>(ID_GREATER_THAN, ">") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareGreaterThan(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return EntityComparisonOperator.compareGreaterThan(lhs, rhs); }
};
static { register("greater", GREATER_THAN); }
static { register("greater-than", GREATER_THAN); }
static { register("greaterThan", GREATER_THAN); }
static { register(">", GREATER_THAN); }
public static final EntityComparisonOperator<?,?> LESS_THAN_EQUAL_TO = new ComparableEntityComparisonOperator<Object>(ID_LESS_THAN_EQUAL_TO, "<=") {
static {
register("greater", GREATER_THAN); }
static {
register("greater-than", GREATER_THAN); }
static {
register("greaterThan", GREATER_THAN); }
static {
register(">", GREATER_THAN); }
public static final EntityComparisonOperator<?, ?> LESS_THAN_EQUAL_TO = new ComparableEntityComparisonOperator<Object>(ID_LESS_THAN_EQUAL_TO, "<=") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareLessThanEqualTo(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return EntityComparisonOperator.compareLessThanEqualTo(lhs, rhs); }
};
static { register("less-equals", LESS_THAN_EQUAL_TO); }
static { register("less-than-equal-to", LESS_THAN_EQUAL_TO); }
static { register("lessThanEqualTo", LESS_THAN_EQUAL_TO); }
static { register("<=", LESS_THAN_EQUAL_TO); }
public static final EntityComparisonOperator<?,?> GREATER_THAN_EQUAL_TO = new ComparableEntityComparisonOperator<Object>(ID_GREATER_THAN_EQUAL_TO, ">=") {
static {
register("less-equals", LESS_THAN_EQUAL_TO); }
static {
register("less-than-equal-to", LESS_THAN_EQUAL_TO); }
static {
register("lessThanEqualTo", LESS_THAN_EQUAL_TO); }
static {
register("<=", LESS_THAN_EQUAL_TO); }
public static final EntityComparisonOperator<?, ?> GREATER_THAN_EQUAL_TO = new ComparableEntityComparisonOperator<Object>(ID_GREATER_THAN_EQUAL_TO, ">=") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareGreaterThanEqualTo(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return EntityComparisonOperator.compareGreaterThanEqualTo(lhs, rhs); }
};
static { register("greater-equals", GREATER_THAN_EQUAL_TO); }
static { register("greater-than-equal-to", GREATER_THAN_EQUAL_TO); }
static { register("greaterThanEqualTo", GREATER_THAN_EQUAL_TO); }
static { register(">=", GREATER_THAN_EQUAL_TO); }
public static final EntityComparisonOperator<?,?> IN = new CollectionEntityComparisonOperator<Object>(ID_IN, "IN") {
static {
register("greater-equals", GREATER_THAN_EQUAL_TO); }
static {
register("greater-than-equal-to", GREATER_THAN_EQUAL_TO); }
static {
register("greaterThanEqualTo", GREATER_THAN_EQUAL_TO); }
static {
register(">=", GREATER_THAN_EQUAL_TO); }
public static final EntityComparisonOperator<?, ?> IN = new CollectionEntityComparisonOperator<Object>(ID_IN, "IN") {
@Override
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) { return EntityComparisonOperator.compareIn(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) {
return EntityComparisonOperator.compareIn(lhs, rhs); }
@Override
protected void makeRHSWhereStringValue(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Collection<Comparable<Object>> rhs, Datasource datasourceInfo) { appendRHSList(entityConditionParams, sb, field, rhs); }
};
static { register("in", IN); }
public static final EntityComparisonOperator<?,?> BETWEEN = new CollectionEntityComparisonOperator<Object>(ID_BETWEEN, "BETWEEN") {
static {
register("in", IN); }
public static final EntityComparisonOperator<?, ?> BETWEEN = new CollectionEntityComparisonOperator<Object>(ID_BETWEEN, "BETWEEN") {
@Override
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) { return EntityComparisonOperator.compareIn(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) {
return EntityComparisonOperator.compareIn(lhs, rhs); }
@Override
protected void makeRHSWhereStringValue(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Collection<Comparable<Object>> rhs, Datasource datasourceInfo) { appendRHSBetweenList(entityConditionParams, sb, field, rhs); }
};
static { register("between", BETWEEN); }
public static final EntityComparisonOperator<?,?> NOT = new EntityComparisonOperator<Object, EntityCondition>(ID_NOT, "NOT") {
static {
register("between", BETWEEN); }
public static final EntityComparisonOperator<?, ?> NOT = new EntityComparisonOperator<Object, EntityCondition>(ID_NOT, "NOT") {
@Override
public boolean compare(Object lhs, EntityCondition rhs) { throw new UnsupportedOperationException(); }
public boolean compare(Object lhs, EntityCondition rhs) {
throw new UnsupportedOperationException(); }
};
static { register("not", NOT); }
static {
register("not", NOT); }
public static final EntityJoinOperator AND = new EntityJoinOperator(ID_AND, "AND", false);
static { register("and", AND); }
static {
register("and", AND); }
public static final EntityJoinOperator OR = new EntityJoinOperator(ID_OR, "OR", true);
static { register("or", OR); }
public static final EntityComparisonOperator<?,?> LIKE = new ComparableEntityComparisonOperator<Object>(ID_LIKE, "LIKE") {
static {
register("or", OR); }
public static final EntityComparisonOperator<?, ?> LIKE = new ComparableEntityComparisonOperator<Object>(ID_LIKE, "LIKE") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareLike(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return EntityComparisonOperator.compareLike(lhs, rhs); }
};
static { register("like", LIKE); }
public static final EntityComparisonOperator<?,?> NOT_LIKE = new ComparableEntityComparisonOperator<Object>(ID_NOT_LIKE, "NOT LIKE") {
static {
register("like", LIKE); }
public static final EntityComparisonOperator<?, ?> NOT_LIKE = new ComparableEntityComparisonOperator<Object>(ID_NOT_LIKE, "NOT LIKE") {
@Override
public boolean compare(Comparable<Object> lhs, Object rhs) { return !EntityComparisonOperator.compareLike(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Object rhs) {
return !EntityComparisonOperator.compareLike(lhs, rhs);
}
};
static { register("not-like", NOT_LIKE); }
public static final EntityComparisonOperator<?,?> NOT_IN = new CollectionEntityComparisonOperator<Object>(ID_NOT_IN, "NOT IN") {
static {
register("not-like", NOT_LIKE);
}
public static final EntityComparisonOperator<?, ?> NOT_IN = new CollectionEntityComparisonOperator<Object>(ID_NOT_IN, "NOT IN") {
@Override
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) { return !EntityComparisonOperator.compareIn(lhs, rhs); }
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) {
return !EntityComparisonOperator.compareIn(lhs, rhs);
}
@Override
protected void makeRHSWhereStringValue(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Collection<Comparable<Object>> rhs, Datasource datasourceInfo) { appendRHSList(entityConditionParams, sb, field, rhs); }
};
static { register("not-in", NOT_IN); }
static {
register("not-in", NOT_IN);
}
protected int idInt;
protected String codeString;
@@ -231,8 +278,8 @@ public abstract class EntityOperator<L, R> implements Serializable {
if (this == obj) {
return true;
}
if (obj instanceof EntityOperator<?,?>) {
EntityOperator<?,?> otherOper = UtilGenerics.cast(obj);
if (obj instanceof EntityOperator<?, ?>) {
EntityOperator<?, ?> otherOper = UtilGenerics.cast(obj);
return this.idInt == otherOper.idInt;
}
return false;
@@ -137,14 +137,14 @@ public class OrderByItem implements Comparator<GenericEntity> {
}
EntityConditionValue value = EntityFieldValue.makeFieldValue(text);
switch (caseSensitivity) {
case UPPER:
value = EntityFunction.UPPER(value);
break;
case LOWER:
value = EntityFunction.LOWER(value);
break;
default:
break;
case UPPER:
value = EntityFunction.UPPER(value);
break;
case LOWER:
value = EntityFunction.LOWER(value);
break;
default:
break;
}
return new OrderByItem(value, descending, nullsFirst);
}
@@ -106,13 +106,14 @@ public class GenericDAO {
ModelEntity modelEntity = entity.getModelEntity();
try (SQLProcessor sqlP = new SQLProcessor(entity.getDelegator(), helperInfo)) {
try {
return singleInsert(entity, modelEntity, modelEntity.getFieldsUnmodifiable(), sqlP);
} catch (GenericEntityException e) {
sqlP.rollback();
// no need to create nested, just throw original which will have all info: throw new GenericEntityException("Exception while inserting the following entity: " + entity.toString(), e);
throw e;
}
try {
return singleInsert(entity, modelEntity, modelEntity.getFieldsUnmodifiable(), sqlP);
} catch (GenericEntityException e) {
sqlP.rollback();
// no need to create nested, just throw original which will have all info: throw new
// GenericEntityException("Exception while inserting the following entity: " + entity.toString(), e);
throw e;
}
}
}
@@ -199,13 +200,14 @@ public class GenericDAO {
private int customUpdate(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave) throws GenericEntityException {
try (SQLProcessor sqlP = new SQLProcessor(entity.getDelegator(), helperInfo)) {
try {
return singleUpdate(entity, modelEntity, fieldsToSave, sqlP);
} catch (GenericEntityException e) {
sqlP.rollback();
// no need to create nested, just throw original which will have all info: throw new GenericEntityException("Exception while updating the following entity: " + entity.toString(), e);
throw e;
}
try {
return singleUpdate(entity, modelEntity, fieldsToSave, sqlP);
} catch (GenericEntityException e) {
sqlP.rollback();
// no need to create nested, just throw original which will have all info: throw new
// GenericEntityException("Exception while updating the following entity: " + entity.toString(), e);
throw e;
}
}
}
@@ -501,23 +503,23 @@ public class GenericDAO {
sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
sqlBuffer.append(SqlJdbcUtil.makeWhereClause(modelEntity, modelEntity.getPkFieldsUnmodifiable(), entity, "AND", datasource.getJoinStyle()));
sqlP.prepareStatement(sqlBuffer.toString(), true, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader);
sqlP.executeQuery();
sqlP.prepareStatement(sqlBuffer.toString(), true, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader);
sqlP.executeQuery();
if (sqlP.next()) {
int idx = 1;
Iterator<ModelField> nopkIter = modelEntity.getNopksIterator();
while (nopkIter.hasNext()) {
ModelField curField = nopkIter.next();
SqlJdbcUtil.getValue(sqlP.getResultSet(), idx, curField, entity, modelFieldTypeReader);
idx++;
}
if (sqlP.next()) {
int idx = 1;
Iterator<ModelField> nopkIter = modelEntity.getNopksIterator();
while (nopkIter.hasNext()) {
ModelField curField = nopkIter.next();
SqlJdbcUtil.getValue(sqlP.getResultSet(), idx, curField, entity, modelFieldTypeReader);
idx++;
}
entity.synchronizedWithDatasource();
} else {
// Debug.logWarning("[GenericDAO.select]: select failed, result set was empty for entity: " + entity.toString(), MODULE);
throw new GenericEntityNotFoundException("Result set was empty for entity: " + entity.toString());
entity.synchronizedWithDatasource();
} else {
// Debug.logWarning("[GenericDAO.select]: select failed, result set was empty for entity: " + entity.toString(), MODULE);
throw new GenericEntityNotFoundException("Result set was empty for entity: " + entity.toString());
}
}
@@ -1074,40 +1076,38 @@ public class GenericDAO {
try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) {
sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(),
findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows());
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn()) {
Debug.logVerbose("Setting the whereEntityConditionParams: " + whereEntityConditionParams, MODULE);
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn()) {
Debug.logVerbose("Setting the whereEntityConditionParams: " + whereEntityConditionParams, MODULE);
}
}
}
// set all of the values from the Where EntityCondition
for (EntityConditionParam whereEntityConditionParam: whereEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn()) {
Debug.logVerbose("Setting the havingEntityConditionParams: " + havingEntityConditionParams, MODULE);
// set all of the values from the Where EntityCondition
for (EntityConditionParam whereEntityConditionParam: whereEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
}
// set all of the values from the Having EntityCondition
for (EntityConditionParam havingEntityConditionParam: havingEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
try {
sqlP.executeQuery();
long count = 0;
ResultSet resultSet = sqlP.getResultSet();
if (resultSet.next()) {
count = resultSet.getLong(1);
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn()) {
Debug.logVerbose("Setting the havingEntityConditionParams: " + havingEntityConditionParams, MODULE);
}
}
return count;
// set all of the values from the Having EntityCondition
for (EntityConditionParam havingEntityConditionParam: havingEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
try {
sqlP.executeQuery();
long count = 0;
ResultSet resultSet = sqlP.getResultSet();
if (resultSet.next()) {
count = resultSet.getLong(1);
}
return count;
} catch (SQLException e) {
throw new GenericDataSourceException("Error getting count value", e);
}
} catch (SQLException e) {
throw new GenericDataSourceException("Error getting count value", e);
}
}
}
@@ -1117,13 +1117,12 @@ public class GenericDAO {
public int delete(GenericEntity entity) throws GenericEntityException {
try (SQLProcessor sqlP = new SQLProcessor(entity.getDelegator(), helperInfo)) {
try {
return delete(entity, sqlP);
} catch (GenericDataSourceException e) {
sqlP.rollback();
throw new GenericDataSourceException("Exception while deleting the following entity: " + entity.toString(), e);
}
try {
return delete(entity, sqlP);
} catch (GenericDataSourceException e) {
sqlP.rollback();
throw new GenericDataSourceException("Exception while deleting the following entity: " + entity.toString(), e);
}
}
}
@@ -1148,12 +1147,12 @@ public class GenericDAO {
public int deleteByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition condition) throws GenericEntityException {
try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) {
try {
return deleteByCondition(modelEntity, condition, sqlP);
} catch (GenericDataSourceException e) {
sqlP.rollback();
throw new GenericDataSourceException("Generic Entity Exception occurred in deleteByCondition", e);
}
try {
return deleteByCondition(modelEntity, condition, sqlP);
} catch (GenericDataSourceException e) {
sqlP.rollback();
throw new GenericDataSourceException("Generic Entity Exception occurred in deleteByCondition", e);
}
}
}
@@ -1170,10 +1169,9 @@ public class GenericDAO {
if (UtilValidate.isNotEmpty(whereCondition)) {
sql.append(" WHERE ").append(whereCondition);
}
sqlP.prepareStatement(sql.toString());
sqlP.prepareStatement(sql.toString());
return sqlP.executeUpdate();
return sqlP.executeUpdate();
}
/* ====================================================================== */
@@ -154,7 +154,7 @@ public final class EntityFinderUtil {
@SuppressWarnings("serial")
public static final class ConditionExpr implements Condition {
private final String fieldName;
private final EntityOperator<?,?> operator;
private final EntityOperator<?, ?> operator;
private final FlexibleMapAccessor<Object> envNameAcsr;
private final FlexibleStringExpander valueExdr;
private final FlexibleStringExpander ignoreExdr;
@@ -239,27 +239,27 @@ public final class EntityFinderUtil {
// this makes more sense logically, but if anyone ever needs it to not behave this way we should add an "or-null" attribute that is true by default
if (ignoreCase) {
return EntityCondition.makeCondition(
EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), EntityFunction.UPPER(value)),
EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), UtilGenerics.<EntityComparisonOperator<?, ?>>cast(operator), EntityFunction.UPPER(value)),
EntityOperator.OR,
EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, null));
}
return EntityCondition.makeCondition(
EntityCondition.makeCondition(fieldName, UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), value),
EntityCondition.makeCondition(fieldName, UtilGenerics.<EntityComparisonOperator<?, ?>>cast(operator), value),
EntityOperator.OR,
EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, null));
}
if (ignoreCase) {
// use the stuff to upper case both sides
return EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), EntityFunction.UPPER(value));
return EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), UtilGenerics.<EntityComparisonOperator<?, ?>>cast(operator), EntityFunction.UPPER(value));
}
return EntityCondition.makeCondition(fieldName, UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), value);
return EntityCondition.makeCondition(fieldName, UtilGenerics.<EntityComparisonOperator<?, ?>>cast(operator), value);
}
}
@SuppressWarnings("serial")
public static final class ConditionList implements Condition {
private final List<Condition> conditionList;
private final EntityOperator<?,?> operator;
private final EntityOperator<?, ?> operator;
public ConditionList(Element conditionListElement) {
String operatorAttribute = conditionListElement.getAttribute("combine");
@@ -576,8 +576,7 @@ public final class SqlJdbcUtil {
while (curField.getEncryptMethod().isEncrypted() && model instanceof ModelViewEntity) {
ModelViewEntity modelView = (ModelViewEntity) model;
String entityName = modelView.getAliasedEntity(
modelView.getAlias(curField.getName()).getEntityAlias(), entity.getDelegator().getModelReader()
).getEntityName();
modelView.getAlias(curField.getName()).getEntityAlias(), entity.getDelegator().getModelReader()).getEntityName();
model = entity.getDelegator().getModelEntity(entityName);
}
String encryptionKeyName = model.getEntityName();
@@ -877,11 +876,11 @@ public final class SqlJdbcUtil {
}
if (Debug.verboseOn()) {
Debug.logVerbose("type of field " + entityName + "." + modelField.getName() +
" is " + fieldClassName + ", was expecting " + mft.getJavaType() + "; this may " +
"indicate an error in the configuration or in the class, and may result " +
"in an SQL-Java data conversion error. Will use the real field type: " +
fieldClassName + ", not the definition.", MODULE);
Debug.logVerbose("type of field " + entityName + "." + modelField.getName()
+ " is " + fieldClassName + ", was expecting " + mft.getJavaType() + "; this may "
+ "indicate an error in the configuration or in the class, and may result "
+ "in an SQL-Java data conversion error. Will use the real field type: "
+ fieldClassName + ", not the definition.", MODULE);
}
fieldType = fieldClassName;
}
@@ -233,11 +233,11 @@ public class XmlSerializer {
}
Element element = document.createElement(elementName);
Map<?,?> value = UtilGenerics.cast(object);
Map<?, ?> value = UtilGenerics.cast(object);
Iterator<Map.Entry<?, ?>> iter = UtilGenerics.cast(value.entrySet().iterator());
while (iter.hasNext()) {
Map.Entry<?,?> entry = iter.next();
Map.Entry<?, ?> entry = iter.next();
Element entryElement = document.createElement("map-Entry");
@@ -130,8 +130,7 @@ public class EntityCryptoTestSuite extends EntityTestCase {
return EntityCondition.makeCondition(
EntityCondition.makeCondition("testingCryptoTypeId", EntityOperator.IN, UtilMisc.toList("SUB_SELECT_1", "SUB_SELECT_3")),
EntityOperator.AND,
EntityCondition.makeCondition("encryptedValue", EntityOperator.EQUALS, nanoTime)
);
EntityCondition.makeCondition("encryptedValue", EntityOperator.EQUALS, nanoTime));
}
protected EntityConditionSubSelect makeSubSelect(String nanoTime) {
@@ -381,8 +381,7 @@ public class EntityTestSuite extends EntityTestCase {
for (GenericValue node: nodeLevel1) {
GenericValue testing = delegator.makeValue("Testing",
"testingId", delegator.getNextSeqId("Testing"),
"testingTypeId", "TEST-TREE-1"
);
"testingTypeId", "TEST-TREE-1");
testing.put("testingName", "leaf-#" + node.getString("testingNodeId"));
testing.put("description", "level1 leaf");
testing.put("comments", "No-comments");
@@ -392,8 +391,7 @@ public class EntityTestSuite extends EntityTestCase {
newValues.add(testing);
GenericValue member = delegator.makeValue("TestingNodeMember",
"testingNodeId", node.get("testingNodeId"),
"testingId", testing.get("testingId")
);
"testingId", testing.get("testingId"));
member.put("fromDate", now);
member.put("thruDate", UtilDateTime.getNextDayStart(now));
@@ -418,14 +416,12 @@ public class EntityTestSuite extends EntityTestCase {
for (GenericValue node: EntityQuery.use(delegator)
.from("TestingNode")
.where(EntityCondition.makeCondition("description", EntityOperator.LIKE, descriptionPrefix + "%"))
.queryList()
) {
.queryList()) {
if (i % 2 == 0) {
GenericValue testing = delegator.create("Testing", "testingId", descriptionPrefix + ":" + node.get("testingNodeId"), "testingTypeId", typeId, "description", node.get("description"));
GenericValue member = delegator.makeValue("TestingNodeMember",
"testingNodeId", node.get("testingNodeId"),
"testingId", testing.get("testingId")
);
"testingId", testing.get("testingId"));
member.put("fromDate", now);
member.put("thruDate", UtilDateTime.getNextDayStart(now));
@@ -446,8 +442,7 @@ public class EntityTestSuite extends EntityTestCase {
EntityCondition isNodeWithMember = EntityCondition.makeCondition(
EntityCondition.makeCondition("testingId", EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD),
EntityOperator.AND,
EntityCondition.makeCondition("description", EntityOperator.LIKE, "count-views:%")
);
EntityCondition.makeCondition("description", EntityOperator.LIKE, "count-views:%"));
List<GenericValue> nodeWithMembers = EntityQuery.use(delegator).from("TestingNodeAndMember").where(isNodeWithMember).queryList();
for (GenericValue v: nodeWithMembers) {
@@ -645,8 +640,7 @@ public class EntityTestSuite extends EntityTestCase {
EntityCondition isRoot = EntityCondition.makeCondition(
EntityCondition.makeCondition("description", EntityOperator.LIKE, "remove-by-pk:%"),
EntityOperator.AND,
EntityCondition.makeCondition("primaryParentNodeId", EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD)
);
EntityCondition.makeCondition("primaryParentNodeId", EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD));
List<GenericValue> rootValues = EntityQuery.use(delegator).select("testingNodeId").from("TestingNode").where(isRoot).queryList();
for (GenericValue value: rootValues) {
@@ -462,7 +462,7 @@ public final class TransactionUtil implements Status {
if (tm != null && tm.getStatus() == STATUS_ACTIVE) {
Transaction tx = tm.getTransaction();
if (tx != null) {
tx.enlistResource(resource);
tx.enlistResource(resource);
}
}
} catch (RollbackException e) {
@@ -489,28 +489,28 @@ public final class TransactionUtil implements Status {
* STATUS_ROLLING_BACK 9
*/
switch (state) {
case Status.STATUS_ACTIVE:
return "Transaction Active (" + state + ")";
case Status.STATUS_COMMITTED:
return "Transaction Committed (" + state + ")";
case Status.STATUS_COMMITTING:
return "Transaction Committing (" + state + ")";
case Status.STATUS_MARKED_ROLLBACK:
return "Transaction Marked Rollback (" + state + ")";
case Status.STATUS_NO_TRANSACTION:
return "No Transaction (" + state + ")";
case Status.STATUS_PREPARED:
return "Transaction Prepared (" + state + ")";
case Status.STATUS_PREPARING:
return "Transaction Preparing (" + state + ")";
case Status.STATUS_ROLLEDBACK:
return "Transaction Rolledback (" + state + ")";
case Status.STATUS_ROLLING_BACK:
return "Transaction Rolling Back (" + state + ")";
case Status.STATUS_UNKNOWN:
return "Transaction Status Unknown (" + state + ")";
default:
return "Not a valid state code (" + state + ")";
case Status.STATUS_ACTIVE:
return "Transaction Active (" + state + ")";
case Status.STATUS_COMMITTED:
return "Transaction Committed (" + state + ")";
case Status.STATUS_COMMITTING:
return "Transaction Committing (" + state + ")";
case Status.STATUS_MARKED_ROLLBACK:
return "Transaction Marked Rollback (" + state + ")";
case Status.STATUS_NO_TRANSACTION:
return "No Transaction (" + state + ")";
case Status.STATUS_PREPARED:
return "Transaction Prepared (" + state + ")";
case Status.STATUS_PREPARING:
return "Transaction Preparing (" + state + ")";
case Status.STATUS_ROLLEDBACK:
return "Transaction Rolledback (" + state + ")";
case Status.STATUS_ROLLING_BACK:
return "Transaction Rolling Back (" + state + ")";
case Status.STATUS_UNKNOWN:
return "Transaction Status Unknown (" + state + ")";
default:
return "Not a valid state code (" + state + ")";
}
}
@@ -24,7 +24,6 @@ import java.util.List;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
public class EntityBatchIterator implements Iterator<GenericValue> {
public static final String MODULE = EntityBatchIterator.class.getName();
@@ -276,20 +276,20 @@ public final class EntityCrypto {
@Override
protected byte[] decryptValue(byte[] key, EncryptMethod encryptMethod, String encryptedString) throws GeneralException {
switch (encryptMethod) {
case SALT:
return saltedCipherService.decrypt(Base64.decodeBase64(encryptedString), key).getBytes();
default:
return cipherService.decrypt(Base64.decodeBase64(encryptedString), key).getBytes();
case SALT:
return saltedCipherService.decrypt(Base64.decodeBase64(encryptedString), key).getBytes();
default:
return cipherService.decrypt(Base64.decodeBase64(encryptedString), key).getBytes();
}
}
@Override
protected String encryptValue(EncryptMethod encryptMethod, byte[] key, byte[] objBytes) throws GeneralException {
switch (encryptMethod) {
case SALT:
return saltedCipherService.encrypt(objBytes, key).toBase64();
default:
return cipherService.encrypt(objBytes, key).toBase64();
case SALT:
return saltedCipherService.encrypt(objBytes, key).toBase64();
default:
return cipherService.encrypt(objBytes, key).toBase64();
}
}
}
@@ -413,15 +413,15 @@ public final class EntityCrypto {
protected String encryptValue(EncryptMethod encryptMethod, byte[] key, byte[] objBytes) throws GeneralException {
byte[] saltBytes;
switch (encryptMethod) {
case SALT:
Random random = new SecureRandom();
// random length 5-16
saltBytes = new byte[5 + random.nextInt(11)];
random.nextBytes(saltBytes);
break;
default:
saltBytes = new byte[0];
break;
case SALT:
Random random = new SecureRandom();
// random length 5-16
saltBytes = new byte[5 + random.nextInt(11)];
random.nextBytes(saltBytes);
break;
default:
saltBytes = new byte[0];
break;
}
byte[] allBytes = new byte[1 + saltBytes.length + objBytes.length];
allBytes[0] = (byte) saltBytes.length;
@@ -136,7 +136,7 @@ public final class EntityTypeUtil {
try {
childTypeValue = EntityQuery.use(delegator).from(entityName).where(primaryKey, childType).cache(true).queryOne();
} catch (GenericEntityException e) {
Debug.logError("Error finding "+entityName+" record for type "+childType, MODULE);
Debug.logError("Error finding " + entityName + " record for type " + childType, MODULE);
}
if (childTypeValue != null) {
if (parentType.equals(childTypeValue.getString(primaryKey))) return true;
@@ -41,7 +41,7 @@ import org.w3c.dom.Element;
public final class ValidateMethodCondition extends MethodOperation implements Conditional {
private static final String MODULE = ValidateMethodCondition.class.getName();
private static final Class<?>[] paramTypes = new Class<?>[] { String.class };
private static final Class<?>[] paramTypes = new Class<?>[] {String.class };
private final String className;
private final FlexibleMapAccessor<Object> fieldFma;
@@ -87,7 +87,7 @@ public final class ValidateMethodCondition extends MethodOperation implements Co
throw new MiniLangRuntimeException(e, this);
}
}
Object[] params = new Object[] { fieldVal };
Object[] params = new Object[] {fieldVal };
try {
Class<?> valClass = methodContext.getLoader().loadClass(className);
Method valMethod = valClass.getMethod(methodName, paramTypes);
@@ -137,36 +137,36 @@ public final class Calculate extends MethodOperation {
resultValue = resultValue.setScale(decimalScale, roundingMode);
Object resultObj = null;
switch (type) {
case TYPE_DOUBLE:
resultObj = resultValue.doubleValue();
break;
case TYPE_FLOAT:
resultObj = resultValue.floatValue();
break;
case TYPE_LONG:
resultValue = resultValue.setScale(0, roundingMode);
resultObj = resultValue.longValue();
break;
case TYPE_INTEGER:
resultValue = resultValue.setScale(0, roundingMode);
resultObj = resultValue.intValue();
break;
case TYPE_STRING:
// run the decimal-formatting
String decimalFormatString = decimalFormatFse.expandString(methodContext.getEnvMap());
DecimalFormat df = null;
if (!decimalFormatString.isEmpty()) {
df = new DecimalFormat(decimalFormatString);
}
if (df != null && resultValue.compareTo(BigDecimal.ZERO) != 0) {
resultObj = df.format(resultValue);
} else {
resultObj = resultValue.toString();
}
break;
case TYPE_BIG_DECIMAL:
resultObj = resultValue;
break;
case TYPE_DOUBLE:
resultObj = resultValue.doubleValue();
break;
case TYPE_FLOAT:
resultObj = resultValue.floatValue();
break;
case TYPE_LONG:
resultValue = resultValue.setScale(0, roundingMode);
resultObj = resultValue.longValue();
break;
case TYPE_INTEGER:
resultValue = resultValue.setScale(0, roundingMode);
resultObj = resultValue.intValue();
break;
case TYPE_STRING:
// run the decimal-formatting
String decimalFormatString = decimalFormatFse.expandString(methodContext.getEnvMap());
DecimalFormat df = null;
if (!decimalFormatString.isEmpty()) {
df = new DecimalFormat(decimalFormatString);
}
if (df != null && resultValue.compareTo(BigDecimal.ZERO) != 0) {
resultObj = df.format(resultValue);
} else {
resultObj = resultValue.toString();
}
break;
case TYPE_BIG_DECIMAL:
resultObj = resultValue;
break;
}
fieldFma.put(methodContext.getEnvMap(), resultObj);
return true;
@@ -282,19 +282,19 @@ public final class Calculate extends MethodOperation {
isFirst = false;
} else {
switch (operator) {
case OPERATOR_ADD:
resultValue = resultValue.add(calcop.calcValue(methodContext, scale, roundingMode));
break;
case OPERATOR_SUBTRACT:
case OPERATOR_NEGATIVE:
resultValue = resultValue.subtract(calcop.calcValue(methodContext, scale, roundingMode));
break;
case OPERATOR_MULTIPLY:
resultValue = resultValue.multiply(calcop.calcValue(methodContext, scale, roundingMode));
break;
case OPERATOR_DIVIDE:
resultValue = resultValue.divide(calcop.calcValue(methodContext, scale, roundingMode), scale, roundingMode);
break;
case OPERATOR_ADD:
resultValue = resultValue.add(calcop.calcValue(methodContext, scale, roundingMode));
break;
case OPERATOR_SUBTRACT:
case OPERATOR_NEGATIVE:
resultValue = resultValue.subtract(calcop.calcValue(methodContext, scale, roundingMode));
break;
case OPERATOR_MULTIPLY:
resultValue = resultValue.multiply(calcop.calcValue(methodContext, scale, roundingMode));
break;
case OPERATOR_DIVIDE:
resultValue = resultValue.divide(calcop.calcValue(methodContext, scale, roundingMode), scale, roundingMode);
break;
}
}
}
@@ -58,7 +58,7 @@ public class ValidateMethod extends SimpleMapOperation {
if (loader == null) {
loader = Thread.currentThread().getContextClassLoader();
}
Class<?>[] paramTypes = new Class<?>[] { String.class };
Class<?>[] paramTypes = new Class<?>[] {String.class };
Object[] params = new Object[] { fieldValue };
Class<?> valClass;
try {
@@ -58,10 +58,10 @@ public class GeneralServiceException extends org.apache.ofbiz.base.util.GeneralE
this.nestedServiceResult = nestedServiceResult;
}
public Map<String, Object> returnError(String MODULE) {
public Map<String, Object> returnError(String module) {
String errMsg = this.getMessage() == null ? "Error in Service" : this.getMessage();
if (this.getNested() != null) {
Debug.logError(this.getNested(), errMsg, MODULE);
Debug.logError(this.getNested(), errMsg, module);
}
return ServiceUtil.returnError(errMsg, this.errorMsgList, this.errorMsgMap, this.nestedServiceResult);
}
@@ -751,7 +751,7 @@ public class RecurrenceRule {
StringBuilder sBuf = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
String thisChar = str.substring(i, i+1);
String thisChar = str.substring(i, i + 1);
if (!hasNumber(thisChar)) {
sBuf.append(thisChar);
@@ -48,7 +48,7 @@ public class ServiceEcaSetField {
this.fieldName = set.getAttribute("field-name");
if (UtilValidate.isNotEmpty(this.fieldName) && this.fieldName.indexOf('.') != -1) {
this.mapName = fieldName.substring(0, this.fieldName.indexOf('.'));
this.fieldName = this.fieldName.substring(this.fieldName.indexOf('.') +1);
this.fieldName = this.fieldName.substring(this.fieldName.indexOf('.') + 1);
}
this.envName = set.getAttribute("env-name");
this.value = set.getAttribute("value");
@@ -255,14 +255,14 @@ public class JavaMailContainer implements Container {
public void notification(StoreEvent event) {
String typeString = "";
switch (event.getMessageType()) {
case StoreEvent.ALERT:
typeString = "ALERT: ";
break;
case StoreEvent.NOTICE:
typeString = "NOTICE: ";
break;
default:
Debug.logWarning("There was a case error in LoggingStoreListener.notification", MODULE);
case StoreEvent.ALERT:
typeString = "ALERT: ";
break;
case StoreEvent.NOTICE:
typeString = "NOTICE: ";
break;
default:
Debug.logWarning("There was a case error in LoggingStoreListener.notification", MODULE);
}
if (Debug.verboseOn()) {
@@ -54,27 +54,27 @@ public class ServiceMcaCondition implements java.io.Serializable {
public ServiceMcaCondition(Element condElement, int condType) {
switch (condType) {
case CONDITION_FIELD:
// fields: from|to|subject|body|sent-date|receieved-date
this.fieldName = condElement.getAttribute("field-name");
// operators: equals|not-equals|empty|not-empty|matches|not-matches
this.operator = condElement.getAttribute("operator");
// value to compare
this.value = condElement.getAttribute("value");
break;
case CONDITION_HEADER:
// free form header name
this.headerName = condElement.getAttribute("header-name");
// operators: equals|not-equals|empty|not-empty|matches|not-matches
this.operator = condElement.getAttribute("operator");
// value to compare
this.value = condElement.getAttribute("value");
break;
case CONDITION_SERVICE:
this.serviceName = condElement.getAttribute("service-name");
break;
default:
Debug.logWarning("There was an error in the switch-case in ServiceMcaCondition", MODULE);
case CONDITION_FIELD:
// fields: from|to|subject|body|sent-date|receieved-date
this.fieldName = condElement.getAttribute("field-name");
// operators: equals|not-equals|empty|not-empty|matches|not-matches
this.operator = condElement.getAttribute("operator");
// value to compare
this.value = condElement.getAttribute("value");
break;
case CONDITION_HEADER:
// free form header name
this.headerName = condElement.getAttribute("header-name");
// operators: equals|not-equals|empty|not-empty|matches|not-matches
this.operator = condElement.getAttribute("operator");
// value to compare
this.value = condElement.getAttribute("value");
break;
case CONDITION_SERVICE:
this.serviceName = condElement.getAttribute("service-name");
break;
default:
Debug.logWarning("There was an error in the switch-case in ServiceMcaCondition", MODULE);
}
}
@@ -88,8 +88,7 @@ public class XmlRpcTests extends AbstractXmlRpcTestCase {
localMap.put("num1", num1);
localMap.put("num2", num2);
result = dctx.getDispatcher().runSync("testXmlRpcLocalEngine", localMap);
}
catch (GenericServiceException e) {
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getLocalizedMessage());
}
if (ServiceUtil.isError(result)) {
@@ -1138,8 +1138,7 @@ public final class LoginWorker {
String headerValue = request.getHeader(httpHeader);
if (UtilValidate.isNotEmpty(headerValue)) {
return LoginWorker.loginUserWithUserLoginId(request, response, headerValue);
}
else {
} else {
// empty headerValue is not good
return "error";
}
@@ -1162,8 +1161,7 @@ public final class LoginWorker {
String remoteUserId = request.getRemoteUser();
if (UtilValidate.isNotEmpty(remoteUserId)) {
return LoginWorker.loginUserWithUserLoginId(request, response, remoteUserId);
}
else {
} else {
// empty remoteUserId is not good
return "error";
}
@@ -62,8 +62,7 @@ public final class WebSiteWorker {
GenericValue result = null;
try {
result = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache(useCache).queryOne();
}
catch (GenericEntityException e) {
} catch (GenericEntityException e) {
Debug.logError("Error looking up website with id " + webSiteId, MODULE);
}
return result;
@@ -300,7 +300,7 @@ public class ArtifactInfoFactory {
public ArtifactInfoBase getArtifactInfoByUniqueIdAndType(String uniqueId, String type) {
if (uniqueId.contains("#")) {
int poundIndex = uniqueId.indexOf('#');
return getArtifactInfoByNameAndType(uniqueId.substring(poundIndex+1), uniqueId.substring(0, poundIndex), type);
return getArtifactInfoByNameAndType(uniqueId.substring(poundIndex + 1), uniqueId.substring(0, poundIndex), type);
} else {
return getArtifactInfoByNameAndType(uniqueId, null, type);
}
@@ -62,7 +62,7 @@ public class ControllerViewArtifactInfo extends ArtifactInfoBase {
String fullScreenName = this.viewInfoMap.page;
if (UtilValidate.isNotEmpty(fullScreenName)) {
int poundIndex = fullScreenName.indexOf('#');
this.screenCalledByThisView = this.aif.getScreenWidgetArtifactInfo(fullScreenName.substring(poundIndex+1), fullScreenName.substring(0, poundIndex));
this.screenCalledByThisView = this.aif.getScreenWidgetArtifactInfo(fullScreenName.substring(poundIndex + 1), fullScreenName.substring(0, poundIndex));
if (this.screenCalledByThisView != null) {
// add the reverse association
UtilMisc.addToSortedSetInMap(this, aif.allViewInfosReferringToScreen, this.screenCalledByThisView.getUniqueId());
@@ -135,8 +135,7 @@ public class LabelManagerFactory {
|| labelKey.contains("check.")
|| (labelKey.length() == 2) // These are languages Ids
|| labelKey.contains("pt_") // These are languages Ids
|| labelKey.contains("en_") // These are languages Ids
)) {
|| labelKey.contains("en_"))) {
continue; // OFBIZ-8154 WIP
}
String labelComment = "";
@@ -121,7 +121,7 @@ public final class WidgetWorker {
if (UtilValidate.isNotEmpty(tokenValue)) {
String currentString = externalWriter.toString();
if (currentString.startsWith("<form")) {
currentString = currentString.substring(currentString.lastIndexOf("\"")+1);
currentString = currentString.substring(currentString.lastIndexOf("\"") + 1);
}
if (currentString.indexOf('?') == -1) {
externalWriter.append("?" + CsrfUtil.getTokenNameNonAjax() + "=" + tokenValue);
@@ -691,7 +691,7 @@ public abstract class AbstractModelCondition implements Serializable, ModelCondi
if (fieldString == null) {
fieldString = "";
}
Class<?>[] paramTypes = { String.class };
Class<?>[] paramTypes = {String.class };
Object[] params = new Object[] { fieldString };
Class<?> valClass;
try {
@@ -395,8 +395,7 @@ public class ModelFormField {
}
if (simpleEncoder != null) {
newCol.add(simpleEncoder.encode(item.toString()));
}
else {
} else {
newCol.add(item.toString());
}
}
@@ -137,82 +137,82 @@ public class ModelTheme implements Serializable {
//second collect value from XML and surcharge
for (Element childElement : UtilXml.childElementList(themeElement)) {
switch (childElement.getNodeName()) {
case "widget-properties":
addWidgetProperties(initWidgetPropertiesMap, childElement);
break;
case "visual-themes":
for (Element visualTheme : UtilXml.childElementList(childElement)) {
initVisualThemes.put(visualTheme.getAttribute("id"), new VisualTheme(this, visualTheme));
case "widget-properties":
addWidgetProperties(initWidgetPropertiesMap, childElement);
break;
case "visual-themes":
for (Element visualTheme : UtilXml.childElementList(childElement)) {
initVisualThemes.put(visualTheme.getAttribute("id"), new VisualTheme(this, visualTheme));
}
break;
case "theme-properties":
for (Element property : UtilXml.childElementList(childElement)) {
addThemeProperty(initThemePropertiesMap, property);
}
break;
case "templates":
for (Element template : UtilXml.childElementList(childElement)) {
String modelTemplateName = template.getAttribute("name");
if (initModelTemplateMap.containsKey(modelTemplateName)) {
ModelTemplate surchargeModelTemplate = new ModelTemplate(template);
ModelTemplate originModelTemplate = initModelTemplateMap.get(modelTemplateName);
initModelTemplateMap.put(modelTemplateName, new ModelTemplate(surchargeModelTemplate, originModelTemplate));
} else {
initModelTemplateMap.put(modelTemplateName, new ModelTemplate(template));
}
break;
case "theme-properties":
for (Element property : UtilXml.childElementList(childElement)) {
addThemeProperty(initThemePropertiesMap, property);
}
break;
case "templates":
for (Element template : UtilXml.childElementList(childElement)) {
String modelTemplateName = template.getAttribute("name");
if (initModelTemplateMap.containsKey(modelTemplateName)) {
ModelTemplate surchargeModelTemplate = new ModelTemplate(template);
ModelTemplate originModelTemplate = initModelTemplateMap.get(modelTemplateName);
initModelTemplateMap.put(modelTemplateName, new ModelTemplate(surchargeModelTemplate, originModelTemplate));
} else {
initModelTemplateMap.put(modelTemplateName, new ModelTemplate(template));
}
break;
case "common-screens":
for (Element screenPurpose : UtilXml.childElementList(childElement)) {
String defaultLocation = screenPurpose.getAttribute("default-location");
for (Element screen : UtilXml.childElementList(screenPurpose)) {
String name = screen.getAttribute("name");
String location = screen.getAttribute("location");
if (UtilValidate.isEmpty(location)) {
location = defaultLocation;
}
}
break;
case "common-screens":
for (Element screenPurpose : UtilXml.childElementList(childElement)) {
String defaultLocation = screenPurpose.getAttribute("default-location");
for (Element screen : UtilXml.childElementList(screenPurpose)) {
String name = screen.getAttribute("name");
String location = screen.getAttribute("location");
if (UtilValidate.isEmpty(location)) {
location = defaultLocation;
}
if (UtilValidate.isEmpty(location)) {
Debug.logWarning("We can resolve the screen location " + name + " in the theme " + this.name + " so no added it", MODULE);
continue;
}
initModelCommonScreensMap.put(name, location);
if (UtilValidate.isEmpty(location)) {
Debug.logWarning("We can resolve the screen location " + name + " in the theme " + this.name + " so no added it", MODULE);
continue;
}
initModelCommonScreensMap.put(name, location);
}
break;
case "common-forms":
for (Element formPurpose : UtilXml.childElementList(childElement)) {
String defaultLocation = formPurpose.getAttribute("default-location");
for (Element form : UtilXml.childElementList(formPurpose)) {
String name = form.getAttribute("name");
String location = form.getAttribute("location");
if (UtilValidate.isEmpty(location)) {
location = defaultLocation;
}
if (UtilValidate.isEmpty(location)) {
Debug.logWarning("We can resolve the form location " + name + " in the theme " + this.name + " so no added it", MODULE);
continue;
}
initModelCommonFormsMap.put(name, location);
}
break;
case "common-forms":
for (Element formPurpose : UtilXml.childElementList(childElement)) {
String defaultLocation = formPurpose.getAttribute("default-location");
for (Element form : UtilXml.childElementList(formPurpose)) {
String name = form.getAttribute("name");
String location = form.getAttribute("location");
if (UtilValidate.isEmpty(location)) {
location = defaultLocation;
}
}
break;
case "common-menus":
for (Element menuPurpose : UtilXml.childElementList(childElement)) {
String defaultLocation = menuPurpose.getAttribute("default-location");
for (Element menu : UtilXml.childElementList(menuPurpose)) {
String name = menu.getAttribute("name");
String location = menu.getAttribute("location");
if (UtilValidate.isEmpty(location)) {
location = defaultLocation;
}
if (UtilValidate.isEmpty(location)) {
Debug.logWarning("We can resolve the menu location " + name + " in the theme " + this.name + " so no added it", MODULE);
continue;
}
initModelCommonMenusMap.put(name, location);
if (UtilValidate.isEmpty(location)) {
Debug.logWarning("We can resolve the form location " + name + " in the theme " + this.name + " so no added it", MODULE);
continue;
}
initModelCommonFormsMap.put(name, location);
}
break;
}
break;
case "common-menus":
for (Element menuPurpose : UtilXml.childElementList(childElement)) {
String defaultLocation = menuPurpose.getAttribute("default-location");
for (Element menu : UtilXml.childElementList(menuPurpose)) {
String name = menu.getAttribute("name");
String location = menu.getAttribute("location");
if (UtilValidate.isEmpty(location)) {
location = defaultLocation;
}
if (UtilValidate.isEmpty(location)) {
Debug.logWarning("We can resolve the menu location " + name + " in the theme " + this.name + " so no added it", MODULE);
continue;
}
initModelCommonMenusMap.put(name, location);
}
}
break;
}
}
@@ -292,25 +292,25 @@ public class ModelTheme implements Serializable {
private static void addWidgetProperties(Map<String, Object> initWidgetPropertiesMap, Element widgetProperties) {
for (Element childElement : UtilXml.childElementList(widgetProperties)) {
switch (childElement.getNodeName()) {
case "default-view-size":
initWidgetPropertiesMap.put("defaultViewSize", Integer.valueOf(childElement.getAttribute("value")));
break;
case "autocompleter":
initWidgetPropertiesMap.put("autocompleterDefaultDelay", Integer.valueOf(childElement.getAttribute("default-delay")));
initWidgetPropertiesMap.put("autocompleterDefaultMinLength", Integer.valueOf(childElement.getAttribute("default-min-lenght")));
initWidgetPropertiesMap.put("autocompleterDefaultViewSize", Integer.valueOf(childElement.getAttribute("default-view-size")));
initWidgetPropertiesMap.put("autocompleterDisplayReturnField", "true".equalsIgnoreCase(childElement.getAttribute("display-return-field")));
break;
case "lookup":
initWidgetPropertiesMap.put("lookupPosition", childElement.getAttribute("position"));
initWidgetPropertiesMap.put("lookupHeight", Integer.valueOf(childElement.getAttribute("height")));
initWidgetPropertiesMap.put("lookupWidth", Integer.valueOf(childElement.getAttribute("width")));
initWidgetPropertiesMap.put("lookupShowDescription", childElement.getAttribute("show-description"));
break;
case "layered-modal":
initWidgetPropertiesMap.put("linkDefaultLayeredModalHeight", Integer.valueOf(childElement.getAttribute("height")));
initWidgetPropertiesMap.put("linkDefaultLayeredModalWidth", Integer.valueOf(childElement.getAttribute("width")));
break;
case "default-view-size":
initWidgetPropertiesMap.put("defaultViewSize", Integer.valueOf(childElement.getAttribute("value")));
break;
case "autocompleter":
initWidgetPropertiesMap.put("autocompleterDefaultDelay", Integer.valueOf(childElement.getAttribute("default-delay")));
initWidgetPropertiesMap.put("autocompleterDefaultMinLength", Integer.valueOf(childElement.getAttribute("default-min-lenght")));
initWidgetPropertiesMap.put("autocompleterDefaultViewSize", Integer.valueOf(childElement.getAttribute("default-view-size")));
initWidgetPropertiesMap.put("autocompleterDisplayReturnField", "true".equalsIgnoreCase(childElement.getAttribute("display-return-field")));
break;
case "lookup":
initWidgetPropertiesMap.put("lookupPosition", childElement.getAttribute("position"));
initWidgetPropertiesMap.put("lookupHeight", Integer.valueOf(childElement.getAttribute("height")));
initWidgetPropertiesMap.put("lookupWidth", Integer.valueOf(childElement.getAttribute("width")));
initWidgetPropertiesMap.put("lookupShowDescription", childElement.getAttribute("show-description"));
break;
case "layered-modal":
initWidgetPropertiesMap.put("linkDefaultLayeredModalHeight", Integer.valueOf(childElement.getAttribute("height")));
initWidgetPropertiesMap.put("linkDefaultLayeredModalWidth", Integer.valueOf(childElement.getAttribute("width")));
break;
}
}
}
@@ -468,21 +468,21 @@ public class ModelTheme implements Serializable {
String errorTemplateLocation = null;
for (Element templateFile : UtilXml.childElementList(template)) {
switch (templateFile.getAttribute("widget")) {
case "screen":
screenRendererLocation = templateFile.getAttribute("location");
break;
case "form":
formRendererLocation = templateFile.getAttribute("location");
break;
case "tree":
treeRendererLocation = templateFile.getAttribute("location");
break;
case "menu":
menuRendererLocation = templateFile.getAttribute("location");
break;
case "error":
errorTemplateLocation = templateFile.getAttribute("location");
break;
case "screen":
screenRendererLocation = templateFile.getAttribute("location");
break;
case "form":
formRendererLocation = templateFile.getAttribute("location");
break;
case "tree":
treeRendererLocation = templateFile.getAttribute("location");
break;
case "menu":
menuRendererLocation = templateFile.getAttribute("location");
break;
case "error":
errorTemplateLocation = templateFile.getAttribute("location");
break;
}
}
this.screenRendererLocation = screenRendererLocation;
@@ -545,8 +545,8 @@ public abstract class ModelWidgetCondition implements Serializable {
if (fieldString == null) {
fieldString = "";
}
Class<?>[] paramTypes = { String.class };
Object[] params = new Object[] { fieldString };
Class<?>[] paramTypes = {String.class };
Object[] params = new Object[] {fieldString };
Class<?> valClass;
try {
valClass = ObjectType.loadClass(className);