You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@freemarker.apache.org by dd...@apache.org on 2017/08/08 17:56:51 UTC
[01/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Repository: incubator-freemarker
Updated Branches:
refs/heads/3 cfd379605 -> ebb39b845
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/ResourcesExtractor.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/ResourcesExtractor.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/ResourcesExtractor.java
index 4e05cdc..a0b4045 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/ResourcesExtractor.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/ResourcesExtractor.java
@@ -32,7 +32,7 @@ import java.util.zip.ZipEntry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -142,8 +142,8 @@ public final class ResourcesExtractor {
int arrowIdx = contLine.indexOf(ARROW);
if (arrowIdx != -1) {
if (!contLine.startsWith("/")) {
- throw new IOException("In " + _StringUtil.jQuote(contResource) + ", this line must start with "
- + "\"/\" as it uses the " + _StringUtil.jQuote(ARROW) + " operator : "
+ throw new IOException("In " + _StringUtils.jQuote(contResource) + ", this line must start with "
+ + "\"/\" as it uses the " + _StringUtils.jQuote(ARROW) + " operator : "
+ contLine);
}
contSrcPath = contLine.substring(0, arrowIdx).trim();
@@ -151,7 +151,7 @@ public final class ResourcesExtractor {
contSrcPathRelative = false;
} else {
if (contLine.startsWith("/")) {
- throw new IOException("In " + _StringUtil.jQuote(contResource)
+ throw new IOException("In " + _StringUtils.jQuote(contResource)
+ ", this line can't start with \"/\": " + contLine);
}
contSrcPathRelative = true;
@@ -172,7 +172,7 @@ public final class ResourcesExtractor {
try {
if (dstFile.exists()) {
throw new IOException(
- "Destination already exists; check if " + _StringUtil.jQuote(contDstPath)
+ "Destination already exists; check if " + _StringUtils.jQuote(contDstPath)
+ " occurs for multiple times in \"" + CONTENTS_TXT + "\".");
}
FileUtils.copyInputStreamToFile(entryIn, dstFile);
@@ -180,8 +180,8 @@ public final class ResourcesExtractor {
File parent = dstFile;
while ((parent = dstFile.getParentFile()) != null) {
if (parent.isFile()) {
- throw new IOException("An ancestor directory of " + _StringUtil.jQuote(dstFile) + ", "
- + _StringUtil.jQuote(parent) + " already exists, but as a file, not as a directory. "
+ throw new IOException("An ancestor directory of " + _StringUtils.jQuote(dstFile) + ", "
+ + _StringUtils.jQuote(parent) + " already exists, but as a file, not as a directory. "
+ "Check if you have accidentally added the directory itself to \"" + CONTENTS_TXT
+ "\". Only files should be listed there.");
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTest.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTest.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTest.java
index 9e588d4..dce3719 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTest.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTest.java
@@ -41,7 +41,7 @@ import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.ByteArrayTemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.junit.Ignore;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@@ -106,7 +106,7 @@ public abstract class TemplateTest {
throw new IOException("Reference output resource not found: " + getClass() + ", " + resName);
}
try {
- expectedOut = TestUtil.removeTxtCopyrightComment(IOUtils.toString(in, StandardCharsets.UTF_8.name()));
+ expectedOut = TestUtils.removeTxtCopyrightComment(IOUtils.toString(in, StandardCharsets.UTF_8.name()));
} finally {
in.close();
}
@@ -300,16 +300,16 @@ public abstract class TemplateTest {
if (needle.startsWith("\\!")) {
String netNeedle = needle.substring(2);
if (msg.contains(netNeedle)) {
- fail("The message shouldn't contain substring " + _StringUtil.jQuote(netNeedle) + ":\n" + msg);
+ fail("The message shouldn't contain substring " + _StringUtils.jQuote(netNeedle) + ":\n" + msg);
}
} else if (!msg.contains(needle)) {
- fail("The message didn't contain substring " + _StringUtil.jQuote(needle) + ":\n" + msg);
+ fail("The message didn't contain substring " + _StringUtils.jQuote(needle) + ":\n" + msg);
}
}
}
private String normalizeNewLines(String s) {
- return _StringUtil.replace(s, "\r\n", "\n").replace('\r', '\n');
+ return _StringUtils.replace(s, "\r\n", "\n").replace('\r', '\n');
}
public static class TestBean {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestCase.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestCase.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestCase.java
index 9c6db39..5774b33 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestCase.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestCase.java
@@ -35,7 +35,7 @@ import org.apache.freemarker.core.Version;
import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader;
import org.apache.freemarker.core.util._NullArgumentException;
import org.apache.freemarker.core.util._NullWriter;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.test.templateutil.AssertDirective;
import org.apache.freemarker.test.templateutil.AssertEqualsDirective;
import org.apache.freemarker.test.templateutil.AssertFailsDirective;
@@ -115,8 +115,8 @@ class TemplateTestCase extends FileTestCase {
} catch (ConfigurationException e) {
throw new RuntimeException(
"Failed to set setting " +
- _StringUtil.jQuote(param) + " to " +
- _StringUtil.jQuote(value) + "; see cause exception.",
+ _StringUtils.jQuote(param) + " to " +
+ _StringUtils.jQuote(value) + "; see cause exception.",
e);
}
}
@@ -153,7 +153,7 @@ class TemplateTestCase extends FileTestCase {
template = confB.build().getTemplate(templateName);
} catch (IOException e) {
throw new AssertionFailedError(
- "Could not load template " + _StringUtil.jQuote(templateName) + ":\n" + getStackTrace(e));
+ "Could not load template " + _StringUtils.jQuote(templateName) + ":\n" + getStackTrace(e));
}
testSuite.validateTemplate(template);
@@ -162,7 +162,7 @@ class TemplateTestCase extends FileTestCase {
try {
template.process(dataModel, out != null ? out : _NullWriter.INSTANCE);
} catch (TemplateException e) {
- throw new AssertionFailedError("Template " + _StringUtil.jQuote(templateName) + " has stopped with error:\n"
+ throw new AssertionFailedError("Template " + _StringUtils.jQuote(templateName) + " has stopped with error:\n"
+ getStackTrace(e));
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestSuite.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestSuite.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestSuite.java
index 932c4ae..93ab0e8 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestSuite.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TemplateTestSuite.java
@@ -35,7 +35,7 @@ import javax.xml.parsers.ParserConfigurationException;
import org.apache.freemarker.core.Configuration;
import org.apache.freemarker.core.Template;
import org.apache.freemarker.core.Version;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.junit.runner.RunWith;
import org.junit.runners.AllTests;
import org.w3c.dom.Attr;
@@ -111,7 +111,7 @@ public abstract class TemplateTestSuite extends TestSuite {
testCaseNameFilter = filterStr != null ? Pattern.compile(filterStr) : null;
if (testCaseNameFilter != null) {
System.out.println(
- "Note: " + TEST_FILTER_PROPERTY_NAME + " is " + _StringUtil.jQuote(testCaseNameFilter));
+ "Note: " + TEST_FILTER_PROPERTY_NAME + " is " + _StringUtils.jQuote(testCaseNameFilter));
}
testSuiteIcis = new ArrayList<>();
@@ -197,7 +197,7 @@ public abstract class TemplateTestSuite extends TestSuite {
*/
private List<TemplateTestCase> createTestCasesFromElement(Element testCaseElem)
throws Exception {
- final String caseName = _StringUtil.emptyToNull(testCaseElem.getAttribute("name"));
+ final String caseName = _StringUtils.emptyToNull(testCaseElem.getAttribute("name"));
if (caseName == null) throw new Exception("Invalid XML: the \"name\" attribute is mandatory.");
if (testCaseNameFilter != null
@@ -218,20 +218,20 @@ public abstract class TemplateTestSuite extends TestSuite {
}
{
- String s = _StringUtil.emptyToNull(testCaseElem.getAttribute(ATTR_TEMPLATE));
+ String s = _StringUtils.emptyToNull(testCaseElem.getAttribute(ATTR_TEMPLATE));
templateName = s != null ? s : beforeEndTN + ".ftl";
}
{
- String s = _StringUtil.emptyToNull(testCaseElem.getAttribute(ATTR_EXPECTED));
+ String s = _StringUtils.emptyToNull(testCaseElem.getAttribute(ATTR_EXPECTED));
expectedFileName = s != null ? s : beforeEndTN + afterEndTN + ".txt";
}
}
final boolean noOutput;
{
- String s = _StringUtil.emptyToNull(testCaseElem.getAttribute(ATTR_NO_OUTPUT));
- noOutput = s != null && _StringUtil.getYesNo(s);
+ String s = _StringUtils.emptyToNull(testCaseElem.getAttribute(ATTR_NO_OUTPUT));
+ noOutput = s != null && _StringUtils.getYesNo(s);
}
final Map<String, String> testCaseSettings = getCaseFMSettings(testCaseElem);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtil.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtil.java
deleted file mode 100644
index 13b03ec..0000000
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtil.java
+++ /dev/null
@@ -1,244 +0,0 @@
-package org.apache.freemarker.test;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.freemarker.core.Configuration;
-import org.apache.freemarker.core.Version;
-
-public final class TestUtil {
-
- private TestUtil() {
- // Not meant to be instantiated
- }
-
- /**
- * Returns the closes FreeMarker version number that doesn't exit yet (so it's illegal).
- */
- public static Version getClosestFutureVersion() {
- Version v = Configuration.getVersion();
- return new Version(v.getMajor(), v.getMinor(), v.getMicro() + 1);
- }
-
- public static String arrayToString(double[] xs) {
- StringBuilder sb = new StringBuilder();
-
- sb.append('[');
- for (double x : xs) {
- if (sb.length() != 1) sb.append(", ");
- sb.append(x);
- }
- sb.append(']');
-
- return sb.toString();
- }
-
- public static String arrayToString(Object[] array) {
- if (array == null) return "null";
-
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- for (int i = 0; i < array.length; i++) {
- if (i != 0) {
- sb.append(", ");
- }
- sb.append(array[i]);
- }
- sb.append(']');
- return sb.toString();
- }
-
- public static String arrayToString(Object[][] arrayArray) {
- if (arrayArray == null) return "null";
-
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- boolean first = true;
- for (Object[] array : arrayArray) {
- if (!first) {
- sb.append(", ");
- } else {
- first = false;
- }
- sb.append(arrayToString(array));
- }
- sb.append(']');
- return sb.toString();
- }
-
- public static String arrayToString(int[] array) {
- if (array == null) return "null";
-
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- for (int i = 0; i < array.length; i++) {
- if (i != 0) {
- sb.append(", ");
- }
- sb.append(array[i]);
- }
- sb.append(']');
- return sb.toString();
- }
-
- public static String arrayToString(int[][] xss) {
- if (xss == null) return "null";
-
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- for (int i = 0; i < xss.length; i++) {
- if (i != 0) {
- sb.append(", ");
- }
- sb.append(arrayToString(xss[i]));
- }
- sb.append(']');
- return sb.toString();
- }
-
- public static String arrayToString(char[] array) {
- if (array == null) return "null";
-
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- for (int i = 0; i < array.length; i++) {
- if (i != 0) {
- sb.append(", ");
- }
- sb.append(array[i]);
- }
- sb.append(']');
- return sb.toString();
- }
-
- public static String arrayToString(boolean[] array) {
- if (array == null) return "null";
-
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- for (int i = 0; i < array.length; i++) {
- if (i != 0) {
- sb.append(", ");
- }
- sb.append(array[i]);
- }
- sb.append(']');
- return sb.toString();
- }
-
- public static String listToString(List<?> list) {
- return collectionToString("", list);
- }
-
- public static String setToString(Set<?> list) {
- return collectionToString("Set", list);
- }
-
- private static String collectionToString(String prefix, Collection<?> list) {
- if (list == null) return "null";
-
- StringBuilder sb = new StringBuilder();
- sb.append(prefix);
- sb.append('[');
- boolean first = true;
- for (Object item : list) {
- if (!first) {
- sb.append(", ");
- } else {
- first = false;
- }
- sb.append(item instanceof Object[] ? arrayToString((Object[]) item) : item);
- }
- sb.append(']');
- return sb.toString();
- }
-
- public static String removeTxtCopyrightComment(String s) {
- if (!s.startsWith("/*")) {
- return s;
- }
-
- int commentEnd = s.indexOf("*/");
- if (commentEnd == -1) {
- return s;
- }
- commentEnd += 2;
- if (commentEnd < s.length()) {
- char c = s.charAt(commentEnd);
- if (c == '\n' || c == '\r') {
- commentEnd++;
- if (c == '\r' && commentEnd < s.length()) {
- if (s.charAt(commentEnd) == '\n') {
- commentEnd++;
- }
- }
- }
- }
-
- String comment = s.substring(0, commentEnd);
- int copyrightIdx = comment.indexOf("copyright");
- if (copyrightIdx == -1) {
- copyrightIdx = comment.indexOf("Copyright");
- }
- if (copyrightIdx == -1) {
- return s;
- }
-
- return s.substring(commentEnd);
- }
-
- public static String removeFTLCopyrightComment(String ftl) {
- if (ftl.contains("<#ftl nsPrefixes = {\"D\" : \"http://example.com/eBook\"}>")) {
- System.out.println();
- }
-
- int copyrightIdx = ftl.indexOf("copyright");
- if (copyrightIdx == -1) {
- copyrightIdx = ftl.indexOf("Copyright");
- }
- if (copyrightIdx == -1) {
- return ftl;
- }
-
- final int commentFirstIdx;
- final boolean squareBracketTagSyntax;
- {
- String ftlBeforeCopyright = ftl.substring(0, copyrightIdx);
- int abCommentStart = ftlBeforeCopyright.lastIndexOf("<#--");
- int sbCommentStart = ftlBeforeCopyright.lastIndexOf("[#--");
- squareBracketTagSyntax = sbCommentStart > abCommentStart;
- commentFirstIdx = squareBracketTagSyntax ? sbCommentStart : abCommentStart;
- if (commentFirstIdx == -1) {
- throw new AssertionError("Can't find copyright comment start");
- }
- }
-
- final int commentLastIdx;
- {
- int commentEndStart = ftl.indexOf(squareBracketTagSyntax ? "--]" : "-->", copyrightIdx);
- if (commentEndStart == -1) {
- throw new AssertionError("Can't find copyright comment end");
- }
- commentLastIdx = commentEndStart + 2;
- }
-
- final int afterCommentNLChars;
- if (commentLastIdx + 1 < ftl.length()) {
- char afterCommentChar = ftl.charAt(commentLastIdx + 1);
- if (afterCommentChar == '\n' || afterCommentChar == '\r') {
- if (afterCommentChar == '\r' && commentLastIdx + 2 < ftl.length() && ftl.charAt(commentLastIdx + 2) == '\n') {
- afterCommentNLChars = 2;
- } else {
- afterCommentNLChars = 1;
- }
- } else {
- afterCommentNLChars = 0;
- }
- } else {
- afterCommentNLChars = 0;
- }
-
- return ftl.substring(0, commentFirstIdx) + ftl.substring(commentLastIdx + afterCommentNLChars + 1);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtils.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtils.java
new file mode 100644
index 0000000..f338b27
--- /dev/null
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/TestUtils.java
@@ -0,0 +1,244 @@
+package org.apache.freemarker.test;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.freemarker.core.Configuration;
+import org.apache.freemarker.core.Version;
+
+public final class TestUtils {
+
+ private TestUtils() {
+ // Not meant to be instantiated
+ }
+
+ /**
+ * Returns the closes FreeMarker version number that doesn't exit yet (so it's illegal).
+ */
+ public static Version getClosestFutureVersion() {
+ Version v = Configuration.getVersion();
+ return new Version(v.getMajor(), v.getMinor(), v.getMicro() + 1);
+ }
+
+ public static String arrayToString(double[] xs) {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append('[');
+ for (double x : xs) {
+ if (sb.length() != 1) sb.append(", ");
+ sb.append(x);
+ }
+ sb.append(']');
+
+ return sb.toString();
+ }
+
+ public static String arrayToString(Object[] array) {
+ if (array == null) return "null";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ for (int i = 0; i < array.length; i++) {
+ if (i != 0) {
+ sb.append(", ");
+ }
+ sb.append(array[i]);
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ public static String arrayToString(Object[][] arrayArray) {
+ if (arrayArray == null) return "null";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ boolean first = true;
+ for (Object[] array : arrayArray) {
+ if (!first) {
+ sb.append(", ");
+ } else {
+ first = false;
+ }
+ sb.append(arrayToString(array));
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ public static String arrayToString(int[] array) {
+ if (array == null) return "null";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ for (int i = 0; i < array.length; i++) {
+ if (i != 0) {
+ sb.append(", ");
+ }
+ sb.append(array[i]);
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ public static String arrayToString(int[][] xss) {
+ if (xss == null) return "null";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ for (int i = 0; i < xss.length; i++) {
+ if (i != 0) {
+ sb.append(", ");
+ }
+ sb.append(arrayToString(xss[i]));
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ public static String arrayToString(char[] array) {
+ if (array == null) return "null";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ for (int i = 0; i < array.length; i++) {
+ if (i != 0) {
+ sb.append(", ");
+ }
+ sb.append(array[i]);
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ public static String arrayToString(boolean[] array) {
+ if (array == null) return "null";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ for (int i = 0; i < array.length; i++) {
+ if (i != 0) {
+ sb.append(", ");
+ }
+ sb.append(array[i]);
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ public static String listToString(List<?> list) {
+ return collectionToString("", list);
+ }
+
+ public static String setToString(Set<?> list) {
+ return collectionToString("Set", list);
+ }
+
+ private static String collectionToString(String prefix, Collection<?> list) {
+ if (list == null) return "null";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(prefix);
+ sb.append('[');
+ boolean first = true;
+ for (Object item : list) {
+ if (!first) {
+ sb.append(", ");
+ } else {
+ first = false;
+ }
+ sb.append(item instanceof Object[] ? arrayToString((Object[]) item) : item);
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+ public static String removeTxtCopyrightComment(String s) {
+ if (!s.startsWith("/*")) {
+ return s;
+ }
+
+ int commentEnd = s.indexOf("*/");
+ if (commentEnd == -1) {
+ return s;
+ }
+ commentEnd += 2;
+ if (commentEnd < s.length()) {
+ char c = s.charAt(commentEnd);
+ if (c == '\n' || c == '\r') {
+ commentEnd++;
+ if (c == '\r' && commentEnd < s.length()) {
+ if (s.charAt(commentEnd) == '\n') {
+ commentEnd++;
+ }
+ }
+ }
+ }
+
+ String comment = s.substring(0, commentEnd);
+ int copyrightIdx = comment.indexOf("copyright");
+ if (copyrightIdx == -1) {
+ copyrightIdx = comment.indexOf("Copyright");
+ }
+ if (copyrightIdx == -1) {
+ return s;
+ }
+
+ return s.substring(commentEnd);
+ }
+
+ public static String removeFTLCopyrightComment(String ftl) {
+ if (ftl.contains("<#ftl nsPrefixes = {\"D\" : \"http://example.com/eBook\"}>")) {
+ System.out.println();
+ }
+
+ int copyrightIdx = ftl.indexOf("copyright");
+ if (copyrightIdx == -1) {
+ copyrightIdx = ftl.indexOf("Copyright");
+ }
+ if (copyrightIdx == -1) {
+ return ftl;
+ }
+
+ final int commentFirstIdx;
+ final boolean squareBracketTagSyntax;
+ {
+ String ftlBeforeCopyright = ftl.substring(0, copyrightIdx);
+ int abCommentStart = ftlBeforeCopyright.lastIndexOf("<#--");
+ int sbCommentStart = ftlBeforeCopyright.lastIndexOf("[#--");
+ squareBracketTagSyntax = sbCommentStart > abCommentStart;
+ commentFirstIdx = squareBracketTagSyntax ? sbCommentStart : abCommentStart;
+ if (commentFirstIdx == -1) {
+ throw new AssertionError("Can't find copyright comment start");
+ }
+ }
+
+ final int commentLastIdx;
+ {
+ int commentEndStart = ftl.indexOf(squareBracketTagSyntax ? "--]" : "-->", copyrightIdx);
+ if (commentEndStart == -1) {
+ throw new AssertionError("Can't find copyright comment end");
+ }
+ commentLastIdx = commentEndStart + 2;
+ }
+
+ final int afterCommentNLChars;
+ if (commentLastIdx + 1 < ftl.length()) {
+ char afterCommentChar = ftl.charAt(commentLastIdx + 1);
+ if (afterCommentChar == '\n' || afterCommentChar == '\r') {
+ if (afterCommentChar == '\r' && commentLastIdx + 2 < ftl.length() && ftl.charAt(commentLastIdx + 2) == '\n') {
+ afterCommentNLChars = 2;
+ } else {
+ afterCommentNLChars = 1;
+ }
+ } else {
+ afterCommentNLChars = 0;
+ }
+ } else {
+ afterCommentNLChars = 0;
+ }
+
+ return ftl.substring(0, commentFirstIdx) + ftl.substring(commentLastIdx + afterCommentNLChars + 1);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertEqualsDirective.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertEqualsDirective.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertEqualsDirective.java
index 51baeb4..b5f62e7 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertEqualsDirective.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertEqualsDirective.java
@@ -34,7 +34,7 @@ import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.util.StringToIndexMap;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
public class AssertEqualsDirective implements TemplateDirectiveModel {
@@ -92,7 +92,7 @@ public class AssertEqualsDirective implements TemplateDirectiveModel {
// This is the same order as comparison goes:
else if (value instanceof TemplateNumberModel) return ((TemplateNumberModel) value).getAsNumber().toString();
else if (value instanceof TemplateDateModel) return ((TemplateDateModel) value).getAsDate().toString();
- else if (value instanceof TemplateScalarModel) return _StringUtil.jQuote(((TemplateScalarModel) value).getAsString());
+ else if (value instanceof TemplateScalarModel) return _StringUtils.jQuote(((TemplateScalarModel) value).getAsString());
else if (value instanceof TemplateBooleanModel) return String.valueOf(((TemplateBooleanModel) value).getAsBoolean());
// This shouldn't be reached, as the comparison should have failed earlier:
else return value.toString();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertFailsDirective.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertFailsDirective.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertFailsDirective.java
index 6fe1505..05a5cb0 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertFailsDirective.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/AssertFailsDirective.java
@@ -34,7 +34,7 @@ import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.util.StringToIndexMap;
import org.apache.freemarker.core.util._NullWriter;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
public class AssertFailsDirective implements TemplateDirectiveModel {
@@ -93,7 +93,7 @@ public class AssertFailsDirective implements TemplateDirectiveModel {
if (e.getMessage() == null) {
throw new AssertationFailedInTemplateException(
"Failure is not like expected. The exception message was null, "
- + "and thus it doesn't contain:\n" + _StringUtil.jQuote(message) + ".",
+ + "and thus it doesn't contain:\n" + _StringUtils.jQuote(message) + ".",
env);
}
if (message != null) {
@@ -101,18 +101,18 @@ public class AssertFailsDirective implements TemplateDirectiveModel {
? ((TemplateException) e).getMessageWithoutStackTop() : e.getMessage();
if (!actualMessage.toLowerCase().contains(message.toLowerCase())) {
throw new AssertationFailedInTemplateException(
- "Failure is not like expected. The exception message:\n" + _StringUtil
+ "Failure is not like expected. The exception message:\n" + _StringUtils
.jQuote(actualMessage)
- + "\ndoesn't contain:\n" + _StringUtil.jQuote(message) + ".",
+ + "\ndoesn't contain:\n" + _StringUtils.jQuote(message) + ".",
env);
}
}
if (messageRegexp != null) {
if (!messageRegexp.matcher(e.getMessage()).find()) {
throw new AssertationFailedInTemplateException(
- "Failure is not like expected. The exception message:\n" + _StringUtil
+ "Failure is not like expected. The exception message:\n" + _StringUtils
.jQuote(e.getMessage())
- + "\ndoesn't match this regexp:\n" + _StringUtil
+ + "\ndoesn't match this regexp:\n" + _StringUtils
.jQuote(messageRegexp.toString())
+ ".",
env);
@@ -121,9 +121,9 @@ public class AssertFailsDirective implements TemplateDirectiveModel {
}
if (exception != null && !e.getClass().getName().contains(exception)) {
throw new AssertationFailedInTemplateException(
- "Failure is not like expected. The exception class name " + _StringUtil
+ "Failure is not like expected. The exception class name " + _StringUtils
.jQuote(e.getClass().getName())
- + " doesn't contain " + _StringUtil.jQuote(message) + ".",
+ + " doesn't contain " + _StringUtils.jQuote(message) + ".",
env);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/BadParameterTypeException.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/BadParameterTypeException.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/BadParameterTypeException.java
index 0a3a350..34b7ec5 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/BadParameterTypeException.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/BadParameterTypeException.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.test.templateutil;
import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateModel;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Indicates that a named directive/function parameter is not of the expected type.
@@ -46,9 +46,9 @@ public class BadParameterTypeException extends ParameterException {
public BadParameterTypeException(
String parameterName, String expectedType, TemplateModel value, String description, Exception cause, Environment env) {
super(parameterName,
- "The type of the parameter " + _StringUtil.jQuote(parameterName) + " should be " + expectedType
+ "The type of the parameter " + _StringUtils.jQuote(parameterName) + " should be " + expectedType
+ ", but the actual value was " + getTypeDescription(value) + "."
- + (description != null ? " " + _StringUtil.jQuote(description) : ""),
+ + (description != null ? " " + _StringUtils.jQuote(description) : ""),
cause, env);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/MissingRequiredParameterException.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/MissingRequiredParameterException.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/MissingRequiredParameterException.java
index b222cfd..19b2927 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/MissingRequiredParameterException.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/MissingRequiredParameterException.java
@@ -20,7 +20,7 @@
package org.apache.freemarker.test.templateutil;
import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Indicates that a named directive/function parameter is missing.
@@ -42,9 +42,9 @@ class MissingRequiredParameterException extends ParameterException {
public MissingRequiredParameterException(String parameterName, String description, Exception cause, Environment env) {
super(parameterName,
- "Required parameter " + _StringUtil.jQuote(parameterName) + " is missing, "
+ "Required parameter " + _StringUtils.jQuote(parameterName) + " is missing, "
+ "or the parameter value was null."
- + (description != null ? " " + _StringUtil.jQuote(description) : ""),
+ + (description != null ? " " + _StringUtils.jQuote(description) : ""),
cause, env);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/UnsupportedParameterException.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/UnsupportedParameterException.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/UnsupportedParameterException.java
index f8278f8..4b0e274 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/UnsupportedParameterException.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/templateutil/UnsupportedParameterException.java
@@ -20,7 +20,7 @@
package org.apache.freemarker.test.templateutil;
import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Indicates that a named directive/function parameter is unsupported (like a typo).
@@ -42,8 +42,8 @@ class UnsupportedParameterException extends ParameterException {
public UnsupportedParameterException(String parameterName, String description, Exception cause, Environment env) {
super(parameterName,
- "Unsuppored parameter: " + _StringUtil.jQuote(parameterName)
- + (description == null ? "." : ". " + _StringUtil.jQuote(description)),
+ "Unsuppored parameter: " + _StringUtils.jQuote(parameterName)
+ + (description == null ? "." : ". " + _StringUtils.jQuote(description)),
cause, env);
}
[12/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForMultipleTypes.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForMultipleTypes.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForMultipleTypes.java
index b1bd1dd..6632654 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForMultipleTypes.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForMultipleTypes.java
@@ -60,7 +60,7 @@ class BuiltInsForMultipleTypes {
return formatNumber(env, model);
} else if (model instanceof TemplateBooleanModel) {
return new SimpleScalar(((TemplateBooleanModel) model).getAsBoolean()
- ? MiscUtil.C_TRUE : MiscUtil.C_FALSE);
+ ? TemplateBooleanFormat.C_TRUE : TemplateBooleanFormat.C_FALSE);
} else {
throw new UnexpectedTypeException(
target, model,
@@ -71,7 +71,7 @@ class BuiltInsForMultipleTypes {
@Override
protected TemplateModel formatNumber(Environment env, TemplateModel model) throws TemplateModelException {
- Number num = _EvalUtil.modelToNumber((TemplateNumberModel) model, target);
+ Number num = _EvalUtils.modelToNumber((TemplateNumberModel) model, target);
if (num instanceof Integer || num instanceof Long) {
// Accelerate these fairly common cases
return new SimpleScalar(num.toString());
@@ -514,7 +514,7 @@ class BuiltInsForMultipleTypes {
defaultFormat = dateType == TemplateDateModel.UNKNOWN
? null // Lazy unknown type error in getAsString()
: env.getTemplateDateFormat(
- dateType, _EvalUtil.modelToDate(dateModel, target).getClass(), target, true);
+ dateType, _EvalUtils.modelToDate(dateModel, target).getClass(), target, true);
}
@Override
@@ -550,16 +550,16 @@ class BuiltInsForMultipleTypes {
if (cachedValue == null) {
if (defaultFormat == null) {
if (dateModel.getDateType() == TemplateDateModel.UNKNOWN) {
- throw MessageUtil.newCantFormatUnknownTypeDateException(target, null);
+ throw MessageUtils.newCantFormatUnknownTypeDateException(target, null);
} else {
throw new BugException();
}
}
try {
- cachedValue = _EvalUtil.assertFormatResultNotNull(defaultFormat.formatToPlainText(dateModel));
+ cachedValue = _EvalUtils.assertFormatResultNotNull(defaultFormat.formatToPlainText(dateModel));
} catch (TemplateValueFormatException e) {
try {
- throw MessageUtil.newCantFormatDateException(defaultFormat, target, e, true);
+ throw MessageUtils.newCantFormatDateException(defaultFormat, target, e, true);
} catch (TemplateException e2) {
// `e` should always be a TemplateModelException here, but to be sure:
throw _CoreAPI.ensureIsTemplateModelException("Failed to format date/time/dateTime", e2);
@@ -587,7 +587,7 @@ class BuiltInsForMultipleTypes {
// As we format lazily, we need a snapshot of the format inputs:
this.numberModel = numberModel;
- number = _EvalUtil.modelToNumber(numberModel, target); // for BackwardCompatibleTemplateNumberFormat-s
+ number = _EvalUtils.modelToNumber(numberModel, target); // for BackwardCompatibleTemplateNumberFormat-s
try {
defaultFormat = env.getTemplateNumberFormat(stringBI.this, true);
} catch (TemplateException e) {
@@ -652,7 +652,7 @@ class BuiltInsForMultipleTypes {
TemplateModel model = target.eval(env);
if (model instanceof TemplateNumberModel) {
TemplateNumberModel numberModel = (TemplateNumberModel) model;
- Number num = _EvalUtil.modelToNumber(numberModel, target);
+ Number num = _EvalUtils.modelToNumber(numberModel, target);
return new NumberFormatter(numberModel, env);
} else if (model instanceof TemplateDateModel) {
TemplateDateModel dm = (TemplateDateModel) model;
@@ -688,7 +688,7 @@ class BuiltInsForMultipleTypes {
return formatNumber(env, model);
} else if (model instanceof TemplateBooleanModel) {
return new SimpleScalar(((TemplateBooleanModel) model).getAsBoolean()
- ? MiscUtil.C_TRUE : MiscUtil.C_FALSE);
+ ? TemplateBooleanFormat.C_TRUE : TemplateBooleanFormat.C_FALSE);
} else {
throw new UnexpectedTypeException(
target, model,
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNodes.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNodes.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNodes.java
index 5390dc4..bd01e06 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNodes.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNodes.java
@@ -26,7 +26,7 @@ import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNodeModel;
import org.apache.freemarker.core.model.TemplateNodeModelEx;
import org.apache.freemarker.core.model.impl.SimpleScalar;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* A holder for builtins that operate exclusively on (XML-)node left-hand value.
@@ -145,7 +145,7 @@ class BuiltInsForNodes {
}
} else {
for (int argIdx = 0; argIdx < args.length; argIdx++) {
- if (_StringUtil.matchesQName(
+ if (_StringUtils.matchesQName(
_CallableUtils.castArgToString(args, argIdx), nodeName, nsURI, env)) {
result.add(tnm);
break;
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNumbers.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNumbers.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNumbers.java
index 58a2aa6..c197756 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNumbers.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForNumbers.java
@@ -31,8 +31,8 @@ import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.model.impl.SimpleDate;
import org.apache.freemarker.core.model.impl.SimpleNumber;
import org.apache.freemarker.core.model.impl.SimpleScalar;
-import org.apache.freemarker.core.util._NumberUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._NumberUtils;
+import org.apache.freemarker.core.util._StringUtils;
/**
* A holder for builtins that operate exclusively on number left-hand value.
@@ -45,7 +45,7 @@ class BuiltInsForNumbers {
TemplateModel calculateResult(Number num, TemplateModel model) throws TemplateModelException {
final int n;
try {
- n = _NumberUtil.toIntExact(num);
+ n = _NumberUtils.toIntExact(num);
} catch (ArithmeticException e) {
throw new _TemplateModelException(target,
"The left side operand value isn't compatible with ?", key, ": ", e.getMessage());
@@ -66,7 +66,7 @@ class BuiltInsForNumbers {
@Override
protected String toABC(int n) {
- return _StringUtil.toLowerABC(n);
+ return _StringUtils.toLowerABC(n);
}
}
@@ -75,7 +75,7 @@ class BuiltInsForNumbers {
@Override
protected String toABC(int n) {
- return _StringUtil.toUpperABC(n);
+ return _StringUtils.toUpperABC(n);
}
}
@@ -202,7 +202,7 @@ class BuiltInsForNumbers {
static class is_infiniteBI extends BuiltInForNumber {
@Override
TemplateModel calculateResult(Number num, TemplateModel model) throws TemplateModelException {
- return _NumberUtil.isInfinite(num) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
+ return _NumberUtils.isInfinite(num) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
}
}
@@ -210,7 +210,7 @@ class BuiltInsForNumbers {
static class is_nanBI extends BuiltInForNumber {
@Override
TemplateModel calculateResult(Number num, TemplateModel model) throws TemplateModelException {
- return _NumberUtil.isNaN(num) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
+ return _NumberUtils.isNaN(num) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
}
}
@@ -222,7 +222,7 @@ class BuiltInsForNumbers {
TemplateModel model = target.eval(env);
if (!(model instanceof TemplateNumberModel)
&& model instanceof TemplateDateModel) {
- Date date = _EvalUtil.modelToDate((TemplateDateModel) model, target);
+ Date date = _EvalUtils.modelToDate((TemplateDateModel) model, target);
return new SimpleNumber(date.getTime());
} else {
Number num = target.modelToNumber(model, env);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForOutputFormatRelated.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForOutputFormatRelated.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForOutputFormatRelated.java
index 2ae2fe7..5ab518c 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForOutputFormatRelated.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForOutputFormatRelated.java
@@ -49,7 +49,7 @@ class BuiltInsForOutputFormatRelated {
@Override
protected TemplateModel calculateResult(Environment env) throws TemplateException {
TemplateModel lhoTM = target.eval(env);
- Object lhoMOOrStr = _EvalUtil.coerceModelToStringOrMarkup(lhoTM, target, null, env);
+ Object lhoMOOrStr = _EvalUtils.coerceModelToStringOrMarkup(lhoTM, target, null, env);
MarkupOutputFormat contextOF = outputFormat;
if (lhoMOOrStr instanceof String) { // TemplateMarkupOutputModel
return calculateResult((String) lhoMOOrStr, contextOF, env);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForSequences.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForSequences.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForSequences.java
index 6757998..f5e3253 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForSequences.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForSequences.java
@@ -44,7 +44,7 @@ import org.apache.freemarker.core.model.impl.SimpleNumber;
import org.apache.freemarker.core.model.impl.SimpleScalar;
import org.apache.freemarker.core.model.impl.TemplateModelListSequence;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* A holder for builtins that operate exclusively on sequence or collection left-hand value.
@@ -215,13 +215,13 @@ class BuiltInsForSequences {
hadItem = true;
}
try {
- sb.append(_EvalUtil.coerceModelToStringOrUnsupportedMarkup(item, null, null, env));
+ sb.append(_EvalUtils.coerceModelToStringOrUnsupportedMarkup(item, null, null, env));
} catch (TemplateException e) {
throw new _TemplateModelException(e,
"\"?", key, "\" failed at index ", idx, " with this error:\n\n",
- MessageUtil.EMBEDDED_MESSAGE_BEGIN,
+ MessageUtils.EMBEDDED_MESSAGE_BEGIN,
new _DelayedGetMessageWithoutStackTop(e),
- MessageUtil.EMBEDDED_MESSAGE_END);
+ MessageUtils.EMBEDDED_MESSAGE_END);
}
}
idx++;
@@ -716,7 +716,7 @@ class BuiltInsForSequences {
startErrorMessage(keyNamesLn, i),
(keyNameI == 0
? "Sequence items must be hashes when using ?sortBy. "
- : "The " + _StringUtil.jQuote(keyNames[keyNameI - 1])),
+ : "The " + _StringUtils.jQuote(keyNames[keyNameI - 1])),
" subvariable is not a hash, so ?sortBy ",
"can't proceed with getting the ",
new _DelayedJQuote(keyNames[keyNameI]),
@@ -728,7 +728,7 @@ class BuiltInsForSequences {
if (key == null) {
throw new _TemplateModelException(
startErrorMessage(keyNamesLn, i),
- "The " + _StringUtil.jQuote(keyNames[keyNameI]), " subvariable was null or missing.");
+ "The " + _StringUtils.jQuote(keyNames[keyNameI]), " subvariable was null or missing.");
}
} // for each key
@@ -864,9 +864,9 @@ class BuiltInsForSequences {
Environment env)
throws TemplateModelException {
try {
- return _EvalUtil.compare(
+ return _EvalUtils.compare(
seqItem, null,
- _EvalUtil.CMP_OP_EQUALS, null,
+ _EvalUtils.CMP_OP_EQUALS, null,
searchedItem, null,
null, false,
true, true, true, // The last one is true to emulate an old bug for BC
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsBasic.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsBasic.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsBasic.java
index 9311626..b7a0e93 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsBasic.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsBasic.java
@@ -32,7 +32,7 @@ import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.impl.SimpleNumber;
import org.apache.freemarker.core.model.impl.SimpleScalar;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
class BuiltInsForStringsBasic {
@@ -56,14 +56,14 @@ class BuiltInsForStringsBasic {
static class capitalizeBI extends BuiltInForString {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.capitalize(s));
+ return new SimpleScalar(_StringUtils.capitalize(s));
}
}
static class chop_linebreakBI extends BuiltInForString {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.chomp(s));
+ return new SimpleScalar(_StringUtils.chomp(s));
}
}
@@ -504,8 +504,8 @@ class BuiltInsForStringsBasic {
try {
return new SimpleScalar(
leftPadder
- ? _StringUtil.leftPad(s, width, filling)
- : _StringUtil.rightPad(s, width, filling));
+ ? _StringUtils.leftPad(s, width, filling)
+ : _StringUtils.rightPad(s, width, filling));
} catch (IllegalArgumentException e) {
if (filling.length() == 0) {
throw new _TemplateModelException(
@@ -516,7 +516,7 @@ class BuiltInsForStringsBasic {
}
}
} else {
- return new SimpleScalar(leftPadder ? _StringUtil.leftPad(s, width) : _StringUtil.rightPad(s, width));
+ return new SimpleScalar(leftPadder ? _StringUtils.leftPad(s, width) : _StringUtils.rightPad(s, width));
}
}
@@ -614,7 +614,7 @@ class BuiltInsForStringsBasic {
String[] result;
if ((flags & RegexpHelper.RE_FLAG_REGEXP) == 0) {
RegexpHelper.checkNonRegexpFlags("split", flags);
- result = _StringUtil.split(s, splitString,
+ result = _StringUtils.split(s, splitString,
(flags & RegexpHelper.RE_FLAG_CASE_INSENSITIVE) != 0);
} else {
Pattern pattern = RegexpHelper.getPattern(splitString, (int) flags);
@@ -692,7 +692,7 @@ class BuiltInsForStringsBasic {
throw newIndexGreaterThanLengthException(1, endIdx, len);
}
if (beginIdx > endIdx) {
- throw MessageUtil.newMethodArgsInvalidValueException("?" + key,
+ throw MessageUtils.newMethodArgsInvalidValueException("?" + key,
"The begin index argument, ", beginIdx,
", shouldn't be greater than the end index argument, ",
endIdx, ".");
@@ -710,7 +710,7 @@ class BuiltInsForStringsBasic {
private TemplateModelException newIndexGreaterThanLengthException(
int argIdx, int idx, final int len) throws TemplateModelException {
- return MessageUtil.newMethodArgInvalidValueException(
+ return MessageUtils.newMethodArgInvalidValueException(
"?" + key, argIdx,
"The index mustn't be greater than the length of the string, ",
len, ", but it was ", idx, ".");
@@ -718,7 +718,7 @@ class BuiltInsForStringsBasic {
private TemplateModelException newIndexLessThan0Exception(
int argIdx, int idx) throws TemplateModelException {
- return MessageUtil.newMethodArgInvalidValueException(
+ return MessageUtils.newMethodArgInvalidValueException(
"?" + key, argIdx,
"The index must be at least 0, but was ", idx, ".");
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsEncoding.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsEncoding.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsEncoding.java
index 794fe94..6d67d4f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsEncoding.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsEncoding.java
@@ -29,7 +29,7 @@ import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.impl.SimpleScalar;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
class BuiltInsForStringsEncoding {
@@ -37,7 +37,7 @@ class BuiltInsForStringsEncoding {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.XHTMLEnc(s));
+ return new SimpleScalar(_StringUtils.XHTMLEnc(s));
}
}
@@ -45,28 +45,28 @@ class BuiltInsForStringsEncoding {
static class j_stringBI extends BuiltInForString {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.javaStringEnc(s));
+ return new SimpleScalar(_StringUtils.javaStringEnc(s));
}
}
static class js_stringBI extends BuiltInForString {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.javaScriptStringEnc(s));
+ return new SimpleScalar(_StringUtils.javaScriptStringEnc(s));
}
}
static class json_stringBI extends BuiltInForString {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.jsonStringEnc(s));
+ return new SimpleScalar(_StringUtils.jsonStringEnc(s));
}
}
static class rtfBI extends BuiltInForLegacyEscaping {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.RTFEnc(s));
+ return new SimpleScalar(_StringUtils.RTFEnc(s));
}
}
@@ -80,7 +80,7 @@ class BuiltInsForStringsEncoding {
@Override
protected String encodeWithCharset(Charset charset) throws UnsupportedEncodingException {
- return _StringUtil.URLEnc(targetAsString, charset);
+ return _StringUtils.URLEnc(targetAsString, charset);
}
}
@@ -102,7 +102,7 @@ class BuiltInsForStringsEncoding {
@Override
protected String encodeWithCharset(Charset charset) throws UnsupportedEncodingException {
- return _StringUtil.URLPathEnc(targetAsString, charset);
+ return _StringUtils.URLPathEnc(targetAsString, charset);
}
}
@@ -117,14 +117,14 @@ class BuiltInsForStringsEncoding {
static class xhtmlBI extends BuiltInForLegacyEscaping {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.XHTMLEnc(s));
+ return new SimpleScalar(_StringUtils.XHTMLEnc(s));
}
}
static class xmlBI extends BuiltInForLegacyEscaping {
@Override
TemplateModel calculateResult(String s, Environment env) {
- return new SimpleScalar(_StringUtil.XMLEnc(s));
+ return new SimpleScalar(_StringUtils.XMLEnc(s));
}
}
@@ -157,7 +157,7 @@ class BuiltInsForStringsEncoding {
charset = Charset.forName(charsetName);
} catch (UnsupportedCharsetException e) {
throw new _TemplateModelException(e, "Wrong charset name, or charset is unsupported by the runtime "
- + "environment: " + _StringUtil.jQuote(charsetName));
+ + "environment: " + _StringUtils.jQuote(charsetName));
}
return new SimpleScalar(encodeWithCharset(charset));
} catch (Exception e) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsMisc.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsMisc.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsMisc.java
index 1bcd592..c90f15d 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsMisc.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsMisc.java
@@ -45,9 +45,9 @@ class BuiltInsForStringsMisc {
@Override
TemplateModel calculateResult(String s, Environment env) throws TemplateException {
final boolean b;
- if (s.equals(MiscUtil.C_TRUE)) {
+ if (s.equals(TemplateBooleanFormat.C_TRUE)) {
b = true;
- } else if (s.equals(MiscUtil.C_FALSE)) {
+ } else if (s.equals(TemplateBooleanFormat.C_FALSE)) {
b = false;
} else if (s.equals(env.getTemplateBooleanFormat().getTrueStringValue())) {
b = true;
@@ -98,9 +98,9 @@ class BuiltInsForStringsMisc {
} catch (ParseException e) {
throw new _MiscTemplateException(this, env,
"Failed to \"?", key, "\" string with this error:\n\n",
- MessageUtil.EMBEDDED_MESSAGE_BEGIN,
+ MessageUtils.EMBEDDED_MESSAGE_BEGIN,
new _DelayedGetMessage(e),
- MessageUtil.EMBEDDED_MESSAGE_END,
+ MessageUtils.EMBEDDED_MESSAGE_END,
"\n\nThe failing expression:");
}
try {
@@ -108,9 +108,9 @@ class BuiltInsForStringsMisc {
} catch (TemplateException e) {
throw new _MiscTemplateException(this, env,
"Failed to \"?", key, "\" string with this error:\n\n",
- MessageUtil.EMBEDDED_MESSAGE_BEGIN,
+ MessageUtils.EMBEDDED_MESSAGE_BEGIN,
new _DelayedGetMessageWithoutStackTop(e),
- MessageUtil.EMBEDDED_MESSAGE_END,
+ MessageUtils.EMBEDDED_MESSAGE_END,
"\n\nThe failing expression:");
}
}
@@ -181,9 +181,9 @@ class BuiltInsForStringsMisc {
} catch (IOException e) {
throw new _MiscTemplateException(this, e, env,
"Template parsing with \"?", key, "\" has failed with this error:\n\n",
- MessageUtil.EMBEDDED_MESSAGE_BEGIN,
+ MessageUtils.EMBEDDED_MESSAGE_BEGIN,
new _DelayedGetMessage(e),
- MessageUtil.EMBEDDED_MESSAGE_END,
+ MessageUtils.EMBEDDED_MESSAGE_END,
"\n\nThe failed expression:");
}
@@ -210,9 +210,9 @@ class BuiltInsForStringsMisc {
} catch (Exception e) {
throw new _TemplateModelException(e,
"Template created with \"?", key, "\" has stopped with this error:\n\n",
- MessageUtil.EMBEDDED_MESSAGE_BEGIN,
+ MessageUtils.EMBEDDED_MESSAGE_BEGIN,
new _DelayedGetMessage(e),
- MessageUtil.EMBEDDED_MESSAGE_END);
+ MessageUtils.EMBEDDED_MESSAGE_END);
}
callPlace.executeNestedContent(null, out, env);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsRegexp.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsRegexp.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsRegexp.java
index ef73e5f..8c75de1 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsRegexp.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForStringsRegexp.java
@@ -33,7 +33,7 @@ import org.apache.freemarker.core.model.TemplateModelIterator;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.TemplateSequenceModel;
import org.apache.freemarker.core.model.impl.SimpleScalar;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
@@ -120,7 +120,7 @@ class BuiltInsForStringsRegexp {
String result;
if ((flags & RegexpHelper.RE_FLAG_REGEXP) == 0) {
RegexpHelper.checkNonRegexpFlags("replace", flags);
- result = _StringUtil.replace(s, arg1, arg2,
+ result = _StringUtils.replace(s, arg1, arg2,
(flags & RegexpHelper.RE_FLAG_CASE_INSENSITIVE) != 0,
(flags & RegexpHelper.RE_FLAG_FIRST_ONLY) != 0);
} else {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsWithParseTimeParameters.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsWithParseTimeParameters.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsWithParseTimeParameters.java
index 1126410..d88c2d9 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsWithParseTimeParameters.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsWithParseTimeParameters.java
@@ -132,9 +132,9 @@ final class BuiltInsWithParseTimeParameters {
for (int i = 0; i + 1 < paramCnt; i += 2) {
ASTExpression caseExp = (ASTExpression) parameters.get(i);
TemplateModel caseValue = caseExp.evalToNonMissing(env);
- if (_EvalUtil.compare(
+ if (_EvalUtils.compare(
targetValue, target,
- _EvalUtil.CMP_OP_EQUALS, "==",
+ _EvalUtils.CMP_OP_EQUALS, "==",
caseValue, caseExp,
this, true,
false, false, false,
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/Configuration.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/Configuration.java b/freemarker-core/src/main/java/org/apache/freemarker/core/Configuration.java
index 3eea7b9..e817c1c 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/Configuration.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/Configuration.java
@@ -80,11 +80,11 @@ import org.apache.freemarker.core.templateresolver.impl.DefaultTemplateNameForma
import org.apache.freemarker.core.templateresolver.impl.DefaultTemplateResolver;
import org.apache.freemarker.core.templateresolver.impl.MruCacheStorage;
import org.apache.freemarker.core.templateresolver.impl.SoftCacheStorage;
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._CollectionUtils;
import org.apache.freemarker.core.util._NullArgumentException;
import org.apache.freemarker.core.util._SortedArraySet;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.util._UnmodifiableCompositeSet;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory;
@@ -340,7 +340,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
this.objectWrapper = builder.getObjectWrapper();
{
- Map<String, Object> sharedVariables = _CollectionUtil.mergeImmutableMaps(builder
+ Map<String, Object> sharedVariables = _CollectionUtils.mergeImmutableMaps(builder
.getImpliedSharedVariables(), builder.getSharedVariables(), false);
HashMap<String, TemplateModel> wrappedSharedVariables = new HashMap<>(
@@ -351,7 +351,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
} catch (TemplateModelException e) {
throw new InvalidSettingValueException(
ExtendableBuilder.SHARED_VARIABLES_KEY, null, false,
- "Failed to wrap shared variable " + _StringUtil.jQuote(ent.getKey()),
+ "Failed to wrap shared variable " + _StringUtils.jQuote(ent.getKey()),
e);
}
}
@@ -390,13 +390,13 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
newBuiltinClassResolver = builder.getNewBuiltinClassResolver();
showErrorTips = builder.getShowErrorTips();
apiBuiltinEnabled = builder.getAPIBuiltinEnabled();
- customDateFormats = _CollectionUtil.mergeImmutableMaps(
+ customDateFormats = _CollectionUtils.mergeImmutableMaps(
builder.getImpliedCustomDateFormats(), builder.getCustomDateFormats(), false);
- customNumberFormats = _CollectionUtil.mergeImmutableMaps(
+ customNumberFormats = _CollectionUtils.mergeImmutableMaps(
builder.getImpliedCustomNumberFormats(), builder.getCustomNumberFormats(), false);
- autoImports = _CollectionUtil.mergeImmutableMaps(
+ autoImports = _CollectionUtils.mergeImmutableMaps(
builder.getImpliedAutoImports(), builder.getAutoImports(), true);
- autoIncludes = _CollectionUtil.mergeImmutableLists(
+ autoIncludes = _CollectionUtils.mergeImmutableLists(
builder.getImpliedAutoIncludes(), builder.getAutoIncludes(), true);
lazyImports = builder.getLazyImports();
lazyAutoImports = builder.getLazyAutoImports();
@@ -744,7 +744,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
if (stdOF == null) {
StringBuilder sb = new StringBuilder();
sb.append("Unregistered output format name, ");
- sb.append(_StringUtil.jQuote(name));
+ sb.append(_StringUtils.jQuote(name));
sb.append(". The output formats registered in the Configuration are: ");
Set<String> registeredNames = new TreeSet<>();
@@ -758,7 +758,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
} else {
sb.append(", ");
}
- sb.append(_StringUtil.jQuote(registeredName));
+ sb.append(_StringUtils.jQuote(registeredName));
}
throw new UnregisteredOutputFormatException(sb.toString());
@@ -1358,29 +1358,29 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
TemplateLoader tl = getTemplateLoader();
String msg;
if (tl == null) {
- msg = "Don't know where to load template " + _StringUtil.jQuote(name)
+ msg = "Don't know where to load template " + _StringUtils.jQuote(name)
+ " from because the \"templateLoader\" FreeMarker "
+ "setting wasn't set (Configuration.setTemplateLoader), so it's null.";
} else {
final String missingTempNormName = maybeTemp.getMissingTemplateNormalizedName();
final String missingTempReason = maybeTemp.getMissingTemplateReason();
final TemplateLookupStrategy templateLookupStrategy = getTemplateLookupStrategy();
- msg = "Template not found for name " + _StringUtil.jQuote(name)
+ msg = "Template not found for name " + _StringUtils.jQuote(name)
+ (missingTempNormName != null && name != null
&& !removeInitialSlash(name).equals(missingTempNormName)
- ? " (normalized: " + _StringUtil.jQuote(missingTempNormName) + ")"
+ ? " (normalized: " + _StringUtils.jQuote(missingTempNormName) + ")"
: "")
+ (customLookupCondition != null ? " and custom lookup condition "
- + _StringUtil.jQuote(customLookupCondition) : "")
+ + _StringUtils.jQuote(customLookupCondition) : "")
+ "."
+ (missingTempReason != null
? "\nReason given: " + ensureSentenceIsClosed(missingTempReason)
: "")
+ "\nThe name was interpreted by this TemplateLoader: "
- + _StringUtil.tryToString(tl) + "."
+ + _StringUtils.tryToString(tl) + "."
+ (!isKnownNonConfusingLookupStrategy(templateLookupStrategy)
? "\n(Before that, the name was possibly changed by this lookup strategy: "
- + _StringUtil.tryToString(templateLookupStrategy) + ".)"
+ + _StringUtils.tryToString(templateLookupStrategy) + ".)"
: "")
+ (missingTempReason == null && name.indexOf('\\') != -1
? "\nWarning: The name contains backslash (\"\\\") instead of slash (\"/\"); "
@@ -1613,7 +1613,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
boolean nameUnhandled = false;
try {
if (LOCALIZED_TEMPLATE_LOOKUP_KEY.equals(name)) {
- setLocalizedTemplateLookup(_StringUtil.getYesNo(value));
+ setLocalizedTemplateLookup(_StringUtils.getYesNo(value));
} else if (REGISTERED_CUSTOM_OUTPUT_FORMATS_KEY.equals(name)) {
List list = (List) _ObjectBuilderSettingEvaluator.eval(
value, List.class, true, _SettingEvaluationEnvironment.getCurrent());
@@ -1630,7 +1630,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
} if (value.indexOf('.') == -1) {
int strongSize = 0;
int softSize = 0;
- Map map = _StringUtil.parseNameValuePairList(
+ Map map = _StringUtils.parseNameValuePairList(
value, String.valueOf(Integer.MAX_VALUE));
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
@@ -1641,7 +1641,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
pValue = Integer.parseInt((String) ent.getValue());
} catch (NumberFormatException e) {
throw new InvalidSettingValueException(name, value,
- "Malformed integer number (shown quoted): " + _StringUtil.jQuote(ent.getValue()));
+ "Malformed integer number (shown quoted): " + _StringUtils.jQuote(ent.getValue()));
}
if ("soft".equalsIgnoreCase(pName)) {
softSize = pValue;
@@ -1650,7 +1650,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
} else {
throw new InvalidSettingValueException(name, value,
"Unsupported cache parameter name (shown quoted): "
- + _StringUtil.jQuote(ent.getValue()));
+ + _StringUtils.jQuote(ent.getValue()));
}
}
if (softSize == 0 && strongSize == 0) {
@@ -1683,7 +1683,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
multipier = 1000 * 60 * 60;
} else if (!unit.isEmpty()) {
throw new InvalidSettingValueException(name, value,
- "Unrecognized time unit " + _StringUtil.jQuote(unit) + ". Valid units are: ms, s, m, h");
+ "Unrecognized time unit " + _StringUtils.jQuote(unit) + ". Valid units are: ms, s, m, h");
} else {
multipier = 0;
}
@@ -1702,7 +1702,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
if (!(key instanceof String)) {
throw new InvalidSettingValueException(name, null, false,
"All keys in this Map must be strings, but one of them is an instance of "
- + "this class: " + _ClassUtil.getShortClassNameOfObject(key), null);
+ + "this class: " + _ClassUtils.getShortClassNameOfObject(key), null);
}
}
setSharedVariables((Map) sharedVariables);
@@ -2319,7 +2319,7 @@ public final class Configuration implements TopLevelConfiguration, CustomStateSc
*/
public void setSharedVariables(Map<String, ?> sharedVariables) {
_NullArgumentException.check("sharedVariables", sharedVariables);
- _CollectionUtil.safeCastMap(
+ _CollectionUtils.safeCastMap(
"sharedVariables", sharedVariables, String.class, false, Object.class,true);
this.sharedVariables = Collections.unmodifiableMap(new HashMap<>(sharedVariables));
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/CoreSettingValueNotSetException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/CoreSettingValueNotSetException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/CoreSettingValueNotSetException.java
index ee7a3bc..5c5b26a 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/CoreSettingValueNotSetException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/CoreSettingValueNotSetException.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Thrown when you try to read a core (that is, non-custom) configuration setting which wasn't set and isn't inherited
@@ -39,7 +39,7 @@ public class CoreSettingValueNotSetException extends SettingValueNotSetException
}
public CoreSettingValueNotSetException(String settingName, Throwable cause) {
- super("The " + _StringUtil.jQuote(settingName) + " setting is not set in this layer and has no default here "
+ super("The " + _StringUtils.jQuote(settingName) + " setting is not set in this layer and has no default here "
+ "either.", cause);
this.settingName = settingName;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/CustomSettingValueNotSetException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/CustomSettingValueNotSetException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/CustomSettingValueNotSetException.java
index 7f427f6..4ad997e 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/CustomSettingValueNotSetException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/CustomSettingValueNotSetException.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core;
import java.io.Serializable;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Thrown by {@link ProcessingConfiguration#getCustomSetting(Serializable)} if the custom setting is not set.
@@ -41,7 +41,7 @@ public class CustomSettingValueNotSetException extends SettingValueNotSetExcepti
* @param key {@link ProcessingConfiguration#getCustomSetting(Serializable)}
*/
public CustomSettingValueNotSetException(Serializable key, Throwable cause) {
- super("The " + _StringUtil.jQuote(key)
+ super("The " + _StringUtils.jQuote(key)
+ (key instanceof String ? "" : " (key class " + key.getClass().getName() + ")")
+ " setting is not set in this layer and has no default here either.",
cause);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/Environment.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/Environment.java b/freemarker-core/src/main/java/org/apache/freemarker/core/Environment.java
index f697309..a035da5 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/Environment.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/Environment.java
@@ -64,10 +64,10 @@ import org.apache.freemarker.core.templateresolver.MalformedTemplateNameExceptio
import org.apache.freemarker.core.templateresolver.TemplateResolver;
import org.apache.freemarker.core.templateresolver.impl.DefaultTemplateNameFormat;
import org.apache.freemarker.core.util.StringToIndexMap;
-import org.apache.freemarker.core.util._DateUtil;
-import org.apache.freemarker.core.util._DateUtil.DateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._DateUtils;
+import org.apache.freemarker.core.util._DateUtils.DateToISO8601CalendarFactory;
import org.apache.freemarker.core.util._NullWriter;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.TemplateDateFormat;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
@@ -941,7 +941,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
*/
public boolean applyEqualsOperator(TemplateModel leftValue, TemplateModel rightValue)
throws TemplateException {
- return _EvalUtil.compare(leftValue, _EvalUtil.CMP_OP_EQUALS, rightValue, this);
+ return _EvalUtils.compare(leftValue, _EvalUtils.CMP_OP_EQUALS, rightValue, this);
}
/**
@@ -951,7 +951,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
*/
public boolean applyEqualsOperatorLenient(TemplateModel leftValue, TemplateModel rightValue)
throws TemplateException {
- return _EvalUtil.compareLenient(leftValue, _EvalUtil.CMP_OP_EQUALS, rightValue, this);
+ return _EvalUtils.compareLenient(leftValue, _EvalUtils.CMP_OP_EQUALS, rightValue, this);
}
/**
@@ -959,7 +959,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
*/
public boolean applyLessThanOperator(TemplateModel leftValue, TemplateModel rightValue)
throws TemplateException {
- return _EvalUtil.compare(leftValue, _EvalUtil.CMP_OP_LESS_THAN, rightValue, this);
+ return _EvalUtils.compare(leftValue, _EvalUtils.CMP_OP_LESS_THAN, rightValue, this);
}
/**
@@ -967,7 +967,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
*/
public boolean applyLessThanOrEqualsOperator(TemplateModel leftValue, TemplateModel rightValue)
throws TemplateException {
- return _EvalUtil.compare(leftValue, _EvalUtil.CMP_OP_LESS_THAN_EQUALS, rightValue, this);
+ return _EvalUtils.compare(leftValue, _EvalUtils.CMP_OP_LESS_THAN_EQUALS, rightValue, this);
}
/**
@@ -975,7 +975,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
*/
public boolean applyGreaterThanOperator(TemplateModel leftValue, TemplateModel rightValue)
throws TemplateException {
- return _EvalUtil.compare(leftValue, _EvalUtil.CMP_OP_GREATER_THAN, rightValue, this);
+ return _EvalUtils.compare(leftValue, _EvalUtils.CMP_OP_GREATER_THAN, rightValue, this);
}
/**
@@ -983,7 +983,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
*/
public boolean applyWithGreaterThanOrEqualsOperator(TemplateModel leftValue, TemplateModel rightValue)
throws TemplateException {
- return _EvalUtil.compare(leftValue, _EvalUtil.CMP_OP_GREATER_THAN_EQUALS, rightValue, this);
+ return _EvalUtils.compare(leftValue, _EvalUtils.CMP_OP_GREATER_THAN_EQUALS, rightValue, this);
}
public void setOut(Writer out) {
@@ -1026,7 +1026,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
String s = templateBooleanFormat.getTrueStringValue();
if (s == null) {
if (fallbackToTrueFalse) {
- return MiscUtil.C_TRUE;
+ return TemplateBooleanFormat.C_TRUE;
} else {
throw new _MiscTemplateException(getNullBooleanFormatErrorDescription());
}
@@ -1037,7 +1037,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
String s = templateBooleanFormat.getFalseStringValue();
if (s == null) {
if (fallbackToTrueFalse) {
- return MiscUtil.C_FALSE;
+ return TemplateBooleanFormat.C_FALSE;
} else {
throw new _MiscTemplateException(getNullBooleanFormatErrorDescription());
}
@@ -1104,9 +1104,9 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
boolean useTempModelExc)
throws TemplateException {
try {
- return _EvalUtil.assertFormatResultNotNull(format.formatToPlainText(number));
+ return _EvalUtils.assertFormatResultNotNull(format.formatToPlainText(number));
} catch (TemplateValueFormatException e) {
- throw MessageUtil.newCantFormatNumberException(format, exp, e, useTempModelExc);
+ throw MessageUtils.newCantFormatNumberException(format, exp, e, useTempModelExc);
}
}
@@ -1269,7 +1269,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
TemplateNumberFormatFactory formatFactory = getCustomNumberFormat(name);
if (formatFactory == null) {
throw new UndefinedCustomFormatException(
- "No custom number format was defined with name " + _StringUtil.jQuote(name));
+ "No custom number format was defined with name " + _StringUtils.jQuote(name));
}
return formatFactory.get(params, locale, this);
@@ -1380,9 +1380,9 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
TemplateDateFormat format = getTemplateDateFormat(tdm, tdmSourceExpr, useTempModelExc);
try {
- return _EvalUtil.assertFormatResultNotNull(format.formatToPlainText(tdm));
+ return _EvalUtils.assertFormatResultNotNull(format.formatToPlainText(tdm));
} catch (TemplateValueFormatException e) {
- throw MessageUtil.newCantFormatDateException(format, tdmSourceExpr, e, useTempModelExc);
+ throw MessageUtils.newCantFormatDateException(format, tdmSourceExpr, e, useTempModelExc);
}
}
@@ -1395,7 +1395,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
String formatDateToPlainText(TemplateDateModel tdm, String formatString,
ASTExpression blamedDateSourceExp, ASTExpression blamedFormatterExp,
boolean useTempModelExc) throws TemplateException {
- Date date = _EvalUtil.modelToDate(tdm, blamedDateSourceExp);
+ Date date = _EvalUtils.modelToDate(tdm, blamedDateSourceExp);
TemplateDateFormat format = getTemplateDateFormat(
formatString, tdm.getDateType(), date.getClass(),
@@ -1403,9 +1403,9 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
useTempModelExc);
try {
- return _EvalUtil.assertFormatResultNotNull(format.formatToPlainText(tdm));
+ return _EvalUtils.assertFormatResultNotNull(format.formatToPlainText(tdm));
} catch (TemplateValueFormatException e) {
- throw MessageUtil.newCantFormatDateException(format, blamedDateSourceExp, e, useTempModelExc);
+ throw MessageUtils.newCantFormatDateException(format, blamedDateSourceExp, e, useTempModelExc);
}
}
@@ -1567,7 +1567,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
TemplateDateFormat getTemplateDateFormat(TemplateDateModel tdm, ASTExpression tdmSourceExpr, boolean useTempModelExc)
throws TemplateException {
- Date date = _EvalUtil.modelToDate(tdm, tdmSourceExpr);
+ Date date = _EvalUtils.modelToDate(tdm, tdmSourceExpr);
return getTemplateDateFormat(
tdm.getDateType(), date.getClass(), tdmSourceExpr,
@@ -1583,7 +1583,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
try {
return getTemplateDateFormat(dateType, dateClass);
} catch (UnknownDateTypeFormattingUnsupportedException e) {
- throw MessageUtil.newCantFormatUnknownTypeDateException(blamedDateSourceExp, e);
+ throw MessageUtils.newCantFormatUnknownTypeDateException(blamedDateSourceExp, e);
} catch (TemplateValueFormatException e) {
String settingName;
String settingValue;
@@ -1626,7 +1626,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
try {
return getTemplateDateFormat(formatString, dateType, dateClass);
} catch (UnknownDateTypeFormattingUnsupportedException e) {
- throw MessageUtil.newCantFormatUnknownTypeDateException(blamedDateSourceExp, e);
+ throw MessageUtils.newCantFormatUnknownTypeDateException(blamedDateSourceExp, e);
} catch (TemplateValueFormatException e) {
_ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
"Can't invoke date/time/dateTime format based on format string ",
@@ -1789,7 +1789,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
formatFactory = getCustomDateFormat(name);
if (formatFactory == null) {
throw new UndefinedCustomFormatException(
- "No custom date format was defined with name " + _StringUtil.jQuote(name));
+ "No custom date format was defined with name " + _StringUtils.jQuote(name));
}
} else {
formatParams = formatString;
@@ -1833,13 +1833,13 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
/**
* Returns the {@link DateToISO8601CalendarFactory} used by the the "iso_" built-ins. Be careful when using this; it
* should only by used with
- * {@link _DateUtil#dateToISO8601String(Date, boolean, boolean, boolean, int, TimeZone, DateToISO8601CalendarFactory)}
- * and {@link _DateUtil#dateToXSString(Date, boolean, boolean, boolean, int, TimeZone, DateToISO8601CalendarFactory)}
+ * {@link _DateUtils#dateToISO8601String(Date, boolean, boolean, boolean, int, TimeZone, DateToISO8601CalendarFactory)}
+ * and {@link _DateUtils#dateToXSString(Date, boolean, boolean, boolean, int, TimeZone, DateToISO8601CalendarFactory)}
* .
*/
DateToISO8601CalendarFactory getISOBuiltInCalendarFactory() {
if (isoBuiltInCalendarFactory == null) {
- isoBuiltInCalendarFactory = new _DateUtil.TrivialDateToISO8601CalendarFactory();
+ isoBuiltInCalendarFactory = new _DateUtils.TrivialDateToISO8601CalendarFactory();
}
return isoBuiltInCalendarFactory;
}
@@ -2114,15 +2114,15 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
}
static void appendInstructionStackItem(ASTElement stackEl, StringBuilder sb) {
- sb.append(MessageUtil.shorten(stackEl.getDescription(), 40));
+ sb.append(MessageUtils.shorten(stackEl.getDescription(), 40));
sb.append(" [");
ASTDirMacroOrFunction enclosingMacro = getEnclosingMacro(stackEl);
if (enclosingMacro != null) {
- sb.append(MessageUtil.formatLocationForEvaluationError(
+ sb.append(MessageUtils.formatLocationForEvaluationError(
enclosingMacro, stackEl.beginLine, stackEl.beginColumn));
} else {
- sb.append(MessageUtil.formatLocationForEvaluationError(
+ sb.append(MessageUtils.formatLocationForEvaluationError(
stackEl.getTemplate(), stackEl.beginLine, stackEl.beginColumn));
}
sb.append("]");
@@ -2761,7 +2761,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
if (status == InitializationStatus.FAILED) {
throw new TemplateModelException(
"Lazy initialization of the imported namespace for "
- + _StringUtil.jQuote(templateName)
+ + _StringUtils.jQuote(templateName)
+ " has already failed earlier; won't retry it.");
}
try {
@@ -2772,7 +2772,7 @@ public final class Environment extends MutableProcessingConfiguration<Environmen
// [FM3] Rethrow TemplateException-s as is
throw new TemplateModelException(
"Lazy initialization of the imported namespace for "
- + _StringUtil.jQuote(templateName)
+ + _StringUtils.jQuote(templateName)
+ " has failed; see cause exception", e);
} finally {
if (status != InitializationStatus.INITIALIZED) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingNameException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingNameException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingNameException.java
index 912619c..dd70ebb 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingNameException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingNameException.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core;
import org.apache.freemarker.core.Configuration.ExtendableBuilder;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Thrown by {@link ExtendableBuilder#setSetting(String, String)} if the setting name was not recognized.
@@ -28,12 +28,12 @@ import org.apache.freemarker.core.util._StringUtil;
public class InvalidSettingNameException extends ConfigurationException {
InvalidSettingNameException(String name, String correctedName) {
- super("Unknown FreeMarker configuration setting: " + _StringUtil.jQuote(name)
- + (correctedName == null ? "" : ". You may meant: " + _StringUtil.jQuote(correctedName)));
+ super("Unknown FreeMarker configuration setting: " + _StringUtils.jQuote(name)
+ + (correctedName == null ? "" : ". You may meant: " + _StringUtils.jQuote(correctedName)));
}
InvalidSettingNameException(String name, Version removedInVersion) {
- super("Unknown FreeMarker configuration setting: " + _StringUtil.jQuote(name)
+ super("Unknown FreeMarker configuration setting: " + _StringUtils.jQuote(name)
+ (removedInVersion == null ? "" : ". This setting was removed in version " + removedInVersion));
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingValueException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingValueException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingValueException.java
index 1acbefa..69d88c3 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingValueException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/InvalidSettingValueException.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core;
import java.util.Date;
import org.apache.freemarker.core.Configuration.ExtendableBuilder;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Thrown by {@link ExtendableBuilder#setSetting(String, String)}; The setting name was recognized, but its value
@@ -65,12 +65,12 @@ public class InvalidSettingValueException extends ConfigurationException {
private static String createMessage(String name, Object value, boolean showValue, String detail1, String detail2) {
StringBuilder sb = new StringBuilder(64);
- sb.append("Failed to set FreeMarker configuration setting ").append(_StringUtil.jQuote(name));
+ sb.append("Failed to set FreeMarker configuration setting ").append(_StringUtils.jQuote(name));
if (showValue) {
sb.append(" to value ")
.append(
value instanceof Number || value instanceof Boolean || value instanceof Date ? value
- : _StringUtil.jQuote(value));
+ : _StringUtils.jQuote(value));
} else {
sb.append(" to the specified value");
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtil.java
deleted file mode 100644
index 8749fd4..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtil.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core;
-
-import java.util.ArrayList;
-
-import org.apache.freemarker.core.model.TemplateModel;
-import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._StringUtil;
-import org.apache.freemarker.core.valueformat.TemplateDateFormat;
-import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
-import org.apache.freemarker.core.valueformat.TemplateValueFormatException;
-import org.apache.freemarker.core.valueformat.UnknownDateTypeFormattingUnsupportedException;
-
-/**
- * Utilities for creating error messages (and other messages).
- */
-class MessageUtil {
-
- static final String UNKNOWN_DATE_TO_STRING_ERROR_MESSAGE
- = "Can't convert the date-like value to string because it isn't "
- + "known if it's a date (no time part), time or date-time value.";
-
- static final String UNKNOWN_DATE_TYPE_ERROR_TIP =
- "Use ?date, ?time, or ?dateTime to tell FreeMarker the exact type.";
-
- static final Object[] UNKNOWN_DATE_TO_STRING_TIPS = {
- UNKNOWN_DATE_TYPE_ERROR_TIP,
- "If you need a particular format only once, use ?string(pattern), like ?string('dd.MM.yyyy HH:mm:ss'), "
- + "to specify which fields to display. "
- };
-
- static final String FM3_SNAKE_CASE = "\nThe name contains '_' character, but since FreeMarker 3 names defined "
- + "by the template language use camel case (e.g. someExampleName).";
-
- static final String EMBEDDED_MESSAGE_BEGIN = "---begin-message---\n";
-
- static final String EMBEDDED_MESSAGE_END = "\n---end-message---";
-
- static final String ERROR_MESSAGE_HR = "----";
-
- // Can't be instantiated
- private MessageUtil() { }
-
- static String formatLocationForSimpleParsingError(Template template, int line, int column) {
- return formatLocation("in", template, line, column);
- }
-
- static String formatLocationForSimpleParsingError(String templateSourceOrLookupName, int line, int column) {
- return formatLocation("in", templateSourceOrLookupName, line, column);
- }
-
- static String formatLocationForEvaluationError(Template template, int line, int column) {
- return formatLocation("at", template, line, column);
- }
-
- static String formatLocationForEvaluationError(ASTDirMacroOrFunction macro, int line, int column) {
- Template t = macro.getTemplate();
- return formatLocation("at", t != null ? t.getSourceOrLookupName() : null, macro.getName(), macro.isFunction(),
- line, column);
- }
-
- private static String formatLocation(String preposition, Template template, int line, int column) {
- return formatLocation(preposition, template != null ? template.getSourceOrLookupName() : null, line, column);
- }
-
- private static String formatLocation(String preposition, String templateSourceName, int line, int column) {
- return formatLocation(
- preposition, templateSourceName,
- null, false,
- line, column);
- }
-
- private static String formatLocation(
- String preposition, String templateSourceName,
- String macroOrFuncName, boolean isFunction,
- int line, int column) {
- String templateDesc;
- if (line < 0) {
- templateDesc = "?eval-ed string";
- macroOrFuncName = null;
- } else {
- templateDesc = templateSourceName != null
- ? "template " + _StringUtil.jQuoteNoXSS(templateSourceName)
- : "nameless template";
- }
- return "in " + templateDesc
- + (macroOrFuncName != null
- ? " in " + (isFunction ? "function " : "macro ") + _StringUtil.jQuote(macroOrFuncName)
- : "")
- + " "
- + preposition + " " + formatPosition(line, column);
- }
-
- static String formatPosition(int line, int column) {
- return "line " + (line >= 0 ? line : line - (ASTNode.RUNTIME_EVAL_LINE_DISPLACEMENT - 1))
- + ", column " + column;
- }
-
- /**
- * Returns a single line string that is no longer than {@code maxLength}.
- * If will truncate the string at line-breaks too.
- * The truncation is always signaled with a a {@code "..."} at the end of the result string.
- */
- static String shorten(String s, int maxLength) {
- if (maxLength < 5) maxLength = 5;
-
- boolean isTruncated = false;
-
- int brIdx = s.indexOf('\n');
- if (brIdx != -1) {
- s = s.substring(0, brIdx);
- isTruncated = true;
- }
- brIdx = s.indexOf('\r');
- if (brIdx != -1) {
- s = s.substring(0, brIdx);
- isTruncated = true;
- }
-
- if (s.length() > maxLength) {
- s = s.substring(0, maxLength - 3);
- isTruncated = true;
- }
-
- if (!isTruncated) {
- return s;
- } else {
- if (s.endsWith(".")) {
- if (s.endsWith("..")) {
- if (s.endsWith("...")) {
- return s;
- } else {
- return s + ".";
- }
- } else {
- return s + "..";
- }
- } else {
- return s + "...";
- }
- }
- }
-
- static StringBuilder appendExpressionAsUntearable(StringBuilder sb, ASTExpression argExp) {
- boolean needParen =
- !(argExp instanceof ASTExpNumberLiteral)
- && !(argExp instanceof ASTExpStringLiteral)
- && !(argExp instanceof ASTExpBooleanLiteral)
- && !(argExp instanceof ASTExpListLiteral)
- && !(argExp instanceof ASTExpHashLiteral)
- && !(argExp instanceof ASTExpVariable)
- && !(argExp instanceof ASTExpDot)
- && !(argExp instanceof ASTExpDynamicKeyName)
- && !(argExp instanceof ASTExpFunctionCall)
- && !(argExp instanceof ASTExpBuiltIn);
- if (needParen) sb.append('(');
- sb.append(argExp.getCanonicalForm());
- if (needParen) sb.append(')');
- return sb;
- }
-
- static TemplateModelException newArgCntError(String methodName, int argCnt, int expectedCnt) {
- return newArgCntError(methodName, argCnt, expectedCnt, expectedCnt);
- }
-
- static TemplateModelException newArgCntError(String methodName, int argCnt, int minCnt, int maxCnt) {
- ArrayList/*<Object>*/ desc = new ArrayList(20);
-
- desc.add(methodName);
-
- desc.add("(");
- if (maxCnt != 0) desc.add("...");
- desc.add(") expects ");
-
- if (minCnt == maxCnt) {
- if (maxCnt == 0) {
- desc.add("no");
- } else {
- desc.add(Integer.valueOf(maxCnt));
- }
- } else if (maxCnt - minCnt == 1) {
- desc.add(Integer.valueOf(minCnt));
- desc.add(" or ");
- desc.add(Integer.valueOf(maxCnt));
- } else {
- desc.add(Integer.valueOf(minCnt));
- if (maxCnt != Integer.MAX_VALUE) {
- desc.add(" to ");
- desc.add(Integer.valueOf(maxCnt));
- } else {
- desc.add(" or more (unlimited)");
- }
- }
- desc.add(" argument");
- if (maxCnt > 1) desc.add("s");
-
- desc.add(" but has received ");
- if (argCnt == 0) {
- desc.add("none");
- } else {
- desc.add(Integer.valueOf(argCnt));
- }
- desc.add(".");
-
- return new _TemplateModelException(desc.toArray());
- }
-
- static TemplateModelException newMethodArgMustBeStringException(String methodName, int argIdx, TemplateModel arg) {
- return newMethodArgUnexpectedTypeException(methodName, argIdx, "string", arg);
- }
-
- static TemplateModelException newMethodArgMustBeNumberException(String methodName, int argIdx, TemplateModel arg) {
- return newMethodArgUnexpectedTypeException(methodName, argIdx, "number", arg);
- }
-
- static TemplateModelException newMethodArgMustBeBooleanException(String methodName, int argIdx, TemplateModel arg) {
- return newMethodArgUnexpectedTypeException(methodName, argIdx, "boolean", arg);
- }
-
- static TemplateModelException newMethodArgMustBeExtendedHashException(
- String methodName, int argIdx, TemplateModel arg) {
- return newMethodArgUnexpectedTypeException(methodName, argIdx, "extended hash", arg);
- }
-
- static TemplateModelException newMethodArgMustBeSequenceException(
- String methodName, int argIdx, TemplateModel arg) {
- return newMethodArgUnexpectedTypeException(methodName, argIdx, "sequence", arg);
- }
-
- static TemplateModelException newMethodArgMustBeSequenceOrCollectionException(
- String methodName, int argIdx, TemplateModel arg) {
- return newMethodArgUnexpectedTypeException(methodName, argIdx, "sequence or collection", arg);
- }
-
- static TemplateModelException newMethodArgUnexpectedTypeException(
- String methodName, int argIdx, String expectedType, TemplateModel arg) {
- return new _TemplateModelException(
- methodName, "(...) expects ", new _DelayedAOrAn(expectedType), " as argument #", Integer.valueOf(argIdx + 1),
- ", but received ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(arg)), ".");
- }
-
- /**
- * The type of the argument was good, but it's value wasn't.
- */
- static TemplateModelException newMethodArgInvalidValueException(
- String methodName, int argIdx, Object... details) {
- return new _TemplateModelException(
- methodName, "(...) argument #", Integer.valueOf(argIdx + 1),
- " had invalid value: ", details);
- }
-
- /**
- * The type of the argument was good, but the values of two or more arguments are inconsistent with each other.
- */
- static TemplateModelException newMethodArgsInvalidValueException(
- String methodName, Object... details) {
- return new _TemplateModelException(methodName, "(...) arguments have invalid value: ", details);
- }
-
- static TemplateException newInstantiatingClassNotAllowedException(String className, Environment env) {
- return new _MiscTemplateException(env,
- "Instantiating ", className, " is not allowed in the template for security reasons.");
- }
-
- static TemplateModelException newCantFormatUnknownTypeDateException(
- ASTExpression dateSourceExpr, UnknownDateTypeFormattingUnsupportedException cause) {
- return new _TemplateModelException(cause, null, new _ErrorDescriptionBuilder(
- MessageUtil.UNKNOWN_DATE_TO_STRING_ERROR_MESSAGE)
- .blame(dateSourceExpr)
- .tips(MessageUtil.UNKNOWN_DATE_TO_STRING_TIPS));
- }
-
- static TemplateException newCantFormatDateException(TemplateDateFormat format, ASTExpression dataSrcExp,
- TemplateValueFormatException e, boolean useTempModelExc) {
- _ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
- "Failed to format date/time/dateTime with format ", new _DelayedJQuote(format.getDescription()), ": ",
- e.getMessage())
- .blame(dataSrcExp);
- return useTempModelExc
- ? new _TemplateModelException(e, null, desc)
- : new _MiscTemplateException(e, null, desc);
- }
-
- static TemplateException newCantFormatNumberException(TemplateNumberFormat format, ASTExpression dataSrcExp,
- TemplateValueFormatException e, boolean useTempModelExc) {
- _ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
- "Failed to format number with format ", new _DelayedJQuote(format.getDescription()), ": ",
- e.getMessage())
- .blame(dataSrcExp);
- return useTempModelExc
- ? new _TemplateModelException(e, null, desc)
- : new _MiscTemplateException(e, null, desc);
- }
-
- /**
- * @return "a" or "an" or "a(n)" (or "" for empty string) for an FTL type name
- */
- static String getAOrAn(String s) {
- if (s == null) return null;
- if (s.length() == 0) return "";
-
- char fc = Character.toLowerCase(s.charAt(0));
- if (fc == 'a' || fc == 'e' || fc == 'i') {
- return "an";
- } else if (fc == 'h') {
- String ls = s.toLowerCase();
- if (ls.startsWith("has") || ls.startsWith("hi")) {
- return "a";
- } else if (ls.startsWith("ht")) {
- return "an";
- } else {
- return "a(n)";
- }
- } else if (fc == 'u' || fc == 'o') {
- return "a(n)";
- } else {
- char sc = (s.length() > 1) ? s.charAt(1) : '\0';
- if (fc == 'x' && !(sc == 'a' || sc == 'e' || sc == 'i' || sc == 'a' || sc == 'o' || sc == 'u')) {
- return "an";
- } else {
- return "a";
- }
- }
- }
-
-}
[07/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtils.java
new file mode 100644
index 0000000..cec556f
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtils.java
@@ -0,0 +1,319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.freemarker.core.model.impl;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.freemarker.core._DelayedConversionToString;
+import org.apache.freemarker.core._DelayedJQuote;
+import org.apache.freemarker.core._TemplateModelException;
+import org.apache.freemarker.core.model.TemplateModelException;
+import org.apache.freemarker.core.util.BugException;
+import org.apache.freemarker.core.util._ClassUtils;
+
+/**
+ * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
+ */
+public final class _MethodUtils {
+
+ private _MethodUtils() {
+ // Not meant to be instantiated
+ }
+
+ /**
+ * Determines whether the type given as the 1st argument is convertible to the type given as the 2nd argument
+ * for method call argument conversion. This follows the rules of the Java reflection-based method call, except
+ * that since we don't have the value here, a boxed class is never seen as convertible to a primitive type.
+ *
+ * @return 0 means {@code false}, non-0 means {@code true}.
+ * That is, 0 is returned less specificity or incomparable specificity, also when if
+ * then method was aborted because of {@code ifHigherThan}.
+ * The absolute value of the returned non-0 number symbolizes how more specific it is:
+ * <ul>
+ * <li>1: The two classes are identical</li>
+ * <li>2: The 1st type is primitive, the 2nd type is the corresponding boxing class</li>
+ * <li>3: Both classes are numerical, and one is convertible into the other with widening conversion.
+ * E.g., {@code int} is convertible to {@code long} and {#code double}, hence {@code int} is more
+ * specific.
+ * This ignores primitive VS boxed mismatches, except that a boxed class is never seen as
+ * convertible to a primitive class.</li>
+ * <li>4: One class is {@code instanceof} of the other, but they aren't identical.
+ * But unlike in Java, primitive numerical types are {@code instanceof} {@link Number} here.</li>
+ * </ul>
+ */
+ // TODO Seems that we don't use the full functionality of this anymore, so we could simplify this. See usages.
+ static int isMoreOrSameSpecificParameterType(final Class<?> specific, final Class<?> generic, boolean bugfixed,
+ int ifHigherThan) {
+ if (ifHigherThan >= 4) return 0;
+ if (generic.isAssignableFrom(specific)) {
+ // Identity or widening reference conversion:
+ return generic == specific ? 1 : 4;
+ } else {
+ final boolean specificIsPrim = specific.isPrimitive();
+ final boolean genericIsPrim = generic.isPrimitive();
+ if (specificIsPrim) {
+ if (genericIsPrim) {
+ if (ifHigherThan >= 3) return 0;
+ return isWideningPrimitiveNumberConversion(specific, generic) ? 3 : 0;
+ } else { // => specificIsPrim && !genericIsPrim
+ if (bugfixed) {
+ final Class<?> specificAsBoxed = _ClassUtils.primitiveClassToBoxingClass(specific);
+ if (specificAsBoxed == generic) {
+ // A primitive class is more specific than its boxing class, because it can't store null
+ return 2;
+ } else if (generic.isAssignableFrom(specificAsBoxed)) {
+ // Note: This only occurs if `specific` is a primitive numerical, and `generic == Number`
+ return 4;
+ } else if (ifHigherThan >= 3) {
+ return 0;
+ } else if (Number.class.isAssignableFrom(specificAsBoxed)
+ && Number.class.isAssignableFrom(generic)) {
+ return isWideningBoxedNumberConversion(specificAsBoxed, generic) ? 3 : 0;
+ } else {
+ return 0;
+ }
+ } else {
+ return 0;
+ }
+ }
+ } else { // => !specificIsPrim
+ if (ifHigherThan >= 3) return 0;
+ if (bugfixed && !genericIsPrim
+ && Number.class.isAssignableFrom(specific) && Number.class.isAssignableFrom(generic)) {
+ return isWideningBoxedNumberConversion(specific, generic) ? 3 : 0;
+ } else {
+ return 0;
+ }
+ }
+ } // of: !generic.isAssignableFrom(specific)
+ }
+
+ private static boolean isWideningPrimitiveNumberConversion(final Class<?> source, final Class<?> target) {
+ if (target == Short.TYPE && (source == Byte.TYPE)) {
+ return true;
+ } else if (target == Integer.TYPE &&
+ (source == Short.TYPE || source == Byte.TYPE)) {
+ return true;
+ } else if (target == Long.TYPE &&
+ (source == Integer.TYPE || source == Short.TYPE ||
+ source == Byte.TYPE)) {
+ return true;
+ } else if (target == Float.TYPE &&
+ (source == Long.TYPE || source == Integer.TYPE ||
+ source == Short.TYPE || source == Byte.TYPE)) {
+ return true;
+ } else if (target == Double.TYPE &&
+ (source == Float.TYPE || source == Long.TYPE ||
+ source == Integer.TYPE || source == Short.TYPE ||
+ source == Byte.TYPE)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private static boolean isWideningBoxedNumberConversion(final Class<?> source, final Class<?> target) {
+ if (target == Short.class && source == Byte.class) {
+ return true;
+ } else if (target == Integer.class &&
+ (source == Short.class || source == Byte.class)) {
+ return true;
+ } else if (target == Long.class &&
+ (source == Integer.class || source == Short.class ||
+ source == Byte.class)) {
+ return true;
+ } else if (target == Float.class &&
+ (source == Long.class || source == Integer.class ||
+ source == Short.class || source == Byte.class)) {
+ return true;
+ } else if (target == Double.class &&
+ (source == Float.class || source == Long.class ||
+ source == Integer.class || source == Short.class ||
+ source == Byte.class)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Attention, this doesn't handle primitive classes correctly, nor numerical conversions.
+ */
+ static Set<Class<?>> getAssignables(Class<?> c1, Class<?> c2) {
+ Set<Class<?>> s = new HashSet<>();
+ collectAssignables(c1, c2, s);
+ return s;
+ }
+
+ private static void collectAssignables(Class<?> c1, Class<?> c2, Set<Class<?>> s) {
+ if (c1.isAssignableFrom(c2)) {
+ s.add(c1);
+ }
+ Class<?> sc = c1.getSuperclass();
+ if (sc != null) {
+ collectAssignables(sc, c2, s);
+ }
+ Class<?>[] itf = c1.getInterfaces();
+ for (Class<?> anItf : itf) {
+ collectAssignables(anItf, c2, s);
+ }
+ }
+
+ public static Class<?>[] getParameterTypes(Member member) {
+ if (member instanceof Method) {
+ return ((Method) member).getParameterTypes();
+ }
+ if (member instanceof Constructor<?>) {
+ return ((Constructor<?>) member).getParameterTypes();
+ }
+ throw new IllegalArgumentException("\"member\" must be Method or Constructor");
+ }
+
+ static boolean isVarargs(Member member) {
+ if (member instanceof Method) {
+ return ((Method) member).isVarArgs();
+ }
+ if (member instanceof Constructor) {
+ return ((Constructor<?>) member).isVarArgs();
+ }
+ throw new BugException();
+ }
+
+ /**
+ * Returns a more streamlined method or constructor description than {@code Member.toString()} does.
+ */
+ public static String toString(Member member) {
+ if (!(member instanceof Method || member instanceof Constructor)) {
+ throw new IllegalArgumentException("\"member\" must be a Method or Constructor");
+ }
+
+ StringBuilder sb = new StringBuilder();
+
+ if ((member.getModifiers() & Modifier.STATIC) != 0) {
+ sb.append("static ");
+ }
+
+ String className = _ClassUtils.getShortClassName(member.getDeclaringClass());
+ if (className != null) {
+ sb.append(className);
+ sb.append('.');
+ }
+ sb.append(member.getName());
+
+ sb.append('(');
+ Class<?>[] paramTypes = _MethodUtils.getParameterTypes(member);
+ for (int i = 0; i < paramTypes.length; i++) {
+ if (i != 0) sb.append(", ");
+ String paramTypeDecl = _ClassUtils.getShortClassName(paramTypes[i]);
+ if (i == paramTypes.length - 1 && paramTypeDecl.endsWith("[]") && _MethodUtils.isVarargs(member)) {
+ sb.append(paramTypeDecl.substring(0, paramTypeDecl.length() - 2));
+ sb.append("...");
+ } else {
+ sb.append(paramTypeDecl);
+ }
+ }
+ sb.append(')');
+
+ return sb.toString();
+ }
+
+ static Object[] invocationErrorMessageStart(Member member) {
+ return invocationErrorMessageStart(member, member instanceof Constructor);
+ }
+
+ private static Object[] invocationErrorMessageStart(Object member, boolean isConstructor) {
+ return new Object[] { "Java ", isConstructor ? "constructor " : "method ", new _DelayedJQuote(member) };
+ }
+
+ static TemplateModelException newInvocationTemplateModelException(Object object, Member member, Throwable e) {
+ return newInvocationTemplateModelException(
+ object,
+ member,
+ (member.getModifiers() & Modifier.STATIC) != 0,
+ member instanceof Constructor,
+ e);
+ }
+
+ static TemplateModelException newInvocationTemplateModelException(Object object, CallableMemberDescriptor callableMemberDescriptor, Throwable e) {
+ return newInvocationTemplateModelException(
+ object,
+ new _DelayedConversionToString(callableMemberDescriptor) {
+ @Override
+ protected String doConversion(Object callableMemberDescriptor) {
+ return ((CallableMemberDescriptor) callableMemberDescriptor).getDeclaration();
+ }
+ },
+ callableMemberDescriptor.isStatic(),
+ callableMemberDescriptor.isConstructor(),
+ e);
+ }
+
+ private static TemplateModelException newInvocationTemplateModelException(
+ Object parentObject, Object member, boolean isStatic, boolean isConstructor, Throwable e) {
+ while (e instanceof InvocationTargetException) {
+ Throwable cause = ((InvocationTargetException) e).getTargetException();
+ if (cause != null) {
+ e = cause;
+ } else {
+ break;
+ }
+ }
+
+ return new _TemplateModelException(e,
+ invocationErrorMessageStart(member, isConstructor),
+ " threw an exception",
+ isStatic || isConstructor ? "" : new Object[] {
+ " when invoked on ", parentObject.getClass(), " object ", new _DelayedJQuote(parentObject)
+ },
+ "; see cause exception in the Java stack trace.");
+ }
+
+ /**
+ * Extracts the JavaBeans property from a reader method name, or returns {@code null} if the method name doesn't
+ * look like a reader method name.
+ */
+ static String getBeanPropertyNameFromReaderMethodName(String name, Class<?> returnType) {
+ int start;
+ if (name.startsWith("get")) {
+ start = 3;
+ } else if (returnType == boolean.class && name.startsWith("is")) {
+ start = 2;
+ } else {
+ return null;
+ }
+ int ln = name.length();
+
+ if (start == ln) {
+ return null;
+ }
+ char c1 = name.charAt(start);
+
+ return start + 1 < ln && Character.isUpperCase(name.charAt(start + 1)) && Character.isUpperCase(c1)
+ ? name.substring(start) // getFOOBar => "FOOBar" (not lower case) according the JavaBeans spec.
+ : new StringBuilder(ln - start).append(Character.toLowerCase(c1)).append(name, start + 1, ln)
+ .toString();
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_ModelAPI.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_ModelAPI.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_ModelAPI.java
index fecb0b0..1cb23d1 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_ModelAPI.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_ModelAPI.java
@@ -26,7 +26,7 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
/**
* For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
@@ -50,7 +50,7 @@ public class _ModelAPI {
*/
private static CallableMemberDescriptor getConstructorDescriptor(Class<?> pClass, Object[] args)
throws NoSuchMethodException {
- if (args == null) args = _CollectionUtil.EMPTY_OBJECT_ARRAY;
+ if (args == null) args = _CollectionUtils.EMPTY_OBJECT_ARRAY;
final ArgumentTypes argTypes = new ArgumentTypes(args);
final List<ReflectionCallableMemberDescriptor> fixedArgMemberDescs
@@ -59,7 +59,7 @@ public class _ModelAPI {
= new ArrayList<>();
for (Constructor<?> constr : pClass.getConstructors()) {
ReflectionCallableMemberDescriptor memberDesc = new ReflectionCallableMemberDescriptor(constr, constr.getParameterTypes());
- if (!_MethodUtil.isVarargs(constr)) {
+ if (!_MethodUtils.isVarargs(constr)) {
fixedArgMemberDescs.add(memberDesc);
} else {
varArgsMemberDescs.add(memberDesc);
@@ -91,7 +91,7 @@ public class _ModelAPI {
private static Object newInstance(CallableMemberDescriptor constrDesc, Object[] args, DefaultObjectWrapper ow)
throws InstantiationException, IllegalAccessException, InvocationTargetException, IllegalArgumentException,
TemplateModelException {
- if (args == null) args = _CollectionUtil.EMPTY_OBJECT_ARRAY;
+ if (args == null) args = _CollectionUtils.EMPTY_OBJECT_ARRAY;
final Object[] packedArgs;
if (constrDesc.isVarargs()) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/OutputFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/OutputFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/OutputFormat.java
index 9aa9e52..e354111 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/OutputFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/OutputFormat.java
@@ -21,8 +21,8 @@ package org.apache.freemarker.core.outputformat;
import org.apache.freemarker.core.Configuration;
import org.apache.freemarker.core.model.TemplateMarkupOutputModel;
import org.apache.freemarker.core.outputformat.impl.UndefinedOutputFormat;
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents an output format. If you need auto-escaping, see its subclass, {@link MarkupOutputFormat}.
@@ -67,8 +67,8 @@ public abstract class OutputFormat {
public final String toString() {
String extras = toStringExtraProperties();
return getName() + "("
- + "mimeType=" + _StringUtil.jQuote(getMimeType()) + ", "
- + "class=" + _ClassUtil.getShortClassNameOfObject(this, true)
+ + "mimeType=" + _StringUtils.jQuote(getMimeType()) + ", "
+ + "class=" + _ClassUtils.getShortClassNameOfObject(this, true)
+ (extras.length() != 0 ? ", " : "") + extras
+ ")";
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/HTMLOutputFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/HTMLOutputFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/HTMLOutputFormat.java
index 0adadc0..aafcc4e 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/HTMLOutputFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/HTMLOutputFormat.java
@@ -24,11 +24,11 @@ import java.io.Writer;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.outputformat.CommonMarkupOutputFormat;
import org.apache.freemarker.core.outputformat.OutputFormat;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents the HTML output format (MIME type "text/html", name "HTML"). This format escapes by default (via
- * {@link _StringUtil#XHTMLEnc(String)}). The {@code ?html}, {@code ?xhtml} and {@code ?xml} built-ins silently bypass
+ * {@link _StringUtils#XHTMLEnc(String)}). The {@code ?html}, {@code ?xhtml} and {@code ?xml} built-ins silently bypass
* template output values of the type produced by this output format ({@link TemplateHTMLOutputModel}).
*/
public final class HTMLOutputFormat extends CommonMarkupOutputFormat<TemplateHTMLOutputModel> {
@@ -54,12 +54,12 @@ public final class HTMLOutputFormat extends CommonMarkupOutputFormat<TemplateHTM
@Override
public void output(String textToEsc, Writer out) throws IOException, TemplateModelException {
- _StringUtil.XHTMLEnc(textToEsc, out);
+ _StringUtils.XHTMLEnc(textToEsc, out);
}
@Override
public String escapePlainText(String plainTextContent) {
- return _StringUtil.XHTMLEnc(plainTextContent);
+ return _StringUtils.XHTMLEnc(plainTextContent);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/RTFOutputFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/RTFOutputFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/RTFOutputFormat.java
index 39a1bca..1397af5 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/RTFOutputFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/RTFOutputFormat.java
@@ -24,11 +24,11 @@ import java.io.Writer;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.outputformat.CommonMarkupOutputFormat;
import org.apache.freemarker.core.outputformat.OutputFormat;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents the Rich Text Format output format (MIME type "application/rtf", name "RTF"). This format escapes by
- * default (via {@link _StringUtil#RTFEnc(String)}). The {@code ?rtf} built-in silently bypasses template output values
+ * default (via {@link _StringUtils#RTFEnc(String)}). The {@code ?rtf} built-in silently bypasses template output values
* of the type produced by this output format ({@link TemplateRTFOutputModel}).
*/
public final class RTFOutputFormat extends CommonMarkupOutputFormat<TemplateRTFOutputModel> {
@@ -54,12 +54,12 @@ public final class RTFOutputFormat extends CommonMarkupOutputFormat<TemplateRTFO
@Override
public void output(String textToEsc, Writer out) throws IOException, TemplateModelException {
- _StringUtil.RTFEnc(textToEsc, out);
+ _StringUtils.RTFEnc(textToEsc, out);
}
@Override
public String escapePlainText(String plainTextContent) {
- return _StringUtil.RTFEnc(plainTextContent);
+ return _StringUtils.RTFEnc(plainTextContent);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XHTMLOutputFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XHTMLOutputFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XHTMLOutputFormat.java
index 769b33f..55a2748 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XHTMLOutputFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XHTMLOutputFormat.java
@@ -24,11 +24,11 @@ import java.io.Writer;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.outputformat.CommonMarkupOutputFormat;
import org.apache.freemarker.core.outputformat.OutputFormat;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents the XML output format (MIME type "application/xhtml+xml", name "XHTML"). This format escapes by default
- * (via {@link _StringUtil#XHTMLEnc(String)}). The {@code ?xml} built-in silently bypasses template output values of the
+ * (via {@link _StringUtils#XHTMLEnc(String)}). The {@code ?xml} built-in silently bypasses template output values of the
* type produced by this output format ({@link TemplateXHTMLOutputModel}).
*/
public final class XHTMLOutputFormat extends CommonMarkupOutputFormat<TemplateXHTMLOutputModel> {
@@ -54,12 +54,12 @@ public final class XHTMLOutputFormat extends CommonMarkupOutputFormat<TemplateXH
@Override
public void output(String textToEsc, Writer out) throws IOException, TemplateModelException {
- _StringUtil.XHTMLEnc(textToEsc, out);
+ _StringUtils.XHTMLEnc(textToEsc, out);
}
@Override
public String escapePlainText(String plainTextContent) {
- return _StringUtil.XHTMLEnc(plainTextContent);
+ return _StringUtils.XHTMLEnc(plainTextContent);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XMLOutputFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XMLOutputFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XMLOutputFormat.java
index 4b03d31..c129135 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XMLOutputFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/outputformat/impl/XMLOutputFormat.java
@@ -24,11 +24,11 @@ import java.io.Writer;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.outputformat.CommonMarkupOutputFormat;
import org.apache.freemarker.core.outputformat.OutputFormat;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents the XML output format (MIME type "application/xml", name "XML"). This format escapes by default (via
- * {@link _StringUtil#XMLEnc(String)}). The {@code ?html}, {@code ?xhtml} and {@code ?xml} built-ins silently bypass
+ * {@link _StringUtils#XMLEnc(String)}). The {@code ?html}, {@code ?xhtml} and {@code ?xml} built-ins silently bypass
* template output values of the type produced by this output format ({@link TemplateXHTMLOutputModel}).
*/
public final class XMLOutputFormat extends CommonMarkupOutputFormat<TemplateXMLOutputModel> {
@@ -54,12 +54,12 @@ public final class XMLOutputFormat extends CommonMarkupOutputFormat<TemplateXMLO
@Override
public void output(String textToEsc, Writer out) throws IOException, TemplateModelException {
- _StringUtil.XMLEnc(textToEsc, out);
+ _StringUtils.XMLEnc(textToEsc, out);
}
@Override
public String escapePlainText(String plainTextContent) {
- return _StringUtil.XMLEnc(plainTextContent);
+ return _StringUtils.XMLEnc(plainTextContent);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FileNameGlobMatcher.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FileNameGlobMatcher.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FileNameGlobMatcher.java
index 3db052d..443b9e6 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FileNameGlobMatcher.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FileNameGlobMatcher.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core.templateresolver;
import java.io.IOException;
import java.util.regex.Pattern;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* As opposed to {@link PathGlobMatcher}, it only compares the "file name" part (the part after the last {@code /}) of
@@ -38,7 +38,7 @@ public class FileNameGlobMatcher extends TemplateSourceMatcher {
/**
* @param glob
- * Glob with the syntax defined by {@link _StringUtil#globToRegularExpression(String, boolean)}. Must not
+ * Glob with the syntax defined by {@link _StringUtils#globToRegularExpression(String, boolean)}. Must not
* start with {@code /}.
*/
public FileNameGlobMatcher(String glob) {
@@ -50,7 +50,7 @@ public class FileNameGlobMatcher extends TemplateSourceMatcher {
}
private void buildPattern() {
- pattern = _StringUtil.globToRegularExpression("**/" + glob, caseInsensitive);
+ pattern = _StringUtils.globToRegularExpression("**/" + glob, caseInsensitive);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FirstMatchTemplateConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FirstMatchTemplateConfigurationFactory.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FirstMatchTemplateConfigurationFactory.java
index 0f09d3d..97218e3 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FirstMatchTemplateConfigurationFactory.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/FirstMatchTemplateConfigurationFactory.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core.templateresolver;
import java.io.IOException;
import org.apache.freemarker.core.TemplateConfiguration;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Returns the first non-{@code null} result of the child factories, ignoring all further child factories. The child
@@ -50,7 +50,7 @@ public class FirstMatchTemplateConfigurationFactory extends TemplateConfiguratio
throw new TemplateConfigurationFactoryException(
FirstMatchTemplateConfigurationFactory.class.getSimpleName()
+ " has found no matching choice for source name "
- + _StringUtil.jQuote(sourceName) + ". "
+ + _StringUtils.jQuote(sourceName) + ". "
+ (noMatchErrorDetails != null
? "Error details: " + noMatchErrorDetails
: "(Set the noMatchErrorDetails property of the factory bean to give a more specific error "
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/MalformedTemplateNameException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/MalformedTemplateNameException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/MalformedTemplateNameException.java
index 49c3b88..0c675cd 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/MalformedTemplateNameException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/MalformedTemplateNameException.java
@@ -23,7 +23,7 @@ import java.io.IOException;
import org.apache.freemarker.core.Configuration;
import org.apache.freemarker.core.TemplateNotFoundException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Indicates that the template name given was malformed according the {@link TemplateNameFormat} in use.
@@ -40,7 +40,7 @@ public class MalformedTemplateNameException extends IOException {
private final String malformednessDescription;
public MalformedTemplateNameException(String templateName, String malformednessDescription) {
- super("Malformed template name, " + _StringUtil.jQuote(templateName) + ": " + malformednessDescription);
+ super("Malformed template name, " + _StringUtils.jQuote(templateName) + ": " + malformednessDescription);
this.templateName = templateName;
this.malformednessDescription = malformednessDescription;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathGlobMatcher.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathGlobMatcher.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathGlobMatcher.java
index 17d1b94..34164d2 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathGlobMatcher.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathGlobMatcher.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core.templateresolver;
import java.io.IOException;
import java.util.regex.Pattern;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Matches the whole template source name (also known as template source path) with the given glob.
@@ -29,7 +29,7 @@ import org.apache.freemarker.core.util._StringUtil;
* it's not the full path of a file on the file system.
*
* <p>This glob implementation recognizes {@code **} (Ant-style directory wildcard) among others. For more details see
- * {@link _StringUtil#globToRegularExpression(String, boolean)}.
+ * {@link _StringUtils#globToRegularExpression(String, boolean)}.
*
* <p>About the usage of {@code /} (slash):
* <ul>
@@ -52,7 +52,7 @@ public class PathGlobMatcher extends TemplateSourceMatcher {
/**
* @param glob
- * Glob with the syntax defined by {@link _StringUtil#globToRegularExpression(String, boolean)}. Must not
+ * Glob with the syntax defined by {@link _StringUtils#globToRegularExpression(String, boolean)}. Must not
* start with {@code /}.
*/
public PathGlobMatcher(String glob) {
@@ -64,7 +64,7 @@ public class PathGlobMatcher extends TemplateSourceMatcher {
}
private void buildPattern() {
- pattern = _StringUtil.globToRegularExpression(glob, caseInsensitive);
+ pattern = _StringUtils.globToRegularExpression(glob, caseInsensitive);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathRegexMatcher.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathRegexMatcher.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathRegexMatcher.java
index 347408b..e568e1a 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathRegexMatcher.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/PathRegexMatcher.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core.templateresolver;
import java.io.IOException;
import java.util.regex.Pattern;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Matches the whole template source name (also known as template source path) with the given regular expression.
@@ -34,7 +34,7 @@ public class PathRegexMatcher extends TemplateSourceMatcher {
/**
* @param regex
- * Glob with the syntax defined by {@link _StringUtil#globToRegularExpression(String)}. Must not
+ * Glob with the syntax defined by {@link _StringUtils#globToRegularExpression(String)}. Must not
* start with {@code /}.
*/
public PathRegexMatcher(String regex) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ByteArrayTemplateLoader.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ByteArrayTemplateLoader.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ByteArrayTemplateLoader.java
index 8df63ed..28a8671 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ByteArrayTemplateLoader.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ByteArrayTemplateLoader.java
@@ -34,7 +34,7 @@ import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.TemplateLoaderSession;
import org.apache.freemarker.core.templateresolver.TemplateLoadingResult;
import org.apache.freemarker.core.templateresolver.TemplateLoadingSource;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* A {@link TemplateLoader} that uses a {@link Map} with {@code byte[]} as its source of templates. This is similar to
@@ -132,7 +132,7 @@ public class ByteArrayTemplateLoader implements TemplateLoader {
sb.append("...");
break;
}
- sb.append(_StringUtil.jQuote(name));
+ sb.append(_StringUtils.jQuote(name));
sb.append("=...");
}
if (cnt != 0) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ClassTemplateLoader.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ClassTemplateLoader.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ClassTemplateLoader.java
index 331307f..414d137 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ClassTemplateLoader.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/ClassTemplateLoader.java
@@ -26,7 +26,7 @@ import java.net.URLConnection;
import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.TemplateLoadingResult;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* A {@link TemplateLoader} that can load templates from the "classpath". Naturally, it can load from jar files, or from
@@ -128,10 +128,10 @@ public class ClassTemplateLoader extends URLTemplateLoader {
return _TemplateLoaderUtils.getClassNameForToString(this) + "("
+ (resourceLoaderClass != null
? "resourceLoaderClass=" + resourceLoaderClass.getName()
- : "classLoader=" + _StringUtil.jQuote(classLoader))
+ : "classLoader=" + _StringUtils.jQuote(classLoader))
+ ", basePackagePath"
+ "="
- + _StringUtil.jQuote(basePackagePath)
+ + _StringUtils.jQuote(basePackagePath)
+ (resourceLoaderClass != null
? (basePackagePath.startsWith("/") ? "" : " /* relatively to resourceLoaderClass pkg */")
: ""
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateNameFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateNameFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateNameFormat.java
index 4144e34..ff2049d 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateNameFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateNameFormat.java
@@ -25,7 +25,7 @@ import org.apache.freemarker.core.Configuration;
import org.apache.freemarker.core.templateresolver.MalformedTemplateNameException;
import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.TemplateNameFormat;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* The default {@linkplain Configuration#getTemplateNameFormat()} template name format}. This defines a format where
@@ -151,7 +151,7 @@ public final class DefaultTemplateNameFormat extends TemplateNameFormat {
String prevName;
do {
prevName = path;
- path = _StringUtil.replace(path, "//", "/");
+ path = _StringUtils.replace(path, "//", "/");
} while (prevName != path);
return path.startsWith("/") ? path.substring(1) : path;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateResolver.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateResolver.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateResolver.java
index 2504ccc..aaf09bc 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateResolver.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/DefaultTemplateResolver.java
@@ -59,7 +59,7 @@ import org.apache.freemarker.core.templateresolver.TemplateResolverDependencies;
import org.apache.freemarker.core.util.BugException;
import org.apache.freemarker.core.util.UndeclaredThrowableException;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -309,8 +309,8 @@ public class DefaultTemplateResolver extends TemplateResolver {
Object newSource = newTemplateLoaderResult.getSource();
if (!nullSafeEquals(newSource, oldCachedResult.source)) {
debugMsg.append("the source has been changed: ")
- .append("cached.source=").append(_StringUtil.jQuoteNoXSS(oldCachedResult.source))
- .append(", current.source=").append(_StringUtil.jQuoteNoXSS(newSource));
+ .append("cached.source=").append(_StringUtils.jQuoteNoXSS(oldCachedResult.source))
+ .append(", current.source=").append(_StringUtils.jQuoteNoXSS(newSource));
} else {
Serializable newVersion = newTemplateLoaderResult.getVersion();
if (!nullSafeEquals(oldCachedResult.version, newVersion)) {
@@ -354,7 +354,7 @@ public class DefaultTemplateResolver extends TemplateResolver {
// If we get here, then we need to (re)load the template
if (debug) {
LOG.debug(debugPrefix + "Reading template content (source: "
- + _StringUtil.jQuoteNoXSS(newCachedResult.source) + ")");
+ + _StringUtils.jQuoteNoXSS(newCachedResult.source) + ")");
}
Template template = loadTemplate(
@@ -576,7 +576,7 @@ public class DefaultTemplateResolver extends TemplateResolver {
reader = new InputStreamReader(inputStream, templateSpecifiedEncoding);
} else {
throw new IllegalStateException(
- "TemplateLanguage " + _StringUtil.jQuote(templateLanguage.getName()) + " has thrown "
+ "TemplateLanguage " + _StringUtils.jQuote(templateLanguage.getName()) + " has thrown "
+ WrongTemplateCharsetException.class.getName()
+ ", but its canSpecifyCharsetInContent property is false.");
}
@@ -650,9 +650,9 @@ public class DefaultTemplateResolver extends TemplateResolver {
}
private String getDebugPrefix(String operation, String name, Locale locale, Object customLookupCondition) {
- return operation + " " + _StringUtil.jQuoteNoXSS(name) + "("
- + _StringUtil.jQuoteNoXSS(locale)
- + (customLookupCondition != null ? ", cond=" + _StringUtil.jQuoteNoXSS(customLookupCondition) : "")
+ return operation + " " + _StringUtils.jQuoteNoXSS(name) + "("
+ + _StringUtils.jQuoteNoXSS(locale)
+ + (customLookupCondition != null ? ", cond=" + _StringUtils.jQuoteNoXSS(customLookupCondition) : "")
+ "): ";
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/FileTemplateLoader.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/FileTemplateLoader.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/FileTemplateLoader.java
index 4976746..e738351 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/FileTemplateLoader.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/FileTemplateLoader.java
@@ -36,8 +36,8 @@ import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.TemplateLoaderSession;
import org.apache.freemarker.core.templateresolver.TemplateLoadingResult;
import org.apache.freemarker.core.templateresolver.TemplateLoadingSource;
-import org.apache.freemarker.core.util._SecurityUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._SecurityUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,11 +58,11 @@ public class FileTemplateLoader implements TemplateLoader {
= "org.freemarker.emulateCaseSensitiveFileSystem";
private static final boolean EMULATE_CASE_SENSITIVE_FILE_SYSTEM_DEFAULT;
static {
- final String s = _SecurityUtil.getSystemProperty(SYSTEM_PROPERTY_NAME_EMULATE_CASE_SENSITIVE_FILE_SYSTEM,
+ final String s = _SecurityUtils.getSystemProperty(SYSTEM_PROPERTY_NAME_EMULATE_CASE_SENSITIVE_FILE_SYSTEM,
"false");
boolean emuCaseSensFS;
try {
- emuCaseSensFS = _StringUtil.getYesNo(s);
+ emuCaseSensFS = _StringUtils.getYesNo(s);
} catch (Exception e) {
emuCaseSensFS = false;
}
@@ -306,7 +306,7 @@ public class FileTemplateLoader implements TemplateLoader {
*/
@Override
public String toString() {
- // We don't _StringUtil.jQuote paths here, because on Windows there will be \\-s then that some may find
+ // We don't _StringUtils.jQuote paths here, because on Windows there will be \\-s then that some may find
// confusing.
return _TemplateLoaderUtils.getClassNameForToString(this) + "("
+ "baseDir=\"" + baseDir + "\""
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/StringTemplateLoader.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/StringTemplateLoader.java b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/StringTemplateLoader.java
index 7cc52ac..47e3b7a 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/StringTemplateLoader.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/templateresolver/impl/StringTemplateLoader.java
@@ -34,7 +34,7 @@ import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.TemplateLoaderSession;
import org.apache.freemarker.core.templateresolver.TemplateLoadingResult;
import org.apache.freemarker.core.templateresolver.TemplateLoadingSource;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* A {@link TemplateLoader} that uses a {@link Map} with {@code String} as its source of templates. This is similar to
@@ -132,7 +132,7 @@ public class StringTemplateLoader implements TemplateLoader {
sb.append("...");
break;
}
- sb.append(_StringUtil.jQuote(name));
+ sb.append(_StringUtils.jQuote(name));
sb.append("=...");
}
if (cnt != 0) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/DuplicateStringKeyException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/DuplicateStringKeyException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/DuplicateStringKeyException.java
index a598694..2456dda 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/DuplicateStringKeyException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/DuplicateStringKeyException.java
@@ -28,7 +28,7 @@ public class DuplicateStringKeyException extends IllegalArgumentException {
private final String key;
public DuplicateStringKeyException(String key) {
- super("Duplicate key: " + _StringUtil.jQuote(key));
+ super("Duplicate key: " + _StringUtils.jQuote(key));
this.key = key;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/FTLUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/FTLUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/FTLUtil.java
index 7c58284..1b5e04a 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/FTLUtil.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/FTLUtil.java
@@ -721,13 +721,13 @@ public final class FTLUtil {
String javaClassName;
Class unwrappedClass = getUnwrappedClass(tm);
if (unwrappedClass != null) {
- javaClassName = _ClassUtil.getShortClassName(unwrappedClass, true);
+ javaClassName = _ClassUtils.getShortClassName(unwrappedClass, true);
} else {
javaClassName = null;
}
sb.append(" (");
- String modelClassName = _ClassUtil.getShortClassName(tm.getClass(), true);
+ String modelClassName = _ClassUtils.getShortClassName(tm.getClass(), true);
if (javaClassName == null) {
sb.append("wrapper: ");
sb.append(modelClassName);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/OptInTemplateClassResolver.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/OptInTemplateClassResolver.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/OptInTemplateClassResolver.java
index faf8e73..558e09d 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/OptInTemplateClassResolver.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/OptInTemplateClassResolver.java
@@ -108,7 +108,7 @@ public class OptInTemplateClassResolver implements TemplateClassResolver {
"\" setting in the FreeMarker configuration.)");
} else {
try {
- return _ClassUtil.forName(className);
+ return _ClassUtils.forName(className);
} catch (ClassNotFoundException e) {
throw new _MiscTemplateException(e, env);
}
@@ -129,12 +129,12 @@ public class OptInTemplateClassResolver implements TemplateClassResolver {
// Detect exploits, return null if one is suspected:
String decodedName = name;
if (decodedName.indexOf('%') != -1) {
- decodedName = _StringUtil.replace(decodedName, "%2e", ".", false, false);
- decodedName = _StringUtil.replace(decodedName, "%2E", ".", false, false);
- decodedName = _StringUtil.replace(decodedName, "%2f", "/", false, false);
- decodedName = _StringUtil.replace(decodedName, "%2F", "/", false, false);
- decodedName = _StringUtil.replace(decodedName, "%5c", "\\", false, false);
- decodedName = _StringUtil.replace(decodedName, "%5C", "\\", false, false);
+ decodedName = _StringUtils.replace(decodedName, "%2e", ".", false, false);
+ decodedName = _StringUtils.replace(decodedName, "%2E", ".", false, false);
+ decodedName = _StringUtils.replace(decodedName, "%2f", "/", false, false);
+ decodedName = _StringUtils.replace(decodedName, "%2F", "/", false, false);
+ decodedName = _StringUtils.replace(decodedName, "%5c", "\\", false, false);
+ decodedName = _StringUtils.replace(decodedName, "%5C", "\\", false, false);
}
int dotDotIdx = decodedName.indexOf("..");
if (dotDotIdx != -1) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/StringToIndexMap.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/StringToIndexMap.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/StringToIndexMap.java
index 65e8153..feb9586 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/StringToIndexMap.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/StringToIndexMap.java
@@ -262,7 +262,7 @@ public final class StringToIndexMap {
while (entry != null) {
if (entry.value < start || entry.value >= end) {
throw new IllegalArgumentException(
- "Entry " + _StringUtil.jQuote(entry.key) + " -> " + entry.value
+ "Entry " + _StringUtils.jQuote(entry.key) + " -> " + entry.value
+ " is out of allowed index range: " + start + " ..< " + end);
}
entry = entry.nextInSameBucket;
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/UnrecognizedTimeZoneException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/UnrecognizedTimeZoneException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/UnrecognizedTimeZoneException.java
index 4a820a0..7894257 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/UnrecognizedTimeZoneException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/UnrecognizedTimeZoneException.java
@@ -27,7 +27,7 @@ public class UnrecognizedTimeZoneException extends Exception {
private final String timeZoneName;
public UnrecognizedTimeZoneException(String timeZoneName) {
- super("Unrecognized time zone: " + _StringUtil.jQuote(timeZoneName));
+ super("Unrecognized time zone: " + _StringUtils.jQuote(timeZoneName));
this.timeZoneName = timeZoneName;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtil.java
deleted file mode 100644
index 7a605b1..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtil.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import org.apache.freemarker.core.model.impl.BeanModel;
-
-public class _ClassUtil {
-
- private static final String ORG_APACHE_FREEMARKER = "org.apache.freemarker.";
- private static final String ORG_APACHE_FREEMARKER_CORE = "org.apache.freemarker.core.";
- private static final String ORG_APACHE_FREEMARKER_CORE_TEMPLATERESOLVER
- = "org.apache.freemarker.core.templateresolver.";
- private static final String ORG_APACHE_FREEMARKER_CORE_MODEL = "org.apache.freemarker.core.model.";
-
- private _ClassUtil() {
- }
-
- /**
- * Similar to {@link Class#forName(java.lang.String)}, but attempts to load
- * through the thread context class loader. Only if thread context class
- * loader is inaccessible, or it can't find the class will it attempt to
- * fall back to the class loader that loads the FreeMarker classes.
- */
- public static Class forName(String className)
- throws ClassNotFoundException {
- try {
- ClassLoader ctcl = Thread.currentThread().getContextClassLoader();
- if (ctcl != null) { // not null: we don't want to fall back to the bootstrap class loader
- return Class.forName(className, true, ctcl);
- }
- } catch (ClassNotFoundException e) {
- // Intentionally ignored
- } catch (SecurityException e) {
- // Intentionally ignored
- }
- // Fall back to the defining class loader of the FreeMarker classes
- return Class.forName(className);
- }
-
- /**
- * Same as {@link #getShortClassName(Class, boolean) getShortClassName(pClass, false)}.
- */
- public static String getShortClassName(Class pClass) {
- return getShortClassName(pClass, false);
- }
-
- /**
- * Returns a class name without "java.lang." and "java.util." prefix, also shows array types in a format like
- * {@code int[]}; useful for printing class names in error messages.
- *
- * @param pClass can be {@code null}, in which case the method returns {@code null}.
- * @param shortenFreeMarkerClasses if {@code true}, it will also shorten FreeMarker class names. The exact rules
- * aren't specified and might change over time, but right now, {@link BeanModel} for
- * example becomes to {@code o.a.f.c.m.BeanModel}.
- */
- public static String getShortClassName(Class pClass, boolean shortenFreeMarkerClasses) {
- if (pClass == null) {
- return null;
- } else if (pClass.isArray()) {
- return getShortClassName(pClass.getComponentType()) + "[]";
- } else {
- String cn = pClass.getName();
- if (cn.startsWith("java.lang.") || cn.startsWith("java.util.")) {
- return cn.substring(10);
- } else {
- if (shortenFreeMarkerClasses) {
- if (cn.startsWith(ORG_APACHE_FREEMARKER_CORE_MODEL)) {
- return "o.a.f.c.m." + cn.substring(ORG_APACHE_FREEMARKER_CORE_MODEL.length());
- } else if (cn.startsWith(ORG_APACHE_FREEMARKER_CORE_TEMPLATERESOLVER)) {
- return "o.a.f.c.t." + cn.substring(ORG_APACHE_FREEMARKER_CORE_TEMPLATERESOLVER.length());
- } else if (cn.startsWith(ORG_APACHE_FREEMARKER_CORE)) {
- return "o.a.f.c." + cn.substring(ORG_APACHE_FREEMARKER_CORE.length());
- } else if (cn.startsWith(ORG_APACHE_FREEMARKER)) {
- return "o.a.f." + cn.substring(ORG_APACHE_FREEMARKER.length());
- }
- // Falls through
- }
- return cn;
- }
- }
- }
-
- /**
- * Same as {@link #getShortClassNameOfObject(Object, boolean) getShortClassNameOfObject(pClass, false)}.
- */
- public static String getShortClassNameOfObject(Object obj) {
- return getShortClassNameOfObject(obj, false);
- }
-
- /**
- * {@link #getShortClassName(Class, boolean)} called with {@code object.getClass()}, but returns the fictional
- * class name {@code Null} for a {@code null} value.
- */
- public static String getShortClassNameOfObject(Object obj, boolean shortenFreeMarkerClasses) {
- if (obj == null) {
- return "Null";
- } else {
- return _ClassUtil.getShortClassName(obj.getClass(), shortenFreeMarkerClasses);
- }
- }
-
- /**
- * Gets the wrapper class for a primitive class, like {@link Integer} for {@code int}, also returns {@link Void}
- * for {@code void}.
- *
- * @param primitiveClass A {@link Class} like {@code int.type}, {@code boolean.type}, etc. If it's not a primitive
- * class, or it's {@code null}, then the parameter value is returned as is. Note that performance-wise the
- * method assumes that it's a primitive class.
- */
- public static Class primitiveClassToBoxingClass(Class primitiveClass) {
- // Tried to sort these with decreasing frequency in API-s:
- if (primitiveClass == int.class) return Integer.class;
- if (primitiveClass == boolean.class) return Boolean.class;
- if (primitiveClass == long.class) return Long.class;
- if (primitiveClass == double.class) return Double.class;
- if (primitiveClass == char.class) return Character.class;
- if (primitiveClass == float.class) return Float.class;
- if (primitiveClass == byte.class) return Byte.class;
- if (primitiveClass == short.class) return Short.class;
- if (primitiveClass == void.class) return Void.class; // not really a primitive, but we normalize it
- return primitiveClass;
- }
-
- /**
- * The exact reverse of {@link #primitiveClassToBoxingClass}.
- */
- public static Class boxingClassToPrimitiveClass(Class boxingClass) {
- // Tried to sort these with decreasing frequency in API-s:
- if (boxingClass == Integer.class) return int.class;
- if (boxingClass == Boolean.class) return boolean.class;
- if (boxingClass == Long.class) return long.class;
- if (boxingClass == Double.class) return double.class;
- if (boxingClass == Character.class) return char.class;
- if (boxingClass == Float.class) return float.class;
- if (boxingClass == Byte.class) return byte.class;
- if (boxingClass == Short.class) return short.class;
- if (boxingClass == Void.class) return void.class; // not really a primitive, but we normalize to it
- return boxingClass;
- }
-
- /**
- * Tells if a type is numerical; works both for primitive types and classes.
- *
- * @param type can't be {@code null}
- */
- public static boolean isNumerical(Class type) {
- return Number.class.isAssignableFrom(type)
- || type.isPrimitive() && type != Boolean.TYPE && type != Character.TYPE && type != Void.TYPE;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtils.java
new file mode 100644
index 0000000..d229c2d
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_ClassUtils.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import org.apache.freemarker.core.model.impl.BeanModel;
+
+public class _ClassUtils {
+
+ private static final String ORG_APACHE_FREEMARKER = "org.apache.freemarker.";
+ private static final String ORG_APACHE_FREEMARKER_CORE = "org.apache.freemarker.core.";
+ private static final String ORG_APACHE_FREEMARKER_CORE_TEMPLATERESOLVER
+ = "org.apache.freemarker.core.templateresolver.";
+ private static final String ORG_APACHE_FREEMARKER_CORE_MODEL = "org.apache.freemarker.core.model.";
+
+ private _ClassUtils() {
+ }
+
+ /**
+ * Similar to {@link Class#forName(java.lang.String)}, but attempts to load
+ * through the thread context class loader. Only if thread context class
+ * loader is inaccessible, or it can't find the class will it attempt to
+ * fall back to the class loader that loads the FreeMarker classes.
+ */
+ public static Class forName(String className)
+ throws ClassNotFoundException {
+ try {
+ ClassLoader ctcl = Thread.currentThread().getContextClassLoader();
+ if (ctcl != null) { // not null: we don't want to fall back to the bootstrap class loader
+ return Class.forName(className, true, ctcl);
+ }
+ } catch (ClassNotFoundException e) {
+ // Intentionally ignored
+ } catch (SecurityException e) {
+ // Intentionally ignored
+ }
+ // Fall back to the defining class loader of the FreeMarker classes
+ return Class.forName(className);
+ }
+
+ /**
+ * Same as {@link #getShortClassName(Class, boolean) getShortClassName(pClass, false)}.
+ */
+ public static String getShortClassName(Class pClass) {
+ return getShortClassName(pClass, false);
+ }
+
+ /**
+ * Returns a class name without "java.lang." and "java.util." prefix, also shows array types in a format like
+ * {@code int[]}; useful for printing class names in error messages.
+ *
+ * @param pClass can be {@code null}, in which case the method returns {@code null}.
+ * @param shortenFreeMarkerClasses if {@code true}, it will also shorten FreeMarker class names. The exact rules
+ * aren't specified and might change over time, but right now, {@link BeanModel} for
+ * example becomes to {@code o.a.f.c.m.BeanModel}.
+ */
+ public static String getShortClassName(Class pClass, boolean shortenFreeMarkerClasses) {
+ if (pClass == null) {
+ return null;
+ } else if (pClass.isArray()) {
+ return getShortClassName(pClass.getComponentType()) + "[]";
+ } else {
+ String cn = pClass.getName();
+ if (cn.startsWith("java.lang.") || cn.startsWith("java.util.")) {
+ return cn.substring(10);
+ } else {
+ if (shortenFreeMarkerClasses) {
+ if (cn.startsWith(ORG_APACHE_FREEMARKER_CORE_MODEL)) {
+ return "o.a.f.c.m." + cn.substring(ORG_APACHE_FREEMARKER_CORE_MODEL.length());
+ } else if (cn.startsWith(ORG_APACHE_FREEMARKER_CORE_TEMPLATERESOLVER)) {
+ return "o.a.f.c.t." + cn.substring(ORG_APACHE_FREEMARKER_CORE_TEMPLATERESOLVER.length());
+ } else if (cn.startsWith(ORG_APACHE_FREEMARKER_CORE)) {
+ return "o.a.f.c." + cn.substring(ORG_APACHE_FREEMARKER_CORE.length());
+ } else if (cn.startsWith(ORG_APACHE_FREEMARKER)) {
+ return "o.a.f." + cn.substring(ORG_APACHE_FREEMARKER.length());
+ }
+ // Falls through
+ }
+ return cn;
+ }
+ }
+ }
+
+ /**
+ * Same as {@link #getShortClassNameOfObject(Object, boolean) getShortClassNameOfObject(pClass, false)}.
+ */
+ public static String getShortClassNameOfObject(Object obj) {
+ return getShortClassNameOfObject(obj, false);
+ }
+
+ /**
+ * {@link #getShortClassName(Class, boolean)} called with {@code object.getClass()}, but returns the fictional
+ * class name {@code Null} for a {@code null} value.
+ */
+ public static String getShortClassNameOfObject(Object obj, boolean shortenFreeMarkerClasses) {
+ if (obj == null) {
+ return "Null";
+ } else {
+ return _ClassUtils.getShortClassName(obj.getClass(), shortenFreeMarkerClasses);
+ }
+ }
+
+ /**
+ * Gets the wrapper class for a primitive class, like {@link Integer} for {@code int}, also returns {@link Void}
+ * for {@code void}.
+ *
+ * @param primitiveClass A {@link Class} like {@code int.type}, {@code boolean.type}, etc. If it's not a primitive
+ * class, or it's {@code null}, then the parameter value is returned as is. Note that performance-wise the
+ * method assumes that it's a primitive class.
+ */
+ public static Class primitiveClassToBoxingClass(Class primitiveClass) {
+ // Tried to sort these with decreasing frequency in API-s:
+ if (primitiveClass == int.class) return Integer.class;
+ if (primitiveClass == boolean.class) return Boolean.class;
+ if (primitiveClass == long.class) return Long.class;
+ if (primitiveClass == double.class) return Double.class;
+ if (primitiveClass == char.class) return Character.class;
+ if (primitiveClass == float.class) return Float.class;
+ if (primitiveClass == byte.class) return Byte.class;
+ if (primitiveClass == short.class) return Short.class;
+ if (primitiveClass == void.class) return Void.class; // not really a primitive, but we normalize it
+ return primitiveClass;
+ }
+
+ /**
+ * The exact reverse of {@link #primitiveClassToBoxingClass}.
+ */
+ public static Class boxingClassToPrimitiveClass(Class boxingClass) {
+ // Tried to sort these with decreasing frequency in API-s:
+ if (boxingClass == Integer.class) return int.class;
+ if (boxingClass == Boolean.class) return boolean.class;
+ if (boxingClass == Long.class) return long.class;
+ if (boxingClass == Double.class) return double.class;
+ if (boxingClass == Character.class) return char.class;
+ if (boxingClass == Float.class) return float.class;
+ if (boxingClass == Byte.class) return byte.class;
+ if (boxingClass == Short.class) return short.class;
+ if (boxingClass == Void.class) return void.class; // not really a primitive, but we normalize to it
+ return boxingClass;
+ }
+
+ /**
+ * Tells if a type is numerical; works both for primitive types and classes.
+ *
+ * @param type can't be {@code null}
+ */
+ public static boolean isNumerical(Class type) {
+ return Number.class.isAssignableFrom(type)
+ || type.isPrimitive() && type != Boolean.TYPE && type != Character.TYPE && type != Void.TYPE;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtil.java
deleted file mode 100644
index af98987..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtil.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Don't use this; used internally by FreeMarker, might changes without notice.
- * {@link Collection} and {@link Map}-related utilities.
- */
-public class _CollectionUtil {
-
- private _CollectionUtil() { }
-
- public static final Object[] EMPTY_OBJECT_ARRAY = new Object[] { };
- public static final Class[] EMPTY_CLASS_ARRAY = new Class[] { };
- public static final String[] EMPTY_STRING_ARRAY = new String[] { };
- public static final char[] EMPTY_CHAR_ARRAY = new char[] { };
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static <T> List<? extends T> safeCastList(
- String argName, List list,
- Class<T> itemClass, boolean allowNullItem) {
- if (list == null) {
- return null;
- }
- for (int i = 0; i < list.size(); i++) {
- Object it = list.get(i);
- if (!itemClass.isInstance(it)) {
- if (it == null) {
- if (!allowNullItem) {
- throw new IllegalArgumentException(
- (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
- + "List item at index " + i + " is null");
- }
- } else {
- throw new IllegalArgumentException(
- (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
- + "List item at index " + i + " is not instance of " + itemClass.getName() + "; "
- + "its class is " + it.getClass().getName() + ".");
- }
- }
- }
-
- return list;
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static <K, V> Map<? extends K, ? extends V> safeCastMap(
- String argName, Map map,
- Class<K> keyClass, boolean allowNullKey,
- Class<V> valueClass, boolean allowNullValue) {
- if (map == null) {
- return null;
- }
- for (Map.Entry<?, ?> ent : ((Map<?, ?>) map).entrySet()) {
- Object key = ent.getKey();
- if (!keyClass.isInstance(key)) {
- if (key == null) {
- if (!allowNullKey) {
- throw new IllegalArgumentException(
- (argName != null ? "Invalid value for argument \"" + argName + "\": " : "")
- + "The Map contains null key");
- }
- } else {
- throw new IllegalArgumentException(
- (argName != null ? "Invalid value for argument \"" + argName + "\": " : "")
- + "The Map contains a key that's not instance of " + keyClass.getName() +
- "; its class is " + key.getClass().getName() + ".");
- }
- }
-
- Object value = ent.getValue();
- if (!valueClass.isInstance(value)) {
- if (value == null) {
- if (!allowNullValue) {
- throw new IllegalArgumentException(
- (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
- + "The Map contains null value");
- }
- } else {
- throw new IllegalArgumentException(
- (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
- + "The Map contains a value that's not instance of " + valueClass.getName() +
- "; its class is " + value.getClass().getName() + ".");
- }
- }
- }
-
- return map;
- }
-
- private static final Class<?> UNMODIFIABLE_MAP_CLASS_1 = Collections.emptyMap().getClass();
- private static final Class<?> UNMODIFIABLE_MAP_CLASS_2 = Collections.unmodifiableMap(
- new HashMap<Object, Object> (1)).getClass();
- private static final Class<?> UNMODIFIABLE_LIST_CLASS_1 = Collections.emptyList().getClass();
- private static final Class<?> UNMODIFIABLE_LIST_CLASS_2 = Collections.unmodifiableList(
- new ArrayList<Object>(1)).getClass();
-
- public static boolean isMapKnownToBeUnmodifiable(Map<?, ?> map) {
- if (map == null) {
- return true;
- }
- Class<? extends Map> mapClass = map.getClass();
- return mapClass == UNMODIFIABLE_MAP_CLASS_1 || mapClass == UNMODIFIABLE_MAP_CLASS_2;
- }
-
- public static boolean isListKnownToBeUnmodifiable(List<?> list) {
- if (list == null) {
- return true;
- }
- Class<? extends List> listClass = list.getClass();
- return listClass == UNMODIFIABLE_LIST_CLASS_1 || listClass == UNMODIFIABLE_LIST_CLASS_2;
- }
-
- /**
- * Optimized version of {@link Collections#unmodifiableMap(Map)} (avoids needless wrapping).
- *
- * @param map The map to return or wrap if not already unmodifiable, or {@code null} which is silently bypassed.
- */
- public static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) {
- return isMapKnownToBeUnmodifiable(map) ? map : Collections.unmodifiableMap(map);
- }
-
- /**
- * Adds two {@link Map}-s (keeping the iteration order); assuming the inputs are already unmodifiable and
- * unchanging, it returns an unmodifiable and unchanging {@link Map} itself.
- */
- public static <K,V> Map<K,V> mergeImmutableMaps(Map<K,V> m1, Map<K,V> m2, boolean keepOriginalOrder) {
- if (m1 == null) return m2;
- if (m2 == null) return m1;
- if (m1.isEmpty()) return m2;
- if (m2.isEmpty()) return m1;
-
- Map<K, V> mergedM = keepOriginalOrder
- ? new LinkedHashMap<K, V>((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f)
- : new HashMap<K, V>((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f);
- mergedM.putAll(m1);
- if (keepOriginalOrder) {
- for (K m2Key : m2.keySet()) {
- mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys
- }
- }
- mergedM.putAll(m2);
- return Collections.unmodifiableMap(mergedM);
- }
-
- /**
- * Adds multiple {@link List}-s; assuming the inputs are already unmodifiable and unchanging, it returns an
- * unmodifiable and unchanging {@link List} itself.
- */
- public static <T> List<T> mergeImmutableLists(boolean skipDuplicatesInList1, List<T> ... lists) {
- if (lists == null || lists.length == 0) {
- return null;
- }
-
- if (lists.length == 1) {
- return mergeImmutableLists(lists[0], null, skipDuplicatesInList1);
- } else if (lists.length == 2) {
- return mergeImmutableLists(lists[0], lists[1], skipDuplicatesInList1);
- } else {
- List<T> [] reducedLists = new List[lists.length - 1];
- reducedLists[0] = mergeImmutableLists(lists[0], lists[1], skipDuplicatesInList1);
- System.arraycopy(lists, 2, reducedLists, 1, lists.length - 2);
- return mergeImmutableLists(skipDuplicatesInList1, reducedLists);
- }
- }
-
- /**
- * Adds two {@link List}-s; assuming the inputs are already unmodifiable and unchanging, it returns an
- * unmodifiable and unchanging {@link List} itself.
- */
- public static <T> List<T> mergeImmutableLists(List<T> list1, List<T> list2,
- boolean skipDuplicatesInList1) {
- if (list1 == null) return list2;
- if (list2 == null) return list1;
- if (list1.isEmpty()) return list2;
- if (list2.isEmpty()) return list1;
-
- ArrayList<T> mergedList = new ArrayList<>(list1.size() + list2.size());
- if (skipDuplicatesInList1) {
- Set<T> list2Set = new HashSet<>(list2);
- for (T it : list1) {
- if (!list2Set.contains(it)) {
- mergedList.add(it);
- }
- }
- } else {
- mergedList.addAll(list1);
- }
- mergedList.addAll(list2);
- return Collections.unmodifiableList(mergedList);
- }
-
-}
[09/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapper.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapper.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapper.java
index 9d797ce..709fe81 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapper.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapper.java
@@ -68,7 +68,7 @@ import org.apache.freemarker.core.model.TemplateSequenceModel;
import org.apache.freemarker.core.model.WrapperTemplateModel;
import org.apache.freemarker.core.util.BugException;
import org.apache.freemarker.core.util.CommonBuilder;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
import org.apache.freemarker.core.util._NullArgumentException;
/**
@@ -561,7 +561,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
Object res = tryUnwrapTo(model, targetClass, typeFlags, null);
if ((typeFlags & TypeFlags.WIDENED_NUMERICAL_UNWRAPPING_HINT) != 0
&& res instanceof Number) {
- return OverloadedNumberUtil.addFallbackType((Number) res, typeFlags);
+ return OverloadedNumberUtils.addFallbackType((Number) res, typeFlags);
} else {
return res;
}
@@ -578,7 +578,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
}
if (targetClass.isPrimitive()) {
- targetClass = _ClassUtil.primitiveClassToBoxingClass(targetClass);
+ targetClass = _ClassUtils.primitiveClassToBoxingClass(targetClass);
}
// This is for transparent interop with other wrappers (and ourselves)
@@ -592,7 +592,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
}
// Attempt numeric conversion:
- if (targetClass != Object.class && (wrapped instanceof Number && _ClassUtil.isNumerical(targetClass))) {
+ if (targetClass != Object.class && (wrapped instanceof Number && _ClassUtils.isNumerical(targetClass))) {
Number number = forceUnwrappedNumberToType((Number) wrapped, targetClass);
if (number != null) return number;
}
@@ -605,7 +605,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
}
// Attempt numeric conversion:
- if (targetClass != Object.class && (wrapped instanceof Number && _ClassUtil.isNumerical(targetClass))) {
+ if (targetClass != Object.class && (wrapped instanceof Number && _ClassUtils.isNumerical(targetClass))) {
Number number = forceUnwrappedNumberToType((Number) wrapped, targetClass);
if (number != null) {
return number;
@@ -629,7 +629,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
}
// Primitive numeric types & Number.class and its subclasses
- if (_ClassUtil.isNumerical(targetClass)) {
+ if (_ClassUtils.isNumerical(targetClass)) {
if (model instanceof TemplateNumberModel) {
Number number = forceUnwrappedNumberToType(
((TemplateNumberModel) model).getAsNumber(), targetClass);
@@ -861,7 +861,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
if (listItem != null && !componentType.isInstance(listItem)) {
// Type conversion is needed. If we can't do it, we just let it fail at Array.set later.
if (!isComponentTypeExamined) {
- isComponentTypeNumerical = _ClassUtil.isNumerical(componentType);
+ isComponentTypeNumerical = _ClassUtils.isNumerical(componentType);
isComponentTypeList = List.class.isAssignableFrom(componentType);
isComponentTypeExamined = true;
}
@@ -889,10 +889,10 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
Array.set(array, i, listItem);
} catch (IllegalArgumentException e) {
throw new TemplateModelException(
- "Failed to convert " + _ClassUtil.getShortClassNameOfObject(list)
- + " object to " + _ClassUtil.getShortClassNameOfObject(array)
+ "Failed to convert " + _ClassUtils.getShortClassNameOfObject(list)
+ + " object to " + _ClassUtils.getShortClassNameOfObject(array)
+ ": Problematic List item at index " + i + " with value type: "
- + _ClassUtil.getShortClassNameOfObject(listItem), e);
+ + _ClassUtils.getShortClassNameOfObject(listItem), e);
}
i++;
}
@@ -953,8 +953,8 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
if (n instanceof BigInteger) {
return n;
} else {
- if (n instanceof OverloadedNumberUtil.IntegerBigDecimal) {
- return ((OverloadedNumberUtil.IntegerBigDecimal) n).bigIntegerValue();
+ if (n instanceof OverloadedNumberUtils.IntegerBigDecimal) {
+ return ((OverloadedNumberUtils.IntegerBigDecimal) n).bigIntegerValue();
} else if (n instanceof BigDecimal) {
return ((BigDecimal) n).toBigInteger();
} else {
@@ -962,8 +962,8 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
}
}
} else {
- final Number oriN = n instanceof OverloadedNumberUtil.NumberWithFallbackType
- ? ((OverloadedNumberUtil.NumberWithFallbackType) n).getSourceNumber() : n;
+ final Number oriN = n instanceof OverloadedNumberUtils.NumberWithFallbackType
+ ? ((OverloadedNumberUtils.NumberWithFallbackType) n).getSourceNumber() : n;
if (targetType.isInstance(oriN)) {
// Handle nonstandard Number subclasses as well as directly java.lang.Number.
return oriN;
@@ -1065,7 +1065,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
try {
return ctor.newInstance(pojoArgs);
} catch (Exception e) {
- throw _MethodUtil.newInvocationTemplateModelException(null, ctor, e);
+ throw _MethodUtils.newInvocationTemplateModelException(null, ctor, e);
}
} else if (ctors instanceof OverloadedMethods) {
// TODO [FM3] Utilize optional java type info in callPlace for overloaded method selection
@@ -1075,7 +1075,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
} catch (Exception e) {
if (e instanceof TemplateModelException) throw (TemplateModelException) e;
- throw _MethodUtil.newInvocationTemplateModelException(null, mma.getCallableMemberDescriptor(), e);
+ throw _MethodUtils.newInvocationTemplateModelException(null, mma.getCallableMemberDescriptor(), e);
}
} else {
// Cannot happen
@@ -1223,7 +1223,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
@Override
public String toString() {
final String propsStr = toPropertiesString();
- return _ClassUtil.getShortClassNameOfObject(this) + "@" + System.identityHashCode(this)
+ return _ClassUtils.getShortClassNameOfObject(this) + "@" + System.identityHashCode(this)
+ "(" + incompatibleImprovements + ", "
+ (propsStr.length() != 0 ? propsStr + ", ..." : "")
+ ")";
@@ -1334,7 +1334,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
throw new IllegalStateException("build() can only be executed once.");
}
- DefaultObjectWrapper singleton = DefaultObjectWrapperTCCLSingletonUtil.getSingleton(
+ DefaultObjectWrapper singleton = DefaultObjectWrapperTCCLSingletonUtils.getSingleton(
this, INSTANCE_CACHE, INSTANCE_CACHE_REF_QUEUE, ConstructorInvoker.INSTANCE);
alreadyBuilt = true;
return singleton;
@@ -1348,7 +1348,7 @@ public class DefaultObjectWrapper implements RichObjectWrapper {
}
private static class ConstructorInvoker
- implements DefaultObjectWrapperTCCLSingletonUtil._ConstructorInvoker<DefaultObjectWrapper, Builder> {
+ implements DefaultObjectWrapperTCCLSingletonUtils._ConstructorInvoker<DefaultObjectWrapper, Builder> {
private static final ConstructorInvoker INSTANCE = new ConstructorInvoker();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtil.java
deleted file mode 100644
index f5b617d..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtil.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.model.impl;
-
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.WeakReference;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.apache.freemarker.core.util.CommonBuilder;
-
-/**
- * Utility method for caching {@link DefaultObjectWrapper} (and subclasses) sigletons per Thread Context Class
- * Loader.
- */
-// [FM3] Maybe generalize and publish this functionality
-final class DefaultObjectWrapperTCCLSingletonUtil {
-
- private DefaultObjectWrapperTCCLSingletonUtil() {
- // Not meant to be instantiated
- }
-
- /**
- * Contains the common parts of the singleton management for {@link DefaultObjectWrapper} and {@link DefaultObjectWrapper}.
- *
- * @param dowConstructorInvoker Creates a <em>new</em> read-only object wrapper of the desired
- * {@link DefaultObjectWrapper} subclass.
- */
- static <
- ObjectWrapperT extends DefaultObjectWrapper,
- BuilderT extends DefaultObjectWrapper.ExtendableBuilder<ObjectWrapperT, BuilderT>>
- ObjectWrapperT getSingleton(
- BuilderT builder,
- Map<ClassLoader, Map<BuilderT, WeakReference<ObjectWrapperT>>> instanceCache,
- ReferenceQueue<ObjectWrapperT> instanceCacheRefQue,
- _ConstructorInvoker<ObjectWrapperT, BuilderT> dowConstructorInvoker) {
- // DefaultObjectWrapper can't be cached across different Thread Context Class Loaders (TCCL), because the result of
- // a class name (String) to Class mappings depends on it, and the staticModels and enumModels need that.
- // (The ClassIntrospector doesn't have to consider the TCCL, as it only works with Class-es, not class
- // names.)
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
-
- Reference<ObjectWrapperT> instanceRef;
- Map<BuilderT, WeakReference<ObjectWrapperT>> tcclScopedCache;
- synchronized (instanceCache) {
- tcclScopedCache = instanceCache.get(tccl);
- if (tcclScopedCache == null) {
- tcclScopedCache = new HashMap<>();
- instanceCache.put(tccl, tcclScopedCache);
- instanceRef = null;
- } else {
- instanceRef = tcclScopedCache.get(builder);
- }
- }
-
- ObjectWrapperT instance = instanceRef != null ? instanceRef.get() : null;
- if (instance != null) { // cache hit
- return instance;
- }
- // cache miss
-
- builder = builder.cloneForCacheKey(); // prevent any aliasing issues
- instance = dowConstructorInvoker.invoke(builder);
-
- synchronized (instanceCache) {
- instanceRef = tcclScopedCache.get(builder);
- ObjectWrapperT concurrentInstance = instanceRef != null ? instanceRef.get() : null;
- if (concurrentInstance == null) {
- tcclScopedCache.put(builder, new WeakReference<>(instance, instanceCacheRefQue));
- } else {
- instance = concurrentInstance;
- }
- }
-
- removeClearedReferencesFromCache(instanceCache, instanceCacheRefQue);
-
- return instance;
- }
-
- private static <
- ObjectWrapperT extends DefaultObjectWrapper, BuilderT extends DefaultObjectWrapper.ExtendableBuilder>
- void removeClearedReferencesFromCache(
- Map<ClassLoader, Map<BuilderT, WeakReference<ObjectWrapperT>>> instanceCache,
- ReferenceQueue<ObjectWrapperT> instanceCacheRefQue) {
- Reference<? extends ObjectWrapperT> clearedRef;
- while ((clearedRef = instanceCacheRefQue.poll()) != null) {
- synchronized (instanceCache) {
- findClearedRef: for (Map<BuilderT, WeakReference<ObjectWrapperT>> tcclScopedCache : instanceCache.values()) {
- for (Iterator<WeakReference<ObjectWrapperT>> it2 = tcclScopedCache.values().iterator(); it2.hasNext(); ) {
- if (it2.next() == clearedRef) {
- it2.remove();
- break findClearedRef;
- }
- }
- }
- } // sync
- } // while poll
- }
-
- /**
- * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
- * Used when the builder delegates the product creation to something else (typically, an instance cache). Calling
- * {@link CommonBuilder#build()} would be infinite recursion in such cases.
- */
- public interface _ConstructorInvoker<ProductT, BuilderT> {
-
- ProductT invoke(BuilderT builder);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtils.java
new file mode 100644
index 0000000..4f7dca6
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperTCCLSingletonUtils.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.model.impl;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.freemarker.core.util.CommonBuilder;
+
+/**
+ * Utility method for caching {@link DefaultObjectWrapper} (and subclasses) sigletons per Thread Context Class
+ * Loader.
+ */
+// [FM3] Maybe generalize and publish this functionality
+final class DefaultObjectWrapperTCCLSingletonUtils {
+
+ private DefaultObjectWrapperTCCLSingletonUtils() {
+ // Not meant to be instantiated
+ }
+
+ /**
+ * Contains the common parts of the singleton management for {@link DefaultObjectWrapper} and {@link DefaultObjectWrapper}.
+ *
+ * @param dowConstructorInvoker Creates a <em>new</em> read-only object wrapper of the desired
+ * {@link DefaultObjectWrapper} subclass.
+ */
+ static <
+ ObjectWrapperT extends DefaultObjectWrapper,
+ BuilderT extends DefaultObjectWrapper.ExtendableBuilder<ObjectWrapperT, BuilderT>>
+ ObjectWrapperT getSingleton(
+ BuilderT builder,
+ Map<ClassLoader, Map<BuilderT, WeakReference<ObjectWrapperT>>> instanceCache,
+ ReferenceQueue<ObjectWrapperT> instanceCacheRefQue,
+ _ConstructorInvoker<ObjectWrapperT, BuilderT> dowConstructorInvoker) {
+ // DefaultObjectWrapper can't be cached across different Thread Context Class Loaders (TCCL), because the result of
+ // a class name (String) to Class mappings depends on it, and the staticModels and enumModels need that.
+ // (The ClassIntrospector doesn't have to consider the TCCL, as it only works with Class-es, not class
+ // names.)
+ ClassLoader tccl = Thread.currentThread().getContextClassLoader();
+
+ Reference<ObjectWrapperT> instanceRef;
+ Map<BuilderT, WeakReference<ObjectWrapperT>> tcclScopedCache;
+ synchronized (instanceCache) {
+ tcclScopedCache = instanceCache.get(tccl);
+ if (tcclScopedCache == null) {
+ tcclScopedCache = new HashMap<>();
+ instanceCache.put(tccl, tcclScopedCache);
+ instanceRef = null;
+ } else {
+ instanceRef = tcclScopedCache.get(builder);
+ }
+ }
+
+ ObjectWrapperT instance = instanceRef != null ? instanceRef.get() : null;
+ if (instance != null) { // cache hit
+ return instance;
+ }
+ // cache miss
+
+ builder = builder.cloneForCacheKey(); // prevent any aliasing issues
+ instance = dowConstructorInvoker.invoke(builder);
+
+ synchronized (instanceCache) {
+ instanceRef = tcclScopedCache.get(builder);
+ ObjectWrapperT concurrentInstance = instanceRef != null ? instanceRef.get() : null;
+ if (concurrentInstance == null) {
+ tcclScopedCache.put(builder, new WeakReference<>(instance, instanceCacheRefQue));
+ } else {
+ instance = concurrentInstance;
+ }
+ }
+
+ removeClearedReferencesFromCache(instanceCache, instanceCacheRefQue);
+
+ return instance;
+ }
+
+ private static <
+ ObjectWrapperT extends DefaultObjectWrapper, BuilderT extends DefaultObjectWrapper.ExtendableBuilder>
+ void removeClearedReferencesFromCache(
+ Map<ClassLoader, Map<BuilderT, WeakReference<ObjectWrapperT>>> instanceCache,
+ ReferenceQueue<ObjectWrapperT> instanceCacheRefQue) {
+ Reference<? extends ObjectWrapperT> clearedRef;
+ while ((clearedRef = instanceCacheRefQue.poll()) != null) {
+ synchronized (instanceCache) {
+ findClearedRef: for (Map<BuilderT, WeakReference<ObjectWrapperT>> tcclScopedCache : instanceCache.values()) {
+ for (Iterator<WeakReference<ObjectWrapperT>> it2 = tcclScopedCache.values().iterator(); it2.hasNext(); ) {
+ if (it2.next() == clearedRef) {
+ it2.remove();
+ break findClearedRef;
+ }
+ }
+ }
+ } // sync
+ } // while poll
+ }
+
+ /**
+ * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
+ * Used when the builder delegates the product creation to something else (typically, an instance cache). Calling
+ * {@link CommonBuilder#build()} would be infinite recursion in such cases.
+ */
+ public interface _ConstructorInvoker<ProductT, BuilderT> {
+
+ ProductT invoke(BuilderT builder);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedJavaMethodModel.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedJavaMethodModel.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedJavaMethodModel.java
index 1877687..b662390 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedJavaMethodModel.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedJavaMethodModel.java
@@ -70,7 +70,7 @@ class OverloadedJavaMethodModel implements JavaMethodModel {
} catch (Exception e) {
if (e instanceof TemplateModelException) throw (TemplateModelException) e;
- throw _MethodUtil.newInvocationTemplateModelException(
+ throw _MethodUtils.newInvocationTemplateModelException(
object,
maa.getCallableMemberDescriptor(),
e);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethods.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethods.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethods.java
index fad854d..5912424 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethods.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethods.java
@@ -31,7 +31,7 @@ import org.apache.freemarker.core.model.TemplateMarkupOutputModel;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.util.FTLUtil;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
/**
* Used instead of {@link java.lang.reflect.Method} or {@link java.lang.reflect.Constructor} for overloaded methods and
@@ -241,8 +241,8 @@ final class OverloadedMethods {
@Override
String argumentToString(Object argType) {
return argType != null
- ? _ClassUtil.getShortClassName((Class<?>) argType)
- : _ClassUtil.getShortClassNameOfObject(null);
+ ? _ClassUtils.getShortClassName((Class<?>) argType)
+ : _ClassUtils.getShortClassNameOfObject(null);
}
};
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethodsSubset.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethodsSubset.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethodsSubset.java
index aab6d43..45cf7f3 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethodsSubset.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedMethodsSubset.java
@@ -29,7 +29,7 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
import org.apache.freemarker.core.util._NullArgumentException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@@ -176,7 +176,7 @@ abstract class OverloadedMethodsSubset {
// c1 primitive class to boxing class:
final boolean c1WasPrim;
if (c1.isPrimitive()) {
- c1 = _ClassUtil.primitiveClassToBoxingClass(c1);
+ c1 = _ClassUtils.primitiveClassToBoxingClass(c1);
c1WasPrim = true;
} else {
c1WasPrim = false;
@@ -185,7 +185,7 @@ abstract class OverloadedMethodsSubset {
// c2 primitive class to boxing class:
final boolean c2WasPrim;
if (c2.isPrimitive()) {
- c2 = _ClassUtil.primitiveClassToBoxingClass(c2);
+ c2 = _ClassUtils.primitiveClassToBoxingClass(c2);
c2WasPrim = true;
} else {
c2WasPrim = false;
@@ -214,8 +214,8 @@ abstract class OverloadedMethodsSubset {
// - One of classes was a primitive type
// - One of classes was a numerical type (either boxing type or primitive)
- Set<Class<?>> commonTypes = _MethodUtil.getAssignables(c1, c2);
- commonTypes.retainAll(_MethodUtil.getAssignables(c2, c1));
+ Set<Class<?>> commonTypes = _MethodUtils.getAssignables(c1, c2);
+ commonTypes.retainAll(_MethodUtils.getAssignables(c2, c1));
if (commonTypes.isEmpty()) {
// Can happen when at least one of the arguments is an interface, as
// they don't have Object at the root of their hierarchy
@@ -231,11 +231,11 @@ abstract class OverloadedMethodsSubset {
for (Class<?> clazz : commonTypes) {
for (Iterator<Class<?>> maxIter = max.iterator(); maxIter.hasNext(); ) {
Class<?> maxClazz = maxIter.next();
- if (_MethodUtil.isMoreOrSameSpecificParameterType(maxClazz, clazz, false /*bugfixed [1]*/, 0) != 0) {
+ if (_MethodUtils.isMoreOrSameSpecificParameterType(maxClazz, clazz, false /*bugfixed [1]*/, 0) != 0) {
// clazz can't be maximal, if there's already a more specific or equal maximal than it.
continue listCommonTypes;
}
- if (_MethodUtil.isMoreOrSameSpecificParameterType(clazz, maxClazz, false /*bugfixed [1]*/, 0) != 0) {
+ if (_MethodUtils.isMoreOrSameSpecificParameterType(clazz, maxClazz, false /*bugfixed [1]*/, 0) != 0) {
// If it's more specific than a currently maximal element,
// that currently maximal is no longer a maximal.
maxIter.remove();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtil.java
deleted file mode 100644
index f501576..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtil.java
+++ /dev/null
@@ -1,1289 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.model.impl;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-
-import org.apache.freemarker.core.model.TemplateNumberModel;
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._NumberUtil;
-
-/**
- * Everything related to coercion to ambiguous numerical types.
- */
-class OverloadedNumberUtil {
-
- // Can't be instantiated
- private OverloadedNumberUtil() { }
-
- /**
- * The lower limit of conversion prices where there's a risk of significant mantissa loss.
- * The value comes from misc/overloadedNumberRules/prices.ods and generator.ftl.
- */
- static final int BIG_MANTISSA_LOSS_PRICE = 4 * 10000;
-
- /** The highest long that can be stored in double without precision loss: 2**53. */
- private static final long MAX_DOUBLE_OR_LONG = 9007199254740992L;
- /** The lowest long that can be stored in double without precision loss: -(2**53). */
- private static final long MIN_DOUBLE_OR_LONG = -9007199254740992L;
- private static final int MAX_DOUBLE_OR_LONG_LOG_2 = 53;
-
- /** The highest long that can be stored in float without precision loss: 2**24. */
- private static final int MAX_FLOAT_OR_INT = 16777216;
- /** The lowest long that can be stored in float without precision loss: -(2**24). */
- private static final int MIN_FLOAT_OR_INT = -16777216;
- private static final int MAX_FLOAT_OR_INT_LOG_2 = 24;
- /** Lowest number that we don't thread as possible integer 0. */
- private static final double LOWEST_ABOVE_ZERO = 0.000001;
- /** Highest number that we don't thread as possible integer 1. */
- private static final double HIGHEST_BELOW_ONE = 0.999999;
-
- /**
- * Attaches the lowest alternative number type to the parameter number via {@link NumberWithFallbackType}, if
- * that's useful according the possible target number types. This transformation is applied on the method call
- * argument list before overloaded method selection.
- *
- * <p>Note that as of this writing, this method is only used when
- * {@link DefaultObjectWrapper#getIncompatibleImprovements()} >= 2.3.21.
- *
- * <p>Why's this needed, how it works: Overloaded method selection only selects methods where the <em>type</em>
- * (not the value!) of the argument is "smaller" or the same as the parameter type. This is similar to how it's in
- * the Java language. That it only decides based on the parameter type is important because this way
- * {@link OverloadedMethodsSubset} can cache method lookup decisions using the types as the cache key. Problem is,
- * since you don't declare the exact numerical types in FTL, and FTL has only a single generic numeric type
- * anyway, what Java type a {@link TemplateNumberModel} uses internally is often seen as a technical detail of which
- * the template author can't always keep track of. So we investigate the <em>value</em> of the number too,
- * then coerce it down without overflow to a type that will match the most overloaded methods. (This
- * is especially important as FTL often stores numbers in {@link BigDecimal}-s, which will hardly ever match any
- * method parameters.) We could simply return that number, like {@code Byte(0)} for an {@code Integer(0)},
- * however, then we would lose the information about what the original type was. The original type is sometimes
- * important, as in ambiguous situations the method where there's an exact type match should be selected (like,
- * when someone wants to select an overload explicitly with {@code m(x?int)}). Also, if an overload wins where
- * the parameter type at the position of the number is {@code Number} or {@code Object} (or {@code Comparable}
- * etc.), it's expected that we pass in the original value (an {@code Integer} in this example), especially if that
- * value is the return value of another Java method. That's why we use
- * {@link NumberWithFallbackType} numerical classes like {@link IntegerOrByte}, which represents both the original
- * type and the coerced type, all encoded into the class of the value, which is used as the overloaded method lookup
- * cache key.
- *
- * <p>See also: <tt>src\main\misc\overloadedNumberRules\prices.ods</tt>.
- *
- * @param num the number to coerce
- * @param typeFlags the type flags of the target parameter position; see {@link TypeFlags}
- *
- * @returns The original number or a {@link NumberWithFallbackType}, depending on the actual value and the types
- * indicated in the {@code targetNumTypes} parameter.
- */
- static Number addFallbackType(final Number num, final int typeFlags) {
- final Class numClass = num.getClass();
- if (numClass == BigDecimal.class) {
- // For now we only support the backward-compatible mode that doesn't prevent roll overs and magnitude loss.
- // However, we push the overloaded selection to the right direction, so we will at least indicate if the
- // number has decimals.
- BigDecimal n = (BigDecimal) num;
- if ((typeFlags & TypeFlags.MASK_KNOWN_INTEGERS) != 0
- && (typeFlags & TypeFlags.MASK_KNOWN_NONINTEGERS) != 0
- && _NumberUtil.isIntegerBigDecimal(n) /* <- can be expensive */) {
- return new IntegerBigDecimal(n);
- } else {
- // Either it was a non-integer, or it didn't mater what it was, as we don't have both integer and
- // non-integer target types.
- return n;
- }
- } else if (numClass == Integer.class) {
- int pn = num.intValue();
- // Note that we try to return the most specific type (i.e., the numerical type with the smallest range), but
- // only among the types that are possible targets. Like if the only target is int and the value is 1, we
- // will return Integer 1, not Byte 1, even though byte is automatically converted to int so it would
- // work too. Why we avoid unnecessarily specific types is that they generate more overloaded method lookup
- // cache entries, since the cache key is the array of the types of the argument values. So we want as few
- // permutations as possible.
- if ((typeFlags & TypeFlags.BYTE) != 0 && pn <= Byte.MAX_VALUE && pn >= Byte.MIN_VALUE) {
- return new IntegerOrByte((Integer) num, (byte) pn);
- } else if ((typeFlags & TypeFlags.SHORT) != 0 && pn <= Short.MAX_VALUE && pn >= Short.MIN_VALUE) {
- return new IntegerOrShort((Integer) num, (short) pn);
- } else {
- return num;
- }
- } else if (numClass == Long.class) {
- final long pn = num.longValue();
- if ((typeFlags & TypeFlags.BYTE) != 0 && pn <= Byte.MAX_VALUE && pn >= Byte.MIN_VALUE) {
- return new LongOrByte((Long) num, (byte) pn);
- } else if ((typeFlags & TypeFlags.SHORT) != 0 && pn <= Short.MAX_VALUE && pn >= Short.MIN_VALUE) {
- return new LongOrShort((Long) num, (short) pn);
- } else if ((typeFlags & TypeFlags.INTEGER) != 0 && pn <= Integer.MAX_VALUE && pn >= Integer.MIN_VALUE) {
- return new LongOrInteger((Long) num, (int) pn);
- } else {
- return num;
- }
- } else if (numClass == Double.class) {
- final double doubleN = num.doubleValue();
-
- // Can we store it in an integer type?
- checkIfWholeNumber: do {
- if ((typeFlags & TypeFlags.MASK_KNOWN_INTEGERS) == 0) break checkIfWholeNumber;
-
- // There's no hope to be 1-precise outside this region. (Although problems can occur even inside it...)
- if (doubleN > MAX_DOUBLE_OR_LONG || doubleN < MIN_DOUBLE_OR_LONG) break checkIfWholeNumber;
-
- long longN = num.longValue();
- double diff = doubleN - longN;
- boolean exact; // We will try to ignore precision glitches (like 0.3 - 0.2 - 0.1 = -2.7E-17)
- if (diff == 0) {
- exact = true;
- } else if (diff > 0) {
- if (diff < LOWEST_ABOVE_ZERO) {
- exact = false;
- } else if (diff > HIGHEST_BELOW_ONE) {
- exact = false;
- longN++;
- } else {
- break checkIfWholeNumber;
- }
- } else { // => diff < 0
- if (diff > -LOWEST_ABOVE_ZERO) {
- exact = false;
- } else if (diff < -HIGHEST_BELOW_ONE) {
- exact = false;
- longN--;
- } else {
- break checkIfWholeNumber;
- }
- }
-
- // If we reach this, it can be treated as a whole number.
-
- if ((typeFlags & TypeFlags.BYTE) != 0
- && longN <= Byte.MAX_VALUE && longN >= Byte.MIN_VALUE) {
- return new DoubleOrByte((Double) num, (byte) longN);
- } else if ((typeFlags & TypeFlags.SHORT) != 0
- && longN <= Short.MAX_VALUE && longN >= Short.MIN_VALUE) {
- return new DoubleOrShort((Double) num, (short) longN);
- } else if ((typeFlags & TypeFlags.INTEGER) != 0
- && longN <= Integer.MAX_VALUE && longN >= Integer.MIN_VALUE) {
- final int intN = (int) longN;
- return (typeFlags & TypeFlags.FLOAT) != 0 && intN >= MIN_FLOAT_OR_INT && intN <= MAX_FLOAT_OR_INT
- ? new DoubleOrIntegerOrFloat((Double) num, intN)
- : new DoubleOrInteger((Double) num, intN);
- } else if ((typeFlags & TypeFlags.LONG) != 0) {
- if (exact) {
- return new DoubleOrLong((Double) num, longN);
- } else {
- // We don't deal with non-exact numbers outside the range of int, as we already reach
- // ULP 2.384185791015625E-7 there.
- if (longN >= Integer.MIN_VALUE && longN <= Integer.MAX_VALUE) {
- return new DoubleOrLong((Double) num, longN);
- } else {
- break checkIfWholeNumber;
- }
- }
- }
- // This point is reached if the double value was out of the range of target integer type(s).
- // Falls through!
- } while (false);
- // If we reach this that means that it can't be treated as a whole number.
-
- if ((typeFlags & TypeFlags.FLOAT) != 0 && doubleN >= -Float.MAX_VALUE && doubleN <= Float.MAX_VALUE) {
- return new DoubleOrFloat((Double) num);
- } else {
- // Simply Double:
- return num;
- }
- } else if (numClass == Float.class) {
- final float floatN = num.floatValue();
-
- // Can we store it in an integer type?
- checkIfWholeNumber: do {
- if ((typeFlags & TypeFlags.MASK_KNOWN_INTEGERS) == 0) break checkIfWholeNumber;
-
- // There's no hope to be 1-precise outside this region. (Although problems can occur even inside it...)
- if (floatN > MAX_FLOAT_OR_INT || floatN < MIN_FLOAT_OR_INT) break checkIfWholeNumber;
-
- int intN = num.intValue();
- double diff = floatN - intN;
- boolean exact; // We will try to ignore precision glitches (like 0.3 - 0.2 - 0.1 = -2.7E-17)
- if (diff == 0) {
- exact = true;
- // We already reach ULP 7.6293945E-6 with bytes, so we don't continue with shorts.
- } else if (intN >= Byte.MIN_VALUE && intN <= Byte.MAX_VALUE) {
- if (diff > 0) {
- if (diff < 0.00001) {
- exact = false;
- } else if (diff > 0.99999) {
- exact = false;
- intN++;
- } else {
- break checkIfWholeNumber;
- }
- } else { // => diff < 0
- if (diff > -0.00001) {
- exact = false;
- } else if (diff < -0.99999) {
- exact = false;
- intN--;
- } else {
- break checkIfWholeNumber;
- }
- }
- } else {
- break checkIfWholeNumber;
- }
-
- // If we reach this, it can be treated as a whole number.
-
- if ((typeFlags & TypeFlags.BYTE) != 0 && intN <= Byte.MAX_VALUE && intN >= Byte.MIN_VALUE) {
- return new FloatOrByte((Float) num, (byte) intN);
- } else if ((typeFlags & TypeFlags.SHORT) != 0 && intN <= Short.MAX_VALUE && intN >= Short.MIN_VALUE) {
- return new FloatOrShort((Float) num, (short) intN);
- } else if ((typeFlags & TypeFlags.INTEGER) != 0) {
- return new FloatOrInteger((Float) num, intN);
- } else if ((typeFlags & TypeFlags.LONG) != 0) {
- // We can't even go outside the range of integers, so we don't need Long variation:
- return exact
- ? new FloatOrInteger((Float) num, intN)
- : new FloatOrByte((Float) num, (byte) intN); // as !exact implies (-128..127)
- }
- // This point is reached if the float value was out of the range of target integer type(s).
- // Falls through!
- } while (false);
- // If we reach this that means that it can't be treated as a whole number. So it's simply a Float:
- return num;
- } else if (numClass == Byte.class) {
- return num;
- } else if (numClass == Short.class) {
- short pn = num.shortValue();
- if ((typeFlags & TypeFlags.BYTE) != 0 && pn <= Byte.MAX_VALUE && pn >= Byte.MIN_VALUE) {
- return new ShortOrByte((Short) num, (byte) pn);
- } else {
- return num;
- }
- } else if (numClass == BigInteger.class) {
- if ((typeFlags
- & ((TypeFlags.MASK_KNOWN_INTEGERS | TypeFlags.MASK_KNOWN_NONINTEGERS)
- ^ (TypeFlags.BIG_INTEGER | TypeFlags.BIG_DECIMAL))) != 0) {
- BigInteger biNum = (BigInteger) num;
- final int bitLength = biNum.bitLength(); // Doesn't include sign bit, so it's one less than expected
- if ((typeFlags & TypeFlags.BYTE) != 0 && bitLength <= 7) {
- return new BigIntegerOrByte(biNum);
- } else if ((typeFlags & TypeFlags.SHORT) != 0 && bitLength <= 15) {
- return new BigIntegerOrShort(biNum);
- } else if ((typeFlags & TypeFlags.INTEGER) != 0 && bitLength <= 31) {
- return new BigIntegerOrInteger(biNum);
- } else if ((typeFlags & TypeFlags.LONG) != 0 && bitLength <= 63) {
- return new BigIntegerOrLong(biNum);
- } else if ((typeFlags & TypeFlags.FLOAT) != 0
- && (bitLength <= MAX_FLOAT_OR_INT_LOG_2
- || bitLength == MAX_FLOAT_OR_INT_LOG_2 + 1
- && biNum.getLowestSetBit() >= MAX_FLOAT_OR_INT_LOG_2)) {
- return new BigIntegerOrFloat(biNum);
- } else if ((typeFlags & TypeFlags.DOUBLE) != 0
- && (bitLength <= MAX_DOUBLE_OR_LONG_LOG_2
- || bitLength == MAX_DOUBLE_OR_LONG_LOG_2 + 1
- && biNum.getLowestSetBit() >= MAX_DOUBLE_OR_LONG_LOG_2)) {
- return new BigIntegerOrDouble(biNum);
- } else {
- return num;
- }
- } else {
- // No relevant coercion target types; return the BigInteger as is:
- return num;
- }
- } else {
- // Unknown number type:
- return num;
- }
- }
-
- interface ByteSource { Byte byteValue(); }
- interface ShortSource { Short shortValue(); }
- interface IntegerSource { Integer integerValue(); }
- interface LongSource { Long longValue(); }
- interface FloatSource { Float floatValue(); }
- interface DoubleSource { Double doubleValue(); }
- interface BigIntegerSource { BigInteger bigIntegerValue(); }
- interface BigDecimalSource { BigDecimal bigDecimalValue(); }
-
- /**
- * Superclass of "Or"-ed numerical types. With an example, a {@code int} 1 has the fallback type {@code byte}, as
- * that's the smallest type that can store the value, so it can be represented as an {@link IntegerOrByte}.
- * This is useful as overloaded method selection only examines the type of the arguments, not the value of them,
- * but with "Or"-ed types we can encode this value-related information into the argument type, hence influencing the
- * method selection.
- */
- abstract static class NumberWithFallbackType extends Number implements Comparable {
-
- protected abstract Number getSourceNumber();
-
- @Override
- public int intValue() {
- return getSourceNumber().intValue();
- }
-
- @Override
- public long longValue() {
- return getSourceNumber().longValue();
- }
-
- @Override
- public float floatValue() {
- return getSourceNumber().floatValue();
- }
-
- @Override
- public double doubleValue() {
- return getSourceNumber().doubleValue();
- }
-
- @Override
- public byte byteValue() {
- return getSourceNumber().byteValue();
- }
-
- @Override
- public short shortValue() {
- return getSourceNumber().shortValue();
- }
-
- @Override
- public int hashCode() {
- return getSourceNumber().hashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj != null && getClass() == obj.getClass()) {
- return getSourceNumber().equals(((NumberWithFallbackType) obj).getSourceNumber());
- } else {
- return false;
- }
- }
-
- @Override
- public String toString() {
- return getSourceNumber().toString();
- }
-
- // We have to implement this, so that if a potential matching method expects a Comparable, which is implemented
- // by all the supported numerical types, the "Or" type will be a match.
- @Override
- public int compareTo(Object o) {
- Number n = getSourceNumber();
- if (n instanceof Comparable) {
- return ((Comparable) n).compareTo(o);
- } else {
- throw new ClassCastException(n.getClass().getName() + " is not Comparable.");
- }
- }
-
- }
-
- /**
- * Holds a {@link BigDecimal} that stores a whole number. When selecting a overloaded method, FreeMarker tries to
- * associate {@link BigDecimal} values to parameters of types that can hold non-whole numbers, unless the
- * {@link BigDecimal} is wrapped into this class, in which case it does the opposite. This mechanism is, however,
- * too rough to prevent roll overs or magnitude losses. Those are not yet handled for backward compatibility (they
- * were suppressed earlier too).
- */
- static final class IntegerBigDecimal extends NumberWithFallbackType {
-
- private final BigDecimal n;
-
- IntegerBigDecimal(BigDecimal n) {
- this.n = n;
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- public BigInteger bigIntegerValue() {
- return n.toBigInteger();
- }
-
- }
-
- static abstract class LongOrSmallerInteger extends NumberWithFallbackType {
-
- private final Long n;
-
- protected LongOrSmallerInteger(Long n) {
- this.n = n;
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- @Override
- public long longValue() {
- return n.longValue();
- }
-
- }
-
- static class LongOrByte extends LongOrSmallerInteger {
-
- private final byte w;
-
- LongOrByte(Long n, byte w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public byte byteValue() {
- return w;
- }
-
- }
-
- static class LongOrShort extends LongOrSmallerInteger {
-
- private final short w;
-
- LongOrShort(Long n, short w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public short shortValue() {
- return w;
- }
-
- }
-
- static class LongOrInteger extends LongOrSmallerInteger {
-
- private final int w;
-
- LongOrInteger(Long n, int w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- }
-
- static abstract class IntegerOrSmallerInteger extends NumberWithFallbackType {
-
- private final Integer n;
-
- protected IntegerOrSmallerInteger(Integer n) {
- this.n = n;
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- @Override
- public int intValue() {
- return n.intValue();
- }
-
- }
-
- static class IntegerOrByte extends IntegerOrSmallerInteger {
-
- private final byte w;
-
- IntegerOrByte(Integer n, byte w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public byte byteValue() {
- return w;
- }
-
- }
-
- static class IntegerOrShort extends IntegerOrSmallerInteger {
-
- private final short w;
-
- IntegerOrShort(Integer n, short w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public short shortValue() {
- return w;
- }
-
- }
-
- static class ShortOrByte extends NumberWithFallbackType {
-
- private final Short n;
- private final byte w;
-
- protected ShortOrByte(Short n, byte w) {
- this.n = n;
- this.w = w;
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- @Override
- public short shortValue() {
- return n.shortValue();
- }
-
- @Override
- public byte byteValue() {
- return w;
- }
-
- }
-
- static abstract class DoubleOrWholeNumber extends NumberWithFallbackType {
-
- private final Double n;
-
- protected DoubleOrWholeNumber(Double n) {
- this.n = n;
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- @Override
- public double doubleValue() {
- return n.doubleValue();
- }
-
- }
-
- static final class DoubleOrByte extends DoubleOrWholeNumber {
-
- private final byte w;
-
- DoubleOrByte(Double n, byte w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public byte byteValue() {
- return w;
- }
-
- @Override
- public short shortValue() {
- return w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- static final class DoubleOrShort extends DoubleOrWholeNumber {
-
- private final short w;
-
- DoubleOrShort(Double n, short w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public short shortValue() {
- return w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- static final class DoubleOrIntegerOrFloat extends DoubleOrWholeNumber {
-
- private final int w;
-
- DoubleOrIntegerOrFloat(Double n, int w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- static final class DoubleOrInteger extends DoubleOrWholeNumber {
-
- private final int w;
-
- DoubleOrInteger(Double n, int w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- static final class DoubleOrLong extends DoubleOrWholeNumber {
-
- private final long w;
-
- DoubleOrLong(Double n, long w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- static final class DoubleOrFloat extends NumberWithFallbackType {
-
- private final Double n;
-
- DoubleOrFloat(Double n) {
- this.n = n;
- }
-
- @Override
- public float floatValue() {
- return n.floatValue();
- }
-
- @Override
- public double doubleValue() {
- return n.doubleValue();
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- }
-
- static abstract class FloatOrWholeNumber extends NumberWithFallbackType {
-
- private final Float n;
-
- FloatOrWholeNumber(Float n) {
- this.n = n;
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- @Override
- public float floatValue() {
- return n.floatValue();
- }
-
- }
-
- static final class FloatOrByte extends FloatOrWholeNumber {
-
- private final byte w;
-
- FloatOrByte(Float n, byte w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public byte byteValue() {
- return w;
- }
-
- @Override
- public short shortValue() {
- return w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- static final class FloatOrShort extends FloatOrWholeNumber {
-
- private final short w;
-
- FloatOrShort(Float n, short w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public short shortValue() {
- return w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- static final class FloatOrInteger extends FloatOrWholeNumber {
-
- private final int w;
-
- FloatOrInteger(Float n, int w) {
- super(n);
- this.w = w;
- }
-
- @Override
- public int intValue() {
- return w;
- }
-
- @Override
- public long longValue() {
- return w;
- }
-
- }
-
- abstract static class BigIntegerOrPrimitive extends NumberWithFallbackType {
-
- protected final BigInteger n;
-
- BigIntegerOrPrimitive(BigInteger n) {
- this.n = n;
- }
-
- @Override
- protected Number getSourceNumber() {
- return n;
- }
-
- }
-
- final static class BigIntegerOrByte extends BigIntegerOrPrimitive {
-
- BigIntegerOrByte(BigInteger n) {
- super(n);
- }
-
- }
-
- final static class BigIntegerOrShort extends BigIntegerOrPrimitive {
-
- BigIntegerOrShort(BigInteger n) {
- super(n);
- }
-
- }
-
- final static class BigIntegerOrInteger extends BigIntegerOrPrimitive {
-
- BigIntegerOrInteger(BigInteger n) {
- super(n);
- }
-
- }
-
- final static class BigIntegerOrLong extends BigIntegerOrPrimitive {
-
- BigIntegerOrLong(BigInteger n) {
- super(n);
- }
-
- }
-
- abstract static class BigIntegerOrFPPrimitive extends BigIntegerOrPrimitive {
-
- BigIntegerOrFPPrimitive(BigInteger n) {
- super(n);
- }
-
- /** Faster version of {@link BigDecimal#floatValue()}, utilizes that the number known to fit into a long. */
- @Override
- public float floatValue() {
- return n.longValue();
- }
-
- /** Faster version of {@link BigDecimal#doubleValue()}, utilizes that the number known to fit into a long. */
- @Override
- public double doubleValue() {
- return n.longValue();
- }
-
- }
-
- final static class BigIntegerOrFloat extends BigIntegerOrFPPrimitive {
-
- BigIntegerOrFloat(BigInteger n) {
- super(n);
- }
-
- }
-
- final static class BigIntegerOrDouble extends BigIntegerOrFPPrimitive {
-
- BigIntegerOrDouble(BigInteger n) {
- super(n);
- }
-
- }
-
- /**
- * Returns a non-negative number that indicates how much we want to avoid a given numerical type conversion. Since
- * we only consider the types here, not the actual value, we always consider the worst case scenario. Like it will
- * say that converting int to short is not allowed, although int 1 can be converted to byte without loss. To account
- * for such situations, "Or"-ed types, like {@link IntegerOrByte} has to be used.
- *
- * @param fromC the non-primitive type of the argument (with other words, the actual type).
- * Must be {@link Number} or its subclass. This is possibly an {@link NumberWithFallbackType} subclass.
- * @param toC the <em>non-primitive</em> type of the target parameter (with other words, the format type).
- * Must be a {@link Number} subclass, not {@link Number} itself.
- * Must <em>not</em> be {@link NumberWithFallbackType} or its subclass.
- *
- * @return
- * <p>The possible values are:
- * <ul>
- * <li>0: No conversion is needed
- * <li>[0, 30000): Lossless conversion
- * <li>[30000, 40000): Smaller precision loss in mantissa is possible.
- * <li>[40000, 50000): Bigger precision loss in mantissa is possible.
- * <li>{@link Integer#MAX_VALUE}: Conversion not allowed due to the possibility of magnitude loss or
- * overflow</li>
- * </ul>
- *
- * <p>At some places, we only care if the conversion is possible, i.e., whether the return value is
- * {@link Integer#MAX_VALUE} or not. But when multiple overloaded methods have an argument type to which we
- * could convert to, this number will influence which of those will be chosen.
- */
- static int getArgumentConversionPrice(Class fromC, Class toC) {
- // DO NOT EDIT, generated code!
- // See: src\main\misc\overloadedNumberRules\README.txt
- if (toC == fromC) {
- return 0;
- } else if (toC == Integer.class) {
- if (fromC == IntegerBigDecimal.class) return 31003;
- else if (fromC == BigDecimal.class) return 41003;
- else if (fromC == Long.class) return Integer.MAX_VALUE;
- else if (fromC == Double.class) return Integer.MAX_VALUE;
- else if (fromC == Float.class) return Integer.MAX_VALUE;
- else if (fromC == Byte.class) return 10003;
- else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
- else if (fromC == LongOrInteger.class) return 21003;
- else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrIntegerOrFloat.class) return 22003;
- else if (fromC == DoubleOrInteger.class) return 22003;
- else if (fromC == DoubleOrLong.class) return Integer.MAX_VALUE;
- else if (fromC == IntegerOrByte.class) return 0;
- else if (fromC == DoubleOrByte.class) return 22003;
- else if (fromC == LongOrByte.class) return 21003;
- else if (fromC == Short.class) return 10003;
- else if (fromC == LongOrShort.class) return 21003;
- else if (fromC == ShortOrByte.class) return 10003;
- else if (fromC == FloatOrInteger.class) return 21003;
- else if (fromC == FloatOrByte.class) return 21003;
- else if (fromC == FloatOrShort.class) return 21003;
- else if (fromC == BigIntegerOrInteger.class) return 16003;
- else if (fromC == BigIntegerOrLong.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrByte.class) return 16003;
- else if (fromC == IntegerOrShort.class) return 0;
- else if (fromC == DoubleOrShort.class) return 22003;
- else if (fromC == BigIntegerOrShort.class) return 16003;
- else return Integer.MAX_VALUE;
- } else if (toC == Long.class) {
- if (fromC == Integer.class) return 10004;
- else if (fromC == IntegerBigDecimal.class) return 31004;
- else if (fromC == BigDecimal.class) return 41004;
- else if (fromC == Double.class) return Integer.MAX_VALUE;
- else if (fromC == Float.class) return Integer.MAX_VALUE;
- else if (fromC == Byte.class) return 10004;
- else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
- else if (fromC == LongOrInteger.class) return 0;
- else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrIntegerOrFloat.class) return 21004;
- else if (fromC == DoubleOrInteger.class) return 21004;
- else if (fromC == DoubleOrLong.class) return 21004;
- else if (fromC == IntegerOrByte.class) return 10004;
- else if (fromC == DoubleOrByte.class) return 21004;
- else if (fromC == LongOrByte.class) return 0;
- else if (fromC == Short.class) return 10004;
- else if (fromC == LongOrShort.class) return 0;
- else if (fromC == ShortOrByte.class) return 10004;
- else if (fromC == FloatOrInteger.class) return 21004;
- else if (fromC == FloatOrByte.class) return 21004;
- else if (fromC == FloatOrShort.class) return 21004;
- else if (fromC == BigIntegerOrInteger.class) return 15004;
- else if (fromC == BigIntegerOrLong.class) return 15004;
- else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrByte.class) return 15004;
- else if (fromC == IntegerOrShort.class) return 10004;
- else if (fromC == DoubleOrShort.class) return 21004;
- else if (fromC == BigIntegerOrShort.class) return 15004;
- else return Integer.MAX_VALUE;
- } else if (toC == Double.class) {
- if (fromC == Integer.class) return 20007;
- else if (fromC == IntegerBigDecimal.class) return 32007;
- else if (fromC == BigDecimal.class) return 32007;
- else if (fromC == Long.class) return 30007;
- else if (fromC == Float.class) return 10007;
- else if (fromC == Byte.class) return 20007;
- else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
- else if (fromC == LongOrInteger.class) return 21007;
- else if (fromC == DoubleOrFloat.class) return 0;
- else if (fromC == DoubleOrIntegerOrFloat.class) return 0;
- else if (fromC == DoubleOrInteger.class) return 0;
- else if (fromC == DoubleOrLong.class) return 0;
- else if (fromC == IntegerOrByte.class) return 20007;
- else if (fromC == DoubleOrByte.class) return 0;
- else if (fromC == LongOrByte.class) return 21007;
- else if (fromC == Short.class) return 20007;
- else if (fromC == LongOrShort.class) return 21007;
- else if (fromC == ShortOrByte.class) return 20007;
- else if (fromC == FloatOrInteger.class) return 10007;
- else if (fromC == FloatOrByte.class) return 10007;
- else if (fromC == FloatOrShort.class) return 10007;
- else if (fromC == BigIntegerOrInteger.class) return 20007;
- else if (fromC == BigIntegerOrLong.class) return 30007;
- else if (fromC == BigIntegerOrDouble.class) return 20007;
- else if (fromC == BigIntegerOrFloat.class) return 20007;
- else if (fromC == BigIntegerOrByte.class) return 20007;
- else if (fromC == IntegerOrShort.class) return 20007;
- else if (fromC == DoubleOrShort.class) return 0;
- else if (fromC == BigIntegerOrShort.class) return 20007;
- else return Integer.MAX_VALUE;
- } else if (toC == Float.class) {
- if (fromC == Integer.class) return 30006;
- else if (fromC == IntegerBigDecimal.class) return 33006;
- else if (fromC == BigDecimal.class) return 33006;
- else if (fromC == Long.class) return 40006;
- else if (fromC == Double.class) return Integer.MAX_VALUE;
- else if (fromC == Byte.class) return 20006;
- else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
- else if (fromC == LongOrInteger.class) return 30006;
- else if (fromC == DoubleOrFloat.class) return 30006;
- else if (fromC == DoubleOrIntegerOrFloat.class) return 23006;
- else if (fromC == DoubleOrInteger.class) return 30006;
- else if (fromC == DoubleOrLong.class) return 40006;
- else if (fromC == IntegerOrByte.class) return 24006;
- else if (fromC == DoubleOrByte.class) return 23006;
- else if (fromC == LongOrByte.class) return 24006;
- else if (fromC == Short.class) return 20006;
- else if (fromC == LongOrShort.class) return 24006;
- else if (fromC == ShortOrByte.class) return 20006;
- else if (fromC == FloatOrInteger.class) return 0;
- else if (fromC == FloatOrByte.class) return 0;
- else if (fromC == FloatOrShort.class) return 0;
- else if (fromC == BigIntegerOrInteger.class) return 30006;
- else if (fromC == BigIntegerOrLong.class) return 40006;
- else if (fromC == BigIntegerOrDouble.class) return 40006;
- else if (fromC == BigIntegerOrFloat.class) return 24006;
- else if (fromC == BigIntegerOrByte.class) return 24006;
- else if (fromC == IntegerOrShort.class) return 24006;
- else if (fromC == DoubleOrShort.class) return 23006;
- else if (fromC == BigIntegerOrShort.class) return 24006;
- else return Integer.MAX_VALUE;
- } else if (toC == Byte.class) {
- if (fromC == Integer.class) return Integer.MAX_VALUE;
- else if (fromC == IntegerBigDecimal.class) return 35001;
- else if (fromC == BigDecimal.class) return 45001;
- else if (fromC == Long.class) return Integer.MAX_VALUE;
- else if (fromC == Double.class) return Integer.MAX_VALUE;
- else if (fromC == Float.class) return Integer.MAX_VALUE;
- else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
- else if (fromC == LongOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrIntegerOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrLong.class) return Integer.MAX_VALUE;
- else if (fromC == IntegerOrByte.class) return 22001;
- else if (fromC == DoubleOrByte.class) return 25001;
- else if (fromC == LongOrByte.class) return 23001;
- else if (fromC == Short.class) return Integer.MAX_VALUE;
- else if (fromC == LongOrShort.class) return Integer.MAX_VALUE;
- else if (fromC == ShortOrByte.class) return 21001;
- else if (fromC == FloatOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == FloatOrByte.class) return 23001;
- else if (fromC == FloatOrShort.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrLong.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrByte.class) return 18001;
- else if (fromC == IntegerOrShort.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrShort.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrShort.class) return Integer.MAX_VALUE;
- else return Integer.MAX_VALUE;
- } else if (toC == Short.class) {
- if (fromC == Integer.class) return Integer.MAX_VALUE;
- else if (fromC == IntegerBigDecimal.class) return 34002;
- else if (fromC == BigDecimal.class) return 44002;
- else if (fromC == Long.class) return Integer.MAX_VALUE;
- else if (fromC == Double.class) return Integer.MAX_VALUE;
- else if (fromC == Float.class) return Integer.MAX_VALUE;
- else if (fromC == Byte.class) return 10002;
- else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
- else if (fromC == LongOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrIntegerOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrLong.class) return Integer.MAX_VALUE;
- else if (fromC == IntegerOrByte.class) return 21002;
- else if (fromC == DoubleOrByte.class) return 24002;
- else if (fromC == LongOrByte.class) return 22002;
- else if (fromC == LongOrShort.class) return 22002;
- else if (fromC == ShortOrByte.class) return 0;
- else if (fromC == FloatOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == FloatOrByte.class) return 22002;
- else if (fromC == FloatOrShort.class) return 22002;
- else if (fromC == BigIntegerOrInteger.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrLong.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == BigIntegerOrByte.class) return 17002;
- else if (fromC == IntegerOrShort.class) return 21002;
- else if (fromC == DoubleOrShort.class) return 24002;
- else if (fromC == BigIntegerOrShort.class) return 17002;
- else return Integer.MAX_VALUE;
- } else if (toC == BigDecimal.class) {
- if (fromC == Integer.class) return 20008;
- else if (fromC == IntegerBigDecimal.class) return 0;
- else if (fromC == Long.class) return 20008;
- else if (fromC == Double.class) return 20008;
- else if (fromC == Float.class) return 20008;
- else if (fromC == Byte.class) return 20008;
- else if (fromC == BigInteger.class) return 10008;
- else if (fromC == LongOrInteger.class) return 20008;
- else if (fromC == DoubleOrFloat.class) return 20008;
- else if (fromC == DoubleOrIntegerOrFloat.class) return 20008;
- else if (fromC == DoubleOrInteger.class) return 20008;
- else if (fromC == DoubleOrLong.class) return 20008;
- else if (fromC == IntegerOrByte.class) return 20008;
- else if (fromC == DoubleOrByte.class) return 20008;
- else if (fromC == LongOrByte.class) return 20008;
- else if (fromC == Short.class) return 20008;
- else if (fromC == LongOrShort.class) return 20008;
- else if (fromC == ShortOrByte.class) return 20008;
- else if (fromC == FloatOrInteger.class) return 20008;
- else if (fromC == FloatOrByte.class) return 20008;
- else if (fromC == FloatOrShort.class) return 20008;
- else if (fromC == BigIntegerOrInteger.class) return 10008;
- else if (fromC == BigIntegerOrLong.class) return 10008;
- else if (fromC == BigIntegerOrDouble.class) return 10008;
- else if (fromC == BigIntegerOrFloat.class) return 10008;
- else if (fromC == BigIntegerOrByte.class) return 10008;
- else if (fromC == IntegerOrShort.class) return 20008;
- else if (fromC == DoubleOrShort.class) return 20008;
- else if (fromC == BigIntegerOrShort.class) return 10008;
- else return Integer.MAX_VALUE;
- } else if (toC == BigInteger.class) {
- if (fromC == Integer.class) return 10005;
- else if (fromC == IntegerBigDecimal.class) return 10005;
- else if (fromC == BigDecimal.class) return 40005;
- else if (fromC == Long.class) return 10005;
- else if (fromC == Double.class) return Integer.MAX_VALUE;
- else if (fromC == Float.class) return Integer.MAX_VALUE;
- else if (fromC == Byte.class) return 10005;
- else if (fromC == LongOrInteger.class) return 10005;
- else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
- else if (fromC == DoubleOrIntegerOrFloat.class) return 21005;
- else if (fromC == DoubleOrInteger.class) return 21005;
- else if (fromC == DoubleOrLong.class) return 21005;
- else if (fromC == IntegerOrByte.class) return 10005;
- else if (fromC == DoubleOrByte.class) return 21005;
- else if (fromC == LongOrByte.class) return 10005;
- else if (fromC == Short.class) return 10005;
- else if (fromC == LongOrShort.class) return 10005;
- else if (fromC == ShortOrByte.class) return 10005;
- else if (fromC == FloatOrInteger.class) return 25005;
- else if (fromC == FloatOrByte.class) return 25005;
- else if (fromC == FloatOrShort.class) return 25005;
- else if (fromC == BigIntegerOrInteger.class) return 0;
- else if (fromC == BigIntegerOrLong.class) return 0;
- else if (fromC == BigIntegerOrDouble.class) return 0;
- else if (fromC == BigIntegerOrFloat.class) return 0;
- else if (fromC == BigIntegerOrByte.class) return 0;
- else if (fromC == IntegerOrShort.class) return 10005;
- else if (fromC == DoubleOrShort.class) return 21005;
- else if (fromC == BigIntegerOrShort.class) return 0;
- else return Integer.MAX_VALUE;
- } else {
- // Unknown toC; we don't know how to convert to it:
- return Integer.MAX_VALUE;
- }
- }
-
- static int compareNumberTypeSpecificity(Class c1, Class c2) {
- // DO NOT EDIT, generated code!
- // See: src\main\misc\overloadedNumberRules\README.txt
- c1 = _ClassUtil.primitiveClassToBoxingClass(c1);
- c2 = _ClassUtil.primitiveClassToBoxingClass(c2);
-
- if (c1 == c2) return 0;
-
- if (c1 == Integer.class) {
- if (c2 == Long.class) return 4 - 3;
- if (c2 == Double.class) return 7 - 3;
- if (c2 == Float.class) return 6 - 3;
- if (c2 == Byte.class) return 1 - 3;
- if (c2 == Short.class) return 2 - 3;
- if (c2 == BigDecimal.class) return 8 - 3;
- if (c2 == BigInteger.class) return 5 - 3;
- return 0;
- }
- if (c1 == Long.class) {
- if (c2 == Integer.class) return 3 - 4;
- if (c2 == Double.class) return 7 - 4;
- if (c2 == Float.class) return 6 - 4;
- if (c2 == Byte.class) return 1 - 4;
- if (c2 == Short.class) return 2 - 4;
- if (c2 == BigDecimal.class) return 8 - 4;
- if (c2 == BigInteger.class) return 5 - 4;
- return 0;
- }
- if (c1 == Double.class) {
- if (c2 == Integer.class) return 3 - 7;
- if (c2 == Long.class) return 4 - 7;
- if (c2 == Float.class) return 6 - 7;
- if (c2 == Byte.class) return 1 - 7;
- if (c2 == Short.class) return 2 - 7;
- if (c2 == BigDecimal.class) return 8 - 7;
- if (c2 == BigInteger.class) return 5 - 7;
- return 0;
- }
- if (c1 == Float.class) {
- if (c2 == Integer.class) return 3 - 6;
- if (c2 == Long.class) return 4 - 6;
- if (c2 == Double.class) return 7 - 6;
- if (c2 == Byte.class) return 1 - 6;
- if (c2 == Short.class) return 2 - 6;
- if (c2 == BigDecimal.class) return 8 - 6;
- if (c2 == BigInteger.class) return 5 - 6;
- return 0;
- }
- if (c1 == Byte.class) {
- if (c2 == Integer.class) return 3 - 1;
- if (c2 == Long.class) return 4 - 1;
- if (c2 == Double.class) return 7 - 1;
- if (c2 == Float.class) return 6 - 1;
- if (c2 == Short.class) return 2 - 1;
- if (c2 == BigDecimal.class) return 8 - 1;
- if (c2 == BigInteger.class) return 5 - 1;
- return 0;
- }
- if (c1 == Short.class) {
- if (c2 == Integer.class) return 3 - 2;
- if (c2 == Long.class) return 4 - 2;
- if (c2 == Double.class) return 7 - 2;
- if (c2 == Float.class) return 6 - 2;
- if (c2 == Byte.class) return 1 - 2;
- if (c2 == BigDecimal.class) return 8 - 2;
- if (c2 == BigInteger.class) return 5 - 2;
- return 0;
- }
- if (c1 == BigDecimal.class) {
- if (c2 == Integer.class) return 3 - 8;
- if (c2 == Long.class) return 4 - 8;
- if (c2 == Double.class) return 7 - 8;
- if (c2 == Float.class) return 6 - 8;
- if (c2 == Byte.class) return 1 - 8;
- if (c2 == Short.class) return 2 - 8;
- if (c2 == BigInteger.class) return 5 - 8;
- return 0;
- }
- if (c1 == BigInteger.class) {
- if (c2 == Integer.class) return 3 - 5;
- if (c2 == Long.class) return 4 - 5;
- if (c2 == Double.class) return 7 - 5;
- if (c2 == Float.class) return 6 - 5;
- if (c2 == Byte.class) return 1 - 5;
- if (c2 == Short.class) return 2 - 5;
- if (c2 == BigDecimal.class) return 8 - 5;
- return 0;
- }
- return 0;
- }
-
-}
[05/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtils.java
new file mode 100644
index 0000000..249a624
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtils.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.freemarker.core.util;
+
+import java.util.Locale;
+
+/**
+ * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
+ */
+public class _LocaleUtils {
+
+ /**
+ * Returns a locale that's one less specific, or {@code null} if there's no less specific locale.
+ */
+ public static Locale getLessSpecificLocale(Locale locale) {
+ String country = locale.getCountry();
+ if (locale.getVariant().length() != 0) {
+ String language = locale.getLanguage();
+ return country != null ? new Locale(language, country) : new Locale(language);
+ }
+ if (country.length() != 0) {
+ return new Locale(locale.getLanguage());
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtil.java
deleted file mode 100644
index c300b5c..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtil.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-
-/** Don't use this; used internally by FreeMarker, might changes without notice. */
-public class _NumberUtil {
-
- private static final BigDecimal BIG_DECIMAL_INT_MIN = BigDecimal.valueOf(Integer.MIN_VALUE);
- private static final BigDecimal BIG_DECIMAL_INT_MAX = BigDecimal.valueOf(Integer.MAX_VALUE);
- private static final BigInteger BIG_INTEGER_INT_MIN = BIG_DECIMAL_INT_MIN.toBigInteger();
- private static final BigInteger BIG_INTEGER_INT_MAX = BIG_DECIMAL_INT_MAX.toBigInteger();
- private static final BigInteger BIG_INTEGER_LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);
- private static final BigInteger BIG_INTEGER_LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);
-
- private _NumberUtil() { }
-
- public static boolean isInfinite(Number num) {
- if (num instanceof Double) {
- return ((Double) num).isInfinite();
- } else if (num instanceof Float) {
- return ((Float) num).isInfinite();
- } else if (isNonFPNumberOfSupportedClass(num)) {
- return false;
- } else {
- throw new UnsupportedNumberClassException(num.getClass());
- }
- }
-
- public static boolean isNaN(Number num) {
- if (num instanceof Double) {
- return ((Double) num).isNaN();
- } else if (num instanceof Float) {
- return ((Float) num).isNaN();
- } else if (isNonFPNumberOfSupportedClass(num)) {
- return false;
- } else {
- throw new UnsupportedNumberClassException(num.getClass());
- }
- }
-
- /**
- * @return -1 for negative, 0 for zero, 1 for positive.
- * @throws ArithmeticException if the number is NaN
- */
- public static int getSignum(Number num) throws ArithmeticException {
- if (num instanceof Integer) {
- int n = num.intValue();
- return n > 0 ? 1 : (n == 0 ? 0 : -1);
- } else if (num instanceof BigDecimal) {
- BigDecimal n = (BigDecimal) num;
- return n.signum();
- } else if (num instanceof Double) {
- double n = num.doubleValue();
- if (n > 0) return 1;
- else if (n == 0) return 0;
- else if (n < 0) return -1;
- else throw new ArithmeticException("The signum of " + n + " is not defined."); // NaN
- } else if (num instanceof Float) {
- float n = num.floatValue();
- if (n > 0) return 1;
- else if (n == 0) return 0;
- else if (n < 0) return -1;
- else throw new ArithmeticException("The signum of " + n + " is not defined."); // NaN
- } else if (num instanceof Long) {
- long n = num.longValue();
- return n > 0 ? 1 : (n == 0 ? 0 : -1);
- } else if (num instanceof Short) {
- short n = num.shortValue();
- return n > 0 ? 1 : (n == 0 ? 0 : -1);
- } else if (num instanceof Byte) {
- byte n = num.byteValue();
- return n > 0 ? 1 : (n == 0 ? 0 : -1);
- } else if (num instanceof BigInteger) {
- BigInteger n = (BigInteger) num;
- return n.signum();
- } else {
- throw new UnsupportedNumberClassException(num.getClass());
- }
- }
-
- /**
- * Tells if a {@link BigDecimal} stores a whole number. For example, it returns {@code true} for {@code 1.0000},
- * but {@code false} for {@code 1.0001}.
- */
- static public boolean isIntegerBigDecimal(BigDecimal bd) {
- // [Java 1.5] Try to utilize BigDecimal.toXxxExact methods
- return bd.scale() <= 0 // A fast check that whole numbers usually (not always) match
- || bd.setScale(0, BigDecimal.ROUND_DOWN).compareTo(bd) == 0; // This is rather slow
- // Note that `bd.signum() == 0 || bd.stripTrailingZeros().scale() <= 0` was also tried for the last
- // condition, but stripTrailingZeros was slower than setScale + compareTo.
- }
-
- private static boolean isNonFPNumberOfSupportedClass(Number num) {
- return num instanceof Integer || num instanceof BigDecimal || num instanceof Long
- || num instanceof Short || num instanceof Byte || num instanceof BigInteger;
- }
-
- /**
- * Converts a {@link Number} to {@code int} whose mathematical value is exactly the same as of the original number.
- *
- * @throws ArithmeticException
- * if the conversion to {@code int} is not possible without losing precision or overflow/underflow.
- */
- public static int toIntExact(Number num) {
- if (num instanceof Integer || num instanceof Short || num instanceof Byte) {
- return num.intValue();
- } else if (num instanceof Long) {
- final long n = num.longValue();
- final int result = (int) n;
- if (n != result) {
- throw newLossyConverionException(num, Integer.class);
- }
- return result;
- } else if (num instanceof Double || num instanceof Float) {
- final double n = num.doubleValue();
- if (n % 1 != 0 || n < Integer.MIN_VALUE || n > Integer.MAX_VALUE) {
- throw newLossyConverionException(num, Integer.class);
- }
- return (int) n;
- } else if (num instanceof BigDecimal) {
- // [Java 1.5] Use BigDecimal.toIntegerExact()
- BigDecimal n = (BigDecimal) num;
- if (!isIntegerBigDecimal(n)
- || n.compareTo(BIG_DECIMAL_INT_MAX) > 0 || n.compareTo(BIG_DECIMAL_INT_MIN) < 0) {
- throw newLossyConverionException(num, Integer.class);
- }
- return n.intValue();
- } else if (num instanceof BigInteger) {
- BigInteger n = (BigInteger) num;
- if (n.compareTo(BIG_INTEGER_INT_MAX) > 0 || n.compareTo(BIG_INTEGER_INT_MIN) < 0) {
- throw newLossyConverionException(num, Integer.class);
- }
- return n.intValue();
- } else {
- throw new UnsupportedNumberClassException(num.getClass());
- }
- }
-
- private static ArithmeticException newLossyConverionException(Number fromValue, Class/*<Number>*/ toType) {
- return new ArithmeticException(
- "Can't convert " + fromValue + " to type " + _ClassUtil.getShortClassName(toType) + " without loss.");
- }
-
- /**
- * This is needed to reverse the extreme conversions in arithmetic
- * operations so that numbers can be meaningfully used with models that
- * don't know what to do with a BigDecimal. Of course, this will make
- * impossible for these models (i.e. Jython) to receive a BigDecimal even if
- * it was originally placed as such in the data model. However, since
- * arithmetic operations aggressively erase the information regarding the
- * original number type, we have no other choice to ensure expected operation
- * in majority of cases.
- */
- public static Number optimizeNumberRepresentation(Number number) {
- if (number instanceof BigDecimal) {
- BigDecimal bd = (BigDecimal) number;
- if (bd.scale() == 0) {
- // BigDecimal -> BigInteger
- number = bd.unscaledValue();
- } else {
- double d = bd.doubleValue();
- if (d != Double.POSITIVE_INFINITY && d != Double.NEGATIVE_INFINITY) {
- // BigDecimal -> Double
- return Double.valueOf(d);
- }
- }
- }
- if (number instanceof BigInteger) {
- BigInteger bi = (BigInteger) number;
- if (bi.compareTo(BIG_INTEGER_INT_MAX) <= 0 && bi.compareTo(BIG_INTEGER_INT_MIN) >= 0) {
- // BigInteger -> Integer
- return Integer.valueOf(bi.intValue());
- }
- if (bi.compareTo(BIG_INTEGER_LONG_MAX) <= 0 && bi.compareTo(BIG_INTEGER_LONG_MIN) >= 0) {
- // BigInteger -> Long
- return Long.valueOf(bi.longValue());
- }
- }
- return number;
- }
-
- public static BigDecimal toBigDecimal(Number num) {
- try {
- return num instanceof BigDecimal ? (BigDecimal) num : new BigDecimal(num.toString());
- } catch (NumberFormatException e) {
- // The exception message is useless, so we add a new one:
- throw new NumberFormatException("Can't parse this as BigDecimal number: " + _StringUtil.jQuote(num));
- }
- }
-
- public static Number toBigDecimalOrDouble(String s) {
- if (s.length() > 2) {
- char c = s.charAt(0);
- if (c == 'I' && (s.equals("INF") || s.equals("Infinity"))) {
- return Double.valueOf(Double.POSITIVE_INFINITY);
- } else if (c == 'N' && s.equals("NaN")) {
- return Double.valueOf(Double.NaN);
- } else if (c == '-' && s.charAt(1) == 'I' && (s.equals("-INF") || s.equals("-Infinity"))) {
- return Double.valueOf(Double.NEGATIVE_INFINITY);
- }
- }
- return new BigDecimal(s);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtils.java
new file mode 100644
index 0000000..5cff40b
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_NumberUtils.java
@@ -0,0 +1,224 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+/** Don't use this; used internally by FreeMarker, might changes without notice. */
+public class _NumberUtils {
+
+ private static final BigDecimal BIG_DECIMAL_INT_MIN = BigDecimal.valueOf(Integer.MIN_VALUE);
+ private static final BigDecimal BIG_DECIMAL_INT_MAX = BigDecimal.valueOf(Integer.MAX_VALUE);
+ private static final BigInteger BIG_INTEGER_INT_MIN = BIG_DECIMAL_INT_MIN.toBigInteger();
+ private static final BigInteger BIG_INTEGER_INT_MAX = BIG_DECIMAL_INT_MAX.toBigInteger();
+ private static final BigInteger BIG_INTEGER_LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);
+ private static final BigInteger BIG_INTEGER_LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);
+
+ private _NumberUtils() { }
+
+ public static boolean isInfinite(Number num) {
+ if (num instanceof Double) {
+ return ((Double) num).isInfinite();
+ } else if (num instanceof Float) {
+ return ((Float) num).isInfinite();
+ } else if (isNonFPNumberOfSupportedClass(num)) {
+ return false;
+ } else {
+ throw new UnsupportedNumberClassException(num.getClass());
+ }
+ }
+
+ public static boolean isNaN(Number num) {
+ if (num instanceof Double) {
+ return ((Double) num).isNaN();
+ } else if (num instanceof Float) {
+ return ((Float) num).isNaN();
+ } else if (isNonFPNumberOfSupportedClass(num)) {
+ return false;
+ } else {
+ throw new UnsupportedNumberClassException(num.getClass());
+ }
+ }
+
+ /**
+ * @return -1 for negative, 0 for zero, 1 for positive.
+ * @throws ArithmeticException if the number is NaN
+ */
+ public static int getSignum(Number num) throws ArithmeticException {
+ if (num instanceof Integer) {
+ int n = num.intValue();
+ return n > 0 ? 1 : (n == 0 ? 0 : -1);
+ } else if (num instanceof BigDecimal) {
+ BigDecimal n = (BigDecimal) num;
+ return n.signum();
+ } else if (num instanceof Double) {
+ double n = num.doubleValue();
+ if (n > 0) return 1;
+ else if (n == 0) return 0;
+ else if (n < 0) return -1;
+ else throw new ArithmeticException("The signum of " + n + " is not defined."); // NaN
+ } else if (num instanceof Float) {
+ float n = num.floatValue();
+ if (n > 0) return 1;
+ else if (n == 0) return 0;
+ else if (n < 0) return -1;
+ else throw new ArithmeticException("The signum of " + n + " is not defined."); // NaN
+ } else if (num instanceof Long) {
+ long n = num.longValue();
+ return n > 0 ? 1 : (n == 0 ? 0 : -1);
+ } else if (num instanceof Short) {
+ short n = num.shortValue();
+ return n > 0 ? 1 : (n == 0 ? 0 : -1);
+ } else if (num instanceof Byte) {
+ byte n = num.byteValue();
+ return n > 0 ? 1 : (n == 0 ? 0 : -1);
+ } else if (num instanceof BigInteger) {
+ BigInteger n = (BigInteger) num;
+ return n.signum();
+ } else {
+ throw new UnsupportedNumberClassException(num.getClass());
+ }
+ }
+
+ /**
+ * Tells if a {@link BigDecimal} stores a whole number. For example, it returns {@code true} for {@code 1.0000},
+ * but {@code false} for {@code 1.0001}.
+ */
+ static public boolean isIntegerBigDecimal(BigDecimal bd) {
+ // [Java 1.5] Try to utilize BigDecimal.toXxxExact methods
+ return bd.scale() <= 0 // A fast check that whole numbers usually (not always) match
+ || bd.setScale(0, BigDecimal.ROUND_DOWN).compareTo(bd) == 0; // This is rather slow
+ // Note that `bd.signum() == 0 || bd.stripTrailingZeros().scale() <= 0` was also tried for the last
+ // condition, but stripTrailingZeros was slower than setScale + compareTo.
+ }
+
+ private static boolean isNonFPNumberOfSupportedClass(Number num) {
+ return num instanceof Integer || num instanceof BigDecimal || num instanceof Long
+ || num instanceof Short || num instanceof Byte || num instanceof BigInteger;
+ }
+
+ /**
+ * Converts a {@link Number} to {@code int} whose mathematical value is exactly the same as of the original number.
+ *
+ * @throws ArithmeticException
+ * if the conversion to {@code int} is not possible without losing precision or overflow/underflow.
+ */
+ public static int toIntExact(Number num) {
+ if (num instanceof Integer || num instanceof Short || num instanceof Byte) {
+ return num.intValue();
+ } else if (num instanceof Long) {
+ final long n = num.longValue();
+ final int result = (int) n;
+ if (n != result) {
+ throw newLossyConverionException(num, Integer.class);
+ }
+ return result;
+ } else if (num instanceof Double || num instanceof Float) {
+ final double n = num.doubleValue();
+ if (n % 1 != 0 || n < Integer.MIN_VALUE || n > Integer.MAX_VALUE) {
+ throw newLossyConverionException(num, Integer.class);
+ }
+ return (int) n;
+ } else if (num instanceof BigDecimal) {
+ // [Java 1.5] Use BigDecimal.toIntegerExact()
+ BigDecimal n = (BigDecimal) num;
+ if (!isIntegerBigDecimal(n)
+ || n.compareTo(BIG_DECIMAL_INT_MAX) > 0 || n.compareTo(BIG_DECIMAL_INT_MIN) < 0) {
+ throw newLossyConverionException(num, Integer.class);
+ }
+ return n.intValue();
+ } else if (num instanceof BigInteger) {
+ BigInteger n = (BigInteger) num;
+ if (n.compareTo(BIG_INTEGER_INT_MAX) > 0 || n.compareTo(BIG_INTEGER_INT_MIN) < 0) {
+ throw newLossyConverionException(num, Integer.class);
+ }
+ return n.intValue();
+ } else {
+ throw new UnsupportedNumberClassException(num.getClass());
+ }
+ }
+
+ private static ArithmeticException newLossyConverionException(Number fromValue, Class/*<Number>*/ toType) {
+ return new ArithmeticException(
+ "Can't convert " + fromValue + " to type " + _ClassUtils.getShortClassName(toType) + " without loss.");
+ }
+
+ /**
+ * This is needed to reverse the extreme conversions in arithmetic
+ * operations so that numbers can be meaningfully used with models that
+ * don't know what to do with a BigDecimal. Of course, this will make
+ * impossible for these models (i.e. Jython) to receive a BigDecimal even if
+ * it was originally placed as such in the data model. However, since
+ * arithmetic operations aggressively erase the information regarding the
+ * original number type, we have no other choice to ensure expected operation
+ * in majority of cases.
+ */
+ public static Number optimizeNumberRepresentation(Number number) {
+ if (number instanceof BigDecimal) {
+ BigDecimal bd = (BigDecimal) number;
+ if (bd.scale() == 0) {
+ // BigDecimal -> BigInteger
+ number = bd.unscaledValue();
+ } else {
+ double d = bd.doubleValue();
+ if (d != Double.POSITIVE_INFINITY && d != Double.NEGATIVE_INFINITY) {
+ // BigDecimal -> Double
+ return Double.valueOf(d);
+ }
+ }
+ }
+ if (number instanceof BigInteger) {
+ BigInteger bi = (BigInteger) number;
+ if (bi.compareTo(BIG_INTEGER_INT_MAX) <= 0 && bi.compareTo(BIG_INTEGER_INT_MIN) >= 0) {
+ // BigInteger -> Integer
+ return Integer.valueOf(bi.intValue());
+ }
+ if (bi.compareTo(BIG_INTEGER_LONG_MAX) <= 0 && bi.compareTo(BIG_INTEGER_LONG_MIN) >= 0) {
+ // BigInteger -> Long
+ return Long.valueOf(bi.longValue());
+ }
+ }
+ return number;
+ }
+
+ public static BigDecimal toBigDecimal(Number num) {
+ try {
+ return num instanceof BigDecimal ? (BigDecimal) num : new BigDecimal(num.toString());
+ } catch (NumberFormatException e) {
+ // The exception message is useless, so we add a new one:
+ throw new NumberFormatException("Can't parse this as BigDecimal number: " + _StringUtils.jQuote(num));
+ }
+ }
+
+ public static Number toBigDecimalOrDouble(String s) {
+ if (s.length() > 2) {
+ char c = s.charAt(0);
+ if (c == 'I' && (s.equals("INF") || s.equals("Infinity"))) {
+ return Double.valueOf(Double.POSITIVE_INFINITY);
+ } else if (c == 'N' && s.equals("NaN")) {
+ return Double.valueOf(Double.NaN);
+ } else if (c == '-' && s.charAt(1) == 'I' && (s.equals("-INF") || s.equals("-Infinity"))) {
+ return Double.valueOf(Double.NEGATIVE_INFINITY);
+ }
+ }
+ return new BigDecimal(s);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtil.java
deleted file mode 100644
index eebed61..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtil.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import java.security.AccessControlException;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- */
-public class _SecurityUtil {
-
- private static final Logger LOG = LoggerFactory.getLogger(_SecurityUtil.class);
-
- private _SecurityUtil() {
- }
-
- public static String getSystemProperty(final String key) {
- return (String) AccessController.doPrivileged(
- new PrivilegedAction()
- {
- @Override
- public Object run() {
- return System.getProperty(key);
- }
- });
- }
-
- public static String getSystemProperty(final String key, final String defValue) {
- try {
- return (String) AccessController.doPrivileged(
- new PrivilegedAction()
- {
- @Override
- public Object run() {
- return System.getProperty(key, defValue);
- }
- });
- } catch (AccessControlException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Insufficient permissions to read system property " +
- _StringUtil.jQuoteNoXSS(key) + ", using default value " +
- _StringUtil.jQuoteNoXSS(defValue));
- }
- return defValue;
- }
- }
-
- public static Integer getSystemProperty(final String key, final int defValue) {
- try {
- return (Integer) AccessController.doPrivileged(
- new PrivilegedAction()
- {
- @Override
- public Object run() {
- return Integer.getInteger(key, defValue);
- }
- });
- } catch (AccessControlException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Insufficient permissions to read system property " +
- _StringUtil.jQuote(key) + ", using default value " + defValue);
- }
- return Integer.valueOf(defValue);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtils.java
new file mode 100644
index 0000000..81688e3
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_SecurityUtils.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import java.security.AccessControlException;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ */
+public class _SecurityUtils {
+
+ private static final Logger LOG = LoggerFactory.getLogger(_SecurityUtils.class);
+
+ private _SecurityUtils() {
+ }
+
+ public static String getSystemProperty(final String key) {
+ return (String) AccessController.doPrivileged(
+ new PrivilegedAction()
+ {
+ @Override
+ public Object run() {
+ return System.getProperty(key);
+ }
+ });
+ }
+
+ public static String getSystemProperty(final String key, final String defValue) {
+ try {
+ return (String) AccessController.doPrivileged(
+ new PrivilegedAction()
+ {
+ @Override
+ public Object run() {
+ return System.getProperty(key, defValue);
+ }
+ });
+ } catch (AccessControlException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Insufficient permissions to read system property " +
+ _StringUtils.jQuoteNoXSS(key) + ", using default value " +
+ _StringUtils.jQuoteNoXSS(defValue));
+ }
+ return defValue;
+ }
+ }
+
+ public static Integer getSystemProperty(final String key, final int defValue) {
+ try {
+ return (Integer) AccessController.doPrivileged(
+ new PrivilegedAction()
+ {
+ @Override
+ public Object run() {
+ return Integer.getInteger(key, defValue);
+ }
+ });
+ } catch (AccessControlException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Insufficient permissions to read system property " +
+ _StringUtils.jQuote(key) + ", using default value " + defValue);
+ }
+ return Integer.valueOf(defValue);
+ }
+ }
+}
[08/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtils.java
new file mode 100644
index 0000000..6ffe937
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtils.java
@@ -0,0 +1,1289 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.model.impl;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import org.apache.freemarker.core.model.TemplateNumberModel;
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._NumberUtils;
+
+/**
+ * Everything related to coercion to ambiguous numerical types.
+ */
+class OverloadedNumberUtils {
+
+ // Can't be instantiated
+ private OverloadedNumberUtils() { }
+
+ /**
+ * The lower limit of conversion prices where there's a risk of significant mantissa loss.
+ * The value comes from misc/overloadedNumberRules/prices.ods and generator.ftl.
+ */
+ static final int BIG_MANTISSA_LOSS_PRICE = 4 * 10000;
+
+ /** The highest long that can be stored in double without precision loss: 2**53. */
+ private static final long MAX_DOUBLE_OR_LONG = 9007199254740992L;
+ /** The lowest long that can be stored in double without precision loss: -(2**53). */
+ private static final long MIN_DOUBLE_OR_LONG = -9007199254740992L;
+ private static final int MAX_DOUBLE_OR_LONG_LOG_2 = 53;
+
+ /** The highest long that can be stored in float without precision loss: 2**24. */
+ private static final int MAX_FLOAT_OR_INT = 16777216;
+ /** The lowest long that can be stored in float without precision loss: -(2**24). */
+ private static final int MIN_FLOAT_OR_INT = -16777216;
+ private static final int MAX_FLOAT_OR_INT_LOG_2 = 24;
+ /** Lowest number that we don't thread as possible integer 0. */
+ private static final double LOWEST_ABOVE_ZERO = 0.000001;
+ /** Highest number that we don't thread as possible integer 1. */
+ private static final double HIGHEST_BELOW_ONE = 0.999999;
+
+ /**
+ * Attaches the lowest alternative number type to the parameter number via {@link NumberWithFallbackType}, if
+ * that's useful according the possible target number types. This transformation is applied on the method call
+ * argument list before overloaded method selection.
+ *
+ * <p>Note that as of this writing, this method is only used when
+ * {@link DefaultObjectWrapper#getIncompatibleImprovements()} >= 2.3.21.
+ *
+ * <p>Why's this needed, how it works: Overloaded method selection only selects methods where the <em>type</em>
+ * (not the value!) of the argument is "smaller" or the same as the parameter type. This is similar to how it's in
+ * the Java language. That it only decides based on the parameter type is important because this way
+ * {@link OverloadedMethodsSubset} can cache method lookup decisions using the types as the cache key. Problem is,
+ * since you don't declare the exact numerical types in FTL, and FTL has only a single generic numeric type
+ * anyway, what Java type a {@link TemplateNumberModel} uses internally is often seen as a technical detail of which
+ * the template author can't always keep track of. So we investigate the <em>value</em> of the number too,
+ * then coerce it down without overflow to a type that will match the most overloaded methods. (This
+ * is especially important as FTL often stores numbers in {@link BigDecimal}-s, which will hardly ever match any
+ * method parameters.) We could simply return that number, like {@code Byte(0)} for an {@code Integer(0)},
+ * however, then we would lose the information about what the original type was. The original type is sometimes
+ * important, as in ambiguous situations the method where there's an exact type match should be selected (like,
+ * when someone wants to select an overload explicitly with {@code m(x?int)}). Also, if an overload wins where
+ * the parameter type at the position of the number is {@code Number} or {@code Object} (or {@code Comparable}
+ * etc.), it's expected that we pass in the original value (an {@code Integer} in this example), especially if that
+ * value is the return value of another Java method. That's why we use
+ * {@link NumberWithFallbackType} numerical classes like {@link IntegerOrByte}, which represents both the original
+ * type and the coerced type, all encoded into the class of the value, which is used as the overloaded method lookup
+ * cache key.
+ *
+ * <p>See also: <tt>src\main\misc\overloadedNumberRules\prices.ods</tt>.
+ *
+ * @param num the number to coerce
+ * @param typeFlags the type flags of the target parameter position; see {@link TypeFlags}
+ *
+ * @returns The original number or a {@link NumberWithFallbackType}, depending on the actual value and the types
+ * indicated in the {@code targetNumTypes} parameter.
+ */
+ static Number addFallbackType(final Number num, final int typeFlags) {
+ final Class numClass = num.getClass();
+ if (numClass == BigDecimal.class) {
+ // For now we only support the backward-compatible mode that doesn't prevent roll overs and magnitude loss.
+ // However, we push the overloaded selection to the right direction, so we will at least indicate if the
+ // number has decimals.
+ BigDecimal n = (BigDecimal) num;
+ if ((typeFlags & TypeFlags.MASK_KNOWN_INTEGERS) != 0
+ && (typeFlags & TypeFlags.MASK_KNOWN_NONINTEGERS) != 0
+ && _NumberUtils.isIntegerBigDecimal(n) /* <- can be expensive */) {
+ return new IntegerBigDecimal(n);
+ } else {
+ // Either it was a non-integer, or it didn't mater what it was, as we don't have both integer and
+ // non-integer target types.
+ return n;
+ }
+ } else if (numClass == Integer.class) {
+ int pn = num.intValue();
+ // Note that we try to return the most specific type (i.e., the numerical type with the smallest range), but
+ // only among the types that are possible targets. Like if the only target is int and the value is 1, we
+ // will return Integer 1, not Byte 1, even though byte is automatically converted to int so it would
+ // work too. Why we avoid unnecessarily specific types is that they generate more overloaded method lookup
+ // cache entries, since the cache key is the array of the types of the argument values. So we want as few
+ // permutations as possible.
+ if ((typeFlags & TypeFlags.BYTE) != 0 && pn <= Byte.MAX_VALUE && pn >= Byte.MIN_VALUE) {
+ return new IntegerOrByte((Integer) num, (byte) pn);
+ } else if ((typeFlags & TypeFlags.SHORT) != 0 && pn <= Short.MAX_VALUE && pn >= Short.MIN_VALUE) {
+ return new IntegerOrShort((Integer) num, (short) pn);
+ } else {
+ return num;
+ }
+ } else if (numClass == Long.class) {
+ final long pn = num.longValue();
+ if ((typeFlags & TypeFlags.BYTE) != 0 && pn <= Byte.MAX_VALUE && pn >= Byte.MIN_VALUE) {
+ return new LongOrByte((Long) num, (byte) pn);
+ } else if ((typeFlags & TypeFlags.SHORT) != 0 && pn <= Short.MAX_VALUE && pn >= Short.MIN_VALUE) {
+ return new LongOrShort((Long) num, (short) pn);
+ } else if ((typeFlags & TypeFlags.INTEGER) != 0 && pn <= Integer.MAX_VALUE && pn >= Integer.MIN_VALUE) {
+ return new LongOrInteger((Long) num, (int) pn);
+ } else {
+ return num;
+ }
+ } else if (numClass == Double.class) {
+ final double doubleN = num.doubleValue();
+
+ // Can we store it in an integer type?
+ checkIfWholeNumber: do {
+ if ((typeFlags & TypeFlags.MASK_KNOWN_INTEGERS) == 0) break checkIfWholeNumber;
+
+ // There's no hope to be 1-precise outside this region. (Although problems can occur even inside it...)
+ if (doubleN > MAX_DOUBLE_OR_LONG || doubleN < MIN_DOUBLE_OR_LONG) break checkIfWholeNumber;
+
+ long longN = num.longValue();
+ double diff = doubleN - longN;
+ boolean exact; // We will try to ignore precision glitches (like 0.3 - 0.2 - 0.1 = -2.7E-17)
+ if (diff == 0) {
+ exact = true;
+ } else if (diff > 0) {
+ if (diff < LOWEST_ABOVE_ZERO) {
+ exact = false;
+ } else if (diff > HIGHEST_BELOW_ONE) {
+ exact = false;
+ longN++;
+ } else {
+ break checkIfWholeNumber;
+ }
+ } else { // => diff < 0
+ if (diff > -LOWEST_ABOVE_ZERO) {
+ exact = false;
+ } else if (diff < -HIGHEST_BELOW_ONE) {
+ exact = false;
+ longN--;
+ } else {
+ break checkIfWholeNumber;
+ }
+ }
+
+ // If we reach this, it can be treated as a whole number.
+
+ if ((typeFlags & TypeFlags.BYTE) != 0
+ && longN <= Byte.MAX_VALUE && longN >= Byte.MIN_VALUE) {
+ return new DoubleOrByte((Double) num, (byte) longN);
+ } else if ((typeFlags & TypeFlags.SHORT) != 0
+ && longN <= Short.MAX_VALUE && longN >= Short.MIN_VALUE) {
+ return new DoubleOrShort((Double) num, (short) longN);
+ } else if ((typeFlags & TypeFlags.INTEGER) != 0
+ && longN <= Integer.MAX_VALUE && longN >= Integer.MIN_VALUE) {
+ final int intN = (int) longN;
+ return (typeFlags & TypeFlags.FLOAT) != 0 && intN >= MIN_FLOAT_OR_INT && intN <= MAX_FLOAT_OR_INT
+ ? new DoubleOrIntegerOrFloat((Double) num, intN)
+ : new DoubleOrInteger((Double) num, intN);
+ } else if ((typeFlags & TypeFlags.LONG) != 0) {
+ if (exact) {
+ return new DoubleOrLong((Double) num, longN);
+ } else {
+ // We don't deal with non-exact numbers outside the range of int, as we already reach
+ // ULP 2.384185791015625E-7 there.
+ if (longN >= Integer.MIN_VALUE && longN <= Integer.MAX_VALUE) {
+ return new DoubleOrLong((Double) num, longN);
+ } else {
+ break checkIfWholeNumber;
+ }
+ }
+ }
+ // This point is reached if the double value was out of the range of target integer type(s).
+ // Falls through!
+ } while (false);
+ // If we reach this that means that it can't be treated as a whole number.
+
+ if ((typeFlags & TypeFlags.FLOAT) != 0 && doubleN >= -Float.MAX_VALUE && doubleN <= Float.MAX_VALUE) {
+ return new DoubleOrFloat((Double) num);
+ } else {
+ // Simply Double:
+ return num;
+ }
+ } else if (numClass == Float.class) {
+ final float floatN = num.floatValue();
+
+ // Can we store it in an integer type?
+ checkIfWholeNumber: do {
+ if ((typeFlags & TypeFlags.MASK_KNOWN_INTEGERS) == 0) break checkIfWholeNumber;
+
+ // There's no hope to be 1-precise outside this region. (Although problems can occur even inside it...)
+ if (floatN > MAX_FLOAT_OR_INT || floatN < MIN_FLOAT_OR_INT) break checkIfWholeNumber;
+
+ int intN = num.intValue();
+ double diff = floatN - intN;
+ boolean exact; // We will try to ignore precision glitches (like 0.3 - 0.2 - 0.1 = -2.7E-17)
+ if (diff == 0) {
+ exact = true;
+ // We already reach ULP 7.6293945E-6 with bytes, so we don't continue with shorts.
+ } else if (intN >= Byte.MIN_VALUE && intN <= Byte.MAX_VALUE) {
+ if (diff > 0) {
+ if (diff < 0.00001) {
+ exact = false;
+ } else if (diff > 0.99999) {
+ exact = false;
+ intN++;
+ } else {
+ break checkIfWholeNumber;
+ }
+ } else { // => diff < 0
+ if (diff > -0.00001) {
+ exact = false;
+ } else if (diff < -0.99999) {
+ exact = false;
+ intN--;
+ } else {
+ break checkIfWholeNumber;
+ }
+ }
+ } else {
+ break checkIfWholeNumber;
+ }
+
+ // If we reach this, it can be treated as a whole number.
+
+ if ((typeFlags & TypeFlags.BYTE) != 0 && intN <= Byte.MAX_VALUE && intN >= Byte.MIN_VALUE) {
+ return new FloatOrByte((Float) num, (byte) intN);
+ } else if ((typeFlags & TypeFlags.SHORT) != 0 && intN <= Short.MAX_VALUE && intN >= Short.MIN_VALUE) {
+ return new FloatOrShort((Float) num, (short) intN);
+ } else if ((typeFlags & TypeFlags.INTEGER) != 0) {
+ return new FloatOrInteger((Float) num, intN);
+ } else if ((typeFlags & TypeFlags.LONG) != 0) {
+ // We can't even go outside the range of integers, so we don't need Long variation:
+ return exact
+ ? new FloatOrInteger((Float) num, intN)
+ : new FloatOrByte((Float) num, (byte) intN); // as !exact implies (-128..127)
+ }
+ // This point is reached if the float value was out of the range of target integer type(s).
+ // Falls through!
+ } while (false);
+ // If we reach this that means that it can't be treated as a whole number. So it's simply a Float:
+ return num;
+ } else if (numClass == Byte.class) {
+ return num;
+ } else if (numClass == Short.class) {
+ short pn = num.shortValue();
+ if ((typeFlags & TypeFlags.BYTE) != 0 && pn <= Byte.MAX_VALUE && pn >= Byte.MIN_VALUE) {
+ return new ShortOrByte((Short) num, (byte) pn);
+ } else {
+ return num;
+ }
+ } else if (numClass == BigInteger.class) {
+ if ((typeFlags
+ & ((TypeFlags.MASK_KNOWN_INTEGERS | TypeFlags.MASK_KNOWN_NONINTEGERS)
+ ^ (TypeFlags.BIG_INTEGER | TypeFlags.BIG_DECIMAL))) != 0) {
+ BigInteger biNum = (BigInteger) num;
+ final int bitLength = biNum.bitLength(); // Doesn't include sign bit, so it's one less than expected
+ if ((typeFlags & TypeFlags.BYTE) != 0 && bitLength <= 7) {
+ return new BigIntegerOrByte(biNum);
+ } else if ((typeFlags & TypeFlags.SHORT) != 0 && bitLength <= 15) {
+ return new BigIntegerOrShort(biNum);
+ } else if ((typeFlags & TypeFlags.INTEGER) != 0 && bitLength <= 31) {
+ return new BigIntegerOrInteger(biNum);
+ } else if ((typeFlags & TypeFlags.LONG) != 0 && bitLength <= 63) {
+ return new BigIntegerOrLong(biNum);
+ } else if ((typeFlags & TypeFlags.FLOAT) != 0
+ && (bitLength <= MAX_FLOAT_OR_INT_LOG_2
+ || bitLength == MAX_FLOAT_OR_INT_LOG_2 + 1
+ && biNum.getLowestSetBit() >= MAX_FLOAT_OR_INT_LOG_2)) {
+ return new BigIntegerOrFloat(biNum);
+ } else if ((typeFlags & TypeFlags.DOUBLE) != 0
+ && (bitLength <= MAX_DOUBLE_OR_LONG_LOG_2
+ || bitLength == MAX_DOUBLE_OR_LONG_LOG_2 + 1
+ && biNum.getLowestSetBit() >= MAX_DOUBLE_OR_LONG_LOG_2)) {
+ return new BigIntegerOrDouble(biNum);
+ } else {
+ return num;
+ }
+ } else {
+ // No relevant coercion target types; return the BigInteger as is:
+ return num;
+ }
+ } else {
+ // Unknown number type:
+ return num;
+ }
+ }
+
+ interface ByteSource { Byte byteValue(); }
+ interface ShortSource { Short shortValue(); }
+ interface IntegerSource { Integer integerValue(); }
+ interface LongSource { Long longValue(); }
+ interface FloatSource { Float floatValue(); }
+ interface DoubleSource { Double doubleValue(); }
+ interface BigIntegerSource { BigInteger bigIntegerValue(); }
+ interface BigDecimalSource { BigDecimal bigDecimalValue(); }
+
+ /**
+ * Superclass of "Or"-ed numerical types. With an example, a {@code int} 1 has the fallback type {@code byte}, as
+ * that's the smallest type that can store the value, so it can be represented as an {@link IntegerOrByte}.
+ * This is useful as overloaded method selection only examines the type of the arguments, not the value of them,
+ * but with "Or"-ed types we can encode this value-related information into the argument type, hence influencing the
+ * method selection.
+ */
+ abstract static class NumberWithFallbackType extends Number implements Comparable {
+
+ protected abstract Number getSourceNumber();
+
+ @Override
+ public int intValue() {
+ return getSourceNumber().intValue();
+ }
+
+ @Override
+ public long longValue() {
+ return getSourceNumber().longValue();
+ }
+
+ @Override
+ public float floatValue() {
+ return getSourceNumber().floatValue();
+ }
+
+ @Override
+ public double doubleValue() {
+ return getSourceNumber().doubleValue();
+ }
+
+ @Override
+ public byte byteValue() {
+ return getSourceNumber().byteValue();
+ }
+
+ @Override
+ public short shortValue() {
+ return getSourceNumber().shortValue();
+ }
+
+ @Override
+ public int hashCode() {
+ return getSourceNumber().hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj != null && getClass() == obj.getClass()) {
+ return getSourceNumber().equals(((NumberWithFallbackType) obj).getSourceNumber());
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return getSourceNumber().toString();
+ }
+
+ // We have to implement this, so that if a potential matching method expects a Comparable, which is implemented
+ // by all the supported numerical types, the "Or" type will be a match.
+ @Override
+ public int compareTo(Object o) {
+ Number n = getSourceNumber();
+ if (n instanceof Comparable) {
+ return ((Comparable) n).compareTo(o);
+ } else {
+ throw new ClassCastException(n.getClass().getName() + " is not Comparable.");
+ }
+ }
+
+ }
+
+ /**
+ * Holds a {@link BigDecimal} that stores a whole number. When selecting a overloaded method, FreeMarker tries to
+ * associate {@link BigDecimal} values to parameters of types that can hold non-whole numbers, unless the
+ * {@link BigDecimal} is wrapped into this class, in which case it does the opposite. This mechanism is, however,
+ * too rough to prevent roll overs or magnitude losses. Those are not yet handled for backward compatibility (they
+ * were suppressed earlier too).
+ */
+ static final class IntegerBigDecimal extends NumberWithFallbackType {
+
+ private final BigDecimal n;
+
+ IntegerBigDecimal(BigDecimal n) {
+ this.n = n;
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ public BigInteger bigIntegerValue() {
+ return n.toBigInteger();
+ }
+
+ }
+
+ static abstract class LongOrSmallerInteger extends NumberWithFallbackType {
+
+ private final Long n;
+
+ protected LongOrSmallerInteger(Long n) {
+ this.n = n;
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ @Override
+ public long longValue() {
+ return n.longValue();
+ }
+
+ }
+
+ static class LongOrByte extends LongOrSmallerInteger {
+
+ private final byte w;
+
+ LongOrByte(Long n, byte w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public byte byteValue() {
+ return w;
+ }
+
+ }
+
+ static class LongOrShort extends LongOrSmallerInteger {
+
+ private final short w;
+
+ LongOrShort(Long n, short w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public short shortValue() {
+ return w;
+ }
+
+ }
+
+ static class LongOrInteger extends LongOrSmallerInteger {
+
+ private final int w;
+
+ LongOrInteger(Long n, int w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ }
+
+ static abstract class IntegerOrSmallerInteger extends NumberWithFallbackType {
+
+ private final Integer n;
+
+ protected IntegerOrSmallerInteger(Integer n) {
+ this.n = n;
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ @Override
+ public int intValue() {
+ return n.intValue();
+ }
+
+ }
+
+ static class IntegerOrByte extends IntegerOrSmallerInteger {
+
+ private final byte w;
+
+ IntegerOrByte(Integer n, byte w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public byte byteValue() {
+ return w;
+ }
+
+ }
+
+ static class IntegerOrShort extends IntegerOrSmallerInteger {
+
+ private final short w;
+
+ IntegerOrShort(Integer n, short w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public short shortValue() {
+ return w;
+ }
+
+ }
+
+ static class ShortOrByte extends NumberWithFallbackType {
+
+ private final Short n;
+ private final byte w;
+
+ protected ShortOrByte(Short n, byte w) {
+ this.n = n;
+ this.w = w;
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ @Override
+ public short shortValue() {
+ return n.shortValue();
+ }
+
+ @Override
+ public byte byteValue() {
+ return w;
+ }
+
+ }
+
+ static abstract class DoubleOrWholeNumber extends NumberWithFallbackType {
+
+ private final Double n;
+
+ protected DoubleOrWholeNumber(Double n) {
+ this.n = n;
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ @Override
+ public double doubleValue() {
+ return n.doubleValue();
+ }
+
+ }
+
+ static final class DoubleOrByte extends DoubleOrWholeNumber {
+
+ private final byte w;
+
+ DoubleOrByte(Double n, byte w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public byte byteValue() {
+ return w;
+ }
+
+ @Override
+ public short shortValue() {
+ return w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ static final class DoubleOrShort extends DoubleOrWholeNumber {
+
+ private final short w;
+
+ DoubleOrShort(Double n, short w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public short shortValue() {
+ return w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ static final class DoubleOrIntegerOrFloat extends DoubleOrWholeNumber {
+
+ private final int w;
+
+ DoubleOrIntegerOrFloat(Double n, int w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ static final class DoubleOrInteger extends DoubleOrWholeNumber {
+
+ private final int w;
+
+ DoubleOrInteger(Double n, int w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ static final class DoubleOrLong extends DoubleOrWholeNumber {
+
+ private final long w;
+
+ DoubleOrLong(Double n, long w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ static final class DoubleOrFloat extends NumberWithFallbackType {
+
+ private final Double n;
+
+ DoubleOrFloat(Double n) {
+ this.n = n;
+ }
+
+ @Override
+ public float floatValue() {
+ return n.floatValue();
+ }
+
+ @Override
+ public double doubleValue() {
+ return n.doubleValue();
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ }
+
+ static abstract class FloatOrWholeNumber extends NumberWithFallbackType {
+
+ private final Float n;
+
+ FloatOrWholeNumber(Float n) {
+ this.n = n;
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ @Override
+ public float floatValue() {
+ return n.floatValue();
+ }
+
+ }
+
+ static final class FloatOrByte extends FloatOrWholeNumber {
+
+ private final byte w;
+
+ FloatOrByte(Float n, byte w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public byte byteValue() {
+ return w;
+ }
+
+ @Override
+ public short shortValue() {
+ return w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ static final class FloatOrShort extends FloatOrWholeNumber {
+
+ private final short w;
+
+ FloatOrShort(Float n, short w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public short shortValue() {
+ return w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ static final class FloatOrInteger extends FloatOrWholeNumber {
+
+ private final int w;
+
+ FloatOrInteger(Float n, int w) {
+ super(n);
+ this.w = w;
+ }
+
+ @Override
+ public int intValue() {
+ return w;
+ }
+
+ @Override
+ public long longValue() {
+ return w;
+ }
+
+ }
+
+ abstract static class BigIntegerOrPrimitive extends NumberWithFallbackType {
+
+ protected final BigInteger n;
+
+ BigIntegerOrPrimitive(BigInteger n) {
+ this.n = n;
+ }
+
+ @Override
+ protected Number getSourceNumber() {
+ return n;
+ }
+
+ }
+
+ final static class BigIntegerOrByte extends BigIntegerOrPrimitive {
+
+ BigIntegerOrByte(BigInteger n) {
+ super(n);
+ }
+
+ }
+
+ final static class BigIntegerOrShort extends BigIntegerOrPrimitive {
+
+ BigIntegerOrShort(BigInteger n) {
+ super(n);
+ }
+
+ }
+
+ final static class BigIntegerOrInteger extends BigIntegerOrPrimitive {
+
+ BigIntegerOrInteger(BigInteger n) {
+ super(n);
+ }
+
+ }
+
+ final static class BigIntegerOrLong extends BigIntegerOrPrimitive {
+
+ BigIntegerOrLong(BigInteger n) {
+ super(n);
+ }
+
+ }
+
+ abstract static class BigIntegerOrFPPrimitive extends BigIntegerOrPrimitive {
+
+ BigIntegerOrFPPrimitive(BigInteger n) {
+ super(n);
+ }
+
+ /** Faster version of {@link BigDecimal#floatValue()}, utilizes that the number known to fit into a long. */
+ @Override
+ public float floatValue() {
+ return n.longValue();
+ }
+
+ /** Faster version of {@link BigDecimal#doubleValue()}, utilizes that the number known to fit into a long. */
+ @Override
+ public double doubleValue() {
+ return n.longValue();
+ }
+
+ }
+
+ final static class BigIntegerOrFloat extends BigIntegerOrFPPrimitive {
+
+ BigIntegerOrFloat(BigInteger n) {
+ super(n);
+ }
+
+ }
+
+ final static class BigIntegerOrDouble extends BigIntegerOrFPPrimitive {
+
+ BigIntegerOrDouble(BigInteger n) {
+ super(n);
+ }
+
+ }
+
+ /**
+ * Returns a non-negative number that indicates how much we want to avoid a given numerical type conversion. Since
+ * we only consider the types here, not the actual value, we always consider the worst case scenario. Like it will
+ * say that converting int to short is not allowed, although int 1 can be converted to byte without loss. To account
+ * for such situations, "Or"-ed types, like {@link IntegerOrByte} has to be used.
+ *
+ * @param fromC the non-primitive type of the argument (with other words, the actual type).
+ * Must be {@link Number} or its subclass. This is possibly an {@link NumberWithFallbackType} subclass.
+ * @param toC the <em>non-primitive</em> type of the target parameter (with other words, the format type).
+ * Must be a {@link Number} subclass, not {@link Number} itself.
+ * Must <em>not</em> be {@link NumberWithFallbackType} or its subclass.
+ *
+ * @return
+ * <p>The possible values are:
+ * <ul>
+ * <li>0: No conversion is needed
+ * <li>[0, 30000): Lossless conversion
+ * <li>[30000, 40000): Smaller precision loss in mantissa is possible.
+ * <li>[40000, 50000): Bigger precision loss in mantissa is possible.
+ * <li>{@link Integer#MAX_VALUE}: Conversion not allowed due to the possibility of magnitude loss or
+ * overflow</li>
+ * </ul>
+ *
+ * <p>At some places, we only care if the conversion is possible, i.e., whether the return value is
+ * {@link Integer#MAX_VALUE} or not. But when multiple overloaded methods have an argument type to which we
+ * could convert to, this number will influence which of those will be chosen.
+ */
+ static int getArgumentConversionPrice(Class fromC, Class toC) {
+ // DO NOT EDIT, generated code!
+ // See: src\main\misc\overloadedNumberRules\README.txt
+ if (toC == fromC) {
+ return 0;
+ } else if (toC == Integer.class) {
+ if (fromC == IntegerBigDecimal.class) return 31003;
+ else if (fromC == BigDecimal.class) return 41003;
+ else if (fromC == Long.class) return Integer.MAX_VALUE;
+ else if (fromC == Double.class) return Integer.MAX_VALUE;
+ else if (fromC == Float.class) return Integer.MAX_VALUE;
+ else if (fromC == Byte.class) return 10003;
+ else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == LongOrInteger.class) return 21003;
+ else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return 22003;
+ else if (fromC == DoubleOrInteger.class) return 22003;
+ else if (fromC == DoubleOrLong.class) return Integer.MAX_VALUE;
+ else if (fromC == IntegerOrByte.class) return 0;
+ else if (fromC == DoubleOrByte.class) return 22003;
+ else if (fromC == LongOrByte.class) return 21003;
+ else if (fromC == Short.class) return 10003;
+ else if (fromC == LongOrShort.class) return 21003;
+ else if (fromC == ShortOrByte.class) return 10003;
+ else if (fromC == FloatOrInteger.class) return 21003;
+ else if (fromC == FloatOrByte.class) return 21003;
+ else if (fromC == FloatOrShort.class) return 21003;
+ else if (fromC == BigIntegerOrInteger.class) return 16003;
+ else if (fromC == BigIntegerOrLong.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrByte.class) return 16003;
+ else if (fromC == IntegerOrShort.class) return 0;
+ else if (fromC == DoubleOrShort.class) return 22003;
+ else if (fromC == BigIntegerOrShort.class) return 16003;
+ else return Integer.MAX_VALUE;
+ } else if (toC == Long.class) {
+ if (fromC == Integer.class) return 10004;
+ else if (fromC == IntegerBigDecimal.class) return 31004;
+ else if (fromC == BigDecimal.class) return 41004;
+ else if (fromC == Double.class) return Integer.MAX_VALUE;
+ else if (fromC == Float.class) return Integer.MAX_VALUE;
+ else if (fromC == Byte.class) return 10004;
+ else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == LongOrInteger.class) return 0;
+ else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return 21004;
+ else if (fromC == DoubleOrInteger.class) return 21004;
+ else if (fromC == DoubleOrLong.class) return 21004;
+ else if (fromC == IntegerOrByte.class) return 10004;
+ else if (fromC == DoubleOrByte.class) return 21004;
+ else if (fromC == LongOrByte.class) return 0;
+ else if (fromC == Short.class) return 10004;
+ else if (fromC == LongOrShort.class) return 0;
+ else if (fromC == ShortOrByte.class) return 10004;
+ else if (fromC == FloatOrInteger.class) return 21004;
+ else if (fromC == FloatOrByte.class) return 21004;
+ else if (fromC == FloatOrShort.class) return 21004;
+ else if (fromC == BigIntegerOrInteger.class) return 15004;
+ else if (fromC == BigIntegerOrLong.class) return 15004;
+ else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrByte.class) return 15004;
+ else if (fromC == IntegerOrShort.class) return 10004;
+ else if (fromC == DoubleOrShort.class) return 21004;
+ else if (fromC == BigIntegerOrShort.class) return 15004;
+ else return Integer.MAX_VALUE;
+ } else if (toC == Double.class) {
+ if (fromC == Integer.class) return 20007;
+ else if (fromC == IntegerBigDecimal.class) return 32007;
+ else if (fromC == BigDecimal.class) return 32007;
+ else if (fromC == Long.class) return 30007;
+ else if (fromC == Float.class) return 10007;
+ else if (fromC == Byte.class) return 20007;
+ else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == LongOrInteger.class) return 21007;
+ else if (fromC == DoubleOrFloat.class) return 0;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return 0;
+ else if (fromC == DoubleOrInteger.class) return 0;
+ else if (fromC == DoubleOrLong.class) return 0;
+ else if (fromC == IntegerOrByte.class) return 20007;
+ else if (fromC == DoubleOrByte.class) return 0;
+ else if (fromC == LongOrByte.class) return 21007;
+ else if (fromC == Short.class) return 20007;
+ else if (fromC == LongOrShort.class) return 21007;
+ else if (fromC == ShortOrByte.class) return 20007;
+ else if (fromC == FloatOrInteger.class) return 10007;
+ else if (fromC == FloatOrByte.class) return 10007;
+ else if (fromC == FloatOrShort.class) return 10007;
+ else if (fromC == BigIntegerOrInteger.class) return 20007;
+ else if (fromC == BigIntegerOrLong.class) return 30007;
+ else if (fromC == BigIntegerOrDouble.class) return 20007;
+ else if (fromC == BigIntegerOrFloat.class) return 20007;
+ else if (fromC == BigIntegerOrByte.class) return 20007;
+ else if (fromC == IntegerOrShort.class) return 20007;
+ else if (fromC == DoubleOrShort.class) return 0;
+ else if (fromC == BigIntegerOrShort.class) return 20007;
+ else return Integer.MAX_VALUE;
+ } else if (toC == Float.class) {
+ if (fromC == Integer.class) return 30006;
+ else if (fromC == IntegerBigDecimal.class) return 33006;
+ else if (fromC == BigDecimal.class) return 33006;
+ else if (fromC == Long.class) return 40006;
+ else if (fromC == Double.class) return Integer.MAX_VALUE;
+ else if (fromC == Byte.class) return 20006;
+ else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == LongOrInteger.class) return 30006;
+ else if (fromC == DoubleOrFloat.class) return 30006;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return 23006;
+ else if (fromC == DoubleOrInteger.class) return 30006;
+ else if (fromC == DoubleOrLong.class) return 40006;
+ else if (fromC == IntegerOrByte.class) return 24006;
+ else if (fromC == DoubleOrByte.class) return 23006;
+ else if (fromC == LongOrByte.class) return 24006;
+ else if (fromC == Short.class) return 20006;
+ else if (fromC == LongOrShort.class) return 24006;
+ else if (fromC == ShortOrByte.class) return 20006;
+ else if (fromC == FloatOrInteger.class) return 0;
+ else if (fromC == FloatOrByte.class) return 0;
+ else if (fromC == FloatOrShort.class) return 0;
+ else if (fromC == BigIntegerOrInteger.class) return 30006;
+ else if (fromC == BigIntegerOrLong.class) return 40006;
+ else if (fromC == BigIntegerOrDouble.class) return 40006;
+ else if (fromC == BigIntegerOrFloat.class) return 24006;
+ else if (fromC == BigIntegerOrByte.class) return 24006;
+ else if (fromC == IntegerOrShort.class) return 24006;
+ else if (fromC == DoubleOrShort.class) return 23006;
+ else if (fromC == BigIntegerOrShort.class) return 24006;
+ else return Integer.MAX_VALUE;
+ } else if (toC == Byte.class) {
+ if (fromC == Integer.class) return Integer.MAX_VALUE;
+ else if (fromC == IntegerBigDecimal.class) return 35001;
+ else if (fromC == BigDecimal.class) return 45001;
+ else if (fromC == Long.class) return Integer.MAX_VALUE;
+ else if (fromC == Double.class) return Integer.MAX_VALUE;
+ else if (fromC == Float.class) return Integer.MAX_VALUE;
+ else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == LongOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrLong.class) return Integer.MAX_VALUE;
+ else if (fromC == IntegerOrByte.class) return 22001;
+ else if (fromC == DoubleOrByte.class) return 25001;
+ else if (fromC == LongOrByte.class) return 23001;
+ else if (fromC == Short.class) return Integer.MAX_VALUE;
+ else if (fromC == LongOrShort.class) return Integer.MAX_VALUE;
+ else if (fromC == ShortOrByte.class) return 21001;
+ else if (fromC == FloatOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == FloatOrByte.class) return 23001;
+ else if (fromC == FloatOrShort.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrLong.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrByte.class) return 18001;
+ else if (fromC == IntegerOrShort.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrShort.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrShort.class) return Integer.MAX_VALUE;
+ else return Integer.MAX_VALUE;
+ } else if (toC == Short.class) {
+ if (fromC == Integer.class) return Integer.MAX_VALUE;
+ else if (fromC == IntegerBigDecimal.class) return 34002;
+ else if (fromC == BigDecimal.class) return 44002;
+ else if (fromC == Long.class) return Integer.MAX_VALUE;
+ else if (fromC == Double.class) return Integer.MAX_VALUE;
+ else if (fromC == Float.class) return Integer.MAX_VALUE;
+ else if (fromC == Byte.class) return 10002;
+ else if (fromC == BigInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == LongOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrLong.class) return Integer.MAX_VALUE;
+ else if (fromC == IntegerOrByte.class) return 21002;
+ else if (fromC == DoubleOrByte.class) return 24002;
+ else if (fromC == LongOrByte.class) return 22002;
+ else if (fromC == LongOrShort.class) return 22002;
+ else if (fromC == ShortOrByte.class) return 0;
+ else if (fromC == FloatOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == FloatOrByte.class) return 22002;
+ else if (fromC == FloatOrShort.class) return 22002;
+ else if (fromC == BigIntegerOrInteger.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrLong.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrDouble.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == BigIntegerOrByte.class) return 17002;
+ else if (fromC == IntegerOrShort.class) return 21002;
+ else if (fromC == DoubleOrShort.class) return 24002;
+ else if (fromC == BigIntegerOrShort.class) return 17002;
+ else return Integer.MAX_VALUE;
+ } else if (toC == BigDecimal.class) {
+ if (fromC == Integer.class) return 20008;
+ else if (fromC == IntegerBigDecimal.class) return 0;
+ else if (fromC == Long.class) return 20008;
+ else if (fromC == Double.class) return 20008;
+ else if (fromC == Float.class) return 20008;
+ else if (fromC == Byte.class) return 20008;
+ else if (fromC == BigInteger.class) return 10008;
+ else if (fromC == LongOrInteger.class) return 20008;
+ else if (fromC == DoubleOrFloat.class) return 20008;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return 20008;
+ else if (fromC == DoubleOrInteger.class) return 20008;
+ else if (fromC == DoubleOrLong.class) return 20008;
+ else if (fromC == IntegerOrByte.class) return 20008;
+ else if (fromC == DoubleOrByte.class) return 20008;
+ else if (fromC == LongOrByte.class) return 20008;
+ else if (fromC == Short.class) return 20008;
+ else if (fromC == LongOrShort.class) return 20008;
+ else if (fromC == ShortOrByte.class) return 20008;
+ else if (fromC == FloatOrInteger.class) return 20008;
+ else if (fromC == FloatOrByte.class) return 20008;
+ else if (fromC == FloatOrShort.class) return 20008;
+ else if (fromC == BigIntegerOrInteger.class) return 10008;
+ else if (fromC == BigIntegerOrLong.class) return 10008;
+ else if (fromC == BigIntegerOrDouble.class) return 10008;
+ else if (fromC == BigIntegerOrFloat.class) return 10008;
+ else if (fromC == BigIntegerOrByte.class) return 10008;
+ else if (fromC == IntegerOrShort.class) return 20008;
+ else if (fromC == DoubleOrShort.class) return 20008;
+ else if (fromC == BigIntegerOrShort.class) return 10008;
+ else return Integer.MAX_VALUE;
+ } else if (toC == BigInteger.class) {
+ if (fromC == Integer.class) return 10005;
+ else if (fromC == IntegerBigDecimal.class) return 10005;
+ else if (fromC == BigDecimal.class) return 40005;
+ else if (fromC == Long.class) return 10005;
+ else if (fromC == Double.class) return Integer.MAX_VALUE;
+ else if (fromC == Float.class) return Integer.MAX_VALUE;
+ else if (fromC == Byte.class) return 10005;
+ else if (fromC == LongOrInteger.class) return 10005;
+ else if (fromC == DoubleOrFloat.class) return Integer.MAX_VALUE;
+ else if (fromC == DoubleOrIntegerOrFloat.class) return 21005;
+ else if (fromC == DoubleOrInteger.class) return 21005;
+ else if (fromC == DoubleOrLong.class) return 21005;
+ else if (fromC == IntegerOrByte.class) return 10005;
+ else if (fromC == DoubleOrByte.class) return 21005;
+ else if (fromC == LongOrByte.class) return 10005;
+ else if (fromC == Short.class) return 10005;
+ else if (fromC == LongOrShort.class) return 10005;
+ else if (fromC == ShortOrByte.class) return 10005;
+ else if (fromC == FloatOrInteger.class) return 25005;
+ else if (fromC == FloatOrByte.class) return 25005;
+ else if (fromC == FloatOrShort.class) return 25005;
+ else if (fromC == BigIntegerOrInteger.class) return 0;
+ else if (fromC == BigIntegerOrLong.class) return 0;
+ else if (fromC == BigIntegerOrDouble.class) return 0;
+ else if (fromC == BigIntegerOrFloat.class) return 0;
+ else if (fromC == BigIntegerOrByte.class) return 0;
+ else if (fromC == IntegerOrShort.class) return 10005;
+ else if (fromC == DoubleOrShort.class) return 21005;
+ else if (fromC == BigIntegerOrShort.class) return 0;
+ else return Integer.MAX_VALUE;
+ } else {
+ // Unknown toC; we don't know how to convert to it:
+ return Integer.MAX_VALUE;
+ }
+ }
+
+ static int compareNumberTypeSpecificity(Class c1, Class c2) {
+ // DO NOT EDIT, generated code!
+ // See: src\main\misc\overloadedNumberRules\README.txt
+ c1 = _ClassUtils.primitiveClassToBoxingClass(c1);
+ c2 = _ClassUtils.primitiveClassToBoxingClass(c2);
+
+ if (c1 == c2) return 0;
+
+ if (c1 == Integer.class) {
+ if (c2 == Long.class) return 4 - 3;
+ if (c2 == Double.class) return 7 - 3;
+ if (c2 == Float.class) return 6 - 3;
+ if (c2 == Byte.class) return 1 - 3;
+ if (c2 == Short.class) return 2 - 3;
+ if (c2 == BigDecimal.class) return 8 - 3;
+ if (c2 == BigInteger.class) return 5 - 3;
+ return 0;
+ }
+ if (c1 == Long.class) {
+ if (c2 == Integer.class) return 3 - 4;
+ if (c2 == Double.class) return 7 - 4;
+ if (c2 == Float.class) return 6 - 4;
+ if (c2 == Byte.class) return 1 - 4;
+ if (c2 == Short.class) return 2 - 4;
+ if (c2 == BigDecimal.class) return 8 - 4;
+ if (c2 == BigInteger.class) return 5 - 4;
+ return 0;
+ }
+ if (c1 == Double.class) {
+ if (c2 == Integer.class) return 3 - 7;
+ if (c2 == Long.class) return 4 - 7;
+ if (c2 == Float.class) return 6 - 7;
+ if (c2 == Byte.class) return 1 - 7;
+ if (c2 == Short.class) return 2 - 7;
+ if (c2 == BigDecimal.class) return 8 - 7;
+ if (c2 == BigInteger.class) return 5 - 7;
+ return 0;
+ }
+ if (c1 == Float.class) {
+ if (c2 == Integer.class) return 3 - 6;
+ if (c2 == Long.class) return 4 - 6;
+ if (c2 == Double.class) return 7 - 6;
+ if (c2 == Byte.class) return 1 - 6;
+ if (c2 == Short.class) return 2 - 6;
+ if (c2 == BigDecimal.class) return 8 - 6;
+ if (c2 == BigInteger.class) return 5 - 6;
+ return 0;
+ }
+ if (c1 == Byte.class) {
+ if (c2 == Integer.class) return 3 - 1;
+ if (c2 == Long.class) return 4 - 1;
+ if (c2 == Double.class) return 7 - 1;
+ if (c2 == Float.class) return 6 - 1;
+ if (c2 == Short.class) return 2 - 1;
+ if (c2 == BigDecimal.class) return 8 - 1;
+ if (c2 == BigInteger.class) return 5 - 1;
+ return 0;
+ }
+ if (c1 == Short.class) {
+ if (c2 == Integer.class) return 3 - 2;
+ if (c2 == Long.class) return 4 - 2;
+ if (c2 == Double.class) return 7 - 2;
+ if (c2 == Float.class) return 6 - 2;
+ if (c2 == Byte.class) return 1 - 2;
+ if (c2 == BigDecimal.class) return 8 - 2;
+ if (c2 == BigInteger.class) return 5 - 2;
+ return 0;
+ }
+ if (c1 == BigDecimal.class) {
+ if (c2 == Integer.class) return 3 - 8;
+ if (c2 == Long.class) return 4 - 8;
+ if (c2 == Double.class) return 7 - 8;
+ if (c2 == Float.class) return 6 - 8;
+ if (c2 == Byte.class) return 1 - 8;
+ if (c2 == Short.class) return 2 - 8;
+ if (c2 == BigInteger.class) return 5 - 8;
+ return 0;
+ }
+ if (c1 == BigInteger.class) {
+ if (c2 == Integer.class) return 3 - 5;
+ if (c2 == Long.class) return 4 - 5;
+ if (c2 == Double.class) return 7 - 5;
+ if (c2 == Float.class) return 6 - 5;
+ if (c2 == Byte.class) return 1 - 5;
+ if (c2 == Short.class) return 2 - 5;
+ if (c2 == BigDecimal.class) return 8 - 5;
+ return 0;
+ }
+ return 0;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ReflectionCallableMemberDescriptor.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ReflectionCallableMemberDescriptor.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ReflectionCallableMemberDescriptor.java
index eb2ade5..afa1cb1 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ReflectionCallableMemberDescriptor.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ReflectionCallableMemberDescriptor.java
@@ -64,7 +64,7 @@ final class ReflectionCallableMemberDescriptor extends CallableMemberDescriptor
@Override
String getDeclaration() {
- return _MethodUtil.toString(member);
+ return _MethodUtils.toString(member);
}
@Override
@@ -79,7 +79,7 @@ final class ReflectionCallableMemberDescriptor extends CallableMemberDescriptor
@Override
boolean isVarargs() {
- return _MethodUtil.isVarargs(member);
+ return _MethodUtils.isVarargs(member);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/RestrictedObjectWrapper.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/RestrictedObjectWrapper.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/RestrictedObjectWrapper.java
index 12ac9e0..c655b93 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/RestrictedObjectWrapper.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/RestrictedObjectWrapper.java
@@ -83,14 +83,14 @@ public class RestrictedObjectWrapper extends DefaultObjectWrapper {
throw new IllegalStateException("build() can only be executed once.");
}
- RestrictedObjectWrapper singleton = DefaultObjectWrapperTCCLSingletonUtil.getSingleton(
+ RestrictedObjectWrapper singleton = DefaultObjectWrapperTCCLSingletonUtils.getSingleton(
this, INSTANCE_CACHE, INSTANCE_CACHE_REF_QUEUE, ConstructorInvoker.INSTANCE);
alreadyBuilt = true;
return singleton;
}
private static class ConstructorInvoker
- implements DefaultObjectWrapperTCCLSingletonUtil._ConstructorInvoker<RestrictedObjectWrapper, Builder> {
+ implements DefaultObjectWrapperTCCLSingletonUtils._ConstructorInvoker<RestrictedObjectWrapper, Builder> {
private static final ConstructorInvoker INSTANCE = new ConstructorInvoker();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleJavaMethodModel.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleJavaMethodModel.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleJavaMethodModel.java
index d27d131..6438596 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleJavaMethodModel.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleJavaMethodModel.java
@@ -72,7 +72,7 @@ public final class SimpleJavaMethodModel extends SimpleMethod implements JavaMet
} catch (TemplateModelException e) {
throw e;
} catch (Exception e) {
- throw _MethodUtil.newInvocationTemplateModelException(object, getMember(), e);
+ throw _MethodUtils.newInvocationTemplateModelException(object, getMember(), e);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleMethod.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleMethod.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleMethod.java
index cebcaf8..b1d756c 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleMethod.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/SimpleMethod.java
@@ -30,7 +30,7 @@ import org.apache.freemarker.core.model.ObjectWrapperAndUnwrapper;
import org.apache.freemarker.core.model.TemplateMarkupOutputModel;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
/**
* This class is used as a base for non-overloaded method models and for constructors.
@@ -54,19 +54,19 @@ class SimpleMethod {
if (args == null) {
args = _CallableUtils.EMPTY_TEMPLATE_MODEL_ARRAY;
}
- boolean isVarArg = _MethodUtil.isVarargs(member);
+ boolean isVarArg = _MethodUtils.isVarargs(member);
int typesLen = argTypes.length;
if (isVarArg) {
if (typesLen - 1 > args.length) {
throw new _TemplateModelException(
- _MethodUtil.invocationErrorMessageStart(member),
+ _MethodUtils.invocationErrorMessageStart(member),
" takes at least ", typesLen - 1,
typesLen - 1 == 1 ? " argument" : " arguments", ", but ",
args.length, " was given.");
}
} else if (typesLen != args.length) {
throw new _TemplateModelException(
- _MethodUtil.invocationErrorMessageStart(member),
+ _MethodUtils.invocationErrorMessageStart(member),
" takes ", typesLen, typesLen == 1 ? " argument" : " arguments", ", but ",
args.length, " was given.");
}
@@ -148,9 +148,9 @@ class SimpleMethod {
private TemplateModelException createArgumentTypeMismatchException(
int argIdx, TemplateModel argVal, Class<?> targetType) {
_ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
- _MethodUtil.invocationErrorMessageStart(member), " couldn't be called: Can't convert the ",
+ _MethodUtils.invocationErrorMessageStart(member), " couldn't be called: Can't convert the ",
new _DelayedOrdinal(argIdx + 1),
- " argument's value to the target Java type, ", _ClassUtil.getShortClassName(targetType),
+ " argument's value to the target Java type, ", _ClassUtils.getShortClassName(targetType),
". The type of the actual value was: ", new _DelayedFTLTypeDescription(argVal));
if (argVal instanceof TemplateMarkupOutputModel && (targetType.isAssignableFrom(String.class))) {
desc.tip(MARKUP_OUTPUT_TO_STRING_TIP);
@@ -160,9 +160,9 @@ class SimpleMethod {
private TemplateModelException createNullToPrimitiveArgumentException(int argIdx, Class<?> targetType) {
return new _TemplateModelException(
- _MethodUtil.invocationErrorMessageStart(member), " couldn't be called: The value of the ",
+ _MethodUtils.invocationErrorMessageStart(member), " couldn't be called: The value of the ",
new _DelayedOrdinal(argIdx + 1),
- " argument was null, but the target Java parameter type (", _ClassUtil.getShortClassName(targetType),
+ " argument was null, but the target Java parameter type (", _ClassUtils.getShortClassName(targetType),
") is primitive and so can't store null.");
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/UnsafeMethods.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/UnsafeMethods.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/UnsafeMethods.java
index 1b6d246..f1b54bf 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/UnsafeMethods.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/UnsafeMethods.java
@@ -29,7 +29,7 @@ import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -80,7 +80,7 @@ class UnsafeMethods {
NoSuchMethodException {
int brace = methodSpec.indexOf('(');
int dot = methodSpec.lastIndexOf('.', brace);
- Class clazz = _ClassUtil.forName(methodSpec.substring(0, dot));
+ Class clazz = _ClassUtils.forName(methodSpec.substring(0, dot));
String methodName = methodSpec.substring(dot + 1, brace);
String argSpec = methodSpec.substring(brace + 1, methodSpec.length() - 1);
StringTokenizer tok = new StringTokenizer(argSpec, ",");
@@ -90,7 +90,7 @@ class UnsafeMethods {
String argClassName = tok.nextToken();
argTypes[i] = (Class) primClasses.get(argClassName);
if (argTypes[i] == null) {
- argTypes[i] = _ClassUtil.forName(argClassName);
+ argTypes[i] = _ClassUtils.forName(argClassName);
}
}
return clazz.getMethod(methodName, argTypes);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtil.java
deleted file mode 100644
index 004ebaa..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/_MethodUtil.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.freemarker.core.model.impl;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.freemarker.core._DelayedConversionToString;
-import org.apache.freemarker.core._DelayedJQuote;
-import org.apache.freemarker.core._TemplateModelException;
-import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._ClassUtil;
-
-/**
- * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
- */
-public final class _MethodUtil {
-
- private _MethodUtil() {
- // Not meant to be instantiated
- }
-
- /**
- * Determines whether the type given as the 1st argument is convertible to the type given as the 2nd argument
- * for method call argument conversion. This follows the rules of the Java reflection-based method call, except
- * that since we don't have the value here, a boxed class is never seen as convertible to a primitive type.
- *
- * @return 0 means {@code false}, non-0 means {@code true}.
- * That is, 0 is returned less specificity or incomparable specificity, also when if
- * then method was aborted because of {@code ifHigherThan}.
- * The absolute value of the returned non-0 number symbolizes how more specific it is:
- * <ul>
- * <li>1: The two classes are identical</li>
- * <li>2: The 1st type is primitive, the 2nd type is the corresponding boxing class</li>
- * <li>3: Both classes are numerical, and one is convertible into the other with widening conversion.
- * E.g., {@code int} is convertible to {@code long} and {#code double}, hence {@code int} is more
- * specific.
- * This ignores primitive VS boxed mismatches, except that a boxed class is never seen as
- * convertible to a primitive class.</li>
- * <li>4: One class is {@code instanceof} of the other, but they aren't identical.
- * But unlike in Java, primitive numerical types are {@code instanceof} {@link Number} here.</li>
- * </ul>
- */
- // TODO Seems that we don't use the full functionality of this anymore, so we could simplify this. See usages.
- static int isMoreOrSameSpecificParameterType(final Class<?> specific, final Class<?> generic, boolean bugfixed,
- int ifHigherThan) {
- if (ifHigherThan >= 4) return 0;
- if (generic.isAssignableFrom(specific)) {
- // Identity or widening reference conversion:
- return generic == specific ? 1 : 4;
- } else {
- final boolean specificIsPrim = specific.isPrimitive();
- final boolean genericIsPrim = generic.isPrimitive();
- if (specificIsPrim) {
- if (genericIsPrim) {
- if (ifHigherThan >= 3) return 0;
- return isWideningPrimitiveNumberConversion(specific, generic) ? 3 : 0;
- } else { // => specificIsPrim && !genericIsPrim
- if (bugfixed) {
- final Class<?> specificAsBoxed = _ClassUtil.primitiveClassToBoxingClass(specific);
- if (specificAsBoxed == generic) {
- // A primitive class is more specific than its boxing class, because it can't store null
- return 2;
- } else if (generic.isAssignableFrom(specificAsBoxed)) {
- // Note: This only occurs if `specific` is a primitive numerical, and `generic == Number`
- return 4;
- } else if (ifHigherThan >= 3) {
- return 0;
- } else if (Number.class.isAssignableFrom(specificAsBoxed)
- && Number.class.isAssignableFrom(generic)) {
- return isWideningBoxedNumberConversion(specificAsBoxed, generic) ? 3 : 0;
- } else {
- return 0;
- }
- } else {
- return 0;
- }
- }
- } else { // => !specificIsPrim
- if (ifHigherThan >= 3) return 0;
- if (bugfixed && !genericIsPrim
- && Number.class.isAssignableFrom(specific) && Number.class.isAssignableFrom(generic)) {
- return isWideningBoxedNumberConversion(specific, generic) ? 3 : 0;
- } else {
- return 0;
- }
- }
- } // of: !generic.isAssignableFrom(specific)
- }
-
- private static boolean isWideningPrimitiveNumberConversion(final Class<?> source, final Class<?> target) {
- if (target == Short.TYPE && (source == Byte.TYPE)) {
- return true;
- } else if (target == Integer.TYPE &&
- (source == Short.TYPE || source == Byte.TYPE)) {
- return true;
- } else if (target == Long.TYPE &&
- (source == Integer.TYPE || source == Short.TYPE ||
- source == Byte.TYPE)) {
- return true;
- } else if (target == Float.TYPE &&
- (source == Long.TYPE || source == Integer.TYPE ||
- source == Short.TYPE || source == Byte.TYPE)) {
- return true;
- } else if (target == Double.TYPE &&
- (source == Float.TYPE || source == Long.TYPE ||
- source == Integer.TYPE || source == Short.TYPE ||
- source == Byte.TYPE)) {
- return true;
- } else {
- return false;
- }
- }
-
- private static boolean isWideningBoxedNumberConversion(final Class<?> source, final Class<?> target) {
- if (target == Short.class && source == Byte.class) {
- return true;
- } else if (target == Integer.class &&
- (source == Short.class || source == Byte.class)) {
- return true;
- } else if (target == Long.class &&
- (source == Integer.class || source == Short.class ||
- source == Byte.class)) {
- return true;
- } else if (target == Float.class &&
- (source == Long.class || source == Integer.class ||
- source == Short.class || source == Byte.class)) {
- return true;
- } else if (target == Double.class &&
- (source == Float.class || source == Long.class ||
- source == Integer.class || source == Short.class ||
- source == Byte.class)) {
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Attention, this doesn't handle primitive classes correctly, nor numerical conversions.
- */
- static Set<Class<?>> getAssignables(Class<?> c1, Class<?> c2) {
- Set<Class<?>> s = new HashSet<>();
- collectAssignables(c1, c2, s);
- return s;
- }
-
- private static void collectAssignables(Class<?> c1, Class<?> c2, Set<Class<?>> s) {
- if (c1.isAssignableFrom(c2)) {
- s.add(c1);
- }
- Class<?> sc = c1.getSuperclass();
- if (sc != null) {
- collectAssignables(sc, c2, s);
- }
- Class<?>[] itf = c1.getInterfaces();
- for (Class<?> anItf : itf) {
- collectAssignables(anItf, c2, s);
- }
- }
-
- public static Class<?>[] getParameterTypes(Member member) {
- if (member instanceof Method) {
- return ((Method) member).getParameterTypes();
- }
- if (member instanceof Constructor<?>) {
- return ((Constructor<?>) member).getParameterTypes();
- }
- throw new IllegalArgumentException("\"member\" must be Method or Constructor");
- }
-
- static boolean isVarargs(Member member) {
- if (member instanceof Method) {
- return ((Method) member).isVarArgs();
- }
- if (member instanceof Constructor) {
- return ((Constructor<?>) member).isVarArgs();
- }
- throw new BugException();
- }
-
- /**
- * Returns a more streamlined method or constructor description than {@code Member.toString()} does.
- */
- public static String toString(Member member) {
- if (!(member instanceof Method || member instanceof Constructor)) {
- throw new IllegalArgumentException("\"member\" must be a Method or Constructor");
- }
-
- StringBuilder sb = new StringBuilder();
-
- if ((member.getModifiers() & Modifier.STATIC) != 0) {
- sb.append("static ");
- }
-
- String className = _ClassUtil.getShortClassName(member.getDeclaringClass());
- if (className != null) {
- sb.append(className);
- sb.append('.');
- }
- sb.append(member.getName());
-
- sb.append('(');
- Class<?>[] paramTypes = _MethodUtil.getParameterTypes(member);
- for (int i = 0; i < paramTypes.length; i++) {
- if (i != 0) sb.append(", ");
- String paramTypeDecl = _ClassUtil.getShortClassName(paramTypes[i]);
- if (i == paramTypes.length - 1 && paramTypeDecl.endsWith("[]") && _MethodUtil.isVarargs(member)) {
- sb.append(paramTypeDecl.substring(0, paramTypeDecl.length() - 2));
- sb.append("...");
- } else {
- sb.append(paramTypeDecl);
- }
- }
- sb.append(')');
-
- return sb.toString();
- }
-
- static Object[] invocationErrorMessageStart(Member member) {
- return invocationErrorMessageStart(member, member instanceof Constructor);
- }
-
- private static Object[] invocationErrorMessageStart(Object member, boolean isConstructor) {
- return new Object[] { "Java ", isConstructor ? "constructor " : "method ", new _DelayedJQuote(member) };
- }
-
- static TemplateModelException newInvocationTemplateModelException(Object object, Member member, Throwable e) {
- return newInvocationTemplateModelException(
- object,
- member,
- (member.getModifiers() & Modifier.STATIC) != 0,
- member instanceof Constructor,
- e);
- }
-
- static TemplateModelException newInvocationTemplateModelException(Object object, CallableMemberDescriptor callableMemberDescriptor, Throwable e) {
- return newInvocationTemplateModelException(
- object,
- new _DelayedConversionToString(callableMemberDescriptor) {
- @Override
- protected String doConversion(Object callableMemberDescriptor) {
- return ((CallableMemberDescriptor) callableMemberDescriptor).getDeclaration();
- }
- },
- callableMemberDescriptor.isStatic(),
- callableMemberDescriptor.isConstructor(),
- e);
- }
-
- private static TemplateModelException newInvocationTemplateModelException(
- Object parentObject, Object member, boolean isStatic, boolean isConstructor, Throwable e) {
- while (e instanceof InvocationTargetException) {
- Throwable cause = ((InvocationTargetException) e).getTargetException();
- if (cause != null) {
- e = cause;
- } else {
- break;
- }
- }
-
- return new _TemplateModelException(e,
- invocationErrorMessageStart(member, isConstructor),
- " threw an exception",
- isStatic || isConstructor ? "" : new Object[] {
- " when invoked on ", parentObject.getClass(), " object ", new _DelayedJQuote(parentObject)
- },
- "; see cause exception in the Java stack trace.");
- }
-
- /**
- * Extracts the JavaBeans property from a reader method name, or returns {@code null} if the method name doesn't
- * look like a reader method name.
- */
- static String getBeanPropertyNameFromReaderMethodName(String name, Class<?> returnType) {
- int start;
- if (name.startsWith("get")) {
- start = 3;
- } else if (returnType == boolean.class && name.startsWith("is")) {
- start = 2;
- } else {
- return null;
- }
- int ln = name.length();
-
- if (start == ln) {
- return null;
- }
- char c1 = name.charAt(start);
-
- return start + 1 < ln && Character.isUpperCase(name.charAt(start + 1)) && Character.isUpperCase(c1)
- ? name.substring(start) // getFOOBar => "FOOBar" (not lower case) according the JavaBeans spec.
- : new StringBuilder(ln - start).append(Character.toLowerCase(c1)).append(name, start + 1, ln)
- .toString();
- }
-
-}
\ No newline at end of file
[04/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtil.java
deleted file mode 100644
index 57ba42c..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtil.java
+++ /dev/null
@@ -1,1625 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.io.Writer;
-import java.nio.charset.Charset;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.regex.Pattern;
-
-import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.Template;
-import org.apache.freemarker.core.Version;
-
-/** Don't use this; used internally by FreeMarker, might changes without notice. */
-public class _StringUtil {
-
- private static final char[] LT = new char[] { '&', 'l', 't', ';' };
- private static final char[] GT = new char[] { '&', 'g', 't', ';' };
- private static final char[] AMP = new char[] { '&', 'a', 'm', 'p', ';' };
- private static final char[] QUOT = new char[] { '&', 'q', 'u', 'o', 't', ';' };
- private static final char[] HTML_APOS = new char[] { '&', '#', '3', '9', ';' };
- private static final char[] XML_APOS = new char[] { '&', 'a', 'p', 'o', 's', ';' };
-
- /**
- * XML Encoding.
- * Replaces all '>' '<' '&', "'" and '"' with entity reference
- */
- public static String XMLEnc(String s) {
- return XMLOrHTMLEnc(s, true, true, XML_APOS);
- }
-
- /**
- * Like {@link #XMLEnc(String)}, but writes the result into a {@link Writer}.
- */
- public static void XMLEnc(String s, Writer out) throws IOException {
- XMLOrHTMLEnc(s, XML_APOS, out);
- }
-
- /**
- * XHTML Encoding.
- * Replaces all '>' '<' '&', "'" and '"' with entity reference
- * suitable for XHTML decoding in common user agents (including legacy
- * user agents, which do not decode "&apos;" to "'", so "&#39;" is used
- * instead [see http://www.w3.org/TR/xhtml1/#C_16])
- */
- public static String XHTMLEnc(String s) {
- return XMLOrHTMLEnc(s, true, true, HTML_APOS);
- }
-
- /**
- * Like {@link #XHTMLEnc(String)}, but writes the result into a {@link Writer}.
- */
- public static void XHTMLEnc(String s, Writer out) throws IOException {
- XMLOrHTMLEnc(s, HTML_APOS, out);
- }
-
- private static String XMLOrHTMLEnc(String s, boolean escGT, boolean escQuot, char[] apos) {
- final int ln = s.length();
-
- // First we find out if we need to escape, and if so, what the length of the output will be:
- int firstEscIdx = -1;
- int lastEscIdx = 0;
- int plusOutLn = 0;
- for (int i = 0; i < ln; i++) {
- escape: do {
- final char c = s.charAt(i);
- switch (c) {
- case '<':
- plusOutLn += LT.length - 1;
- break;
- case '>':
- if (!(escGT || maybeCDataEndGT(s, i))) {
- break escape;
- }
- plusOutLn += GT.length - 1;
- break;
- case '&':
- plusOutLn += AMP.length - 1;
- break;
- case '"':
- if (!escQuot) {
- break escape;
- }
- plusOutLn += QUOT.length - 1;
- break;
- case '\'': // apos
- if (apos == null) {
- break escape;
- }
- plusOutLn += apos.length - 1;
- break;
- default:
- break escape;
- }
-
- if (firstEscIdx == -1) {
- firstEscIdx = i;
- }
- lastEscIdx = i;
- } while (false);
- }
-
- if (firstEscIdx == -1) {
- return s; // Nothing to escape
- } else {
- final char[] esced = new char[ln + plusOutLn];
- if (firstEscIdx != 0) {
- s.getChars(0, firstEscIdx, esced, 0);
- }
- int dst = firstEscIdx;
- scan: for (int i = firstEscIdx; i <= lastEscIdx; i++) {
- final char c = s.charAt(i);
- switch (c) {
- case '<':
- dst = shortArrayCopy(LT, esced, dst);
- continue scan;
- case '>':
- if (!(escGT || maybeCDataEndGT(s, i))) {
- break;
- }
- dst = shortArrayCopy(GT, esced, dst);
- continue scan;
- case '&':
- dst = shortArrayCopy(AMP, esced, dst);
- continue scan;
- case '"':
- if (!escQuot) {
- break;
- }
- dst = shortArrayCopy(QUOT, esced, dst);
- continue scan;
- case '\'': // apos
- if (apos == null) {
- break;
- }
- dst = shortArrayCopy(apos, esced, dst);
- continue scan;
- }
- esced[dst++] = c;
- }
- if (lastEscIdx != ln - 1) {
- s.getChars(lastEscIdx + 1, ln, esced, dst);
- }
-
- return String.valueOf(esced);
- }
- }
-
- private static boolean maybeCDataEndGT(String s, int i) {
- if (i == 0) return true;
- if (s.charAt(i - 1) != ']') return false;
- return i == 1 || s.charAt(i - 2) == ']';
- }
-
- private static void XMLOrHTMLEnc(String s, char[] apos, Writer out) throws IOException {
- int writtenEnd = 0; // exclusive end
- int ln = s.length();
- for (int i = 0; i < ln; i++) {
- char c = s.charAt(i);
- if (c == '<' || c == '>' || c == '&' || c == '"' || c == '\'') {
- int flushLn = i - writtenEnd;
- if (flushLn != 0) {
- out.write(s, writtenEnd, flushLn);
- }
- writtenEnd = i + 1;
-
- switch (c) {
- case '<': out.write(LT); break;
- case '>': out.write(GT); break;
- case '&': out.write(AMP); break;
- case '"': out.write(QUOT); break;
- default: out.write(apos); break;
- }
- }
- }
- if (writtenEnd < ln) {
- out.write(s, writtenEnd, ln - writtenEnd);
- }
- }
-
- /**
- * For efficiently copying very short char arrays.
- */
- private static int shortArrayCopy(char[] src, char[] dst, int dstOffset) {
- for (char aSrc : src) {
- dst[dstOffset++] = aSrc;
- }
- return dstOffset;
- }
-
- /**
- * XML encoding without replacing apostrophes.
- * @see #XMLEnc(String)
- */
- public static String XMLEncNA(String s) {
- return XMLOrHTMLEnc(s, true, true, null);
- }
-
- /**
- * XML encoding for attribute values quoted with <tt>"</tt> (not with <tt>'</tt>!).
- * Also can be used for HTML attributes that are quoted with <tt>"</tt>.
- * @see #XMLEnc(String)
- */
- public static String XMLEncQAttr(String s) {
- return XMLOrHTMLEnc(s, false, true, null);
- }
-
- /**
- * XML encoding without replacing apostrophes and quotation marks and
- * greater-thans (except in {@code ]]>}).
- * @see #XMLEnc(String)
- */
- public static String XMLEncNQG(String s) {
- return XMLOrHTMLEnc(s, false, false, null);
- }
-
- /**
- * Rich Text Format encoding (does not replace line breaks).
- * Escapes all '\' '{' '}'.
- */
- public static String RTFEnc(String s) {
- int ln = s.length();
-
- // First we find out if we need to escape, and if so, what the length of the output will be:
- int firstEscIdx = -1;
- int lastEscIdx = 0;
- int plusOutLn = 0;
- for (int i = 0; i < ln; i++) {
- char c = s.charAt(i);
- if (c == '{' || c == '}' || c == '\\') {
- if (firstEscIdx == -1) {
- firstEscIdx = i;
- }
- lastEscIdx = i;
- plusOutLn++;
- }
- }
-
- if (firstEscIdx == -1) {
- return s; // Nothing to escape
- } else {
- char[] esced = new char[ln + plusOutLn];
- if (firstEscIdx != 0) {
- s.getChars(0, firstEscIdx, esced, 0);
- }
- int dst = firstEscIdx;
- for (int i = firstEscIdx; i <= lastEscIdx; i++) {
- char c = s.charAt(i);
- if (c == '{' || c == '}' || c == '\\') {
- esced[dst++] = '\\';
- }
- esced[dst++] = c;
- }
- if (lastEscIdx != ln - 1) {
- s.getChars(lastEscIdx + 1, ln, esced, dst);
- }
-
- return String.valueOf(esced);
- }
- }
-
- /**
- * Like {@link #RTFEnc(String)}, but writes the result into a {@link Writer}.
- */
- public static void RTFEnc(String s, Writer out) throws IOException {
- int writtenEnd = 0; // exclusive end
- int ln = s.length();
- for (int i = 0; i < ln; i++) {
- char c = s.charAt(i);
- if (c == '{' || c == '}' || c == '\\') {
- int flushLn = i - writtenEnd;
- if (flushLn != 0) {
- out.write(s, writtenEnd, flushLn);
- }
- out.write('\\');
- writtenEnd = i; // Not i + 1, so c will be written out later
- }
- }
- if (writtenEnd < ln) {
- out.write(s, writtenEnd, ln - writtenEnd);
- }
- }
-
-
- /**
- * URL encoding (like%20this) for query parameter values, path <em>segments</em>, fragments; this encodes all
- * characters that are reserved anywhere.
- */
- public static String URLEnc(String s, Charset charset) throws UnsupportedEncodingException {
- return URLEnc(s, charset, false);
- }
-
- /**
- * Like {@link #URLEnc(String, Charset)} but doesn't escape the slash character ({@code /}).
- * This can be used to encode a path only if you know that no folder or file name will contain {@code /}
- * character (not in the path, but in the name itself), which usually stands, as the commonly used OS-es don't
- * allow that.
- */
- public static String URLPathEnc(String s, Charset charset) throws UnsupportedEncodingException {
- return URLEnc(s, charset, true);
- }
-
- private static String URLEnc(String s, Charset charset, boolean keepSlash)
- throws UnsupportedEncodingException {
- int ln = s.length();
- int i;
- for (i = 0; i < ln; i++) {
- char c = s.charAt(i);
- if (!safeInURL(c, keepSlash)) {
- break;
- }
- }
- if (i == ln) {
- // Nothing to escape
- return s;
- }
-
- StringBuilder b = new StringBuilder(ln + ln / 3 + 2);
- b.append(s.substring(0, i));
-
- int encStart = i;
- for (i++; i < ln; i++) {
- char c = s.charAt(i);
- if (safeInURL(c, keepSlash)) {
- if (encStart != -1) {
- byte[] o = s.substring(encStart, i).getBytes(charset);
- for (byte bc : o) {
- b.append('%');
- int c1 = bc & 0x0F;
- int c2 = (bc >> 4) & 0x0F;
- b.append((char) (c2 < 10 ? c2 + '0' : c2 - 10 + 'A'));
- b.append((char) (c1 < 10 ? c1 + '0' : c1 - 10 + 'A'));
- }
- encStart = -1;
- }
- b.append(c);
- } else {
- if (encStart == -1) {
- encStart = i;
- }
- }
- }
- if (encStart != -1) {
- byte[] o = s.substring(encStart, i).getBytes(charset);
- for (byte bc : o) {
- b.append('%');
- int c1 = bc & 0x0F;
- int c2 = (bc >> 4) & 0x0F;
- b.append((char) (c2 < 10 ? c2 + '0' : c2 - 10 + 'A'));
- b.append((char) (c1 < 10 ? c1 + '0' : c1 - 10 + 'A'));
- }
- }
-
- return b.toString();
- }
-
- private static boolean safeInURL(char c, boolean keepSlash) {
- return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
- || c >= '0' && c <= '9'
- || c == '_' || c == '-' || c == '.' || c == '!' || c == '~'
- || c >= '\'' && c <= '*'
- || keepSlash && c == '/';
- }
-
- public static Locale deduceLocale(String input) {
- if (input == null) return null;
- Locale locale = Locale.getDefault();
- if (input.length() > 0 && input.charAt(0) == '"') input = input.substring(1, input.length() - 1);
- StringTokenizer st = new StringTokenizer(input, ",_ ");
- String lang = "", country = "";
- if (st.hasMoreTokens()) {
- lang = st.nextToken();
- }
- if (st.hasMoreTokens()) {
- country = st.nextToken();
- }
- if (!st.hasMoreTokens()) {
- locale = new Locale(lang, country);
- } else {
- locale = new Locale(lang, country, st.nextToken());
- }
- return locale;
- }
-
- public static String capitalize(String s) {
- StringTokenizer st = new StringTokenizer(s, " \t\r\n", true);
- StringBuilder buf = new StringBuilder(s.length());
- while (st.hasMoreTokens()) {
- String tok = st.nextToken();
- buf.append(tok.substring(0, 1).toUpperCase());
- buf.append(tok.substring(1).toLowerCase());
- }
- return buf.toString();
- }
-
- public static boolean getYesNo(String s) {
- if (s.startsWith("\"")) {
- s = s.substring(1, s.length() - 1);
-
- }
- if (s.equalsIgnoreCase("n")
- || s.equalsIgnoreCase("no")
- || s.equalsIgnoreCase("f")
- || s.equalsIgnoreCase("false")) {
- return false;
- } else if (s.equalsIgnoreCase("y")
- || s.equalsIgnoreCase("yes")
- || s.equalsIgnoreCase("t")
- || s.equalsIgnoreCase("true")) {
- return true;
- }
- throw new IllegalArgumentException("Illegal boolean value: " + s);
- }
-
- /**
- * Splits a string at the specified character.
- */
- public static String[] split(String s, char c) {
- int i, b, e;
- int cnt;
- String res[];
- int ln = s.length();
-
- i = 0;
- cnt = 1;
- while ((i = s.indexOf(c, i)) != -1) {
- cnt++;
- i++;
- }
- res = new String[cnt];
-
- i = 0;
- b = 0;
- while (b <= ln) {
- e = s.indexOf(c, b);
- if (e == -1) e = ln;
- res[i++] = s.substring(b, e);
- b = e + 1;
- }
- return res;
- }
-
- /**
- * Splits a string at the specified string.
- */
- public static String[] split(String s, String sep, boolean caseInsensitive) {
- String splitString = caseInsensitive ? sep.toLowerCase() : sep;
- String input = caseInsensitive ? s.toLowerCase() : s;
- int i, b, e;
- int cnt;
- String res[];
- int ln = s.length();
- int sln = sep.length();
-
- if (sln == 0) throw new IllegalArgumentException(
- "The separator string has 0 length");
-
- i = 0;
- cnt = 1;
- while ((i = input.indexOf(splitString, i)) != -1) {
- cnt++;
- i += sln;
- }
- res = new String[cnt];
-
- i = 0;
- b = 0;
- while (b <= ln) {
- e = input.indexOf(splitString, b);
- if (e == -1) e = ln;
- res[i++] = s.substring(b, e);
- b = e + sln;
- }
- return res;
- }
-
- /**
- * Same as {@link #replace(String, String, String, boolean, boolean)} with two {@code false} parameters.
- */
- public static String replace(String text, String oldSub, String newSub) {
- return replace(text, oldSub, newSub, false, false);
- }
-
- /**
- * Replaces all occurrences of a sub-string in a string.
- * @param text The string where it will replace <code>oldSub</code> with
- * <code>newSub</code>.
- * @return String The string after the replacements.
- */
- public static String replace(String text,
- String oldSub,
- String newSub,
- boolean caseInsensitive,
- boolean firstOnly) {
- StringBuilder buf;
- int tln;
- int oln = oldSub.length();
-
- if (oln == 0) {
- int nln = newSub.length();
- if (nln == 0) {
- return text;
- } else {
- if (firstOnly) {
- return newSub + text;
- } else {
- tln = text.length();
- buf = new StringBuilder(tln + (tln + 1) * nln);
- buf.append(newSub);
- for (int i = 0; i < tln; i++) {
- buf.append(text.charAt(i));
- buf.append(newSub);
- }
- return buf.toString();
- }
- }
- } else {
- oldSub = caseInsensitive ? oldSub.toLowerCase() : oldSub;
- String input = caseInsensitive ? text.toLowerCase() : text;
- int e = input.indexOf(oldSub);
- if (e == -1) {
- return text;
- }
- int b = 0;
- tln = text.length();
- buf = new StringBuilder(
- tln + Math.max(newSub.length() - oln, 0) * 3);
- do {
- buf.append(text.substring(b, e));
- buf.append(newSub);
- b = e + oln;
- e = input.indexOf(oldSub, b);
- } while (e != -1 && !firstOnly);
- buf.append(text.substring(b));
- return buf.toString();
- }
- }
-
- /**
- * Removes a line-break from the end of the string (if there's any).
- */
- public static String chomp(String s) {
- if (s.endsWith("\r\n")) return s.substring(0, s.length() - 2);
- if (s.endsWith("\r") || s.endsWith("\n"))
- return s.substring(0, s.length() - 1);
- return s;
- }
-
- /**
- * Converts a 0-length string to null, leaves the string as is otherwise.
- * @param s maybe {@code null}.
- */
- public static String emptyToNull(String s) {
- if (s == null) return null;
- return s.length() == 0 ? null : s;
- }
-
- /**
- * Converts the parameter with <code>toString</code> (if it's not <code>null</code>) and passes it to
- * {@link #jQuote(String)}.
- */
- public static String jQuote(Object obj) {
- return jQuote(obj != null ? obj.toString() : null);
- }
-
- /**
- * Quotes string as Java Language string literal.
- * Returns string <code>"null"</code> if <code>s</code>
- * is <code>null</code>.
- */
- public static String jQuote(String s) {
- if (s == null) {
- return "null";
- }
- int ln = s.length();
- StringBuilder b = new StringBuilder(ln + 4);
- b.append('"');
- for (int i = 0; i < ln; i++) {
- char c = s.charAt(i);
- if (c == '"') {
- b.append("\\\"");
- } else if (c == '\\') {
- b.append("\\\\");
- } else if (c < 0x20) {
- if (c == '\n') {
- b.append("\\n");
- } else if (c == '\r') {
- b.append("\\r");
- } else if (c == '\f') {
- b.append("\\f");
- } else if (c == '\b') {
- b.append("\\b");
- } else if (c == '\t') {
- b.append("\\t");
- } else {
- b.append("\\u00");
- int x = c / 0x10;
- b.append(toHexDigit(x));
- x = c & 0xF;
- b.append(toHexDigit(x));
- }
- } else {
- b.append(c);
- }
- } // for each characters
- b.append('"');
- return b.toString();
- }
-
- /**
- * Converts the parameter with <code>toString</code> (if not
- * <code>null</code>)and passes it to {@link #jQuoteNoXSS(String)}.
- */
- public static String jQuoteNoXSS(Object obj) {
- return jQuoteNoXSS(obj != null ? obj.toString() : null);
- }
-
- /**
- * Same as {@link #jQuote(String)} but also escapes <code>'<'</code>
- * as <code>\</code><code>u003C</code>. This is used for log messages to prevent XSS
- * on poorly written Web-based log viewers.
- */
- public static String jQuoteNoXSS(String s) {
- if (s == null) {
- return "null";
- }
- int ln = s.length();
- StringBuilder b = new StringBuilder(ln + 4);
- b.append('"');
- for (int i = 0; i < ln; i++) {
- char c = s.charAt(i);
- if (c == '"') {
- b.append("\\\"");
- } else if (c == '\\') {
- b.append("\\\\");
- } else if (c == '<') {
- b.append("\\u003C");
- } else if (c < 0x20) {
- if (c == '\n') {
- b.append("\\n");
- } else if (c == '\r') {
- b.append("\\r");
- } else if (c == '\f') {
- b.append("\\f");
- } else if (c == '\b') {
- b.append("\\b");
- } else if (c == '\t') {
- b.append("\\t");
- } else {
- b.append("\\u00");
- int x = c / 0x10;
- b.append(toHexDigit(x));
- x = c & 0xF;
- b.append(toHexDigit(x));
- }
- } else {
- b.append(c);
- }
- } // for each characters
- b.append('"');
- return b.toString();
- }
-
- /**
- * Escapes the <code>String</code> with the escaping rules of Java language
- * string literals, so it's safe to insert the value into a string literal.
- * The resulting string will not be quoted.
- *
- * <p>All characters under UCS code point 0x20 will be escaped.
- * Where they have no dedicated escape sequence in Java, they will
- * be replaced with hexadecimal escape (<tt>\</tt><tt>u<i>XXXX</i></tt>).
- *
- * @see #jQuote(String)
- */
- public static String javaStringEnc(String s) {
- int ln = s.length();
- for (int i = 0; i < ln; i++) {
- char c = s.charAt(i);
- if (c == '"' || c == '\\' || c < 0x20) {
- StringBuilder b = new StringBuilder(ln + 4);
- b.append(s.substring(0, i));
- while (true) {
- if (c == '"') {
- b.append("\\\"");
- } else if (c == '\\') {
- b.append("\\\\");
- } else if (c < 0x20) {
- if (c == '\n') {
- b.append("\\n");
- } else if (c == '\r') {
- b.append("\\r");
- } else if (c == '\f') {
- b.append("\\f");
- } else if (c == '\b') {
- b.append("\\b");
- } else if (c == '\t') {
- b.append("\\t");
- } else {
- b.append("\\u00");
- int x = c / 0x10;
- b.append((char)
- (x < 0xA ? x + '0' : x - 0xA + 'a'));
- x = c & 0xF;
- b.append((char)
- (x < 0xA ? x + '0' : x - 0xA + 'a'));
- }
- } else {
- b.append(c);
- }
- i++;
- if (i >= ln) {
- return b.toString();
- }
- c = s.charAt(i);
- }
- } // if has to be escaped
- } // for each characters
- return s;
- }
-
- /**
- * Escapes a {@link String} to be safely insertable into a JavaScript string literal; for more see
- * {@link #jsStringEnc(String, boolean) jsStringEnc(s, false)}.
- */
- public static String javaScriptStringEnc(String s) {
- return jsStringEnc(s, false);
- }
-
- /**
- * Escapes a {@link String} to be safely insertable into a JSON string literal; for more see
- * {@link #jsStringEnc(String, boolean) jsStringEnc(s, true)}.
- */
- public static String jsonStringEnc(String s) {
- return jsStringEnc(s, true);
- }
-
- private static final int NO_ESC = 0;
- private static final int ESC_HEXA = 1;
- private static final int ESC_BACKSLASH = 3;
-
- /**
- * Escapes a {@link String} to be safely insertable into a JavaScript or a JSON string literal.
- * The resulting string will <em>not</em> be quoted; the caller must ensure that they are there in the final
- * output. Note that for JSON, the quotation marks must be {@code "}, not {@code '}, because JSON doesn't escape
- * {@code '}.
- *
- * <p>The escaping rules guarantee that if the inside of the JavaScript/JSON string literal is from one or more
- * touching pieces that were escaped with this, no character sequence can occur that closes the
- * JavaScript/JSON string literal, or has a meaning in HTML/XML that causes the HTML script section to be closed.
- * (If, however, the escaped section is preceded by or followed by strings from other sources, this can't be
- * guaranteed in some rare cases. Like <tt>x = "</${a?jsString}"</tt> might closes the "script"
- * element if {@code a} is {@code "script>"}.)
- *
- * The escaped characters are:
- *
- * <table style="width: auto; border-collapse: collapse" border="1" summary="Characters escaped by jsStringEnc">
- * <tr>
- * <th>Input
- * <th>Output
- * <tr>
- * <td><tt>"</tt>
- * <td><tt>\"</tt>
- * <tr>
- * <td><tt>'</tt> if not in JSON-mode
- * <td><tt>\'</tt>
- * <tr>
- * <td><tt>\</tt>
- * <td><tt>\\</tt>
- * <tr>
- * <td><tt>/</tt> if the method can't know that it won't be directly after <tt><</tt>
- * <td><tt>\/</tt>
- * <tr>
- * <td><tt>></tt> if the method can't know that it won't be directly after <tt>]]</tt> or <tt>--</tt>
- * <td>JavaScript: <tt>\></tt>; JSON: <tt>\</tt><tt>u003E</tt>
- * <tr>
- * <td><tt><</tt> if the method can't know that it won't be directly followed by <tt>!</tt> or <tt>?</tt>
- * <td><tt><tt>\</tt>u003C</tt>
- * <tr>
- * <td>
- * u0000-u001f (UNICODE control characters - disallowed by JSON)<br>
- * u007f-u009f (UNICODE control characters - disallowed by JSON)
- * <td><tt>\n</tt>, <tt>\r</tt> and such, or if there's no such dedicated escape:
- * JavaScript: <tt>\x<i>XX</i></tt>, JSON: <tt>\<tt>u</tt><i>XXXX</i></tt>
- * <tr>
- * <td>
- * u2028 (Line separator - source code line-break in ECMAScript)<br>
- * u2029 (Paragraph separator - source code line-break in ECMAScript)<br>
- * <td><tt>\<tt>u</tt><i>XXXX</i></tt>
- * </table>
- */
- public static String jsStringEnc(String s, boolean json) {
- _NullArgumentException.check("s", s);
-
- int ln = s.length();
- StringBuilder sb = null;
- for (int i = 0; i < ln; i++) {
- final char c = s.charAt(i);
- final int escapeType; //
- if (!(c > '>' && c < 0x7F && c != '\\') && c != ' ' && !(c >= 0xA0 && c < 0x2028)) { // skip common chars
- if (c <= 0x1F) { // control chars range 1
- if (c == '\n') {
- escapeType = 'n';
- } else if (c == '\r') {
- escapeType = 'r';
- } else if (c == '\f') {
- escapeType = 'f';
- } else if (c == '\b') {
- escapeType = 'b';
- } else if (c == '\t') {
- escapeType = 't';
- } else {
- escapeType = ESC_HEXA;
- }
- } else if (c == '"') {
- escapeType = ESC_BACKSLASH;
- } else if (c == '\'') {
- escapeType = json ? NO_ESC : ESC_BACKSLASH;
- } else if (c == '\\') {
- escapeType = ESC_BACKSLASH;
- } else if (c == '/' && (i == 0 || s.charAt(i - 1) == '<')) { // against closing elements
- escapeType = ESC_BACKSLASH;
- } else if (c == '>') { // against "]]> and "-->"
- final boolean dangerous;
- if (i == 0) {
- dangerous = true;
- } else {
- final char prevC = s.charAt(i - 1);
- if (prevC == ']' || prevC == '-') {
- if (i == 1) {
- dangerous = true;
- } else {
- final char prevPrevC = s.charAt(i - 2);
- dangerous = prevPrevC == prevC;
- }
- } else {
- dangerous = false;
- }
- }
- escapeType = dangerous ? (json ? ESC_HEXA : ESC_BACKSLASH) : NO_ESC;
- } else if (c == '<') { // against "<!"
- final boolean dangerous;
- if (i == ln - 1) {
- dangerous = true;
- } else {
- char nextC = s.charAt(i + 1);
- dangerous = nextC == '!' || nextC == '?';
- }
- escapeType = dangerous ? ESC_HEXA : NO_ESC;
- } else if ((c >= 0x7F && c <= 0x9F) // control chars range 2
- || (c == 0x2028 || c == 0x2029) // UNICODE line terminators
- ) {
- escapeType = ESC_HEXA;
- } else {
- escapeType = NO_ESC;
- }
-
- if (escapeType != NO_ESC) { // If needs escaping
- if (sb == null) {
- sb = new StringBuilder(ln + 6);
- sb.append(s.substring(0, i));
- }
-
- sb.append('\\');
- if (escapeType > 0x20) {
- sb.append((char) escapeType);
- } else if (escapeType == ESC_HEXA) {
- if (!json && c < 0x100) {
- sb.append('x');
- sb.append(toHexDigit(c >> 4));
- sb.append(toHexDigit(c & 0xF));
- } else {
- sb.append('u');
- sb.append(toHexDigit((c >> 12) & 0xF));
- sb.append(toHexDigit((c >> 8) & 0xF));
- sb.append(toHexDigit((c >> 4) & 0xF));
- sb.append(toHexDigit(c & 0xF));
- }
- } else { // escapeType == ESC_BACKSLASH
- sb.append(c);
- }
- continue;
- }
- // Falls through when escapeType == NO_ESC
- }
- // Needs no escaping
-
- if (sb != null) sb.append(c);
- } // for each characters
-
- return sb == null ? s : sb.toString();
- }
-
- private static char toHexDigit(int d) {
- return (char) (d < 0xA ? d + '0' : d - 0xA + 'A');
- }
-
- /**
- * Parses a name-value pair list, where the pairs are separated with comma,
- * and the name and value is separated with colon.
- * The keys and values can contain only letters, digits and <tt>_</tt>. They
- * can't be quoted. White-space around the keys and values are ignored. The
- * value can be omitted if <code>defaultValue</code> is not null. When a
- * value is omitted, then the colon after the key must be omitted as well.
- * The same key can't be used for multiple times.
- *
- * @param s the string to parse.
- * For example: <code>"strong:100, soft:900"</code>.
- * @param defaultValue the value used when the value is omitted in a
- * key-value pair.
- *
- * @return the map that contains the name-value pairs.
- *
- * @throws java.text.ParseException if the string is not a valid name-value
- * pair list.
- */
- public static Map parseNameValuePairList(String s, String defaultValue)
- throws java.text.ParseException {
- Map map = new HashMap();
-
- char c = ' ';
- int ln = s.length();
- int p = 0;
- int keyStart;
- int valueStart;
- String key;
- String value;
-
- fetchLoop: while (true) {
- // skip ws
- while (p < ln) {
- c = s.charAt(p);
- if (!Character.isWhitespace(c)) {
- break;
- }
- p++;
- }
- if (p == ln) {
- break fetchLoop;
- }
- keyStart = p;
-
- // seek key end
- while (p < ln) {
- c = s.charAt(p);
- if (!(Character.isLetterOrDigit(c) || c == '_')) {
- break;
- }
- p++;
- }
- if (keyStart == p) {
- throw new java.text.ParseException(
- "Expecting letter, digit or \"_\" "
- + "here, (the first character of the key) but found "
- + jQuote(String.valueOf(c))
- + " at position " + p + ".",
- p);
- }
- key = s.substring(keyStart, p);
-
- // skip ws
- while (p < ln) {
- c = s.charAt(p);
- if (!Character.isWhitespace(c)) {
- break;
- }
- p++;
- }
- if (p == ln) {
- if (defaultValue == null) {
- throw new java.text.ParseException(
- "Expecting \":\", but reached "
- + "the end of the string "
- + " at position " + p + ".",
- p);
- }
- value = defaultValue;
- } else if (c != ':') {
- if (defaultValue == null || c != ',') {
- throw new java.text.ParseException(
- "Expecting \":\" here, but found "
- + jQuote(String.valueOf(c))
- + " at position " + p + ".",
- p);
- }
-
- // skip ","
- p++;
-
- value = defaultValue;
- } else {
- // skip ":"
- p++;
-
- // skip ws
- while (p < ln) {
- c = s.charAt(p);
- if (!Character.isWhitespace(c)) {
- break;
- }
- p++;
- }
- if (p == ln) {
- throw new java.text.ParseException(
- "Expecting the value of the key "
- + "here, but reached the end of the string "
- + " at position " + p + ".",
- p);
- }
- valueStart = p;
-
- // seek value end
- while (p < ln) {
- c = s.charAt(p);
- if (!(Character.isLetterOrDigit(c) || c == '_')) {
- break;
- }
- p++;
- }
- if (valueStart == p) {
- throw new java.text.ParseException(
- "Expecting letter, digit or \"_\" "
- + "here, (the first character of the value) "
- + "but found "
- + jQuote(String.valueOf(c))
- + " at position " + p + ".",
- p);
- }
- value = s.substring(valueStart, p);
-
- // skip ws
- while (p < ln) {
- c = s.charAt(p);
- if (!Character.isWhitespace(c)) {
- break;
- }
- p++;
- }
-
- // skip ","
- if (p < ln) {
- if (c != ',') {
- throw new java.text.ParseException(
- "Excpecting \",\" or the end "
- + "of the string here, but found "
- + jQuote(String.valueOf(c))
- + " at position " + p + ".",
- p);
- } else {
- p++;
- }
- }
- }
-
- // store the key-value pair
- if (map.put(key, value) != null) {
- throw new java.text.ParseException(
- "Dublicated key: "
- + jQuote(key), keyStart);
- }
- }
-
- return map;
- }
-
- /**
- * @return whether the qname matches the combination of nodeName, nsURI, and environment prefix settings.
- */
- static public boolean matchesQName(String qname, String nodeName, String nsURI, Environment env) {
- String defaultNS = env.getDefaultNS();
- if ((defaultNS != null) && defaultNS.equals(nsURI)) {
- return qname.equals(nodeName)
- || qname.equals(Template.DEFAULT_NAMESPACE_PREFIX + ":" + nodeName);
- }
- if ("".equals(nsURI)) {
- if (defaultNS != null) {
- return qname.equals(Template.NO_NS_PREFIX + ":" + nodeName);
- } else {
- return qname.equals(nodeName) || qname.equals(Template.NO_NS_PREFIX + ":" + nodeName);
- }
- }
- String prefix = env.getPrefixForNamespace(nsURI);
- if (prefix == null) {
- return false; // Is this the right thing here???
- }
- return qname.equals(prefix + ":" + nodeName);
- }
-
- /**
- * Pads the string at the left with spaces until it reaches the desired
- * length. If the string is longer than this length, then it returns the
- * unchanged string.
- *
- * @param s the string that will be padded.
- * @param minLength the length to reach.
- */
- public static String leftPad(String s, int minLength) {
- return leftPad(s, minLength, ' ');
- }
-
- /**
- * Pads the string at the left with the specified character until it reaches
- * the desired length. If the string is longer than this length, then it
- * returns the unchanged string.
- *
- * @param s the string that will be padded.
- * @param minLength the length to reach.
- * @param filling the filling pattern.
- */
- public static String leftPad(String s, int minLength, char filling) {
- int ln = s.length();
- if (minLength <= ln) {
- return s;
- }
-
- StringBuilder res = new StringBuilder(minLength);
-
- int dif = minLength - ln;
- for (int i = 0; i < dif; i++) {
- res.append(filling);
- }
-
- res.append(s);
-
- return res.toString();
- }
-
- /**
- * Pads the string at the left with a filling pattern until it reaches the
- * desired length. If the string is longer than this length, then it returns
- * the unchanged string. For example: <code>leftPad('ABC', 9, '1234')</code>
- * returns <code>"123412ABC"</code>.
- *
- * @param s the string that will be padded.
- * @param minLength the length to reach.
- * @param filling the filling pattern. Must be at least 1 characters long.
- * Can't be <code>null</code>.
- */
- public static String leftPad(String s, int minLength, String filling) {
- int ln = s.length();
- if (minLength <= ln) {
- return s;
- }
-
- StringBuilder res = new StringBuilder(minLength);
-
- int dif = minLength - ln;
- int fln = filling.length();
- if (fln == 0) {
- throw new IllegalArgumentException(
- "The \"filling\" argument can't be 0 length string.");
- }
- int cnt = dif / fln;
- for (int i = 0; i < cnt; i++) {
- res.append(filling);
- }
- cnt = dif % fln;
- for (int i = 0; i < cnt; i++) {
- res.append(filling.charAt(i));
- }
-
- res.append(s);
-
- return res.toString();
- }
-
- /**
- * Pads the string at the right with spaces until it reaches the desired
- * length. If the string is longer than this length, then it returns the
- * unchanged string.
- *
- * @param s the string that will be padded.
- * @param minLength the length to reach.
- */
- public static String rightPad(String s, int minLength) {
- return rightPad(s, minLength, ' ');
- }
-
- /**
- * Pads the string at the right with the specified character until it
- * reaches the desired length. If the string is longer than this length,
- * then it returns the unchanged string.
- *
- * @param s the string that will be padded.
- * @param minLength the length to reach.
- * @param filling the filling pattern.
- */
- public static String rightPad(String s, int minLength, char filling) {
- int ln = s.length();
- if (minLength <= ln) {
- return s;
- }
-
- StringBuilder res = new StringBuilder(minLength);
-
- res.append(s);
-
- int dif = minLength - ln;
- for (int i = 0; i < dif; i++) {
- res.append(filling);
- }
-
- return res.toString();
- }
-
- /**
- * Pads the string at the right with a filling pattern until it reaches the
- * desired length. If the string is longer than this length, then it returns
- * the unchanged string. For example: <code>rightPad('ABC', 9, '1234')</code>
- * returns <code>"ABC412341"</code>. Note that the filling pattern is
- * started as if you overlay <code>"123412341"</code> with the left-aligned
- * <code>"ABC"</code>, so it starts with <code>"4"</code>.
- *
- * @param s the string that will be padded.
- * @param minLength the length to reach.
- * @param filling the filling pattern. Must be at least 1 characters long.
- * Can't be <code>null</code>.
- */
- public static String rightPad(String s, int minLength, String filling) {
- int ln = s.length();
- if (minLength <= ln) {
- return s;
- }
-
- StringBuilder res = new StringBuilder(minLength);
-
- res.append(s);
-
- int dif = minLength - ln;
- int fln = filling.length();
- if (fln == 0) {
- throw new IllegalArgumentException(
- "The \"filling\" argument can't be 0 length string.");
- }
- int start = ln % fln;
- int end = fln - start <= dif
- ? fln
- : start + dif;
- for (int i = start; i < end; i++) {
- res.append(filling.charAt(i));
- }
- dif -= end - start;
- int cnt = dif / fln;
- for (int i = 0; i < cnt; i++) {
- res.append(filling);
- }
- cnt = dif % fln;
- for (int i = 0; i < cnt; i++) {
- res.append(filling.charAt(i));
- }
-
- return res.toString();
- }
-
- /**
- * Converts a version number string to an integer for easy comparison.
- * The version number must start with numbers separated with
- * dots. There can be any number of such dot-separated numbers, but only
- * the first three will be considered. After the numbers arbitrary text can
- * follow, and will be ignored.
- *
- * The string will be trimmed before interpretation.
- *
- * @return major * 1000000 + minor * 1000 + micro
- */
- public static int versionStringToInt(String version) {
- return new Version(version).intValue();
- }
-
- /**
- * Tries to run {@code toString()}, but if that fails, returns a
- * {@code "[com.example.SomeClass.toString() failed: " + e + "]"} instead. Also, it returns {@code null} for
- * {@code null} parameter.
- */
- public static String tryToString(Object object) {
- if (object == null) return null;
-
- try {
- return object.toString();
- } catch (Throwable e) {
- return failedToStringSubstitute(object, e);
- }
- }
-
- private static String failedToStringSubstitute(Object object, Throwable e) {
- String eStr;
- try {
- eStr = e.toString();
- } catch (Throwable e2) {
- eStr = _ClassUtil.getShortClassNameOfObject(e);
- }
- return "[" + _ClassUtil.getShortClassNameOfObject(object) + ".toString() failed: " + eStr + "]";
- }
-
- /**
- * Converts {@code 1}, {@code 2}, {@code 3} and so forth to {@code "A"}, {@code "B"}, {@code "C"} and so fort. When
- * reaching {@code "Z"}, it continues like {@code "AA"}, {@code "AB"}, etc. The lowest supported number is 1, but
- * there's no upper limit.
- *
- * @throws IllegalArgumentException
- * If the argument is 0 or less.
- */
- public static String toUpperABC(int n) {
- return toABC(n, 'A');
- }
-
- /**
- * Same as {@link #toUpperABC(int)}, but produces lower case result, like {@code "ab"}.
- */
- public static String toLowerABC(int n) {
- return toABC(n, 'a');
- }
-
- /**
- * @param oneDigit
- * The character that stands for the value 1.
- */
- private static String toABC(final int n, char oneDigit) {
- if (n < 1) {
- throw new IllegalArgumentException("Can't convert 0 or negative "
- + "numbers to latin-number: " + n);
- }
-
- // First find out how many "digits" will we need. We start from A, then
- // try AA, then AAA, etc. (Note that the smallest digit is "A", which is
- // 1, not 0. Hence this isn't like a usual 26-based number-system):
- int reached = 1;
- int weight = 1;
- while (true) {
- int nextWeight = weight * 26;
- int nextReached = reached + nextWeight;
- if (nextReached <= n) {
- // So we will have one more digit
- weight = nextWeight;
- reached = nextReached;
- } else {
- // No more digits
- break;
- }
- }
-
- // Increase the digits of the place values until we get as close
- // to n as possible (but don't step over it).
- StringBuilder sb = new StringBuilder();
- while (weight != 0) {
- // digitIncrease: how many we increase the digit which is already 1
- final int digitIncrease = (n - reached) / weight;
- sb.append((char) (oneDigit + digitIncrease));
- reached += digitIncrease * weight;
-
- weight /= 26;
- }
-
- return sb.toString();
- }
-
- /**
- * Behaves exactly like {@link String#trim()}, but works on arrays. If the resulting array would have the same
- * content after trimming, it returns the original array instance. Otherwise it returns a new array instance (or
- * {@link _CollectionUtil#EMPTY_CHAR_ARRAY}).
- */
- public static char[] trim(final char[] cs) {
- if (cs.length == 0) {
- return cs;
- }
-
- int start = 0;
- int end = cs.length;
- while (start < end && cs[start] <= ' ') {
- start++;
- }
- while (start < end && cs[end - 1] <= ' ') {
- end--;
- }
-
- if (start == 0 && end == cs.length) {
- return cs;
- }
- if (start == end) {
- return _CollectionUtil.EMPTY_CHAR_ARRAY;
- }
-
- char[] newCs = new char[end - start];
- System.arraycopy(cs, start, newCs, 0, end - start);
- return newCs;
- }
-
- /**
- * Tells if {@link String#trim()} will return a 0-length string for the {@link String} equivalent of the argument.
- */
- public static boolean isTrimmableToEmpty(char[] text) {
- return isTrimmableToEmpty(text, 0, text.length);
- }
-
- /**
- * Like {@link #isTrimmableToEmpty(char[])}, but acts on a sub-array that starts at {@code start} (inclusive index).
- */
- public static boolean isTrimmableToEmpty(char[] text, int start) {
- return isTrimmableToEmpty(text, start, text.length);
- }
-
- /**
- * Like {@link #isTrimmableToEmpty(char[])}, but acts on a sub-array that starts at {@code start} (inclusive index)
- * and ends at {@code end} (exclusive index).
- */
- public static boolean isTrimmableToEmpty(char[] text, int start, int end) {
- for (int i = start; i < end; i++) {
- // We follow Java's String.trim() here, which simply states that c <= ' ' is whitespace.
- if (text[i] > ' ') {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Same as {@link #globToRegularExpression(String, boolean)} with {@code caseInsensitive} argument {@code false}.
- */
- public static Pattern globToRegularExpression(String glob) {
- return globToRegularExpression(glob, false);
- }
-
- /**
- * Creates a regular expression from a glob. The glob must use {@code /} for as file separator, not {@code \}
- * (backslash), and is always case sensitive.
- *
- * <p>This glob implementation recognizes these special characters:
- * <ul>
- * <li>{@code ?}: Wildcard that matches exactly one character, other than {@code /}
- * <li>{@code *}: Wildcard that matches zero, one or multiple characters, other than {@code /}
- * <li>{@code **}: Wildcard that matches zero, one or multiple directories. For example, {@code **}{@code /head.ftl}
- * matches {@code foo/bar/head.ftl}, {@code foo/head.ftl} and {@code head.ftl} too. {@code **} must be either
- * preceded by {@code /} or be at the beginning of the glob. {@code **} must be either followed by {@code /} or be
- * at the end of the glob. When {@code **} is at the end of the glob, it also matches file names, like
- * {@code a/**} matches {@code a/b/c.ftl}. If the glob only consist of a {@code **}, it will be a match for
- * everything.
- * <li>{@code \} (backslash): Makes the next character non-special (a literal). For example {@code How\?.ftl} will
- * match {@code How?.ftl}, but not {@code HowX.ftl}. Naturally, two backslashes produce one literal backslash.
- * <li>{@code [}: Reserved for future purposes; can't be used
- * <li><code>{</code>: Reserved for future purposes; can't be used
- * </ul>
- */
- public static Pattern globToRegularExpression(String glob, boolean caseInsensitive) {
- StringBuilder regex = new StringBuilder();
-
- int nextStart = 0;
- boolean escaped = false;
- int ln = glob.length();
- for (int idx = 0; idx < ln; idx++) {
- char c = glob.charAt(idx);
- if (!escaped) {
- if (c == '?') {
- appendLiteralGlobSection(regex, glob, nextStart, idx);
- regex.append("[^/]");
- nextStart = idx + 1;
- } else if (c == '*') {
- appendLiteralGlobSection(regex, glob, nextStart, idx);
- if (idx + 1 < ln && glob.charAt(idx + 1) == '*') {
- if (!(idx == 0 || glob.charAt(idx - 1) == '/')) {
- throw new IllegalArgumentException(
- "The \"**\" wildcard must be directly after a \"/\" or it must be at the "
- + "beginning, in this glob: " + glob);
- }
-
- if (idx + 2 == ln) { // trailing "**"
- regex.append(".*");
- idx++;
- } else { // "**/"
- if (!(idx + 2 < ln && glob.charAt(idx + 2) == '/')) {
- throw new IllegalArgumentException(
- "The \"**\" wildcard must be followed by \"/\", or must be at tehe end, "
- + "in this glob: " + glob);
- }
- regex.append("(.*?/)*");
- idx += 2; // "*/".length()
- }
- } else {
- regex.append("[^/]*");
- }
- nextStart = idx + 1;
- } else if (c == '\\') {
- escaped = true;
- } else if (c == '[' || c == '{') {
- throw new IllegalArgumentException(
- "The \"" + c + "\" glob operator is currently unsupported "
- + "(precede it with \\ for literal matching), "
- + "in this glob: " + glob);
- }
- } else {
- escaped = false;
- }
- }
- appendLiteralGlobSection(regex, glob, nextStart, glob.length());
-
- return Pattern.compile(regex.toString(), caseInsensitive ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE : 0);
- }
-
- private static void appendLiteralGlobSection(StringBuilder regex, String glob, int start, int end) {
- if (start == end) return;
- String part = unescapeLiteralGlobSection(glob.substring(start, end));
- regex.append(Pattern.quote(part));
- }
-
- private static String unescapeLiteralGlobSection(String s) {
- int backslashIdx = s.indexOf('\\');
- if (backslashIdx == -1) {
- return s;
- }
- int ln = s.length();
- StringBuilder sb = new StringBuilder(ln - 1);
- int nextStart = 0;
- do {
- sb.append(s, nextStart, backslashIdx);
- nextStart = backslashIdx + 1;
- } while ((backslashIdx = s.indexOf('\\', nextStart + 1)) != -1);
- if (nextStart < ln) {
- sb.append(s, nextStart, ln);
- }
- return sb.toString();
- }
-
- public static String toFTLIdentifierReferenceAfterDot(String name) {
- return FTLUtil.escapeIdentifier(name);
- }
-
- public static String toFTLTopLevelIdentifierReference(String name) {
- return FTLUtil.escapeIdentifier(name);
- }
-
- public static String toFTLTopLevelTragetIdentifier(final String name) {
- char quotationType = 0;
- scanForQuotationType: for (int i = 0; i < name.length(); i++) {
- final char c = name.charAt(i);
- if (!(i == 0 ? FTLUtil.isNonEscapedIdentifierStart(c) : FTLUtil.isNonEscapedIdentifierPart(c)) && c != '@') {
- if ((quotationType == 0 || quotationType == '\\') && (c == '-' || c == '.' || c == ':')) {
- quotationType = '\\';
- } else {
- quotationType = '"';
- break scanForQuotationType;
- }
- }
- }
- switch (quotationType) {
- case 0:
- return name;
- case '"':
- return FTLUtil.toStringLiteral(name);
- case '\\':
- return FTLUtil.escapeIdentifier(name);
- default:
- throw new BugException();
- }
- }
-
- public static String snakeCaseToCamelCase(String s) {
- if (s == null) {
- return null;
- }
-
- int wordEndIdx = s.indexOf('_');
- if (wordEndIdx == -1) {
- return s.toLowerCase();
- }
-
- StringBuilder sb = new StringBuilder(s.length());
- int wordStartIdx = 0;
- do {
- if (wordStartIdx < wordEndIdx) {
- char wordStartC = s.charAt(wordStartIdx);
- sb.append(sb.length() != 0 ? Character.toUpperCase(wordStartC) : Character.toLowerCase(wordStartC));
- sb.append(s.substring(wordStartIdx + 1, wordEndIdx).toLowerCase());
- }
-
- wordStartIdx = wordEndIdx + 1;
- wordEndIdx = s.indexOf('_', wordStartIdx);
- if (wordEndIdx == -1) {
- wordEndIdx = s.length();
- }
- } while (wordStartIdx < s.length());
- return sb.toString();
- }
-
- public static boolean isASCIIDigit(char c) {
- return c >= '0' && c <= '9';
- }
-
- public static boolean isUpperUSASCII(char c) {
- return c >= 'A' && c <= 'Z';
- }
-
- private static final Pattern NORMALIZE_EOLS_REGEXP = Pattern.compile("\\r\\n?+");
-
- /**
- * Converts all non UN*X End-Of-Line character sequences (CR and CRLF) to UN*X format (LF).
- * Returns {@code null} for {@code null} input.
- */
- public static String normalizeEOLs(String s) {
- if (s == null) {
- return null;
- }
- return NORMALIZE_EOLS_REGEXP.matcher(s).replaceAll("\n");
- }
-
-}
[06/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtils.java
new file mode 100644
index 0000000..5801f2e
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_CollectionUtils.java
@@ -0,0 +1,220 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Don't use this; used internally by FreeMarker, might changes without notice.
+ * {@link Collection} and {@link Map}-related utilities.
+ */
+public class _CollectionUtils {
+
+ private _CollectionUtils() { }
+
+ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[] { };
+ public static final Class[] EMPTY_CLASS_ARRAY = new Class[] { };
+ public static final String[] EMPTY_STRING_ARRAY = new String[] { };
+ public static final char[] EMPTY_CHAR_ARRAY = new char[] { };
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public static <T> List<? extends T> safeCastList(
+ String argName, List list,
+ Class<T> itemClass, boolean allowNullItem) {
+ if (list == null) {
+ return null;
+ }
+ for (int i = 0; i < list.size(); i++) {
+ Object it = list.get(i);
+ if (!itemClass.isInstance(it)) {
+ if (it == null) {
+ if (!allowNullItem) {
+ throw new IllegalArgumentException(
+ (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
+ + "List item at index " + i + " is null");
+ }
+ } else {
+ throw new IllegalArgumentException(
+ (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
+ + "List item at index " + i + " is not instance of " + itemClass.getName() + "; "
+ + "its class is " + it.getClass().getName() + ".");
+ }
+ }
+ }
+
+ return list;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public static <K, V> Map<? extends K, ? extends V> safeCastMap(
+ String argName, Map map,
+ Class<K> keyClass, boolean allowNullKey,
+ Class<V> valueClass, boolean allowNullValue) {
+ if (map == null) {
+ return null;
+ }
+ for (Map.Entry<?, ?> ent : ((Map<?, ?>) map).entrySet()) {
+ Object key = ent.getKey();
+ if (!keyClass.isInstance(key)) {
+ if (key == null) {
+ if (!allowNullKey) {
+ throw new IllegalArgumentException(
+ (argName != null ? "Invalid value for argument \"" + argName + "\": " : "")
+ + "The Map contains null key");
+ }
+ } else {
+ throw new IllegalArgumentException(
+ (argName != null ? "Invalid value for argument \"" + argName + "\": " : "")
+ + "The Map contains a key that's not instance of " + keyClass.getName() +
+ "; its class is " + key.getClass().getName() + ".");
+ }
+ }
+
+ Object value = ent.getValue();
+ if (!valueClass.isInstance(value)) {
+ if (value == null) {
+ if (!allowNullValue) {
+ throw new IllegalArgumentException(
+ (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
+ + "The Map contains null value");
+ }
+ } else {
+ throw new IllegalArgumentException(
+ (argName != null ? "Invalid value for argument \"" + argName + "\"" : "")
+ + "The Map contains a value that's not instance of " + valueClass.getName() +
+ "; its class is " + value.getClass().getName() + ".");
+ }
+ }
+ }
+
+ return map;
+ }
+
+ private static final Class<?> UNMODIFIABLE_MAP_CLASS_1 = Collections.emptyMap().getClass();
+ private static final Class<?> UNMODIFIABLE_MAP_CLASS_2 = Collections.unmodifiableMap(
+ new HashMap<Object, Object> (1)).getClass();
+ private static final Class<?> UNMODIFIABLE_LIST_CLASS_1 = Collections.emptyList().getClass();
+ private static final Class<?> UNMODIFIABLE_LIST_CLASS_2 = Collections.unmodifiableList(
+ new ArrayList<Object>(1)).getClass();
+
+ public static boolean isMapKnownToBeUnmodifiable(Map<?, ?> map) {
+ if (map == null) {
+ return true;
+ }
+ Class<? extends Map> mapClass = map.getClass();
+ return mapClass == UNMODIFIABLE_MAP_CLASS_1 || mapClass == UNMODIFIABLE_MAP_CLASS_2;
+ }
+
+ public static boolean isListKnownToBeUnmodifiable(List<?> list) {
+ if (list == null) {
+ return true;
+ }
+ Class<? extends List> listClass = list.getClass();
+ return listClass == UNMODIFIABLE_LIST_CLASS_1 || listClass == UNMODIFIABLE_LIST_CLASS_2;
+ }
+
+ /**
+ * Optimized version of {@link Collections#unmodifiableMap(Map)} (avoids needless wrapping).
+ *
+ * @param map The map to return or wrap if not already unmodifiable, or {@code null} which is silently bypassed.
+ */
+ public static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) {
+ return isMapKnownToBeUnmodifiable(map) ? map : Collections.unmodifiableMap(map);
+ }
+
+ /**
+ * Adds two {@link Map}-s (keeping the iteration order); assuming the inputs are already unmodifiable and
+ * unchanging, it returns an unmodifiable and unchanging {@link Map} itself.
+ */
+ public static <K,V> Map<K,V> mergeImmutableMaps(Map<K,V> m1, Map<K,V> m2, boolean keepOriginalOrder) {
+ if (m1 == null) return m2;
+ if (m2 == null) return m1;
+ if (m1.isEmpty()) return m2;
+ if (m2.isEmpty()) return m1;
+
+ Map<K, V> mergedM = keepOriginalOrder
+ ? new LinkedHashMap<K, V>((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f)
+ : new HashMap<K, V>((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f);
+ mergedM.putAll(m1);
+ if (keepOriginalOrder) {
+ for (K m2Key : m2.keySet()) {
+ mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys
+ }
+ }
+ mergedM.putAll(m2);
+ return Collections.unmodifiableMap(mergedM);
+ }
+
+ /**
+ * Adds multiple {@link List}-s; assuming the inputs are already unmodifiable and unchanging, it returns an
+ * unmodifiable and unchanging {@link List} itself.
+ */
+ public static <T> List<T> mergeImmutableLists(boolean skipDuplicatesInList1, List<T> ... lists) {
+ if (lists == null || lists.length == 0) {
+ return null;
+ }
+
+ if (lists.length == 1) {
+ return mergeImmutableLists(lists[0], null, skipDuplicatesInList1);
+ } else if (lists.length == 2) {
+ return mergeImmutableLists(lists[0], lists[1], skipDuplicatesInList1);
+ } else {
+ List<T> [] reducedLists = new List[lists.length - 1];
+ reducedLists[0] = mergeImmutableLists(lists[0], lists[1], skipDuplicatesInList1);
+ System.arraycopy(lists, 2, reducedLists, 1, lists.length - 2);
+ return mergeImmutableLists(skipDuplicatesInList1, reducedLists);
+ }
+ }
+
+ /**
+ * Adds two {@link List}-s; assuming the inputs are already unmodifiable and unchanging, it returns an
+ * unmodifiable and unchanging {@link List} itself.
+ */
+ public static <T> List<T> mergeImmutableLists(List<T> list1, List<T> list2,
+ boolean skipDuplicatesInList1) {
+ if (list1 == null) return list2;
+ if (list2 == null) return list1;
+ if (list1.isEmpty()) return list2;
+ if (list2.isEmpty()) return list1;
+
+ ArrayList<T> mergedList = new ArrayList<>(list1.size() + list2.size());
+ if (skipDuplicatesInList1) {
+ Set<T> list2Set = new HashSet<>(list2);
+ for (T it : list1) {
+ if (!list2Set.contains(it)) {
+ mergedList.add(it);
+ }
+ }
+ } else {
+ mergedList.addAll(list1);
+ }
+ mergedList.addAll(list2);
+ return Collections.unmodifiableList(mergedList);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtil.java
deleted file mode 100644
index 0cf2fea..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtil.java
+++ /dev/null
@@ -1,914 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import java.text.ParseException;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.TimeZone;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Don't use this; used internally by FreeMarker, might changes without notice.
- * Date and time related utilities.
- */
-public class _DateUtil {
-
- /**
- * Show hours (24h); always 2 digits, like {@code 00}, {@code 05}, etc.
- */
- public static final int ACCURACY_HOURS = 4;
-
- /**
- * Show hours and minutes (even if minutes is 00).
- */
- public static final int ACCURACY_MINUTES = 5;
-
- /**
- * Show hours, minutes and seconds (even if seconds is 00).
- */
- public static final int ACCURACY_SECONDS = 6;
-
- /**
- * Show hours, minutes and seconds and up to 3 fraction second digits, without trailing 0-s in the fraction part.
- */
- public static final int ACCURACY_MILLISECONDS = 7;
-
- /**
- * Show hours, minutes and seconds and exactly 3 fraction second digits (even if it's 000)
- */
- public static final int ACCURACY_MILLISECONDS_FORCED = 8;
-
- public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
-
- private static final String REGEX_XS_TIME_ZONE
- = "Z|(?:[-+][0-9]{2}:[0-9]{2})";
- private static final String REGEX_ISO8601_BASIC_TIME_ZONE
- = "Z|(?:[-+][0-9]{2}(?:[0-9]{2})?)";
- private static final String REGEX_ISO8601_EXTENDED_TIME_ZONE
- = "Z|(?:[-+][0-9]{2}(?::[0-9]{2})?)";
-
- private static final String REGEX_XS_OPTIONAL_TIME_ZONE
- = "(" + REGEX_XS_TIME_ZONE + ")?";
- private static final String REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE
- = "(" + REGEX_ISO8601_BASIC_TIME_ZONE + ")?";
- private static final String REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE
- = "(" + REGEX_ISO8601_EXTENDED_TIME_ZONE + ")?";
-
- private static final String REGEX_XS_DATE_BASE
- = "(-?[0-9]+)-([0-9]{2})-([0-9]{2})";
- private static final String REGEX_ISO8601_BASIC_DATE_BASE
- = "(-?[0-9]{4,}?)([0-9]{2})([0-9]{2})";
- private static final String REGEX_ISO8601_EXTENDED_DATE_BASE
- = "(-?[0-9]{4,})-([0-9]{2})-([0-9]{2})";
-
- private static final String REGEX_XS_TIME_BASE
- = "([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]+))?";
- private static final String REGEX_ISO8601_BASIC_TIME_BASE
- = "([0-9]{2})(?:([0-9]{2})(?:([0-9]{2})(?:[\\.,]([0-9]+))?)?)?";
- private static final String REGEX_ISO8601_EXTENDED_TIME_BASE
- = "([0-9]{2})(?::([0-9]{2})(?::([0-9]{2})(?:[\\.,]([0-9]+))?)?)?";
-
- private static final Pattern PATTERN_XS_DATE = Pattern.compile(
- REGEX_XS_DATE_BASE + REGEX_XS_OPTIONAL_TIME_ZONE);
- private static final Pattern PATTERN_ISO8601_BASIC_DATE = Pattern.compile(
- REGEX_ISO8601_BASIC_DATE_BASE); // No time zone allowed here
- private static final Pattern PATTERN_ISO8601_EXTENDED_DATE = Pattern.compile(
- REGEX_ISO8601_EXTENDED_DATE_BASE); // No time zone allowed here
-
- private static final Pattern PATTERN_XS_TIME = Pattern.compile(
- REGEX_XS_TIME_BASE + REGEX_XS_OPTIONAL_TIME_ZONE);
- private static final Pattern PATTERN_ISO8601_BASIC_TIME = Pattern.compile(
- REGEX_ISO8601_BASIC_TIME_BASE + REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE);
- private static final Pattern PATTERN_ISO8601_EXTENDED_TIME = Pattern.compile(
- REGEX_ISO8601_EXTENDED_TIME_BASE + REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE);
-
- private static final Pattern PATTERN_XS_DATE_TIME = Pattern.compile(
- REGEX_XS_DATE_BASE
- + "T" + REGEX_XS_TIME_BASE
- + REGEX_XS_OPTIONAL_TIME_ZONE);
- private static final Pattern PATTERN_ISO8601_BASIC_DATE_TIME = Pattern.compile(
- REGEX_ISO8601_BASIC_DATE_BASE
- + "T" + REGEX_ISO8601_BASIC_TIME_BASE
- + REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE);
- private static final Pattern PATTERN_ISO8601_EXTENDED_DATE_TIME = Pattern.compile(
- REGEX_ISO8601_EXTENDED_DATE_BASE
- + "T" + REGEX_ISO8601_EXTENDED_TIME_BASE
- + REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE);
-
- private static final Pattern PATTERN_XS_TIME_ZONE = Pattern.compile(
- REGEX_XS_TIME_ZONE);
-
- private static final String MSG_YEAR_0_NOT_ALLOWED
- = "Year 0 is not allowed in XML schema dates. BC 1 is -1, AD 1 is 1.";
-
- private _DateUtil() {
- // can't be instantiated
- }
-
- /**
- * Returns the time zone object for the name (or ID). This differs from
- * {@link TimeZone#getTimeZone(String)} in that the latest returns GMT
- * if it doesn't recognize the name, while this throws an
- * {@link UnrecognizedTimeZoneException}.
- *
- * @throws UnrecognizedTimeZoneException If the time zone name wasn't understood
- */
- public static TimeZone getTimeZone(String name)
- throws UnrecognizedTimeZoneException {
- if (isGMTish(name)) {
- if (name.equalsIgnoreCase("UTC")) {
- return UTC;
- }
- return TimeZone.getTimeZone(name);
- }
- TimeZone tz = TimeZone.getTimeZone(name);
- if (isGMTish(tz.getID())) {
- throw new UnrecognizedTimeZoneException(name);
- }
- return tz;
- }
-
- /**
- * Tells if a offset or time zone is GMT. GMT is a fuzzy term, it used to
- * referred both to UTC and UT1.
- */
- private static boolean isGMTish(String name) {
- if (name.length() < 3) {
- return false;
- }
- char c1 = name.charAt(0);
- char c2 = name.charAt(1);
- char c3 = name.charAt(2);
- if (
- !(
- (c1 == 'G' || c1 == 'g')
- && (c2 == 'M' || c2 == 'm')
- && (c3 == 'T' || c3 == 't')
- )
- &&
- !(
- (c1 == 'U' || c1 == 'u')
- && (c2 == 'T' || c2 == 't')
- && (c3 == 'C' || c3 == 'c')
- )
- &&
- !(
- (c1 == 'U' || c1 == 'u')
- && (c2 == 'T' || c2 == 't')
- && (c3 == '1')
- )
- ) {
- return false;
- }
-
- if (name.length() == 3) {
- return true;
- }
-
- String offset = name.substring(3);
- if (offset.startsWith("+")) {
- return offset.equals("+0") || offset.equals("+00")
- || offset.equals("+00:00");
- } else {
- return offset.equals("-0") || offset.equals("-00")
- || offset.equals("-00:00");
- }
- }
-
- /**
- * Format a date, time or dateTime with one of the ISO 8601 extended
- * formats that is also compatible with the XML Schema format (as far as you
- * don't have dates in the BC era). Examples of possible outputs:
- * {@code "2005-11-27T15:30:00+02:00"}, {@code "2005-11-27"},
- * {@code "15:30:00Z"}. Note the {@code ":00"} in the time zone offset;
- * this is not required by ISO 8601, but included for compatibility with
- * the XML Schema format. Regarding the B.C. issue, those dates will be
- * one year off when read back according the XML Schema format, because of a
- * mismatch between that format and ISO 8601:2000 Second Edition.
- *
- * <p>This method is thread-safe.
- *
- * @param date the date to convert to ISO 8601 string
- * @param datePart whether the date part (year, month, day) will be included
- * or not
- * @param timePart whether the time part (hours, minutes, seconds,
- * milliseconds) will be included or not
- * @param offsetPart whether the time zone offset part will be included or
- * not. This will be shown as an offset to UTC (examples:
- * {@code "+01"}, {@code "-02"}, {@code "+04:30"}) or as {@code "Z"}
- * for UTC (and for UT1 and for GMT+00, since the Java platform
- * doesn't really care about the difference).
- * Note that this can't be {@code true} when {@code timePart} is
- * {@code false}, because ISO 8601 (2004) doesn't mention such
- * patterns.
- * @param accuracy tells which parts of the date/time to drop. The
- * {@code datePart} and {@code timePart} parameters are stronger than
- * this. Note that when {@link #ACCURACY_MILLISECONDS} is specified,
- * the milliseconds part will be displayed as fraction seconds
- * (like {@code "15:30.00.25"}) with the minimum number of
- * digits needed to show the milliseconds without precision lose.
- * Thus, if the milliseconds happen to be exactly 0, no fraction
- * seconds will be shown at all.
- * @param timeZone the time zone in which the date/time will be shown. (You
- * may find {@link _DateUtil#UTC} handy here.) Note
- * that although date-only formats has no time zone offset part,
- * the result still depends on the time zone, as days start and end
- * at different points on the time line in different zones.
- * @param calendarFactory the factory that will invoke the calendar used
- * internally for calculations. The point of this parameter is that
- * creating a new calendar is relatively expensive, so it's desirable
- * to reuse calendars and only set their time and zone. (This was
- * tested on Sun JDK 1.6 x86 Win, where it gave 2x-3x speedup.)
- */
- public static String dateToISO8601String(
- Date date,
- boolean datePart, boolean timePart, boolean offsetPart,
- int accuracy,
- TimeZone timeZone,
- DateToISO8601CalendarFactory calendarFactory) {
- return dateToString(date, datePart, timePart, offsetPart, accuracy, timeZone, false, calendarFactory);
- }
-
- /**
- * Same as {@link #dateToISO8601String}, but gives XML Schema compliant format.
- */
- public static String dateToXSString(
- Date date,
- boolean datePart, boolean timePart, boolean offsetPart,
- int accuracy,
- TimeZone timeZone,
- DateToISO8601CalendarFactory calendarFactory) {
- return dateToString(date, datePart, timePart, offsetPart, accuracy, timeZone, true, calendarFactory);
- }
-
- private static String dateToString(
- Date date,
- boolean datePart, boolean timePart, boolean offsetPart,
- int accuracy,
- TimeZone timeZone, boolean xsMode,
- DateToISO8601CalendarFactory calendarFactory) {
- if (!xsMode && !timePart && offsetPart) {
- throw new IllegalArgumentException(
- "ISO 8601:2004 doesn't specify any formats where the "
- + "offset is shown but the time isn't.");
- }
-
- if (timeZone == null) {
- timeZone = UTC;
- }
-
- GregorianCalendar cal = calendarFactory.get(timeZone, date);
-
- int maxLength;
- if (!timePart) {
- maxLength = 10 + (xsMode ? 6 : 0); // YYYY-MM-DD+00:00
- } else {
- if (!datePart) {
- maxLength = 12 + 6; // HH:MM:SS.mmm+00:00
- } else {
- maxLength = 10 + 1 + 12 + 6;
- }
- }
- char[] res = new char[maxLength];
- int dstIdx = 0;
-
- if (datePart) {
- int x = cal.get(Calendar.YEAR);
- if (x > 0 && cal.get(Calendar.ERA) == GregorianCalendar.BC) {
- x = -x + (xsMode ? 0 : 1);
- }
- if (x >= 0 && x < 9999) {
- res[dstIdx++] = (char) ('0' + x / 1000);
- res[dstIdx++] = (char) ('0' + x % 1000 / 100);
- res[dstIdx++] = (char) ('0' + x % 100 / 10);
- res[dstIdx++] = (char) ('0' + x % 10);
- } else {
- String yearString = String.valueOf(x);
-
- // Re-allocate buffer:
- maxLength = maxLength - 4 + yearString.length();
- res = new char[maxLength];
-
- for (int i = 0; i < yearString.length(); i++) {
- res[dstIdx++] = yearString.charAt(i);
- }
- }
-
- res[dstIdx++] = '-';
-
- x = cal.get(Calendar.MONTH) + 1;
- dstIdx = append00(res, dstIdx, x);
-
- res[dstIdx++] = '-';
-
- x = cal.get(Calendar.DAY_OF_MONTH);
- dstIdx = append00(res, dstIdx, x);
-
- if (timePart) {
- res[dstIdx++] = 'T';
- }
- }
-
- if (timePart) {
- int x = cal.get(Calendar.HOUR_OF_DAY);
- dstIdx = append00(res, dstIdx, x);
-
- if (accuracy >= ACCURACY_MINUTES) {
- res[dstIdx++] = ':';
-
- x = cal.get(Calendar.MINUTE);
- dstIdx = append00(res, dstIdx, x);
-
- if (accuracy >= ACCURACY_SECONDS) {
- res[dstIdx++] = ':';
-
- x = cal.get(Calendar.SECOND);
- dstIdx = append00(res, dstIdx, x);
-
- if (accuracy >= ACCURACY_MILLISECONDS) {
- x = cal.get(Calendar.MILLISECOND);
- int forcedDigits = accuracy == ACCURACY_MILLISECONDS_FORCED ? 3 : 0;
- if (x != 0 || forcedDigits != 0) {
- if (x > 999) {
- // Shouldn't ever happen...
- throw new RuntimeException(
- "Calendar.MILLISECOND > 999");
- }
- res[dstIdx++] = '.';
- do {
- res[dstIdx++] = (char) ('0' + (x / 100));
- forcedDigits--;
- x = x % 100 * 10;
- } while (x != 0 || forcedDigits > 0);
- }
- }
- }
- }
- }
-
- if (offsetPart) {
- if (timeZone == UTC) {
- res[dstIdx++] = 'Z';
- } else {
- int dt = timeZone.getOffset(date.getTime());
- boolean positive;
- if (dt < 0) {
- positive = false;
- dt = -dt;
- } else {
- positive = true;
- }
-
- dt /= 1000;
- int offS = dt % 60;
- dt /= 60;
- int offM = dt % 60;
- dt /= 60;
- int offH = dt;
-
- if (offS == 0 && offM == 0 && offH == 0) {
- res[dstIdx++] = 'Z';
- } else {
- res[dstIdx++] = positive ? '+' : '-';
- dstIdx = append00(res, dstIdx, offH);
- res[dstIdx++] = ':';
- dstIdx = append00(res, dstIdx, offM);
- if (offS != 0) {
- res[dstIdx++] = ':';
- dstIdx = append00(res, dstIdx, offS);
- }
- }
- }
- }
-
- return new String(res, 0, dstIdx);
- }
-
- /**
- * Appends a number between 0 and 99 padded to 2 digits.
- */
- private static int append00(char[] res, int dstIdx, int x) {
- res[dstIdx++] = (char) ('0' + x / 10);
- res[dstIdx++] = (char) ('0' + x % 10);
- return dstIdx;
- }
-
- /**
- * Parses an W3C XML Schema date string (not time or date-time).
- * Unlike in ISO 8601:2000 Second Edition, year -1 means B.C 1, and year 0 is invalid.
- *
- * @param dateStr the string to parse.
- * @param defaultTimeZone used if the date doesn't specify the
- * time zone offset explicitly. Can't be {@code null}.
- * @param calToDateConverter Used internally to calculate the result from the calendar field values.
- * If you don't have a such object around, you can just use
- * {@code new }{@link TrivialCalendarFieldsToDateConverter}{@code ()}.
- *
- * @throws DateParseException if the date is malformed, or if the time
- * zone offset is unspecified and the {@code defaultTimeZone} is
- * {@code null}.
- */
- public static Date parseXSDate(
- String dateStr, TimeZone defaultTimeZone,
- CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- Matcher m = PATTERN_XS_DATE.matcher(dateStr);
- if (!m.matches()) {
- throw new DateParseException("The value didn't match the expected pattern: " + PATTERN_XS_DATE);
- }
- return parseDate_parseMatcher(
- m, defaultTimeZone, true, calToDateConverter);
- }
-
- /**
- * Same as {@link #parseXSDate(String, TimeZone, CalendarFieldsToDateConverter)}, but for ISO 8601 dates.
- */
- public static Date parseISO8601Date(
- String dateStr, TimeZone defaultTimeZone,
- CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- Matcher m = PATTERN_ISO8601_EXTENDED_DATE.matcher(dateStr);
- if (!m.matches()) {
- m = PATTERN_ISO8601_BASIC_DATE.matcher(dateStr);
- if (!m.matches()) {
- throw new DateParseException("The value didn't match the expected pattern: "
- + PATTERN_ISO8601_EXTENDED_DATE + " or "
- + PATTERN_ISO8601_BASIC_DATE);
- }
- }
- return parseDate_parseMatcher(
- m, defaultTimeZone, false, calToDateConverter);
- }
-
- private static Date parseDate_parseMatcher(
- Matcher m, TimeZone defaultTZ,
- boolean xsMode,
- CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- _NullArgumentException.check("defaultTZ", defaultTZ);
- try {
- int year = groupToInt(m.group(1), "year", Integer.MIN_VALUE, Integer.MAX_VALUE);
-
- int era;
- // Starting from ISO 8601:2000 Second Edition, 0001 is AD 1, 0000 is BC 1, -0001 is BC 2.
- // However, according to http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/, XML schemas are based
- // on the earlier version where 0000 didn't exist, and year -1 is BC 1.
- if (year <= 0) {
- era = GregorianCalendar.BC;
- year = -year + (xsMode ? 0 : 1);
- if (year == 0) {
- throw new DateParseException(MSG_YEAR_0_NOT_ALLOWED);
- }
- } else {
- era = GregorianCalendar.AD;
- }
-
- int month = groupToInt(m.group(2), "month", 1, 12) - 1;
- int day = groupToInt(m.group(3), "day-of-month", 1, 31);
-
- TimeZone tz = xsMode ? parseMatchingTimeZone(m.group(4), defaultTZ) : defaultTZ;
-
- return calToDateConverter.calculate(era, year, month, day, 0, 0, 0, 0, false, tz);
- } catch (IllegalArgumentException e) {
- // Calendar methods used to throw this for illegal dates.
- throw new DateParseException(
- "Date calculation faliure. "
- + "Probably the date is formally correct, but refers "
- + "to an unexistent date (like February 30).");
- }
- }
-
- /**
- * Parses an W3C XML Schema time string (not date or date-time).
- * If the time string doesn't specify the time zone offset explicitly,
- * the value of the {@code defaultTZ} paramter will be used.
- */
- public static Date parseXSTime(
- String timeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- Matcher m = PATTERN_XS_TIME.matcher(timeStr);
- if (!m.matches()) {
- throw new DateParseException("The value didn't match the expected pattern: " + PATTERN_XS_TIME);
- }
- return parseTime_parseMatcher(m, defaultTZ, calToDateConverter);
- }
-
- /**
- * Same as {@link #parseXSTime(String, TimeZone, CalendarFieldsToDateConverter)} but for ISO 8601 times.
- */
- public static Date parseISO8601Time(
- String timeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- Matcher m = PATTERN_ISO8601_EXTENDED_TIME.matcher(timeStr);
- if (!m.matches()) {
- m = PATTERN_ISO8601_BASIC_TIME.matcher(timeStr);
- if (!m.matches()) {
- throw new DateParseException("The value didn't match the expected pattern: "
- + PATTERN_ISO8601_EXTENDED_TIME + " or "
- + PATTERN_ISO8601_BASIC_TIME);
- }
- }
- return parseTime_parseMatcher(m, defaultTZ, calToDateConverter);
- }
-
- private static Date parseTime_parseMatcher(
- Matcher m, TimeZone defaultTZ,
- CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- _NullArgumentException.check("defaultTZ", defaultTZ);
- try {
- // ISO 8601 allows both 00:00 and 24:00,
- // but Calendar.set(...) doesn't if the Calendar is not lenient.
- int hours = groupToInt(m.group(1), "hour-of-day", 0, 24);
- boolean hourWas24;
- if (hours == 24) {
- hours = 0;
- hourWas24 = true;
- // And a day will be added later...
- } else {
- hourWas24 = false;
- }
-
- final String minutesStr = m.group(2);
- int minutes = minutesStr != null ? groupToInt(minutesStr, "minute", 0, 59) : 0;
-
- final String secsStr = m.group(3);
- // Allow 60 because of leap seconds
- int secs = secsStr != null ? groupToInt(secsStr, "second", 0, 60) : 0;
-
- int millisecs = groupToMillisecond(m.group(4));
-
- // As a time is just the distance from the beginning of the day,
- // the time-zone offest should be 0 usually.
- TimeZone tz = parseMatchingTimeZone(m.group(5), defaultTZ);
-
- // Continue handling the 24:00 special case
- int day;
- if (hourWas24) {
- if (minutes == 0 && secs == 0 && millisecs == 0) {
- day = 2;
- } else {
- throw new DateParseException(
- "Hour 24 is only allowed in the case of "
- + "midnight.");
- }
- } else {
- day = 1;
- }
-
- return calToDateConverter.calculate(
- GregorianCalendar.AD, 1970, 0, day, hours, minutes, secs, millisecs, false, tz);
- } catch (IllegalArgumentException e) {
- // Calendar methods used to throw this for illegal dates.
- throw new DateParseException(
- "Unexpected time calculation faliure.");
- }
- }
-
- /**
- * Parses an W3C XML Schema date-time string (not date or time).
- * Unlike in ISO 8601:2000 Second Edition, year -1 means B.C 1, and year 0 is invalid.
- *
- * @param dateTimeStr the string to parse.
- * @param defaultTZ used if the dateTime doesn't specify the
- * time zone offset explicitly. Can't be {@code null}.
- *
- * @throws DateParseException if the dateTime is malformed.
- */
- public static Date parseXSDateTime(
- String dateTimeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- Matcher m = PATTERN_XS_DATE_TIME.matcher(dateTimeStr);
- if (!m.matches()) {
- throw new DateParseException(
- "The value didn't match the expected pattern: " + PATTERN_XS_DATE_TIME);
- }
- return parseDateTime_parseMatcher(
- m, defaultTZ, true, calToDateConverter);
- }
-
- /**
- * Same as {@link #parseXSDateTime(String, TimeZone, CalendarFieldsToDateConverter)} but for ISO 8601 format.
- */
- public static Date parseISO8601DateTime(
- String dateTimeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- Matcher m = PATTERN_ISO8601_EXTENDED_DATE_TIME.matcher(dateTimeStr);
- if (!m.matches()) {
- m = PATTERN_ISO8601_BASIC_DATE_TIME.matcher(dateTimeStr);
- if (!m.matches()) {
- throw new DateParseException("The value (" + dateTimeStr + ") didn't match the expected pattern: "
- + PATTERN_ISO8601_EXTENDED_DATE_TIME + " or "
- + PATTERN_ISO8601_BASIC_DATE_TIME);
- }
- }
- return parseDateTime_parseMatcher(
- m, defaultTZ, false, calToDateConverter);
- }
-
- private static Date parseDateTime_parseMatcher(
- Matcher m, TimeZone defaultTZ,
- boolean xsMode,
- CalendarFieldsToDateConverter calToDateConverter)
- throws DateParseException {
- _NullArgumentException.check("defaultTZ", defaultTZ);
- try {
- int year = groupToInt(m.group(1), "year", Integer.MIN_VALUE, Integer.MAX_VALUE);
-
- int era;
- // Starting from ISO 8601:2000 Second Edition, 0001 is AD 1, 0000 is BC 1, -0001 is BC 2.
- // However, according to http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/, XML schemas are based
- // on the earlier version where 0000 didn't exist, and year -1 is BC 1.
- if (year <= 0) {
- era = GregorianCalendar.BC;
- year = -year + (xsMode ? 0 : 1);
- if (year == 0) {
- throw new DateParseException(MSG_YEAR_0_NOT_ALLOWED);
- }
- } else {
- era = GregorianCalendar.AD;
- }
-
- int month = groupToInt(m.group(2), "month", 1, 12) - 1;
- int day = groupToInt(m.group(3), "day-of-month", 1, 31);
-
- // ISO 8601 allows both 00:00 and 24:00,
- // but cal.set(...) doesn't if the Calendar is not lenient.
- int hours = groupToInt(m.group(4), "hour-of-day", 0, 24);
- boolean hourWas24;
- if (hours == 24) {
- hours = 0;
- hourWas24 = true;
- // And a day will be added later...
- } else {
- hourWas24 = false;
- }
-
- final String minutesStr = m.group(5);
- int minutes = minutesStr != null ? groupToInt(minutesStr, "minute", 0, 59) : 0;
-
- final String secsStr = m.group(6);
- // Allow 60 because of leap seconds
- int secs = secsStr != null ? groupToInt(secsStr, "second", 0, 60) : 0;
-
- int millisecs = groupToMillisecond(m.group(7));
-
- // As a time is just the distance from the beginning of the day,
- // the time-zone offest should be 0 usually.
- TimeZone tz = parseMatchingTimeZone(m.group(8), defaultTZ);
-
- // Continue handling the 24:00 specail case
- if (hourWas24) {
- if (minutes != 0 || secs != 0 || millisecs != 0) {
- throw new DateParseException(
- "Hour 24 is only allowed in the case of "
- + "midnight.");
- }
- }
-
- return calToDateConverter.calculate(
- era, year, month, day, hours, minutes, secs, millisecs, hourWas24, tz);
- } catch (IllegalArgumentException e) {
- // Calendar methods used to throw this for illegal dates.
- throw new DateParseException(
- "Date-time calculation faliure. "
- + "Probably the date-time is formally correct, but "
- + "refers to an unexistent date-time "
- + "(like February 30).");
- }
- }
-
- /**
- * Parses the time zone part from a W3C XML Schema date/time/dateTime.
- * @throws DateParseException if the zone is malformed.
- */
- public static TimeZone parseXSTimeZone(String timeZoneStr)
- throws DateParseException {
- Matcher m = PATTERN_XS_TIME_ZONE.matcher(timeZoneStr);
- if (!m.matches()) {
- throw new DateParseException(
- "The time zone offset didn't match the expected pattern: " + PATTERN_XS_TIME_ZONE);
- }
- return parseMatchingTimeZone(timeZoneStr, null);
- }
-
- private static int groupToInt(String g, String gName,
- int min, int max)
- throws DateParseException {
- if (g == null) {
- throw new DateParseException("The " + gName + " part "
- + "is missing.");
- }
-
- int start;
-
- // Remove minus sign, so we can remove the 0-s later:
- boolean negative;
- if (g.startsWith("-")) {
- negative = true;
- start = 1;
- } else {
- negative = false;
- start = 0;
- }
-
- // Remove leading 0-s:
- while (start < g.length() - 1 && g.charAt(start) == '0') {
- start++;
- }
- if (start != 0) {
- g = g.substring(start);
- }
-
- try {
- int r = Integer.parseInt(g);
- if (negative) {
- r = -r;
- }
- if (r < min) {
- throw new DateParseException("The " + gName + " part "
- + "must be at least " + min + ".");
- }
- if (r > max) {
- throw new DateParseException("The " + gName + " part "
- + "can't be more than " + max + ".");
- }
- return r;
- } catch (NumberFormatException e) {
- throw new DateParseException("The " + gName + " part "
- + "is a malformed integer.");
- }
- }
-
- private static TimeZone parseMatchingTimeZone(
- String s, TimeZone defaultZone)
- throws DateParseException {
- if (s == null) {
- return defaultZone;
- }
- if (s.equals("Z")) {
- return _DateUtil.UTC;
- }
-
- StringBuilder sb = new StringBuilder(9);
- sb.append("GMT");
- sb.append(s.charAt(0));
-
- String h = s.substring(1, 3);
- groupToInt(h, "offset-hours", 0, 23);
- sb.append(h);
-
- String m;
- int ln = s.length();
- if (ln > 3) {
- int startIdx = s.charAt(3) == ':' ? 4 : 3;
- m = s.substring(startIdx, startIdx + 2);
- groupToInt(m, "offset-minutes", 0, 59);
- sb.append(':');
- sb.append(m);
- }
-
- return TimeZone.getTimeZone(sb.toString());
- }
-
- private static int groupToMillisecond(String g)
- throws DateParseException {
- if (g == null) {
- return 0;
- }
-
- if (g.length() > 3) {
- g = g.substring(0, 3);
- }
- int i = groupToInt(g, "partial-seconds", 0, Integer.MAX_VALUE);
- return g.length() == 1 ? i * 100 : (g.length() == 2 ? i * 10 : i);
- }
-
- /**
- * Used internally by {@link _DateUtil}; don't use its implementations for
- * anything else.
- */
- public interface DateToISO8601CalendarFactory {
-
- /**
- * Returns a {@link GregorianCalendar} with the desired time zone and
- * time and US locale. The returned calendar is used as read-only.
- * It must be guaranteed that within a thread the instance returned last time
- * is not in use anymore when this method is called again.
- */
- GregorianCalendar get(TimeZone tz, Date date);
-
- }
-
- /**
- * Used internally by {@link _DateUtil}; don't use its implementations for anything else.
- */
- public interface CalendarFieldsToDateConverter {
-
- /**
- * Calculates the {@link Date} from the specified calendar fields.
- */
- Date calculate(int era, int year, int month, int day, int hours, int minutes, int secs, int millisecs,
- boolean addOneDay,
- TimeZone tz);
-
- }
-
- /**
- * Non-thread-safe factory that hard-references a calendar internally.
- */
- public static final class TrivialDateToISO8601CalendarFactory
- implements DateToISO8601CalendarFactory {
-
- private GregorianCalendar calendar;
- private TimeZone lastlySetTimeZone;
-
- @Override
- public GregorianCalendar get(TimeZone tz, Date date) {
- if (calendar == null) {
- calendar = new GregorianCalendar(tz, Locale.US);
- calendar.setGregorianChange(new Date(Long.MIN_VALUE)); // never use Julian calendar
- } else {
- // At least on Java 6, calendar.getTimeZone is slow due to a bug, so we need lastlySetTimeZone.
- if (lastlySetTimeZone != tz) { // Deliberately `!=` instead of `!<...>.equals()`
- calendar.setTimeZone(tz);
- lastlySetTimeZone = tz;
- }
- }
- calendar.setTime(date);
- return calendar;
- }
-
- }
-
- /**
- * Non-thread-safe implementation that hard-references a calendar internally.
- */
- public static final class TrivialCalendarFieldsToDateConverter
- implements CalendarFieldsToDateConverter {
-
- private GregorianCalendar calendar;
- private TimeZone lastlySetTimeZone;
-
- @Override
- public Date calculate(int era, int year, int month, int day, int hours, int minutes, int secs, int millisecs,
- boolean addOneDay, TimeZone tz) {
- if (calendar == null) {
- calendar = new GregorianCalendar(tz, Locale.US);
- calendar.setLenient(false);
- calendar.setGregorianChange(new Date(Long.MIN_VALUE)); // never use Julian calendar
- } else {
- // At least on Java 6, calendar.getTimeZone is slow due to a bug, so we need lastlySetTimeZone.
- if (lastlySetTimeZone != tz) { // Deliberately `!=` instead of `!<...>.equals()`
- calendar.setTimeZone(tz);
- lastlySetTimeZone = tz;
- }
- }
-
- calendar.set(Calendar.ERA, era);
- calendar.set(Calendar.YEAR, year);
- calendar.set(Calendar.MONTH, month);
- calendar.set(Calendar.DAY_OF_MONTH, day);
- calendar.set(Calendar.HOUR_OF_DAY, hours);
- calendar.set(Calendar.MINUTE, minutes);
- calendar.set(Calendar.SECOND, secs);
- calendar.set(Calendar.MILLISECOND, millisecs);
- if (addOneDay) {
- calendar.add(Calendar.DAY_OF_MONTH, 1);
- }
-
- return calendar.getTime();
- }
-
- }
-
- public static final class DateParseException extends ParseException {
-
- public DateParseException(String message) {
- super(message, 0);
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtils.java
new file mode 100644
index 0000000..60201b6
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_DateUtils.java
@@ -0,0 +1,914 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import java.text.ParseException;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Don't use this; used internally by FreeMarker, might changes without notice.
+ * Date and time related utilities.
+ */
+public class _DateUtils {
+
+ /**
+ * Show hours (24h); always 2 digits, like {@code 00}, {@code 05}, etc.
+ */
+ public static final int ACCURACY_HOURS = 4;
+
+ /**
+ * Show hours and minutes (even if minutes is 00).
+ */
+ public static final int ACCURACY_MINUTES = 5;
+
+ /**
+ * Show hours, minutes and seconds (even if seconds is 00).
+ */
+ public static final int ACCURACY_SECONDS = 6;
+
+ /**
+ * Show hours, minutes and seconds and up to 3 fraction second digits, without trailing 0-s in the fraction part.
+ */
+ public static final int ACCURACY_MILLISECONDS = 7;
+
+ /**
+ * Show hours, minutes and seconds and exactly 3 fraction second digits (even if it's 000)
+ */
+ public static final int ACCURACY_MILLISECONDS_FORCED = 8;
+
+ public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
+
+ private static final String REGEX_XS_TIME_ZONE
+ = "Z|(?:[-+][0-9]{2}:[0-9]{2})";
+ private static final String REGEX_ISO8601_BASIC_TIME_ZONE
+ = "Z|(?:[-+][0-9]{2}(?:[0-9]{2})?)";
+ private static final String REGEX_ISO8601_EXTENDED_TIME_ZONE
+ = "Z|(?:[-+][0-9]{2}(?::[0-9]{2})?)";
+
+ private static final String REGEX_XS_OPTIONAL_TIME_ZONE
+ = "(" + REGEX_XS_TIME_ZONE + ")?";
+ private static final String REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE
+ = "(" + REGEX_ISO8601_BASIC_TIME_ZONE + ")?";
+ private static final String REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE
+ = "(" + REGEX_ISO8601_EXTENDED_TIME_ZONE + ")?";
+
+ private static final String REGEX_XS_DATE_BASE
+ = "(-?[0-9]+)-([0-9]{2})-([0-9]{2})";
+ private static final String REGEX_ISO8601_BASIC_DATE_BASE
+ = "(-?[0-9]{4,}?)([0-9]{2})([0-9]{2})";
+ private static final String REGEX_ISO8601_EXTENDED_DATE_BASE
+ = "(-?[0-9]{4,})-([0-9]{2})-([0-9]{2})";
+
+ private static final String REGEX_XS_TIME_BASE
+ = "([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]+))?";
+ private static final String REGEX_ISO8601_BASIC_TIME_BASE
+ = "([0-9]{2})(?:([0-9]{2})(?:([0-9]{2})(?:[\\.,]([0-9]+))?)?)?";
+ private static final String REGEX_ISO8601_EXTENDED_TIME_BASE
+ = "([0-9]{2})(?::([0-9]{2})(?::([0-9]{2})(?:[\\.,]([0-9]+))?)?)?";
+
+ private static final Pattern PATTERN_XS_DATE = Pattern.compile(
+ REGEX_XS_DATE_BASE + REGEX_XS_OPTIONAL_TIME_ZONE);
+ private static final Pattern PATTERN_ISO8601_BASIC_DATE = Pattern.compile(
+ REGEX_ISO8601_BASIC_DATE_BASE); // No time zone allowed here
+ private static final Pattern PATTERN_ISO8601_EXTENDED_DATE = Pattern.compile(
+ REGEX_ISO8601_EXTENDED_DATE_BASE); // No time zone allowed here
+
+ private static final Pattern PATTERN_XS_TIME = Pattern.compile(
+ REGEX_XS_TIME_BASE + REGEX_XS_OPTIONAL_TIME_ZONE);
+ private static final Pattern PATTERN_ISO8601_BASIC_TIME = Pattern.compile(
+ REGEX_ISO8601_BASIC_TIME_BASE + REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE);
+ private static final Pattern PATTERN_ISO8601_EXTENDED_TIME = Pattern.compile(
+ REGEX_ISO8601_EXTENDED_TIME_BASE + REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE);
+
+ private static final Pattern PATTERN_XS_DATE_TIME = Pattern.compile(
+ REGEX_XS_DATE_BASE
+ + "T" + REGEX_XS_TIME_BASE
+ + REGEX_XS_OPTIONAL_TIME_ZONE);
+ private static final Pattern PATTERN_ISO8601_BASIC_DATE_TIME = Pattern.compile(
+ REGEX_ISO8601_BASIC_DATE_BASE
+ + "T" + REGEX_ISO8601_BASIC_TIME_BASE
+ + REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE);
+ private static final Pattern PATTERN_ISO8601_EXTENDED_DATE_TIME = Pattern.compile(
+ REGEX_ISO8601_EXTENDED_DATE_BASE
+ + "T" + REGEX_ISO8601_EXTENDED_TIME_BASE
+ + REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE);
+
+ private static final Pattern PATTERN_XS_TIME_ZONE = Pattern.compile(
+ REGEX_XS_TIME_ZONE);
+
+ private static final String MSG_YEAR_0_NOT_ALLOWED
+ = "Year 0 is not allowed in XML schema dates. BC 1 is -1, AD 1 is 1.";
+
+ private _DateUtils() {
+ // can't be instantiated
+ }
+
+ /**
+ * Returns the time zone object for the name (or ID). This differs from
+ * {@link TimeZone#getTimeZone(String)} in that the latest returns GMT
+ * if it doesn't recognize the name, while this throws an
+ * {@link UnrecognizedTimeZoneException}.
+ *
+ * @throws UnrecognizedTimeZoneException If the time zone name wasn't understood
+ */
+ public static TimeZone getTimeZone(String name)
+ throws UnrecognizedTimeZoneException {
+ if (isGMTish(name)) {
+ if (name.equalsIgnoreCase("UTC")) {
+ return UTC;
+ }
+ return TimeZone.getTimeZone(name);
+ }
+ TimeZone tz = TimeZone.getTimeZone(name);
+ if (isGMTish(tz.getID())) {
+ throw new UnrecognizedTimeZoneException(name);
+ }
+ return tz;
+ }
+
+ /**
+ * Tells if a offset or time zone is GMT. GMT is a fuzzy term, it used to
+ * referred both to UTC and UT1.
+ */
+ private static boolean isGMTish(String name) {
+ if (name.length() < 3) {
+ return false;
+ }
+ char c1 = name.charAt(0);
+ char c2 = name.charAt(1);
+ char c3 = name.charAt(2);
+ if (
+ !(
+ (c1 == 'G' || c1 == 'g')
+ && (c2 == 'M' || c2 == 'm')
+ && (c3 == 'T' || c3 == 't')
+ )
+ &&
+ !(
+ (c1 == 'U' || c1 == 'u')
+ && (c2 == 'T' || c2 == 't')
+ && (c3 == 'C' || c3 == 'c')
+ )
+ &&
+ !(
+ (c1 == 'U' || c1 == 'u')
+ && (c2 == 'T' || c2 == 't')
+ && (c3 == '1')
+ )
+ ) {
+ return false;
+ }
+
+ if (name.length() == 3) {
+ return true;
+ }
+
+ String offset = name.substring(3);
+ if (offset.startsWith("+")) {
+ return offset.equals("+0") || offset.equals("+00")
+ || offset.equals("+00:00");
+ } else {
+ return offset.equals("-0") || offset.equals("-00")
+ || offset.equals("-00:00");
+ }
+ }
+
+ /**
+ * Format a date, time or dateTime with one of the ISO 8601 extended
+ * formats that is also compatible with the XML Schema format (as far as you
+ * don't have dates in the BC era). Examples of possible outputs:
+ * {@code "2005-11-27T15:30:00+02:00"}, {@code "2005-11-27"},
+ * {@code "15:30:00Z"}. Note the {@code ":00"} in the time zone offset;
+ * this is not required by ISO 8601, but included for compatibility with
+ * the XML Schema format. Regarding the B.C. issue, those dates will be
+ * one year off when read back according the XML Schema format, because of a
+ * mismatch between that format and ISO 8601:2000 Second Edition.
+ *
+ * <p>This method is thread-safe.
+ *
+ * @param date the date to convert to ISO 8601 string
+ * @param datePart whether the date part (year, month, day) will be included
+ * or not
+ * @param timePart whether the time part (hours, minutes, seconds,
+ * milliseconds) will be included or not
+ * @param offsetPart whether the time zone offset part will be included or
+ * not. This will be shown as an offset to UTC (examples:
+ * {@code "+01"}, {@code "-02"}, {@code "+04:30"}) or as {@code "Z"}
+ * for UTC (and for UT1 and for GMT+00, since the Java platform
+ * doesn't really care about the difference).
+ * Note that this can't be {@code true} when {@code timePart} is
+ * {@code false}, because ISO 8601 (2004) doesn't mention such
+ * patterns.
+ * @param accuracy tells which parts of the date/time to drop. The
+ * {@code datePart} and {@code timePart} parameters are stronger than
+ * this. Note that when {@link #ACCURACY_MILLISECONDS} is specified,
+ * the milliseconds part will be displayed as fraction seconds
+ * (like {@code "15:30.00.25"}) with the minimum number of
+ * digits needed to show the milliseconds without precision lose.
+ * Thus, if the milliseconds happen to be exactly 0, no fraction
+ * seconds will be shown at all.
+ * @param timeZone the time zone in which the date/time will be shown. (You
+ * may find {@link _DateUtils#UTC} handy here.) Note
+ * that although date-only formats has no time zone offset part,
+ * the result still depends on the time zone, as days start and end
+ * at different points on the time line in different zones.
+ * @param calendarFactory the factory that will invoke the calendar used
+ * internally for calculations. The point of this parameter is that
+ * creating a new calendar is relatively expensive, so it's desirable
+ * to reuse calendars and only set their time and zone. (This was
+ * tested on Sun JDK 1.6 x86 Win, where it gave 2x-3x speedup.)
+ */
+ public static String dateToISO8601String(
+ Date date,
+ boolean datePart, boolean timePart, boolean offsetPart,
+ int accuracy,
+ TimeZone timeZone,
+ DateToISO8601CalendarFactory calendarFactory) {
+ return dateToString(date, datePart, timePart, offsetPart, accuracy, timeZone, false, calendarFactory);
+ }
+
+ /**
+ * Same as {@link #dateToISO8601String}, but gives XML Schema compliant format.
+ */
+ public static String dateToXSString(
+ Date date,
+ boolean datePart, boolean timePart, boolean offsetPart,
+ int accuracy,
+ TimeZone timeZone,
+ DateToISO8601CalendarFactory calendarFactory) {
+ return dateToString(date, datePart, timePart, offsetPart, accuracy, timeZone, true, calendarFactory);
+ }
+
+ private static String dateToString(
+ Date date,
+ boolean datePart, boolean timePart, boolean offsetPart,
+ int accuracy,
+ TimeZone timeZone, boolean xsMode,
+ DateToISO8601CalendarFactory calendarFactory) {
+ if (!xsMode && !timePart && offsetPart) {
+ throw new IllegalArgumentException(
+ "ISO 8601:2004 doesn't specify any formats where the "
+ + "offset is shown but the time isn't.");
+ }
+
+ if (timeZone == null) {
+ timeZone = UTC;
+ }
+
+ GregorianCalendar cal = calendarFactory.get(timeZone, date);
+
+ int maxLength;
+ if (!timePart) {
+ maxLength = 10 + (xsMode ? 6 : 0); // YYYY-MM-DD+00:00
+ } else {
+ if (!datePart) {
+ maxLength = 12 + 6; // HH:MM:SS.mmm+00:00
+ } else {
+ maxLength = 10 + 1 + 12 + 6;
+ }
+ }
+ char[] res = new char[maxLength];
+ int dstIdx = 0;
+
+ if (datePart) {
+ int x = cal.get(Calendar.YEAR);
+ if (x > 0 && cal.get(Calendar.ERA) == GregorianCalendar.BC) {
+ x = -x + (xsMode ? 0 : 1);
+ }
+ if (x >= 0 && x < 9999) {
+ res[dstIdx++] = (char) ('0' + x / 1000);
+ res[dstIdx++] = (char) ('0' + x % 1000 / 100);
+ res[dstIdx++] = (char) ('0' + x % 100 / 10);
+ res[dstIdx++] = (char) ('0' + x % 10);
+ } else {
+ String yearString = String.valueOf(x);
+
+ // Re-allocate buffer:
+ maxLength = maxLength - 4 + yearString.length();
+ res = new char[maxLength];
+
+ for (int i = 0; i < yearString.length(); i++) {
+ res[dstIdx++] = yearString.charAt(i);
+ }
+ }
+
+ res[dstIdx++] = '-';
+
+ x = cal.get(Calendar.MONTH) + 1;
+ dstIdx = append00(res, dstIdx, x);
+
+ res[dstIdx++] = '-';
+
+ x = cal.get(Calendar.DAY_OF_MONTH);
+ dstIdx = append00(res, dstIdx, x);
+
+ if (timePart) {
+ res[dstIdx++] = 'T';
+ }
+ }
+
+ if (timePart) {
+ int x = cal.get(Calendar.HOUR_OF_DAY);
+ dstIdx = append00(res, dstIdx, x);
+
+ if (accuracy >= ACCURACY_MINUTES) {
+ res[dstIdx++] = ':';
+
+ x = cal.get(Calendar.MINUTE);
+ dstIdx = append00(res, dstIdx, x);
+
+ if (accuracy >= ACCURACY_SECONDS) {
+ res[dstIdx++] = ':';
+
+ x = cal.get(Calendar.SECOND);
+ dstIdx = append00(res, dstIdx, x);
+
+ if (accuracy >= ACCURACY_MILLISECONDS) {
+ x = cal.get(Calendar.MILLISECOND);
+ int forcedDigits = accuracy == ACCURACY_MILLISECONDS_FORCED ? 3 : 0;
+ if (x != 0 || forcedDigits != 0) {
+ if (x > 999) {
+ // Shouldn't ever happen...
+ throw new RuntimeException(
+ "Calendar.MILLISECOND > 999");
+ }
+ res[dstIdx++] = '.';
+ do {
+ res[dstIdx++] = (char) ('0' + (x / 100));
+ forcedDigits--;
+ x = x % 100 * 10;
+ } while (x != 0 || forcedDigits > 0);
+ }
+ }
+ }
+ }
+ }
+
+ if (offsetPart) {
+ if (timeZone == UTC) {
+ res[dstIdx++] = 'Z';
+ } else {
+ int dt = timeZone.getOffset(date.getTime());
+ boolean positive;
+ if (dt < 0) {
+ positive = false;
+ dt = -dt;
+ } else {
+ positive = true;
+ }
+
+ dt /= 1000;
+ int offS = dt % 60;
+ dt /= 60;
+ int offM = dt % 60;
+ dt /= 60;
+ int offH = dt;
+
+ if (offS == 0 && offM == 0 && offH == 0) {
+ res[dstIdx++] = 'Z';
+ } else {
+ res[dstIdx++] = positive ? '+' : '-';
+ dstIdx = append00(res, dstIdx, offH);
+ res[dstIdx++] = ':';
+ dstIdx = append00(res, dstIdx, offM);
+ if (offS != 0) {
+ res[dstIdx++] = ':';
+ dstIdx = append00(res, dstIdx, offS);
+ }
+ }
+ }
+ }
+
+ return new String(res, 0, dstIdx);
+ }
+
+ /**
+ * Appends a number between 0 and 99 padded to 2 digits.
+ */
+ private static int append00(char[] res, int dstIdx, int x) {
+ res[dstIdx++] = (char) ('0' + x / 10);
+ res[dstIdx++] = (char) ('0' + x % 10);
+ return dstIdx;
+ }
+
+ /**
+ * Parses an W3C XML Schema date string (not time or date-time).
+ * Unlike in ISO 8601:2000 Second Edition, year -1 means B.C 1, and year 0 is invalid.
+ *
+ * @param dateStr the string to parse.
+ * @param defaultTimeZone used if the date doesn't specify the
+ * time zone offset explicitly. Can't be {@code null}.
+ * @param calToDateConverter Used internally to calculate the result from the calendar field values.
+ * If you don't have a such object around, you can just use
+ * {@code new }{@link TrivialCalendarFieldsToDateConverter}{@code ()}.
+ *
+ * @throws DateParseException if the date is malformed, or if the time
+ * zone offset is unspecified and the {@code defaultTimeZone} is
+ * {@code null}.
+ */
+ public static Date parseXSDate(
+ String dateStr, TimeZone defaultTimeZone,
+ CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ Matcher m = PATTERN_XS_DATE.matcher(dateStr);
+ if (!m.matches()) {
+ throw new DateParseException("The value didn't match the expected pattern: " + PATTERN_XS_DATE);
+ }
+ return parseDate_parseMatcher(
+ m, defaultTimeZone, true, calToDateConverter);
+ }
+
+ /**
+ * Same as {@link #parseXSDate(String, TimeZone, CalendarFieldsToDateConverter)}, but for ISO 8601 dates.
+ */
+ public static Date parseISO8601Date(
+ String dateStr, TimeZone defaultTimeZone,
+ CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ Matcher m = PATTERN_ISO8601_EXTENDED_DATE.matcher(dateStr);
+ if (!m.matches()) {
+ m = PATTERN_ISO8601_BASIC_DATE.matcher(dateStr);
+ if (!m.matches()) {
+ throw new DateParseException("The value didn't match the expected pattern: "
+ + PATTERN_ISO8601_EXTENDED_DATE + " or "
+ + PATTERN_ISO8601_BASIC_DATE);
+ }
+ }
+ return parseDate_parseMatcher(
+ m, defaultTimeZone, false, calToDateConverter);
+ }
+
+ private static Date parseDate_parseMatcher(
+ Matcher m, TimeZone defaultTZ,
+ boolean xsMode,
+ CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ _NullArgumentException.check("defaultTZ", defaultTZ);
+ try {
+ int year = groupToInt(m.group(1), "year", Integer.MIN_VALUE, Integer.MAX_VALUE);
+
+ int era;
+ // Starting from ISO 8601:2000 Second Edition, 0001 is AD 1, 0000 is BC 1, -0001 is BC 2.
+ // However, according to http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/, XML schemas are based
+ // on the earlier version where 0000 didn't exist, and year -1 is BC 1.
+ if (year <= 0) {
+ era = GregorianCalendar.BC;
+ year = -year + (xsMode ? 0 : 1);
+ if (year == 0) {
+ throw new DateParseException(MSG_YEAR_0_NOT_ALLOWED);
+ }
+ } else {
+ era = GregorianCalendar.AD;
+ }
+
+ int month = groupToInt(m.group(2), "month", 1, 12) - 1;
+ int day = groupToInt(m.group(3), "day-of-month", 1, 31);
+
+ TimeZone tz = xsMode ? parseMatchingTimeZone(m.group(4), defaultTZ) : defaultTZ;
+
+ return calToDateConverter.calculate(era, year, month, day, 0, 0, 0, 0, false, tz);
+ } catch (IllegalArgumentException e) {
+ // Calendar methods used to throw this for illegal dates.
+ throw new DateParseException(
+ "Date calculation faliure. "
+ + "Probably the date is formally correct, but refers "
+ + "to an unexistent date (like February 30).");
+ }
+ }
+
+ /**
+ * Parses an W3C XML Schema time string (not date or date-time).
+ * If the time string doesn't specify the time zone offset explicitly,
+ * the value of the {@code defaultTZ} paramter will be used.
+ */
+ public static Date parseXSTime(
+ String timeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ Matcher m = PATTERN_XS_TIME.matcher(timeStr);
+ if (!m.matches()) {
+ throw new DateParseException("The value didn't match the expected pattern: " + PATTERN_XS_TIME);
+ }
+ return parseTime_parseMatcher(m, defaultTZ, calToDateConverter);
+ }
+
+ /**
+ * Same as {@link #parseXSTime(String, TimeZone, CalendarFieldsToDateConverter)} but for ISO 8601 times.
+ */
+ public static Date parseISO8601Time(
+ String timeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ Matcher m = PATTERN_ISO8601_EXTENDED_TIME.matcher(timeStr);
+ if (!m.matches()) {
+ m = PATTERN_ISO8601_BASIC_TIME.matcher(timeStr);
+ if (!m.matches()) {
+ throw new DateParseException("The value didn't match the expected pattern: "
+ + PATTERN_ISO8601_EXTENDED_TIME + " or "
+ + PATTERN_ISO8601_BASIC_TIME);
+ }
+ }
+ return parseTime_parseMatcher(m, defaultTZ, calToDateConverter);
+ }
+
+ private static Date parseTime_parseMatcher(
+ Matcher m, TimeZone defaultTZ,
+ CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ _NullArgumentException.check("defaultTZ", defaultTZ);
+ try {
+ // ISO 8601 allows both 00:00 and 24:00,
+ // but Calendar.set(...) doesn't if the Calendar is not lenient.
+ int hours = groupToInt(m.group(1), "hour-of-day", 0, 24);
+ boolean hourWas24;
+ if (hours == 24) {
+ hours = 0;
+ hourWas24 = true;
+ // And a day will be added later...
+ } else {
+ hourWas24 = false;
+ }
+
+ final String minutesStr = m.group(2);
+ int minutes = minutesStr != null ? groupToInt(minutesStr, "minute", 0, 59) : 0;
+
+ final String secsStr = m.group(3);
+ // Allow 60 because of leap seconds
+ int secs = secsStr != null ? groupToInt(secsStr, "second", 0, 60) : 0;
+
+ int millisecs = groupToMillisecond(m.group(4));
+
+ // As a time is just the distance from the beginning of the day,
+ // the time-zone offest should be 0 usually.
+ TimeZone tz = parseMatchingTimeZone(m.group(5), defaultTZ);
+
+ // Continue handling the 24:00 special case
+ int day;
+ if (hourWas24) {
+ if (minutes == 0 && secs == 0 && millisecs == 0) {
+ day = 2;
+ } else {
+ throw new DateParseException(
+ "Hour 24 is only allowed in the case of "
+ + "midnight.");
+ }
+ } else {
+ day = 1;
+ }
+
+ return calToDateConverter.calculate(
+ GregorianCalendar.AD, 1970, 0, day, hours, minutes, secs, millisecs, false, tz);
+ } catch (IllegalArgumentException e) {
+ // Calendar methods used to throw this for illegal dates.
+ throw new DateParseException(
+ "Unexpected time calculation faliure.");
+ }
+ }
+
+ /**
+ * Parses an W3C XML Schema date-time string (not date or time).
+ * Unlike in ISO 8601:2000 Second Edition, year -1 means B.C 1, and year 0 is invalid.
+ *
+ * @param dateTimeStr the string to parse.
+ * @param defaultTZ used if the dateTime doesn't specify the
+ * time zone offset explicitly. Can't be {@code null}.
+ *
+ * @throws DateParseException if the dateTime is malformed.
+ */
+ public static Date parseXSDateTime(
+ String dateTimeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ Matcher m = PATTERN_XS_DATE_TIME.matcher(dateTimeStr);
+ if (!m.matches()) {
+ throw new DateParseException(
+ "The value didn't match the expected pattern: " + PATTERN_XS_DATE_TIME);
+ }
+ return parseDateTime_parseMatcher(
+ m, defaultTZ, true, calToDateConverter);
+ }
+
+ /**
+ * Same as {@link #parseXSDateTime(String, TimeZone, CalendarFieldsToDateConverter)} but for ISO 8601 format.
+ */
+ public static Date parseISO8601DateTime(
+ String dateTimeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ Matcher m = PATTERN_ISO8601_EXTENDED_DATE_TIME.matcher(dateTimeStr);
+ if (!m.matches()) {
+ m = PATTERN_ISO8601_BASIC_DATE_TIME.matcher(dateTimeStr);
+ if (!m.matches()) {
+ throw new DateParseException("The value (" + dateTimeStr + ") didn't match the expected pattern: "
+ + PATTERN_ISO8601_EXTENDED_DATE_TIME + " or "
+ + PATTERN_ISO8601_BASIC_DATE_TIME);
+ }
+ }
+ return parseDateTime_parseMatcher(
+ m, defaultTZ, false, calToDateConverter);
+ }
+
+ private static Date parseDateTime_parseMatcher(
+ Matcher m, TimeZone defaultTZ,
+ boolean xsMode,
+ CalendarFieldsToDateConverter calToDateConverter)
+ throws DateParseException {
+ _NullArgumentException.check("defaultTZ", defaultTZ);
+ try {
+ int year = groupToInt(m.group(1), "year", Integer.MIN_VALUE, Integer.MAX_VALUE);
+
+ int era;
+ // Starting from ISO 8601:2000 Second Edition, 0001 is AD 1, 0000 is BC 1, -0001 is BC 2.
+ // However, according to http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/, XML schemas are based
+ // on the earlier version where 0000 didn't exist, and year -1 is BC 1.
+ if (year <= 0) {
+ era = GregorianCalendar.BC;
+ year = -year + (xsMode ? 0 : 1);
+ if (year == 0) {
+ throw new DateParseException(MSG_YEAR_0_NOT_ALLOWED);
+ }
+ } else {
+ era = GregorianCalendar.AD;
+ }
+
+ int month = groupToInt(m.group(2), "month", 1, 12) - 1;
+ int day = groupToInt(m.group(3), "day-of-month", 1, 31);
+
+ // ISO 8601 allows both 00:00 and 24:00,
+ // but cal.set(...) doesn't if the Calendar is not lenient.
+ int hours = groupToInt(m.group(4), "hour-of-day", 0, 24);
+ boolean hourWas24;
+ if (hours == 24) {
+ hours = 0;
+ hourWas24 = true;
+ // And a day will be added later...
+ } else {
+ hourWas24 = false;
+ }
+
+ final String minutesStr = m.group(5);
+ int minutes = minutesStr != null ? groupToInt(minutesStr, "minute", 0, 59) : 0;
+
+ final String secsStr = m.group(6);
+ // Allow 60 because of leap seconds
+ int secs = secsStr != null ? groupToInt(secsStr, "second", 0, 60) : 0;
+
+ int millisecs = groupToMillisecond(m.group(7));
+
+ // As a time is just the distance from the beginning of the day,
+ // the time-zone offest should be 0 usually.
+ TimeZone tz = parseMatchingTimeZone(m.group(8), defaultTZ);
+
+ // Continue handling the 24:00 specail case
+ if (hourWas24) {
+ if (minutes != 0 || secs != 0 || millisecs != 0) {
+ throw new DateParseException(
+ "Hour 24 is only allowed in the case of "
+ + "midnight.");
+ }
+ }
+
+ return calToDateConverter.calculate(
+ era, year, month, day, hours, minutes, secs, millisecs, hourWas24, tz);
+ } catch (IllegalArgumentException e) {
+ // Calendar methods used to throw this for illegal dates.
+ throw new DateParseException(
+ "Date-time calculation faliure. "
+ + "Probably the date-time is formally correct, but "
+ + "refers to an unexistent date-time "
+ + "(like February 30).");
+ }
+ }
+
+ /**
+ * Parses the time zone part from a W3C XML Schema date/time/dateTime.
+ * @throws DateParseException if the zone is malformed.
+ */
+ public static TimeZone parseXSTimeZone(String timeZoneStr)
+ throws DateParseException {
+ Matcher m = PATTERN_XS_TIME_ZONE.matcher(timeZoneStr);
+ if (!m.matches()) {
+ throw new DateParseException(
+ "The time zone offset didn't match the expected pattern: " + PATTERN_XS_TIME_ZONE);
+ }
+ return parseMatchingTimeZone(timeZoneStr, null);
+ }
+
+ private static int groupToInt(String g, String gName,
+ int min, int max)
+ throws DateParseException {
+ if (g == null) {
+ throw new DateParseException("The " + gName + " part "
+ + "is missing.");
+ }
+
+ int start;
+
+ // Remove minus sign, so we can remove the 0-s later:
+ boolean negative;
+ if (g.startsWith("-")) {
+ negative = true;
+ start = 1;
+ } else {
+ negative = false;
+ start = 0;
+ }
+
+ // Remove leading 0-s:
+ while (start < g.length() - 1 && g.charAt(start) == '0') {
+ start++;
+ }
+ if (start != 0) {
+ g = g.substring(start);
+ }
+
+ try {
+ int r = Integer.parseInt(g);
+ if (negative) {
+ r = -r;
+ }
+ if (r < min) {
+ throw new DateParseException("The " + gName + " part "
+ + "must be at least " + min + ".");
+ }
+ if (r > max) {
+ throw new DateParseException("The " + gName + " part "
+ + "can't be more than " + max + ".");
+ }
+ return r;
+ } catch (NumberFormatException e) {
+ throw new DateParseException("The " + gName + " part "
+ + "is a malformed integer.");
+ }
+ }
+
+ private static TimeZone parseMatchingTimeZone(
+ String s, TimeZone defaultZone)
+ throws DateParseException {
+ if (s == null) {
+ return defaultZone;
+ }
+ if (s.equals("Z")) {
+ return _DateUtils.UTC;
+ }
+
+ StringBuilder sb = new StringBuilder(9);
+ sb.append("GMT");
+ sb.append(s.charAt(0));
+
+ String h = s.substring(1, 3);
+ groupToInt(h, "offset-hours", 0, 23);
+ sb.append(h);
+
+ String m;
+ int ln = s.length();
+ if (ln > 3) {
+ int startIdx = s.charAt(3) == ':' ? 4 : 3;
+ m = s.substring(startIdx, startIdx + 2);
+ groupToInt(m, "offset-minutes", 0, 59);
+ sb.append(':');
+ sb.append(m);
+ }
+
+ return TimeZone.getTimeZone(sb.toString());
+ }
+
+ private static int groupToMillisecond(String g)
+ throws DateParseException {
+ if (g == null) {
+ return 0;
+ }
+
+ if (g.length() > 3) {
+ g = g.substring(0, 3);
+ }
+ int i = groupToInt(g, "partial-seconds", 0, Integer.MAX_VALUE);
+ return g.length() == 1 ? i * 100 : (g.length() == 2 ? i * 10 : i);
+ }
+
+ /**
+ * Used internally by {@link _DateUtils}; don't use its implementations for
+ * anything else.
+ */
+ public interface DateToISO8601CalendarFactory {
+
+ /**
+ * Returns a {@link GregorianCalendar} with the desired time zone and
+ * time and US locale. The returned calendar is used as read-only.
+ * It must be guaranteed that within a thread the instance returned last time
+ * is not in use anymore when this method is called again.
+ */
+ GregorianCalendar get(TimeZone tz, Date date);
+
+ }
+
+ /**
+ * Used internally by {@link _DateUtils}; don't use its implementations for anything else.
+ */
+ public interface CalendarFieldsToDateConverter {
+
+ /**
+ * Calculates the {@link Date} from the specified calendar fields.
+ */
+ Date calculate(int era, int year, int month, int day, int hours, int minutes, int secs, int millisecs,
+ boolean addOneDay,
+ TimeZone tz);
+
+ }
+
+ /**
+ * Non-thread-safe factory that hard-references a calendar internally.
+ */
+ public static final class TrivialDateToISO8601CalendarFactory
+ implements DateToISO8601CalendarFactory {
+
+ private GregorianCalendar calendar;
+ private TimeZone lastlySetTimeZone;
+
+ @Override
+ public GregorianCalendar get(TimeZone tz, Date date) {
+ if (calendar == null) {
+ calendar = new GregorianCalendar(tz, Locale.US);
+ calendar.setGregorianChange(new Date(Long.MIN_VALUE)); // never use Julian calendar
+ } else {
+ // At least on Java 6, calendar.getTimeZone is slow due to a bug, so we need lastlySetTimeZone.
+ if (lastlySetTimeZone != tz) { // Deliberately `!=` instead of `!<...>.equals()`
+ calendar.setTimeZone(tz);
+ lastlySetTimeZone = tz;
+ }
+ }
+ calendar.setTime(date);
+ return calendar;
+ }
+
+ }
+
+ /**
+ * Non-thread-safe implementation that hard-references a calendar internally.
+ */
+ public static final class TrivialCalendarFieldsToDateConverter
+ implements CalendarFieldsToDateConverter {
+
+ private GregorianCalendar calendar;
+ private TimeZone lastlySetTimeZone;
+
+ @Override
+ public Date calculate(int era, int year, int month, int day, int hours, int minutes, int secs, int millisecs,
+ boolean addOneDay, TimeZone tz) {
+ if (calendar == null) {
+ calendar = new GregorianCalendar(tz, Locale.US);
+ calendar.setLenient(false);
+ calendar.setGregorianChange(new Date(Long.MIN_VALUE)); // never use Julian calendar
+ } else {
+ // At least on Java 6, calendar.getTimeZone is slow due to a bug, so we need lastlySetTimeZone.
+ if (lastlySetTimeZone != tz) { // Deliberately `!=` instead of `!<...>.equals()`
+ calendar.setTimeZone(tz);
+ lastlySetTimeZone = tz;
+ }
+ }
+
+ calendar.set(Calendar.ERA, era);
+ calendar.set(Calendar.YEAR, year);
+ calendar.set(Calendar.MONTH, month);
+ calendar.set(Calendar.DAY_OF_MONTH, day);
+ calendar.set(Calendar.HOUR_OF_DAY, hours);
+ calendar.set(Calendar.MINUTE, minutes);
+ calendar.set(Calendar.SECOND, secs);
+ calendar.set(Calendar.MILLISECOND, millisecs);
+ if (addOneDay) {
+ calendar.add(Calendar.DAY_OF_MONTH, 1);
+ }
+
+ return calendar.getTime();
+ }
+
+ }
+
+ public static final class DateParseException extends ParseException {
+
+ public DateParseException(String message) {
+ super(message, 0);
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_JavaVersions.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_JavaVersions.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_JavaVersions.java
index 96a9583..88efaca 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_JavaVersions.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_JavaVersions.java
@@ -37,7 +37,7 @@ public final class _JavaVersions {
private static final boolean IS_AT_LEAST_8;
static {
boolean result = false;
- String vStr = _SecurityUtil.getSystemProperty("java.version", null);
+ String vStr = _SecurityUtils.getSystemProperty("java.version", null);
if (vStr != null) {
try {
Version v = new Version(vStr);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtil.java
deleted file mode 100644
index 2f09c88..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_LocaleUtil.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.freemarker.core.util;
-
-import java.util.Locale;
-
-/**
- * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
- */
-public class _LocaleUtil {
-
- /**
- * Returns a locale that's one less specific, or {@code null} if there's no less specific locale.
- */
- public static Locale getLessSpecificLocale(Locale locale) {
- String country = locale.getCountry();
- if (locale.getVariant().length() != 0) {
- String language = locale.getLanguage();
- return country != null ? new Locale(language, country) : new Locale(language);
- }
- if (country.length() != 0) {
- return new Locale(locale.getLanguage());
- }
- return null;
- }
-
-}
[02/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtil.java b/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtil.java
deleted file mode 100644
index f5b58f8..0000000
--- a/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtil.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.dom;
-
-/**
- * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
- * This class is to work around the lack of module system in Java, i.e., so that other FreeMarker packages can
- * access things inside this package that users shouldn't.
- */
-final class DomStringUtil {
-
- private DomStringUtil() {
- // Not meant to be instantiated
- }
-
- static boolean isXMLNameLike(String name) {
- return isXMLNameLike(name, 0);
- }
-
- /**
- * Check if the name looks like an XML element name.
- *
- * @param firstCharIdx The index of the character in the string parameter that we treat as the beginning of the
- * string to check. This is to spare substringing that has become more expensive in Java 7.
- *
- * @return whether the name is a valid XML element name. (This routine might only be 99% accurate. REVISIT)
- */
- static boolean isXMLNameLike(String name, int firstCharIdx) {
- int ln = name.length();
- for (int i = firstCharIdx; i < ln; i++) {
- char c = name.charAt(i);
- if (i == firstCharIdx && (c == '-' || c == '.' || Character.isDigit(c))) {
- return false;
- }
- if (!Character.isLetterOrDigit(c) && c != '_' && c != '-' && c != '.') {
- if (c == ':') {
- if (i + 1 < ln && name.charAt(i + 1) == ':') {
- // "::" is used in XPath
- return false;
- }
- // We don't return here, as a lonely ":" is allowed.
- } else {
- return false;
- }
- }
- }
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtils.java b/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtils.java
new file mode 100644
index 0000000..b796c1e
--- /dev/null
+++ b/freemarker-dom/src/main/java/org/apache/freemarker/dom/DomStringUtils.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.dom;
+
+/**
+ * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
+ * This class is to work around the lack of module system in Java, i.e., so that other FreeMarker packages can
+ * access things inside this package that users shouldn't.
+ */
+final class DomStringUtils {
+
+ private DomStringUtils() {
+ // Not meant to be instantiated
+ }
+
+ static boolean isXMLNameLike(String name) {
+ return isXMLNameLike(name, 0);
+ }
+
+ /**
+ * Check if the name looks like an XML element name.
+ *
+ * @param firstCharIdx The index of the character in the string parameter that we treat as the beginning of the
+ * string to check. This is to spare substringing that has become more expensive in Java 7.
+ *
+ * @return whether the name is a valid XML element name. (This routine might only be 99% accurate. REVISIT)
+ */
+ static boolean isXMLNameLike(String name, int firstCharIdx) {
+ int ln = name.length();
+ for (int i = firstCharIdx; i < ln; i++) {
+ char c = name.charAt(i);
+ if (i == firstCharIdx && (c == '-' || c == '.' || Character.isDigit(c))) {
+ return false;
+ }
+ if (!Character.isLetterOrDigit(c) && c != '_' && c != '-' && c != '.') {
+ if (c == ':') {
+ if (i + 1 < ln && name.charAt(i + 1) == ':') {
+ // "::" is used in XPath
+ return false;
+ }
+ // We don't return here, as a lonely ":" is allowed.
+ } else {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-dom/src/main/java/org/apache/freemarker/dom/ElementModel.java
----------------------------------------------------------------------
diff --git a/freemarker-dom/src/main/java/org/apache/freemarker/dom/ElementModel.java b/freemarker-dom/src/main/java/org/apache/freemarker/dom/ElementModel.java
index 220f414..5e9de70 100644
--- a/freemarker-dom/src/main/java/org/apache/freemarker/dom/ElementModel.java
+++ b/freemarker-dom/src/main/java/org/apache/freemarker/dom/ElementModel.java
@@ -28,7 +28,7 @@ import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.TemplateSequenceModel;
import org.apache.freemarker.core.model.impl.SimpleScalar;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -104,7 +104,7 @@ class ElementModel extends NodeModel implements TemplateScalarModel {
return super.get(key);
}
} else { // Starts with "@", but not with "@@"
- if (DomStringUtil.isXMLNameLike(key, 1)) {
+ if (DomStringUtils.isXMLNameLike(key, 1)) {
Attr att = getAttribute(key.substring(1));
if (att == null) {
return new NodeListModel(this);
@@ -117,7 +117,7 @@ class ElementModel extends NodeModel implements TemplateScalarModel {
return super.get(key);
}
}
- } else if (DomStringUtil.isXMLNameLike(key)) {
+ } else if (DomStringUtils.isXMLNameLike(key)) {
// We interpret key as an element name
NodeListModel result = ((NodeListModel) getChildNodes()).filterByName(key);
return result.size() != 1 ? result : result.get(0);
@@ -229,6 +229,6 @@ class ElementModel extends NodeModel implements TemplateScalarModel {
}
boolean matchesName(String name, Environment env) {
- return _StringUtil.matchesQName(name, getNodeName(), getNodeNamespace(), env);
+ return _StringUtils.matchesQName(name, getNodeName(), getNodeNamespace(), env);
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeListModel.java
----------------------------------------------------------------------
diff --git a/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeListModel.java b/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeListModel.java
index 333bb5c..ab7d701 100644
--- a/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeListModel.java
+++ b/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeListModel.java
@@ -137,9 +137,9 @@ class NodeListModel extends SimpleSequence implements TemplateHashModel, _Unexpe
}
}
}
- if (DomStringUtil.isXMLNameLike(key)
+ if (DomStringUtils.isXMLNameLike(key)
|| ((key.startsWith("@")
- && (DomStringUtil.isXMLNameLike(key, 1) || key.equals("@@") || key.equals("@*"))))
+ && (DomStringUtils.isXMLNameLike(key, 1) || key.equals("@@") || key.equals("@*"))))
|| key.equals("*") || key.equals("**")) {
NodeListModel result = new NodeListModel(contextNode);
for (int i = 0; i < size(); i++) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeOutputter.java
----------------------------------------------------------------------
diff --git a/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeOutputter.java b/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeOutputter.java
index bda38ac..7b543f4 100644
--- a/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeOutputter.java
+++ b/freemarker-dom/src/main/java/org/apache/freemarker/dom/NodeOutputter.java
@@ -25,7 +25,7 @@ import java.util.LinkedHashMap;
import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.Template;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
@@ -78,7 +78,7 @@ class NodeOutputter {
if (prefix == null) {
// Assign a generated prefix:
do {
- prefix = _StringUtil.toLowerABC(nextGeneratedPrefixNumber++);
+ prefix = _StringUtils.toLowerABC(nextGeneratedPrefixNumber++);
} while (env.getNamespaceForPrefix(prefix) != null);
}
}
@@ -150,7 +150,7 @@ class NodeOutputter {
buf.append(' ');
outputQualifiedName(n, buf);
buf.append("=\"")
- .append(_StringUtil.XMLEncQAttr(n.getNodeValue()))
+ .append(_StringUtils.XMLEncQAttr(n.getNodeValue()))
.append('"');
}
break;
@@ -216,7 +216,7 @@ class NodeOutputter {
}*/
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE: {
- buf.append(_StringUtil.XMLEncNQG(n.getNodeValue()));
+ buf.append(_StringUtils.XMLEncNQG(n.getNodeValue()));
break;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-dom/src/test/java/org/apache/freemarker/dom/test/DOMLoader.java
----------------------------------------------------------------------
diff --git a/freemarker-dom/src/test/java/org/apache/freemarker/dom/test/DOMLoader.java b/freemarker-dom/src/test/java/org/apache/freemarker/dom/test/DOMLoader.java
index bc957c5..cbb06e5 100644
--- a/freemarker-dom/src/test/java/org/apache/freemarker/dom/test/DOMLoader.java
+++ b/freemarker-dom/src/test/java/org/apache/freemarker/dom/test/DOMLoader.java
@@ -30,7 +30,7 @@ import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.dom.NodeModel;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@@ -89,7 +89,7 @@ public final class DOMLoader {
InputStream in = baseClass.getResourceAsStream(resourcePath);
if (in == null) {
throw new FileNotFoundException("Class loader resource not found: baseClass=" + baseClass.getName()
- + "; path=" + _StringUtil.jQuote(resourcePath));
+ + "; path=" + _StringUtils.jQuote(resourcePath));
}
return toModel(new InputSource(in));
}
@@ -121,7 +121,7 @@ public final class DOMLoader {
InputStream in = baseClass.getResourceAsStream(resourcePath);
if (in == null) {
throw new FileNotFoundException("Class loader resource not found: baseClass="
- + baseClass.getName() + "; " + "path=" + _StringUtil.jQuote(resourcePath));
+ + baseClass.getName() + "; " + "path=" + _StringUtils.jQuote(resourcePath));
}
return builder.parse(new InputSource(in));
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/BaseNTemplateNumberFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/BaseNTemplateNumberFormatFactory.java b/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/BaseNTemplateNumberFormatFactory.java
index f987dcd..a670b62 100644
--- a/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/BaseNTemplateNumberFormatFactory.java
+++ b/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/BaseNTemplateNumberFormatFactory.java
@@ -23,8 +23,8 @@ import java.util.Locale;
import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNumberModel;
-import org.apache.freemarker.core.util._NumberUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._NumberUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.TemplateFormatUtil;
import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
@@ -60,7 +60,7 @@ public class BaseNTemplateNumberFormatFactory extends TemplateNumberFormatFactor
} catch (TemplateValueFormatException e) {
throw new InvalidFormatParametersException(
"Couldn't get the fallback number format (specified after the \"|\"), "
- + _StringUtil.jQuote(fallbackFormatStr) + ". Reason: " + e.getMessage(),
+ + _StringUtils.jQuote(fallbackFormatStr) + ". Reason: " + e.getMessage(),
e);
}
} else {
@@ -78,7 +78,7 @@ public class BaseNTemplateNumberFormatFactory extends TemplateNumberFormatFactor
}
throw new InvalidFormatParametersException(
"The format paramter must be an integer, but was (shown quoted): "
- + _StringUtil.jQuote(params));
+ + _StringUtils.jQuote(params));
}
if (base < 2) {
throw new InvalidFormatParametersException("A base must be at least 2.");
@@ -101,7 +101,7 @@ public class BaseNTemplateNumberFormatFactory extends TemplateNumberFormatFactor
throws TemplateModelException, TemplateValueFormatException {
Number n = TemplateFormatUtil.getNonNullNumber(numberModel);
try {
- return Integer.toString(_NumberUtil.toIntExact(n), base);
+ return Integer.toString(_NumberUtils.toIntExact(n), base);
} catch (ArithmeticException e) {
if (fallbackFormat == null) {
throw new UnformattableValueException(
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/TemplateConfigurationExamples.java
----------------------------------------------------------------------
diff --git a/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/TemplateConfigurationExamples.java b/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/TemplateConfigurationExamples.java
index 078e4db..d1b5e3e 100644
--- a/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/TemplateConfigurationExamples.java
+++ b/freemarker-manual/src/test/java/org/apache/freemarker/manual/examples/TemplateConfigurationExamples.java
@@ -37,7 +37,7 @@ import org.apache.freemarker.core.templateresolver.FirstMatchTemplateConfigurati
import org.apache.freemarker.core.templateresolver.MergingTemplateConfigurationFactory;
import org.apache.freemarker.core.templateresolver.OrMatcher;
import org.apache.freemarker.core.templateresolver.PathGlobMatcher;
-import org.apache.freemarker.core.util._DateUtil;
+import org.apache.freemarker.core.util._DateUtils;
import org.apache.freemarker.test.TemplateTest;
import org.apache.freemarker.test.TestConfigurationBuilder;
import org.junit.Test;
@@ -144,7 +144,7 @@ public class TemplateConfigurationExamples extends TemplateTest {
.dateTimeFormat("iso")
.dateFormat("iso")
.timeFormat("iso")
- .timeZone(_DateUtil.UTC)
+ .timeZone(_DateUtils.UTC)
.build()),
new ConditionalTemplateConfigurationFactory(
new PathGlobMatcher("mail/**"),
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/FreemarkerServlet.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/FreemarkerServlet.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/FreemarkerServlet.java
index 181d0ab..2121720 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/FreemarkerServlet.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/FreemarkerServlet.java
@@ -61,9 +61,9 @@ import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.FileTemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader;
-import org.apache.freemarker.core.util._CollectionUtil;
-import org.apache.freemarker.core.util._SecurityUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
+import org.apache.freemarker.core.util._SecurityUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.servlet.jsp.TaglibFactory;
import org.apache.freemarker.servlet.jsp.TaglibFactory.ClasspathMetaInfTldSource;
import org.apache.freemarker.servlet.jsp.TaglibFactory.MetaInfTldSource;
@@ -566,7 +566,7 @@ public class FreemarkerServlet extends HttpServlet {
}
if (value == null) {
throw new MalformedWebXmlException(
- "init-param " + _StringUtil.jQuote(name) + " without param-value. "
+ "init-param " + _StringUtils.jQuote(name) + " without param-value. "
+ "Maybe the web.xml is not well-formed?");
}
@@ -611,16 +611,16 @@ public class FreemarkerServlet extends HttpServlet {
"Not one of the supported values.");
}
} else if (name.equals(INIT_PARAM_NO_CACHE)) {
- noCache = _StringUtil.getYesNo(value);
+ noCache = _StringUtils.getYesNo(value);
} else if (name.equals(INIT_PARAM_BUFFER_SIZE)) {
bufferSize = Integer.valueOf(parseSize(value));
} else if (name.equals(DEPR_INITPARAM_DEBUG)) { // BC
if (getInitParameter(INIT_PARAM_DEBUG) != null) {
throw new ConflictingInitParamsException(INIT_PARAM_DEBUG, DEPR_INITPARAM_DEBUG);
}
- debug = _StringUtil.getYesNo(value);
+ debug = _StringUtils.getYesNo(value);
} else if (name.equals(INIT_PARAM_DEBUG)) {
- debug = _StringUtil.getYesNo(value);
+ debug = _StringUtils.getYesNo(value);
} else if (name.equals(INIT_PARAM_CONTENT_TYPE)) {
contentType = new ContentType(value);
} else if (name.equals(INIT_PARAM_OVERRIDE_RESPONSE_CONTENT_TYPE)) {
@@ -634,7 +634,7 @@ public class FreemarkerServlet extends HttpServlet {
} else if (name.equals(INIT_PARAM_OVERRIDE_RESPONSE_LOCALE)) {
overrideResponseLocale = initParamValueToEnum(value, OverrideResponseLocale.values());
} else if (name.equals(INIT_PARAM_EXCEPTION_ON_MISSING_TEMPLATE)) {
- exceptionOnMissingTemplate = _StringUtil.getYesNo(value);
+ exceptionOnMissingTemplate = _StringUtils.getYesNo(value);
} else if (name.equals(INIT_PARAM_META_INF_TLD_LOCATIONS)) {
metaInfTldSources = TaglibFactory.parseMetaInfTldLocations(InitParamParser.parseCommaSeparatedList(value));
} else if (name.equals(INIT_PARAM_CLASSPATH_TLDS)) {
@@ -722,7 +722,7 @@ public class FreemarkerServlet extends HttpServlet {
String templatePath = requestUrlToTemplatePath(request);
if (LOG.isDebugEnabled()) {
- LOG.debug("Requested template " + _StringUtil.jQuoteNoXSS(templatePath) + ".");
+ LOG.debug("Requested template " + _StringUtils.jQuoteNoXSS(templatePath) + ".");
}
Locale locale = request.getLocale();
@@ -736,21 +736,21 @@ public class FreemarkerServlet extends HttpServlet {
} catch (TemplateNotFoundException e) {
if (exceptionOnMissingTemplate) {
throw newServletExceptionWithFreeMarkerLogging(
- "Template not found for name " + _StringUtil.jQuoteNoXSS(templatePath) + ".", e);
+ "Template not found for name " + _StringUtils.jQuoteNoXSS(templatePath) + ".", e);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Responding HTTP 404 \"Not found\" for missing template "
- + _StringUtil.jQuoteNoXSS(templatePath) + ".", e);
+ + _StringUtils.jQuoteNoXSS(templatePath) + ".", e);
}
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Page template not found");
return;
}
} catch (org.apache.freemarker.core.ParseException e) {
throw newServletExceptionWithFreeMarkerLogging(
- "Parsing error with template " + _StringUtil.jQuoteNoXSS(templatePath) + ".", e);
+ "Parsing error with template " + _StringUtils.jQuoteNoXSS(templatePath) + ".", e);
} catch (Exception e) {
throw newServletExceptionWithFreeMarkerLogging(
- "Unexpected error when loading template " + _StringUtil.jQuoteNoXSS(templatePath) + ".", e);
+ "Unexpected error when loading template " + _StringUtils.jQuoteNoXSS(templatePath) + ".", e);
}
boolean tempSpecContentTypeContainsCharset = false;
@@ -810,7 +810,7 @@ public class FreemarkerServlet extends HttpServlet {
throw new IllegalStateException(
"Failed to resolve charset name returned by "
+ " HttpServletResponse.getCharacterEncoding(): "
- + _StringUtil.jQuote(actualOutputCharsetName),
+ + _StringUtils.jQuote(actualOutputCharsetName),
e);
}
env.setOutputEncoding(actualOutputCharset);
@@ -1001,7 +1001,7 @@ public class FreemarkerServlet extends HttpServlet {
List<MetaInfTldSource> metaInfTldSourcesFromSysProp = null;
try {
- final String prop = _SecurityUtil.getSystemProperty(SYSTEM_PROPERTY_META_INF_TLD_SOURCES, null);
+ final String prop = _SecurityUtils.getSystemProperty(SYSTEM_PROPERTY_META_INF_TLD_SOURCES, null);
metaInfTldSourcesFromSysProp = (List<MetaInfTldSource>) ((prop != null)
? TaglibFactory.parseMetaInfTldLocations(InitParamParser.parseCommaSeparatedList(prop))
: Collections.emptyList());
@@ -1026,7 +1026,7 @@ public class FreemarkerServlet extends HttpServlet {
List<String> classpathTldsFromSysProp = null;
try {
- final String prop = _SecurityUtil.getSystemProperty(SYSTEM_PROPERTY_CLASSPATH_TLDS, null);
+ final String prop = _SecurityUtils.getSystemProperty(SYSTEM_PROPERTY_CLASSPATH_TLDS, null);
classpathTldsFromSysProp = (prop != null) ? InitParamParser.parseCommaSeparatedList(prop)
: Collections.<String>emptyList();
} catch (ParseException e) {
@@ -1035,10 +1035,10 @@ public class FreemarkerServlet extends HttpServlet {
}
return new TaglibFactory.Builder(servletContext, objectWrapper)
- .metaInfTldSources(_CollectionUtil.mergeImmutableLists(true, metaInfTldSources,
+ .metaInfTldSources(_CollectionUtils.mergeImmutableLists(true, metaInfTldSources,
metaInfTldSourcesFromSysProp, jettyMetaInfTldSources))
.classpathTlds(
- _CollectionUtil.mergeImmutableLists(classpathTlds, classpathTldsFromSysProp, true))
+ _CollectionUtils.mergeImmutableLists(classpathTlds, classpathTldsFromSysProp, true))
.build();
}
@@ -1329,14 +1329,14 @@ public class FreemarkerServlet extends HttpServlet {
private static class InitParamValueException extends Exception {
InitParamValueException(String initParamName, String initParamValue, Throwable casue) {
- super("Failed to set the " + _StringUtil.jQuote(initParamName) + " servlet init-param to "
- + _StringUtil.jQuote(initParamValue) + "; see cause exception.",
+ super("Failed to set the " + _StringUtils.jQuote(initParamName) + " servlet init-param to "
+ + _StringUtils.jQuote(initParamValue) + "; see cause exception.",
casue);
}
public InitParamValueException(String initParamName, String initParamValue, String cause) {
- super("Failed to set the " + _StringUtil.jQuote(initParamName) + " servlet init-param to "
- + _StringUtil.jQuote(initParamValue) + ": " + cause);
+ super("Failed to set the " + _StringUtils.jQuote(initParamName) + " servlet init-param to "
+ + _StringUtils.jQuote(initParamValue) + ": " + cause);
}
}
@@ -1346,8 +1346,8 @@ public class FreemarkerServlet extends HttpServlet {
ConflictingInitParamsException(String recommendedName, String otherName) {
super("Conflicting servlet init-params: "
- + _StringUtil.jQuote(recommendedName) + " and " + _StringUtil.jQuote(otherName)
- + ". Only use " + _StringUtil.jQuote(recommendedName) + ".");
+ + _StringUtils.jQuote(recommendedName) + " and " + _StringUtils.jQuote(otherName)
+ + ". Only use " + _StringUtils.jQuote(recommendedName) + ".");
}
}
@@ -1411,7 +1411,7 @@ public class FreemarkerServlet extends HttpServlet {
}
StringBuilder sb = new StringBuilder();
- sb.append(_StringUtil.jQuote(initParamValue));
+ sb.append(_StringUtils.jQuote(initParamValue));
sb.append(" is not a one of the enumeration values: ");
boolean first = true;
for (T value : enumValues) {
@@ -1420,7 +1420,7 @@ public class FreemarkerServlet extends HttpServlet {
} else {
first = false;
}
- sb.append(_StringUtil.jQuote(value.getInitParamValue()));
+ sb.append(_StringUtils.jQuote(value.getInitParamValue()));
}
throw new IllegalArgumentException(sb.toString());
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/InitParamParser.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/InitParamParser.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/InitParamParser.java
index 323e15f..e74d475 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/InitParamParser.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/InitParamParser.java
@@ -33,7 +33,7 @@ import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.FileTemplateLoader;
import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -127,7 +127,7 @@ final class InitParamParser {
static List<String> parseCommaSeparatedList(String value) throws ParseException {
List<String> valuesList = new ArrayList<>();
- String[] values = _StringUtil.split(value, ',');
+ String[] values = _StringUtils.split(value, ',');
for (int i = 0; i < values.length; i++) {
final String s = values[i].trim();
if (s.length() != 0) {
@@ -243,7 +243,7 @@ final class InitParamParser {
if (!biName.equals(TEMPLATE_PATH_SETTINGS_BI_NAME)) {
throw new TemplatePathParsingException(
- _StringUtil.jQuote(biName) + " is unexpected after the \"?\". "
+ _StringUtils.jQuote(biName) + " is unexpected after the \"?\". "
+ "Expected \"" + TEMPLATE_PATH_SETTINGS_BI_NAME + "\".");
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/WebAppTemplateLoader.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/WebAppTemplateLoader.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/WebAppTemplateLoader.java
index adbc5e0..b72ce78 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/WebAppTemplateLoader.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/WebAppTemplateLoader.java
@@ -38,9 +38,9 @@ import org.apache.freemarker.core.templateresolver.TemplateLoadingResult;
import org.apache.freemarker.core.templateresolver.TemplateLoadingSource;
import org.apache.freemarker.core.templateresolver.impl.URLTemplateLoader;
import org.apache.freemarker.core.templateresolver.impl._TemplateLoaderUtils;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -119,16 +119,16 @@ public class WebAppTemplateLoader implements TemplateLoader {
@Override
public String toString() {
return _TemplateLoaderUtils.getClassNameForToString(this)
- + "(subdirPath=" + _StringUtil.jQuote(subdirPath)
- + ", servletContext={contextPath=" + _StringUtil.jQuote(getContextPath())
- + ", displayName=" + _StringUtil.jQuote(servletContext.getServletContextName()) + "})";
+ + "(subdirPath=" + _StringUtils.jQuote(subdirPath)
+ + ", servletContext={contextPath=" + _StringUtils.jQuote(getContextPath())
+ + ", displayName=" + _StringUtils.jQuote(servletContext.getServletContextName()) + "})";
}
/** Gets the context path if we are on Servlet 2.5+, or else returns failure description string. */
private String getContextPath() {
try {
- Method m = servletContext.getClass().getMethod("getContextPath", _CollectionUtil.EMPTY_CLASS_ARRAY);
- return (String) m.invoke(servletContext, _CollectionUtil.EMPTY_OBJECT_ARRAY);
+ Method m = servletContext.getClass().getMethod("getContextPath", _CollectionUtils.EMPTY_CLASS_ARRAY);
+ return (String) m.invoke(servletContext, _CollectionUtils.EMPTY_OBJECT_ARRAY);
} catch (Throwable e) {
return "[can't query before Serlvet 2.5]";
}
@@ -221,7 +221,7 @@ public class WebAppTemplateLoader implements TemplateLoader {
url = servletContext.getResource(fullPath);
} catch (MalformedURLException e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Could not retrieve resource " + _StringUtil.jQuoteNoXSS(fullPath), e);
+ LOG.warn("Could not retrieve resource " + _StringUtils.jQuoteNoXSS(fullPath), e);
}
return null;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/FreeMarkerJspApplicationContext.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/FreeMarkerJspApplicationContext.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/FreeMarkerJspApplicationContext.java
index 12f0d3c..559c70f 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/FreeMarkerJspApplicationContext.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/FreeMarkerJspApplicationContext.java
@@ -40,7 +40,7 @@ import javax.servlet.jsp.JspApplicationContext;
import javax.servlet.jsp.el.ImplicitObjectELResolver;
import javax.servlet.jsp.el.ScopedAttributeELResolver;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -85,7 +85,7 @@ class FreeMarkerJspApplicationContext implements JspApplicationContext {
private static ExpressionFactory tryExpressionFactoryImplementation(String packagePrefix) {
String className = packagePrefix + ".el.ExpressionFactoryImpl";
try {
- Class cl = _ClassUtil.forName(className);
+ Class cl = _ClassUtils.forName(className);
if (ExpressionFactory.class.isAssignableFrom(cl)) {
LOG.info("Using {} as implementation of {}", className, ExpressionFactory.class.getName());
return (ExpressionFactory) cl.newInstance();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspTagModelBase.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspTagModelBase.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspTagModelBase.java
index 01418ba..bf2a433 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspTagModelBase.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspTagModelBase.java
@@ -45,7 +45,7 @@ import org.apache.freemarker.core.model.TemplateHashModelEx2;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.impl.DefaultObjectWrapper;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.servlet.jsp.SimpleTagDirectiveModel.TemplateExceptionWrapperJspException;
class JspTagModelBase {
@@ -93,7 +93,7 @@ class JspTagModelBase {
}
} else {
throw new TemplateModelException("Unknown property "
- + _StringUtil.jQuote(paramName.toString())
+ + _StringUtils.jQuote(paramName.toString())
+ " on instance of " + tagClass.getName());
}
} else {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspWriterAdapter.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspWriterAdapter.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspWriterAdapter.java
index 2136968..8f135c2 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspWriterAdapter.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/JspWriterAdapter.java
@@ -24,10 +24,10 @@ import java.io.Writer;
import javax.servlet.jsp.JspWriter;
-import org.apache.freemarker.core.util._SecurityUtil;
+import org.apache.freemarker.core.util._SecurityUtils;
class JspWriterAdapter extends JspWriter {
- static final char[] NEWLINE = _SecurityUtil.getSystemProperty("line.separator", "\n").toCharArray();
+ static final char[] NEWLINE = _SecurityUtils.getSystemProperty("line.separator", "\n").toCharArray();
private final Writer out;
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibFactory.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibFactory.java
index a1525af..6aaae12 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibFactory.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibFactory.java
@@ -72,9 +72,9 @@ import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.impl.DefaultObjectWrapper;
import org.apache.freemarker.core.util.BugException;
import org.apache.freemarker.core.util.CommonBuilder;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.servlet.FreemarkerServlet;
import org.apache.freemarker.servlet.HttpRequestHashModel;
import org.slf4j.Logger;
@@ -251,7 +251,7 @@ public class TaglibFactory implements TemplateHashModel {
try {
if (LOG.isDebugEnabled()) {
- LOG.debug("Locating TLD for taglib URI " + _StringUtil.jQuoteNoXSS(taglibUri) + ".");
+ LOG.debug("Locating TLD for taglib URI " + _StringUtils.jQuoteNoXSS(taglibUri) + ".");
}
TldLocation explicitlyMappedTldLocation = getExplicitlyMappedTldLocation(taglibUri);
@@ -267,7 +267,7 @@ public class TaglibFactory implements TemplateHashModel {
try {
urlType = getUriType(taglibUri);
} catch (MalformedURLException e) {
- throw new TaglibGettingException("Malformed taglib URI: " + _StringUtil.jQuote(taglibUri), e);
+ throw new TaglibGettingException("Malformed taglib URI: " + _StringUtils.jQuote(taglibUri), e);
}
if (urlType == URL_TYPE_RELATIVE) {
@@ -279,7 +279,7 @@ public class TaglibFactory implements TemplateHashModel {
String failedTLDsList = getFailedTLDsList();
failedTldListAlreadyIncluded = true;
throw new TaglibGettingException("No TLD was found for the "
- + _StringUtil.jQuoteNoXSS(taglibUri) + " JSP taglib URI. (TLD-s are searched according "
+ + _StringUtils.jQuoteNoXSS(taglibUri) + " JSP taglib URI. (TLD-s are searched according "
+ "the JSP 2.2 specification. In development- and embedded-servlet-container "
+ "setups you may also need the "
+ "\"" + FreemarkerServlet.INIT_PARAM_META_INF_TLD_LOCATIONS + "\" and "
@@ -310,7 +310,7 @@ public class TaglibFactory implements TemplateHashModel {
} catch (Exception e) {
String failedTLDsList = failedTldListAlreadyIncluded ? null : getFailedTLDsList();
throw new TemplateModelException(
- "Error while looking for TLD file for " + _StringUtil.jQuoteNoXSS(taglibUri)
+ "Error while looking for TLD file for " + _StringUtils.jQuoteNoXSS(taglibUri)
+ "; see cause exception."
+ (failedTLDsList == null
? ""
@@ -323,8 +323,8 @@ public class TaglibFactory implements TemplateHashModel {
return loadTaglib(tldLocation, normalizedTaglibUri);
} catch (Exception e) {
throw new TemplateModelException("Error while loading tag library for URI "
- + _StringUtil.jQuoteNoXSS(normalizedTaglibUri) + " from TLD location "
- + _StringUtil.jQuoteNoXSS(tldLocation) + "; see cause exception.",
+ + _StringUtils.jQuoteNoXSS(normalizedTaglibUri) + " from TLD location "
+ + _StringUtils.jQuoteNoXSS(tldLocation) + "; see cause exception.",
e);
}
}
@@ -345,7 +345,7 @@ public class TaglibFactory implements TemplateHashModel {
if (i != 0) {
sb.append(", ");
}
- sb.append(_StringUtil.jQuote(failedTldLocations.get(i)));
+ sb.append(_StringUtils.jQuote(failedTldLocations.get(i)));
}
return sb.toString();
@@ -575,7 +575,7 @@ public class TaglibFactory implements TemplateHashModel {
in = tldLocation.getInputStream();
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Ignored classpath TLD location " + _StringUtil.jQuoteNoXSS(tldResourcePath)
+ LOG.warn("Ignored classpath TLD location " + _StringUtils.jQuoteNoXSS(tldResourcePath)
+ " because of error", e);
}
in = null;
@@ -755,7 +755,7 @@ public class TaglibFactory implements TemplateHashModel {
private void addTldLocationsFromFileDirectory(final File dir) throws IOException, SAXException {
if (dir.isDirectory()) {
if (LOG.isDebugEnabled()) {
- LOG.debug("Scanning for *.tld-s in File directory: " + _StringUtil.jQuoteNoXSS(dir));
+ LOG.debug("Scanning for *.tld-s in File directory: " + _StringUtils.jQuoteNoXSS(dir));
}
File[] tldFiles = dir.listFiles(new FilenameFilter() {
@@ -773,7 +773,7 @@ public class TaglibFactory implements TemplateHashModel {
addTldLocationFromTld(new FileTldLocation(file));
}
} else {
- LOG.warn("Skipped scanning for *.tld for non-existent directory: " + _StringUtil.jQuoteNoXSS(dir));
+ LOG.warn("Skipped scanning for *.tld for non-existent directory: " + _StringUtils.jQuoteNoXSS(dir));
}
}
@@ -822,15 +822,15 @@ public class TaglibFactory implements TemplateHashModel {
private void addTldLocation(TldLocation tldLocation, String taglibUri) {
if (tldLocations.containsKey(taglibUri)) {
if (LOG.isDebugEnabled()) {
- LOG.debug("Ignored duplicate mapping of taglib URI " + _StringUtil.jQuoteNoXSS(taglibUri)
- + " to TLD location " + _StringUtil.jQuoteNoXSS(tldLocation));
+ LOG.debug("Ignored duplicate mapping of taglib URI " + _StringUtils.jQuoteNoXSS(taglibUri)
+ + " to TLD location " + _StringUtils.jQuoteNoXSS(tldLocation));
}
} else {
tldLocations.put(taglibUri, tldLocation);
if (LOG.isDebugEnabled()) {
- LOG.debug("Mapped taglib URI " + _StringUtil.jQuoteNoXSS(taglibUri)
- + " to TLD location " + _StringUtil.jQuoteNoXSS(tldLocation));
+ LOG.debug("Mapped taglib URI " + _StringUtils.jQuoteNoXSS(taglibUri)
+ + " to TLD location " + _StringUtils.jQuoteNoXSS(tldLocation));
}
}
}
@@ -873,8 +873,8 @@ public class TaglibFactory implements TemplateHashModel {
*/
private TemplateHashModel loadTaglib(TldLocation tldLocation, String taglibUri) throws IOException, SAXException {
if (LOG.isDebugEnabled()) {
- LOG.debug("Loading taglib for URI " + _StringUtil.jQuoteNoXSS(taglibUri)
- + " from TLD location " + _StringUtil.jQuoteNoXSS(tldLocation));
+ LOG.debug("Loading taglib for URI " + _StringUtils.jQuoteNoXSS(taglibUri)
+ + " from TLD location " + _StringUtils.jQuoteNoXSS(tldLocation));
}
final Taglib taglib = new Taglib(servletContext, tldLocation, objectWrapper);
@@ -1006,7 +1006,7 @@ public class TaglibFactory implements TemplateHashModel {
}
try {
- return new URL(jarBaseEntryUrl, _StringUtil.URLPathEnc(relativeEntryPath, Charset.defaultCharset()));
+ return new URL(jarBaseEntryUrl, _StringUtils.URLPathEnc(relativeEntryPath, Charset.defaultCharset()));
} catch (UnsupportedEncodingException e) {
throw new BugException();
}
@@ -1107,8 +1107,8 @@ public class TaglibFactory implements TemplateHashModel {
Charset.defaultCharset().name()));
} catch (Exception e) {
LOG.error("Couldn't get URL for serlvetContext resource "
- + _StringUtil.jQuoteNoXSS(servletContextJarFilePath)
- + " / jar entry " + _StringUtil.jQuoteNoXSS(entryPath),
+ + _StringUtils.jQuoteNoXSS(servletContextJarFilePath)
+ + " / jar entry " + _StringUtils.jQuoteNoXSS(entryPath),
e);
return null;
}
@@ -1404,7 +1404,7 @@ public class TaglibFactory implements TemplateHashModel {
while (true) {
final ZipEntry macthedJarEntry = zipIn.getNextEntry();
if (macthedJarEntry == null) {
- throw new IOException("Could not find JAR entry " + _StringUtil.jQuoteNoXSS(entryPath) + ".");
+ throw new IOException("Could not find JAR entry " + _StringUtils.jQuoteNoXSS(entryPath) + ".");
}
if (entryPath.equals(normalizeJarEntryPath(macthedJarEntry.getName(), false))) {
returnedZipIn = true;
@@ -1781,7 +1781,7 @@ public class TaglibFactory implements TemplateHashModel {
customTagModel, (TemplateFunctionModel) replacedTagOrFunction));
} else {
if (LOG.isWarnEnabled()) {
- LOG.warn("TLD contains multiple tags with name " + _StringUtil.jQuote(tagNameCData)
+ LOG.warn("TLD contains multiple tags with name " + _StringUtils.jQuote(tagNameCData)
+ "; keeping only the last one.");
}
}
@@ -1799,13 +1799,13 @@ public class TaglibFactory implements TemplateHashModel {
final Method functionMethod;
try {
- functionMethod = TaglibMethodUtil.getMethodByFunctionSignature(
+ functionMethod = TaglibMethodUtils.getMethodByFunctionSignature(
functionClass, functionSignatureCData);
} catch (Exception e) {
throw new TldParsingSAXException(
- "Error while trying to resolve signature " + _StringUtil.jQuote(functionSignatureCData)
- + " on class " + _StringUtil.jQuote(functionClass.getName())
- + " for custom EL function " + _StringUtil.jQuote(functionNameCData) + ".",
+ "Error while trying to resolve signature " + _StringUtils.jQuote(functionSignatureCData)
+ + " on class " + _StringUtils.jQuote(functionClass.getName())
+ + " for custom EL function " + _StringUtils.jQuote(functionNameCData) + ".",
locator,
e);
}
@@ -1835,7 +1835,7 @@ public class TaglibFactory implements TemplateHashModel {
} else {
if (LOG.isWarnEnabled()) {
LOG.warn("TLD contains multiple functions with name "
- + _StringUtil.jQuote(functionNameCData) + "; keeping only the last one.");
+ + _StringUtils.jQuote(functionNameCData) + "; keeping only the last one.");
}
}
}
@@ -1885,7 +1885,7 @@ public class TaglibFactory implements TemplateHashModel {
private Class<?> resoveClassFromTLD(String className, String entryType, String entryName)
throws TldParsingSAXException {
try {
- return _ClassUtil.forName(className);
+ return _ClassUtils.forName(className);
} catch (LinkageError e) {
throw newTLDEntryClassLoadingException(e, className, entryType, entryName);
} catch (ClassNotFoundException e) {
@@ -1905,8 +1905,8 @@ public class TaglibFactory implements TemplateHashModel {
&& Character.isUpperCase(className.charAt(dotIdx + 1));
return new TldParsingSAXException(
(e instanceof ClassNotFoundException ? "Not found class " : "Can't load class ")
- + _StringUtil.jQuote(className) + " for " + entryType
- + (entryName != null ? " " + _StringUtil.jQuote(entryName) : "") + "."
+ + _StringUtils.jQuote(className) + " for " + entryType
+ + (entryName != null ? " " + _StringUtils.jQuote(entryName) : "") + "."
+ (looksLikeNestedClass
? " Hint: Before nested classes, use \"$\", not \".\"."
: ""),
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtil.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtil.java
deleted file mode 100644
index a732cbb..0000000
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtil.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.servlet.jsp;
-
-import java.lang.reflect.Method;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._StringUtil;
-
-final class TaglibMethodUtil {
-
- private TaglibMethodUtil() {
- // Not meant to be instantiated
- }
-
- private static final Pattern FUNCTION_SIGNATURE_PATTERN =
- Pattern.compile("^([\\w\\.]+(\\s*\\[\\s*\\])?)\\s+([\\w]+)\\s*\\((.*)\\)$");
- private static final Pattern FUNCTION_PARAMETER_PATTERN =
- Pattern.compile("^([\\w\\.]+)(\\s*\\[\\s*\\])?$");
-
- /**
- * Finds method by function signature string which is compliant with
- * Tag Library function signature in Java Server Page (TM) Specification.
- * A function signature example is as follows: {@code java.lang.String nickName( java.lang.String, int)}
- *
- * @param clazz Class having the method.
- * @param signature Java Server Page (TM) Specification compliant function signature string.
- * @return method if found.
- */
- public static Method getMethodByFunctionSignature(Class clazz, String signature)
- throws SecurityException, NoSuchMethodException, ClassNotFoundException {
- Matcher m1 = FUNCTION_SIGNATURE_PATTERN.matcher(signature);
-
- if (!m1.matches()) {
- throw new IllegalArgumentException("Invalid function signature.");
- }
-
- String methodName = m1.group(3);
- String params = m1.group(4).trim();
- Class [] paramTypes = null;
-
- if ("".equals(params)) {
- paramTypes = new Class[0];
- } else {
- String [] paramsArray = _StringUtil.split(params, ',');
- paramTypes = new Class[paramsArray.length];
- String token = null;
- String paramType = null;
- boolean isPrimitive = false;
- boolean isArrayType = false;
- Matcher m2 = null;
-
- for (int i = 0; i < paramsArray.length; i++) {
- token = paramsArray[i].trim();
- m2 = FUNCTION_PARAMETER_PATTERN.matcher(token);
-
- if (!m2.matches()) {
- throw new IllegalArgumentException("Invalid argument signature: '" + token + "'.");
- }
-
- paramType = m2.group(1);
- isPrimitive = (paramType.indexOf('.') == -1);
- isArrayType = (m2.group(2) != null);
-
- if (isPrimitive) {
- if ("byte".equals(paramType)) {
- paramTypes[i] = (isArrayType ? byte[].class : byte.class);
- } else if ("short".equals(paramType)) {
- paramTypes[i] = (isArrayType ? short[].class : short.class);
- } else if ("int".equals(paramType)) {
- paramTypes[i] = (isArrayType ? int[].class : int.class);
- } else if ("long".equals(paramType)) {
- paramTypes[i] = (isArrayType ? long[].class : long.class);
- } else if ("float".equals(paramType)) {
- paramTypes[i] = (isArrayType ? float[].class : float.class);
- } else if ("double".equals(paramType)) {
- paramTypes[i] = (isArrayType ? double[].class : double.class);
- } else if ("boolean".equals(paramType)) {
- paramTypes[i] = (isArrayType ? boolean[].class : boolean.class);
- } else if ("char".equals(paramType)) {
- paramTypes[i] = (isArrayType ? char[].class : char.class);
- } else {
- throw new IllegalArgumentException("Invalid primitive type: '" + paramType + "'.");
- }
- } else {
- if (isArrayType) {
- paramTypes[i] = _ClassUtil.forName("[L" + paramType + ";");
- } else {
- paramTypes[i] = _ClassUtil.forName(paramType);
- }
- }
- }
- }
-
- return clazz.getMethod(methodName, paramTypes);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtils.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtils.java
new file mode 100644
index 0000000..8222f6e
--- /dev/null
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtils.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.servlet.jsp;
+
+import java.lang.reflect.Method;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._StringUtils;
+
+final class TaglibMethodUtils {
+
+ private TaglibMethodUtils() {
+ // Not meant to be instantiated
+ }
+
+ private static final Pattern FUNCTION_SIGNATURE_PATTERN =
+ Pattern.compile("^([\\w\\.]+(\\s*\\[\\s*\\])?)\\s+([\\w]+)\\s*\\((.*)\\)$");
+ private static final Pattern FUNCTION_PARAMETER_PATTERN =
+ Pattern.compile("^([\\w\\.]+)(\\s*\\[\\s*\\])?$");
+
+ /**
+ * Finds method by function signature string which is compliant with
+ * Tag Library function signature in Java Server Page (TM) Specification.
+ * A function signature example is as follows: {@code java.lang.String nickName( java.lang.String, int)}
+ *
+ * @param clazz Class having the method.
+ * @param signature Java Server Page (TM) Specification compliant function signature string.
+ * @return method if found.
+ */
+ public static Method getMethodByFunctionSignature(Class clazz, String signature)
+ throws SecurityException, NoSuchMethodException, ClassNotFoundException {
+ Matcher m1 = FUNCTION_SIGNATURE_PATTERN.matcher(signature);
+
+ if (!m1.matches()) {
+ throw new IllegalArgumentException("Invalid function signature.");
+ }
+
+ String methodName = m1.group(3);
+ String params = m1.group(4).trim();
+ Class [] paramTypes = null;
+
+ if ("".equals(params)) {
+ paramTypes = new Class[0];
+ } else {
+ String [] paramsArray = _StringUtils.split(params, ',');
+ paramTypes = new Class[paramsArray.length];
+ String token = null;
+ String paramType = null;
+ boolean isPrimitive = false;
+ boolean isArrayType = false;
+ Matcher m2 = null;
+
+ for (int i = 0; i < paramsArray.length; i++) {
+ token = paramsArray[i].trim();
+ m2 = FUNCTION_PARAMETER_PATTERN.matcher(token);
+
+ if (!m2.matches()) {
+ throw new IllegalArgumentException("Invalid argument signature: '" + token + "'.");
+ }
+
+ paramType = m2.group(1);
+ isPrimitive = (paramType.indexOf('.') == -1);
+ isArrayType = (m2.group(2) != null);
+
+ if (isPrimitive) {
+ if ("byte".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? byte[].class : byte.class);
+ } else if ("short".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? short[].class : short.class);
+ } else if ("int".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? int[].class : int.class);
+ } else if ("long".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? long[].class : long.class);
+ } else if ("float".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? float[].class : float.class);
+ } else if ("double".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? double[].class : double.class);
+ } else if ("boolean".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? boolean[].class : boolean.class);
+ } else if ("char".equals(paramType)) {
+ paramTypes[i] = (isArrayType ? char[].class : char.class);
+ } else {
+ throw new IllegalArgumentException("Invalid primitive type: '" + paramType + "'.");
+ }
+ } else {
+ if (isArrayType) {
+ paramTypes[i] = _ClassUtils.forName("[L" + paramType + ";");
+ } else {
+ paramTypes[i] = _ClassUtils.forName(paramType);
+ }
+ }
+ }
+ }
+
+ return clazz.getMethod(methodName, paramTypes);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/_FreeMarkerPageContext21.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/_FreeMarkerPageContext21.java b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/_FreeMarkerPageContext21.java
index 2500665..be9d58a 100644
--- a/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/_FreeMarkerPageContext21.java
+++ b/freemarker-servlet/src/main/java/org/apache/freemarker/servlet/jsp/_FreeMarkerPageContext21.java
@@ -32,7 +32,7 @@ import javax.servlet.jsp.el.ExpressionEvaluator;
import javax.servlet.jsp.el.VariableResolver;
import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -111,7 +111,7 @@ public class _FreeMarkerPageContext21 extends FreeMarkerPageContext {
} else {
throw new UnsupportedOperationException(
"Can not invoke an ELContext using a foreign JspApplicationContext (of class "
- + _ClassUtil.getShortClassNameOfObject(jspctx) + ").\n" +
+ + _ClassUtils.getShortClassNameOfObject(jspctx) + ").\n" +
"Hint: The cause of this is often that you are trying to use JSTL tags/functions in FTL. "
+ "In that case, know that that's not really suppored, and you are supposed to use FTL "
+ "constrcuts instead, like #list instead of JSTL's forEach, etc.");
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilTest.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilTest.java b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilTest.java
deleted file mode 100644
index 5733abc..0000000
--- a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.servlet.jsp;
-
-import static org.junit.Assert.*;
-
-import java.lang.reflect.Method;
-
-import org.apache.freemarker.servlet.jsp.TaglibMethodUtil;
-import org.junit.Test;
-
-public class TaglibMethodUtilTest {
-
- @Test
- public void testGetMethodByFunctionSignature() throws Exception {
- Method expected = Functions.class.getMethod("plus", int.class, int.class);
- String signature = "int plus(int, int)";
- Method method = TaglibMethodUtil.getMethodByFunctionSignature(Functions.class, signature);
- assertEquals(expected, method);
-
- expected = Functions.class.getMethod("plus", double.class, double.class);
- signature = "double plus ( double , double )";
- method = TaglibMethodUtil.getMethodByFunctionSignature(Functions.class, signature);
- assertEquals(expected, method);
-
- expected = Functions.class.getMethod("plus", String.class, String.class);
- signature = "java.lang.String plus ( java.lang.String ,java.lang.String )";
- method = TaglibMethodUtil.getMethodByFunctionSignature(Functions.class, signature);
- assertEquals(expected, method);
-
- expected = Functions.class.getMethod("plus", double[].class, double[].class);
- signature = "double[] plus ( double[] ,double [] )";
- method = TaglibMethodUtil.getMethodByFunctionSignature(Functions.class, signature);
- assertEquals(expected, method);
-
- expected = Functions.class.getMethod("plus", String[].class, String[].class);
- signature = "java.lang.String [] plus ( java.lang.String[] ,java.lang.String [] )";
- method = TaglibMethodUtil.getMethodByFunctionSignature(Functions.class, signature);
- assertEquals(expected, method);
-
- expected = Functions.class.getMethod("sum", double[].class);
- signature = "double sum ( double[] )";
- method = TaglibMethodUtil.getMethodByFunctionSignature(Functions.class, signature);
- assertEquals(expected, method);
- }
-
- @SuppressWarnings("unused")
- private static class Functions {
-
- public static int plus(int a, int b) {
- return a + b;
- }
-
- public static double plus(double a, double b) {
- return a + b;
- }
-
- public static String plus(String a, String b) {
- return a + b;
- }
-
- public static double [] plus(double [] a, double [] b) {
- double [] sum = new double[a.length];
-
- for (int i = 0; i < a.length; i++) {
- sum[i] = a[i] + b[i];
- }
-
- return sum;
- }
-
- public static String [] plus(String [] a, String [] b) {
- String [] joins = new String[a.length];
-
- for (int i = 0; i < a.length; i++) {
- joins[i] = a[i] + b[i];
- }
-
- return joins;
- }
-
- public static double sum(double [] a) {
- double sum = 0.0;
- for (double i : a) {
- sum += i;
- }
- return sum;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilsTest.java b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilsTest.java
new file mode 100644
index 0000000..fa341e5
--- /dev/null
+++ b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/TaglibMethodUtilsTest.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.servlet.jsp;
+
+import static org.junit.Assert.*;
+
+import java.lang.reflect.Method;
+
+import org.junit.Test;
+
+public class TaglibMethodUtilsTest {
+
+ @Test
+ public void testGetMethodByFunctionSignature() throws Exception {
+ Method expected = Functions.class.getMethod("plus", int.class, int.class);
+ String signature = "int plus(int, int)";
+ Method method = TaglibMethodUtils.getMethodByFunctionSignature(Functions.class, signature);
+ assertEquals(expected, method);
+
+ expected = Functions.class.getMethod("plus", double.class, double.class);
+ signature = "double plus ( double , double )";
+ method = TaglibMethodUtils.getMethodByFunctionSignature(Functions.class, signature);
+ assertEquals(expected, method);
+
+ expected = Functions.class.getMethod("plus", String.class, String.class);
+ signature = "java.lang.String plus ( java.lang.String ,java.lang.String )";
+ method = TaglibMethodUtils.getMethodByFunctionSignature(Functions.class, signature);
+ assertEquals(expected, method);
+
+ expected = Functions.class.getMethod("plus", double[].class, double[].class);
+ signature = "double[] plus ( double[] ,double [] )";
+ method = TaglibMethodUtils.getMethodByFunctionSignature(Functions.class, signature);
+ assertEquals(expected, method);
+
+ expected = Functions.class.getMethod("plus", String[].class, String[].class);
+ signature = "java.lang.String [] plus ( java.lang.String[] ,java.lang.String [] )";
+ method = TaglibMethodUtils.getMethodByFunctionSignature(Functions.class, signature);
+ assertEquals(expected, method);
+
+ expected = Functions.class.getMethod("sum", double[].class);
+ signature = "double sum ( double[] )";
+ method = TaglibMethodUtils.getMethodByFunctionSignature(Functions.class, signature);
+ assertEquals(expected, method);
+ }
+
+ @SuppressWarnings("unused")
+ private static class Functions {
+
+ public static int plus(int a, int b) {
+ return a + b;
+ }
+
+ public static double plus(double a, double b) {
+ return a + b;
+ }
+
+ public static String plus(String a, String b) {
+ return a + b;
+ }
+
+ public static double [] plus(double [] a, double [] b) {
+ double [] sum = new double[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ sum[i] = a[i] + b[i];
+ }
+
+ return sum;
+ }
+
+ public static String [] plus(String [] a, String [] b) {
+ String [] joins = new String[a.length];
+
+ for (int i = 0; i < a.length; i++) {
+ joins[i] = a[i] + b[i];
+ }
+
+ return joins;
+ }
+
+ public static double sum(double [] a) {
+ double sum = 0.0;
+ for (double i : a) {
+ sum += i;
+ }
+ return sum;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeAccessorTag.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeAccessorTag.java b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeAccessorTag.java
index d068204..49e071b 100644
--- a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeAccessorTag.java
+++ b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeAccessorTag.java
@@ -22,7 +22,7 @@ package org.apache.freemarker.servlet.jsp.taglibmembers;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
public abstract class AttributeAccessorTag extends SimpleTagSupport {
@@ -62,7 +62,7 @@ public abstract class AttributeAccessorTag extends SimpleTagSupport {
if (scope.equals("application")) {
return PageContext.APPLICATION_SCOPE;
}
- throw new IllegalArgumentException("Invalid scope name: " + _StringUtil.jQuote(scope));
+ throw new IllegalArgumentException("Invalid scope name: " + _StringUtils.jQuote(scope));
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeInfoTag.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeInfoTag.java b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeInfoTag.java
index 2d306a0..e8b6eea 100644
--- a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeInfoTag.java
+++ b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/jsp/taglibmembers/AttributeInfoTag.java
@@ -26,8 +26,8 @@ import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
-import org.apache.freemarker.core.util._DateUtil;
-import org.apache.freemarker.core.util._DateUtil.TrivialDateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._DateUtils;
+import org.apache.freemarker.core.util._DateUtils.TrivialDateToISO8601CalendarFactory;
public class AttributeInfoTag extends AttributeAccessorTag {
@@ -41,8 +41,8 @@ public class AttributeInfoTag extends AttributeAccessorTag {
final String formattedVal;
if (attrVal instanceof Date) {
- formattedVal = _DateUtil.dateToISO8601String((Date) attrVal, true, true, true, _DateUtil.ACCURACY_SECONDS,
- _DateUtil.UTC,
+ formattedVal = _DateUtils.dateToISO8601String((Date) attrVal, true, true, true, _DateUtils.ACCURACY_SECONDS,
+ _DateUtils.UTC,
new TrivialDateToISO8601CalendarFactory());
} else {
formattedVal = String.valueOf(attrVal);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/Model2TesterServlet.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/Model2TesterServlet.java b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/Model2TesterServlet.java
index 52cdf4b..c0e9739 100644
--- a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/Model2TesterServlet.java
+++ b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/Model2TesterServlet.java
@@ -29,7 +29,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.servlet.FreemarkerServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -109,7 +109,7 @@ public class Model2TesterServlet extends HttpServlet {
final RequestDispatcher requestDispatcher = getServletContext().getNamedDispatcher(paramViewServlet);
if (requestDispatcher == null) {
throw new ServletException("Can't find request dispatched for servlet name "
- + _StringUtil.jQuote(paramViewServlet) + ".");
+ + _StringUtils.jQuote(paramViewServlet) + ".");
}
final HttpServletRequestWrapper viewReq = new HttpServletRequestWrapper(req) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/WebAppTestCase.java
----------------------------------------------------------------------
diff --git a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/WebAppTestCase.java b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/WebAppTestCase.java
index 05138fd..01e6072 100644
--- a/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/WebAppTestCase.java
+++ b/freemarker-servlet/src/test/java/org/apache/freemarker/servlet/test/WebAppTestCase.java
@@ -36,7 +36,7 @@ import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.freemarker.test.ResourcesExtractor;
-import org.apache.freemarker.test.TestUtil;
+import org.apache.freemarker.test.TestUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
@@ -192,7 +192,7 @@ public class WebAppTestCase {
throw new IOException("Test resource not found: " + expectedResource);
}
try {
- expected = TestUtil.removeTxtCopyrightComment(normalizeWS(
+ expected = TestUtils.removeTxtCopyrightComment(normalizeWS(
IOUtils.toString(in, StandardCharsets.UTF_8.name()),
compressWS));
} finally {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java
index 3b6ea39..3c03a87 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java
@@ -81,7 +81,7 @@ public class CopyrightCommentRemoverTemplateLoader implements TemplateLoader {
}
try {
String content = IOUtils.toString(reader);
- return new StringReader(TestUtil.removeFTLCopyrightComment(content));
+ return new StringReader(TestUtils.removeFTLCopyrightComment(content));
} finally {
reader.close();
}
@@ -95,7 +95,7 @@ public class CopyrightCommentRemoverTemplateLoader implements TemplateLoader {
// Encoding then decosing in ISO-8859-1 is binary loseless
String content = IOUtils.toString(in, StandardCharsets.ISO_8859_1.name());
return new ReaderInputStream(
- new StringReader(TestUtil.removeFTLCopyrightComment(content)),
+ new StringReader(TestUtils.removeFTLCopyrightComment(content)),
StandardCharsets.ISO_8859_1);
} finally {
in.close();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-test-utils/src/main/java/org/apache/freemarker/test/FileTestCase.java
----------------------------------------------------------------------
diff --git a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/FileTestCase.java b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/FileTestCase.java
index 1d70d8c..c0adb72 100644
--- a/freemarker-test-utils/src/main/java/org/apache/freemarker/test/FileTestCase.java
+++ b/freemarker-test-utils/src/main/java/org/apache/freemarker/test/FileTestCase.java
@@ -29,7 +29,7 @@ import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -68,8 +68,8 @@ public abstract class FileTestCase extends TestCase {
}
private void multilineAssertEquals(String expected, String actual) {
- String normExpected = _StringUtil.normalizeEOLs(expected);
- final String normActual = _StringUtil.normalizeEOLs(actual);
+ String normExpected = _StringUtils.normalizeEOLs(expected);
+ final String normActual = _StringUtils.normalizeEOLs(actual);
// Ignore final line-break difference:
if (normActual.endsWith("\n") && !normExpected.endsWith("\n")) {
@@ -117,7 +117,7 @@ public abstract class FileTestCase extends TestCase {
if (resource == null) {
throw new FileNotFoundException("Class-loader resource not found for: "
+ "baseClass: " + baseClass.getName() + "; "
- + "resourcePath (shown quoted): " + _StringUtil.jQuote(resourcePath));
+ + "resourcePath (shown quoted): " + _StringUtils.jQuote(resourcePath));
}
return resource;
}
@@ -205,7 +205,7 @@ public abstract class FileTestCase extends TestCase {
}
protected String loadTestTextResource(URL resource, Charset charset) throws IOException {
- return TestUtil.removeTxtCopyrightComment(
+ return TestUtils.removeTxtCopyrightComment(
IOUtils.toString(resource, charset.name()));
}
[15/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/OverloadedMethods2.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/OverloadedMethods2.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/OverloadedMethods2.java
index e9084c9..495a72e 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/OverloadedMethods2.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/OverloadedMethods2.java
@@ -38,8 +38,8 @@ import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.model.WrapperTemplateModel;
import org.apache.freemarker.core.model.impl.RationalNumber;
-import org.apache.freemarker.core.util._StringUtil;
-import org.apache.freemarker.test.TestUtil;
+import org.apache.freemarker.core.util._StringUtils;
+import org.apache.freemarker.test.TestUtils;
public class OverloadedMethods2 {
@@ -321,80 +321,80 @@ public class OverloadedMethods2 {
}
public String varargs1(String s, int... xs) {
- return "varargs1(String s = " + _StringUtil.jQuote(s) + ", int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs1(String s = " + _StringUtils.jQuote(s) + ", int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs1(String s, double... xs) {
- return "varargs1(String s = " + _StringUtil.jQuote(s) + ", double... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs1(String s = " + _StringUtils.jQuote(s) + ", double... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs1(String s, Object... xs) {
- return "varargs1(String s = " + _StringUtil.jQuote(s) + ", Object... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs1(String s = " + _StringUtils.jQuote(s) + ", Object... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs1(Object s, Object... xs) {
- return "varargs1(Object s = " + s + ", Object... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs1(Object s = " + s + ", Object... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs2(int... xs) {
- return "varargs2(int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs2(int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs2(double... xs) {
- return "varargs2(double... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs2(double... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs3(String... xs) {
- return "varargs3(String... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs3(String... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs3(Comparable... xs) {
- return "varargs3(Comparable... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs3(Comparable... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs3(Object... xs) {
- return "varargs3(Object... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs3(Object... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs4(Integer... xs) {
- return "varargs4(Integer... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs4(Integer... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs4(int... xs) {
- return "varargs4(int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs4(int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs5(int... xs) {
- return "varargs5(int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs5(int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs5(int a1, int... xs) {
- return "varargs5(int a1 = " + a1 + ", int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs5(int a1 = " + a1 + ", int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs5(int a1, int a2, int... xs) {
- return "varargs5(int a1 = " + a1 + ", int a2 = " + a2 + ", int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs5(int a1 = " + a1 + ", int a2 = " + a2 + ", int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs5(int a1, int a2, int a3, int... xs) {
return "varargs5(int a1 = " + a1 + ", int a2 = " + a2 + ", int a3 = " + a3
- + ", int... xs = " + TestUtil.arrayToString(xs) + ")";
+ + ", int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs6(String a1, int... xs) {
- return "varargs6(String a1 = " + a1 + ", int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs6(String a1 = " + a1 + ", int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs6(Object a1, int a2, int... xs) {
- return "varargs6(Object a1 = " + a1 + ", int a2 = " + a2 + ", int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs6(Object a1 = " + a1 + ", int a2 = " + a2 + ", int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs7(int... xs) {
- return "varargs7(int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs7(int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String varargs7(short a1, int... xs) {
- return "varargs7(short a1 = " + a1 + ", int... xs = " + TestUtil.arrayToString(xs) + ")";
+ return "varargs7(short a1 = " + a1 + ", int... xs = " + TestUtils.arrayToString(xs) + ")";
}
public String mNullAmbiguous(String s) {
@@ -430,11 +430,11 @@ public class OverloadedMethods2 {
}
public String mVarargsIgnoredTail(int i, double... ds) {
- return "mVarargsIgnoredTail(int i = " + i + ", double... ds = " + TestUtil.arrayToString(ds) + ")";
+ return "mVarargsIgnoredTail(int i = " + i + ", double... ds = " + TestUtils.arrayToString(ds) + ")";
}
public String mVarargsIgnoredTail(int... is) {
- return "mVarargsIgnoredTail(int... is = " + TestUtil.arrayToString(is) + ")";
+ return "mVarargsIgnoredTail(int... is = " + TestUtils.arrayToString(is) + ")";
}
public String mLowRankWins(int x, int y, Object o) {
@@ -473,19 +473,19 @@ public class OverloadedMethods2 {
}
public String mSeqToArrayNonOverloaded(String[] items, String s) {
- return "mSeqToArrayNonOverloaded(String[] " + TestUtil.arrayToString(items) + ", String " + s + ")";
+ return "mSeqToArrayNonOverloaded(String[] " + TestUtils.arrayToString(items) + ", String " + s + ")";
}
public String mSeqToArrayGoodHint(String[] items, String s) {
- return "mSeqToArrayGoodHint(String[] " + TestUtil.arrayToString(items) + ", String " + s + ")";
+ return "mSeqToArrayGoodHint(String[] " + TestUtils.arrayToString(items) + ", String " + s + ")";
}
public String mSeqToArrayGoodHint(String[] items, int i) {
- return "mSeqToArrayGoodHint(String[] " + TestUtil.arrayToString(items) + ", int " + i + ")";
+ return "mSeqToArrayGoodHint(String[] " + TestUtils.arrayToString(items) + ", int " + i + ")";
}
public String mSeqToArrayGoodHint2(String[] items, String s) {
- return "mSeqToArrayGoodHint2(String[] " + TestUtil.arrayToString(items) + ", String " + s + ")";
+ return "mSeqToArrayGoodHint2(String[] " + TestUtils.arrayToString(items) + ", String " + s + ")";
}
public String mSeqToArrayGoodHint2(String item) {
@@ -493,7 +493,7 @@ public class OverloadedMethods2 {
}
public String mSeqToArrayPoorHint(String[] items, String s) {
- return "mSeqToArrayPoorHint(String[] " + TestUtil.arrayToString(items) + ", String " + s + ")";
+ return "mSeqToArrayPoorHint(String[] " + TestUtils.arrayToString(items) + ", String " + s + ")";
}
public String mSeqToArrayPoorHint(String item, int i) {
@@ -501,7 +501,7 @@ public class OverloadedMethods2 {
}
public String mSeqToArrayPoorHint2(String[] items) {
- return "mSeqToArrayPoorHint2(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mSeqToArrayPoorHint2(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mSeqToArrayPoorHint2(String item) {
@@ -509,43 +509,43 @@ public class OverloadedMethods2 {
}
public String mSeqToArrayPoorHint3(String[] items) {
- return "mSeqToArrayPoorHint3(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mSeqToArrayPoorHint3(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mSeqToArrayPoorHint3(int[] items) {
- return "mSeqToArrayPoorHint3(int[] " + TestUtil.arrayToString(items) + ")";
+ return "mSeqToArrayPoorHint3(int[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVsListPreference(String[] items) {
- return "mStringArrayVsListPreference(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVsListPreference(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVsListPreference(List items) {
- return "mStringArrayVsListPreference(List " + TestUtil.listToString(items) + ")";
+ return "mStringArrayVsListPreference(List " + TestUtils.listToString(items) + ")";
}
public String mStringArrayVsObjectArrayPreference(String[] items) {
- return "mStringArrayVsObjectArrayPreference(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVsObjectArrayPreference(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVsObjectArrayPreference(Object[] items) {
- return "mStringArrayVsObjectArrayPreference(Object[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVsObjectArrayPreference(Object[] " + TestUtils.arrayToString(items) + ")";
}
public String mIntArrayVsIntegerArrayPreference(int[] items) {
- return "mIntArrayVsIntegerArrayPreference(int[] " + TestUtil.arrayToString(items) + ")";
+ return "mIntArrayVsIntegerArrayPreference(int[] " + TestUtils.arrayToString(items) + ")";
}
public String mIntArrayVsIntegerArrayPreference(Integer[] items) {
- return "mIntArrayVsIntegerArrayPreference(Integer[] " + TestUtil.arrayToString(items) + ")";
+ return "mIntArrayVsIntegerArrayPreference(Integer[] " + TestUtils.arrayToString(items) + ")";
}
public String mIntArrayNonOverloaded(int[] items) {
- return "mIntArrayNonOverloaded(int[] " + TestUtil.arrayToString(items) + ")";
+ return "mIntArrayNonOverloaded(int[] " + TestUtils.arrayToString(items) + ")";
}
public String mIntegerArrayNonOverloaded(Integer[] items) {
- return "mIntegerArrayNonOverloaded(Integer[] " + TestUtil.arrayToString(items) + ")";
+ return "mIntegerArrayNonOverloaded(Integer[] " + TestUtils.arrayToString(items) + ")";
}
public String mIntegerListNonOverloaded(List<Integer> items) {
@@ -557,7 +557,7 @@ public class OverloadedMethods2 {
}
public String mStringArrayNonOverloaded(String[] items) {
- return "mStringArrayNonOverloaded(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayNonOverloaded(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mObjectListNonOverloaded(List<Object> items) {
@@ -565,11 +565,11 @@ public class OverloadedMethods2 {
}
public String mObjectArrayNonOverloaded(Object[] items) {
- return "mObjectArrayNonOverloaded(Object[] " + TestUtil.arrayToString(items) + ")";
+ return "mObjectArrayNonOverloaded(Object[] " + TestUtils.arrayToString(items) + ")";
}
public String mIntegerArrayOverloaded(Integer[] items, int i) {
- return "mIntegerArrayOverloaded(Integer[] " + TestUtil.arrayToString(items) + ", int " + i + ")";
+ return "mIntegerArrayOverloaded(Integer[] " + TestUtils.arrayToString(items) + ", int " + i + ")";
}
public String mIntegerArrayOverloaded(Object obj, boolean b) {
@@ -577,7 +577,7 @@ public class OverloadedMethods2 {
}
public String mStringArrayOverloaded(String[] items, int i) {
- return "mStringArrayOverloaded(String[] " + TestUtil.arrayToString(items) + ", int " + i + ")";
+ return "mStringArrayOverloaded(String[] " + TestUtils.arrayToString(items) + ", int " + i + ")";
}
public String mStringArrayOverloaded(Object obj, boolean b) {
@@ -585,11 +585,11 @@ public class OverloadedMethods2 {
}
public String mCharArrayOverloaded(char[] items, int i) {
- return "mCharArrayOverloaded(char[] " + TestUtil.arrayToString(items) + ", int " + i + ")";
+ return "mCharArrayOverloaded(char[] " + TestUtils.arrayToString(items) + ", int " + i + ")";
}
public String mCharArrayOverloaded(Character[] items, String s) {
- return "mCharArrayOverloaded(Character[] " + TestUtil.arrayToString(items) + ", String " + s + ")";
+ return "mCharArrayOverloaded(Character[] " + TestUtils.arrayToString(items) + ", String " + s + ")";
}
public String mCharArrayOverloaded(Object obj, boolean b) {
@@ -597,7 +597,7 @@ public class OverloadedMethods2 {
}
public String mStringArrayArrayOverloaded(String[][] arrayArray, int i) {
- return "mStringArrayArrayOverloaded(String[][] " + TestUtil.arrayToString(arrayArray) + ", int " + i + ")";
+ return "mStringArrayArrayOverloaded(String[][] " + TestUtils.arrayToString(arrayArray) + ", int " + i + ")";
}
public String mStringArrayArrayOverloaded(Object obj, boolean b) {
@@ -605,7 +605,7 @@ public class OverloadedMethods2 {
}
public String mIntArrayArrayOverloaded(int[][] xss) {
- return "mIntArrayArrayOverloaded(" + TestUtil.arrayToString(xss) + ")";
+ return "mIntArrayArrayOverloaded(" + TestUtils.arrayToString(xss) + ")";
}
public String mIntArrayArrayOverloaded(String s) {
@@ -613,7 +613,7 @@ public class OverloadedMethods2 {
}
public String mArrayOfListsOverloaded(List[] xss) {
- return "mArrayOfListsOverloaded(" + TestUtil.arrayToString(xss) + ")";
+ return "mArrayOfListsOverloaded(" + TestUtils.arrayToString(xss) + ")";
}
public String mArrayOfListsOverloaded(String x) {
@@ -621,31 +621,31 @@ public class OverloadedMethods2 {
}
public String mIntArrayArrayNonOverloaded(int[][] xss) {
- return "mIntArrayArrayNonOverloaded(" + TestUtil.arrayToString(xss) + ")";
+ return "mIntArrayArrayNonOverloaded(" + TestUtils.arrayToString(xss) + ")";
}
public String mArrayOfListsNonOverloaded(List[] xss) {
- return "mArrayOfListsNonOverloaded(" + TestUtil.arrayToString(xss) + ")";
+ return "mArrayOfListsNonOverloaded(" + TestUtils.arrayToString(xss) + ")";
}
public String mStringArrayVarargsNonOverloaded(String... items) {
- return "mStringArrayVarargsNonOverloaded(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVarargsNonOverloaded(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVarargsOverloaded(String... items) {
- return "mStringArrayVarargsNonOverloaded(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVarargsNonOverloaded(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVarargsOverloaded1(String... items) {
- return "mStringArrayVarargsOverloaded1(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVarargsOverloaded1(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVarargsOverloaded1(List<String> items) {
- return "mStringArrayVarargsOverloaded1(List " + TestUtil.listToString(items) + ")";
+ return "mStringArrayVarargsOverloaded1(List " + TestUtils.listToString(items) + ")";
}
public String mStringArrayVarargsOverloaded2(String... items) {
- return "mStringArrayVarargsOverloaded2(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVarargsOverloaded2(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVarargsOverloaded2(String item) {
@@ -653,7 +653,7 @@ public class OverloadedMethods2 {
}
public String mStringArrayVarargsOverloaded3(String... items) {
- return "mStringArrayVarargsOverloaded3(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVarargsOverloaded3(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVarargsOverloaded3(String item1, String item2) {
@@ -661,15 +661,15 @@ public class OverloadedMethods2 {
}
public String mStringArrayVarargsOverloaded4(String... items) {
- return "mStringArrayVarargsOverloaded4(String[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVarargsOverloaded4(String[] " + TestUtils.arrayToString(items) + ")";
}
public String mStringArrayVarargsOverloaded4(List... items) {
- return "mStringArrayVarargsOverloaded4(List[] " + TestUtil.arrayToString(items) + ")";
+ return "mStringArrayVarargsOverloaded4(List[] " + TestUtils.arrayToString(items) + ")";
}
public String mListOrString(List<String> items) {
- return "mListOrString(List " + TestUtil.listToString(items) + ")";
+ return "mListOrString(List " + TestUtils.listToString(items) + ")";
}
public String mListOrString(String item) {
@@ -677,7 +677,7 @@ public class OverloadedMethods2 {
}
public String mListListOrString(List<List<Object>> items) {
- return "mListListOrString(List " + TestUtil.listToString(items) + ")";
+ return "mListListOrString(List " + TestUtils.listToString(items) + ")";
}
public String mListListOrString(String item) {
@@ -693,11 +693,11 @@ public class OverloadedMethods2 {
}
public String mMapOrBooleanVarargs(Map... v) {
- return "mMapOrBooleanVarargs(Map... " + TestUtil.arrayToString(v) + ")";
+ return "mMapOrBooleanVarargs(Map... " + TestUtils.arrayToString(v) + ")";
}
public String mMapOrBooleanVarargs(boolean... v) {
- return "mMapOrBooleanVarargs(boolean... " + TestUtil.arrayToString(v) + ")";
+ return "mMapOrBooleanVarargs(boolean... " + TestUtils.arrayToString(v) + ")";
}
public String mMapOrBooleanFixedAndVarargs(Map v) {
@@ -709,11 +709,11 @@ public class OverloadedMethods2 {
}
public String mMapOrBooleanFixedAndVarargs(Map... v) {
- return "mMapOrBooleanFixedAndVarargs(Map... " + TestUtil.arrayToString(v) + ")";
+ return "mMapOrBooleanFixedAndVarargs(Map... " + TestUtils.arrayToString(v) + ")";
}
public String mMapOrBooleanFixedAndVarargs(boolean... v) {
- return "mMapOrBooleanFixedAndVarargs(boolean... " + TestUtil.arrayToString(v) + ")";
+ return "mMapOrBooleanFixedAndVarargs(boolean... " + TestUtils.arrayToString(v) + ")";
}
public String mNumberOrArray(Number v) {
@@ -721,7 +721,7 @@ public class OverloadedMethods2 {
}
public String mNumberOrArray(Object[] v) {
- return "mNumberOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mNumberOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mIntOrArray(int v) {
@@ -729,7 +729,7 @@ public class OverloadedMethods2 {
}
public String mIntOrArray(Object[] v) {
- return "mIntOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mIntOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mDateOrArray(Date v) {
@@ -737,7 +737,7 @@ public class OverloadedMethods2 {
}
public String mDateOrArray(Object[] v) {
- return "mDateOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mDateOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mStringOrArray(String v) {
@@ -745,7 +745,7 @@ public class OverloadedMethods2 {
}
public String mStringOrArray(Object[] v) {
- return "mStringOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mStringOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mBooleanOrArray(boolean v) {
@@ -753,7 +753,7 @@ public class OverloadedMethods2 {
}
public String mBooleanOrArray(Object[] v) {
- return "mBooleanOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mBooleanOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mMapOrArray(Map v) {
@@ -761,7 +761,7 @@ public class OverloadedMethods2 {
}
public String mMapOrArray(Object[] v) {
- return "mMapOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mMapOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mListOrArray(List v) {
@@ -769,7 +769,7 @@ public class OverloadedMethods2 {
}
public String mListOrArray(Object[] v) {
- return "mListOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mListOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mSetOrArray(Set v) {
@@ -777,7 +777,7 @@ public class OverloadedMethods2 {
}
public String mSetOrArray(Object[] v) {
- return "mSetOrArray(Object[] " + TestUtil.arrayToString(v) + ")";
+ return "mSetOrArray(Object[] " + TestUtils.arrayToString(v) + ")";
}
public String mCharNonOverloaded(char c) {
@@ -1010,7 +1010,7 @@ public class OverloadedMethods2 {
}
public String bugReport363(Object... fields) {
- return "Executed: testMethod(Object... fields) on input: fields=" + TestUtil.arrayToString(fields);
+ return "Executed: testMethod(Object... fields) on input: fields=" + TestUtils.arrayToString(fields);
}
private static class MyAdapterNumberModel implements TemplateNumberModel, AdapterTemplateModel {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/BaseNTemplateNumberFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/BaseNTemplateNumberFormatFactory.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/BaseNTemplateNumberFormatFactory.java
index e5def77..aa5d4db 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/BaseNTemplateNumberFormatFactory.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/BaseNTemplateNumberFormatFactory.java
@@ -23,8 +23,8 @@ import java.util.Locale;
import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNumberModel;
-import org.apache.freemarker.core.util._NumberUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._NumberUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.TemplateFormatUtil;
import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
@@ -60,7 +60,7 @@ public class BaseNTemplateNumberFormatFactory extends TemplateNumberFormatFactor
} catch (TemplateValueFormatException e) {
throw new InvalidFormatParametersException(
"Couldn't get the fallback number format (specified after the \"|\"), "
- + _StringUtil.jQuote(fallbackFormatStr) + ". Reason: " + e.getMessage(),
+ + _StringUtils.jQuote(fallbackFormatStr) + ". Reason: " + e.getMessage(),
e);
}
} else {
@@ -78,7 +78,7 @@ public class BaseNTemplateNumberFormatFactory extends TemplateNumberFormatFactor
}
throw new InvalidFormatParametersException(
"The format paramter must be an integer, but was (shown quoted): "
- + _StringUtil.jQuote(params));
+ + _StringUtils.jQuote(params));
}
if (base < 2) {
throw new InvalidFormatParametersException("A base must be at least 2.");
@@ -101,7 +101,7 @@ public class BaseNTemplateNumberFormatFactory extends TemplateNumberFormatFactor
throws TemplateModelException, TemplateValueFormatException {
Number n = TemplateFormatUtil.getNonNullNumber(numberModel);
try {
- return Integer.toString(_NumberUtil.toIntExact(n), base);
+ return Integer.toString(_NumberUtils.toIntExact(n), base);
} catch (ArithmeticException e) {
if (fallbackFormat == null) {
throw new UnformattableValueException(
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/CustomHTMLOutputFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/CustomHTMLOutputFormat.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/CustomHTMLOutputFormat.java
index 96a6a63..a8576bd 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/CustomHTMLOutputFormat.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/CustomHTMLOutputFormat.java
@@ -23,7 +23,7 @@ import java.io.Writer;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.outputformat.CommonMarkupOutputFormat;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents the HTML output format.
@@ -54,7 +54,7 @@ public final class CustomHTMLOutputFormat extends CommonMarkupOutputFormat<Custo
@Override
public String escapePlainText(String plainTextContent) {
- return _StringUtil.XHTMLEnc(plainTextContent.replace('x', 'X'));
+ return _StringUtils.XHTMLEnc(plainTextContent.replace('x', 'X'));
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/EpochMillisDivTemplateDateFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/EpochMillisDivTemplateDateFormatFactory.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/EpochMillisDivTemplateDateFormatFactory.java
index 8799eef..be06442 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/EpochMillisDivTemplateDateFormatFactory.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/EpochMillisDivTemplateDateFormatFactory.java
@@ -25,7 +25,7 @@ import java.util.TimeZone;
import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateDateModel;
import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.TemplateDateFormat;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
@@ -54,7 +54,7 @@ public class EpochMillisDivTemplateDateFormatFactory extends TemplateDateFormatF
"A format parameter is required, which specifies the divisor.");
}
throw new InvalidFormatParametersException(
- "The format paramter must be an integer, but was (shown quoted): " + _StringUtil.jQuote(params));
+ "The format paramter must be an integer, but was (shown quoted): " + _StringUtils.jQuote(params));
}
return new EpochMillisDivTemplateDateFormat(divisor);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HTMLISOTemplateDateFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HTMLISOTemplateDateFormatFactory.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HTMLISOTemplateDateFormatFactory.java
index 357034c..83e349f 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HTMLISOTemplateDateFormatFactory.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HTMLISOTemplateDateFormatFactory.java
@@ -26,9 +26,9 @@ import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateDateModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.outputformat.impl.HTMLOutputFormat;
-import org.apache.freemarker.core.util._DateUtil;
-import org.apache.freemarker.core.util._DateUtil.CalendarFieldsToDateConverter;
-import org.apache.freemarker.core.util._DateUtil.DateParseException;
+import org.apache.freemarker.core.util._DateUtils;
+import org.apache.freemarker.core.util._DateUtils.CalendarFieldsToDateConverter;
+import org.apache.freemarker.core.util._DateUtils.DateParseException;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.TemplateDateFormat;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
@@ -57,7 +57,7 @@ public class HTMLISOTemplateDateFormatFactory extends TemplateDateFormatFactory
private static final HTMLISOTemplateDateFormat INSTANCE = new HTMLISOTemplateDateFormat();
- private _DateUtil.TrivialDateToISO8601CalendarFactory calendarFactory;
+ private _DateUtils.TrivialDateToISO8601CalendarFactory calendarFactory;
private CalendarFieldsToDateConverter calToDateConverter;
@@ -67,11 +67,11 @@ public class HTMLISOTemplateDateFormatFactory extends TemplateDateFormatFactory
public String formatToPlainText(TemplateDateModel dateModel)
throws UnformattableValueException, TemplateModelException {
if (calendarFactory == null) {
- calendarFactory = new _DateUtil.TrivialDateToISO8601CalendarFactory();
+ calendarFactory = new _DateUtils.TrivialDateToISO8601CalendarFactory();
}
- return _DateUtil.dateToISO8601String(
+ return _DateUtils.dateToISO8601String(
TemplateFormatUtil.getNonNullDate(dateModel),
- true, true, true, _DateUtil.ACCURACY_SECONDS, _DateUtil.UTC,
+ true, true, true, _DateUtils.ACCURACY_SECONDS, _DateUtils.UTC,
calendarFactory);
}
@@ -89,9 +89,9 @@ public class HTMLISOTemplateDateFormatFactory extends TemplateDateFormatFactory
public Date parse(String s, int dateType) throws UnparsableValueException {
try {
if (calToDateConverter == null) {
- calToDateConverter = new _DateUtil.TrivialCalendarFieldsToDateConverter();
+ calToDateConverter = new _DateUtils.TrivialCalendarFieldsToDateConverter();
}
- return _DateUtil.parseISO8601DateTime(s, _DateUtil.UTC, calToDateConverter);
+ return _DateUtils.parseISO8601DateTime(s, _DateUtils.UTC, calToDateConverter);
} catch (DateParseException e) {
throw new UnparsableValueException("Malformed ISO date-time", e);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HexTemplateNumberFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HexTemplateNumberFormatFactory.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HexTemplateNumberFormatFactory.java
index 6d72c20..c1f34b4 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HexTemplateNumberFormatFactory.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/HexTemplateNumberFormatFactory.java
@@ -23,7 +23,7 @@ import java.util.Locale;
import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNumberModel;
-import org.apache.freemarker.core.util._NumberUtil;
+import org.apache.freemarker.core.util._NumberUtils;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.TemplateFormatUtil;
import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
@@ -56,7 +56,7 @@ public class HexTemplateNumberFormatFactory extends TemplateNumberFormatFactory
throws UnformattableValueException, TemplateModelException {
Number n = TemplateFormatUtil.getNonNullNumber(numberModel);
try {
- return Integer.toHexString(_NumberUtil.toIntExact(n));
+ return Integer.toHexString(_NumberUtils.toIntExact(n));
} catch (ArithmeticException e) {
throw new UnformattableValueException(n + " doesn't fit into an int");
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/PrintfGTemplateNumberFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/PrintfGTemplateNumberFormatFactory.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/PrintfGTemplateNumberFormatFactory.java
index e8d5f2b..7be09f7 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/PrintfGTemplateNumberFormatFactory.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/PrintfGTemplateNumberFormatFactory.java
@@ -26,7 +26,7 @@ import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.outputformat.impl.HTMLOutputFormat;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.TemplateFormatUtil;
import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
@@ -55,7 +55,7 @@ public class PrintfGTemplateNumberFormatFactory extends TemplateNumberFormatFact
} catch (NumberFormatException e) {
throw new InvalidFormatParametersException(
"The format parameter must be an integer, but was (shown quoted) "
- + _StringUtil.jQuote(params) + ".");
+ + _StringUtils.jQuote(params) + ".");
}
} else {
// Use the default of %G
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/TestTemplateCallableModel.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/TestTemplateCallableModel.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/TestTemplateCallableModel.java
index a1b263c..9cedddd 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/TestTemplateCallableModel.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/userpkg/TestTemplateCallableModel.java
@@ -29,7 +29,7 @@ import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.TemplateSequenceModel;
import org.apache.freemarker.core.util.FTLUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
public abstract class TestTemplateCallableModel implements TemplateCallableModel {
@@ -91,7 +91,7 @@ public abstract class TestTemplateCallableModel implements TemplateCallableModel
}
sb.append('}');
} else if (value instanceof String) {
- sb.append(_StringUtil.jQuote(value));
+ sb.append(_StringUtils.jQuote(value));
} else if (value instanceof Number) {
sb.append(value.toString());
} else if (value instanceof Boolean) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilTest.java
deleted file mode 100644
index a18d585..0000000
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import static org.junit.Assert.*;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.junit.Test;
-
-public class CollectionUtilTest {
-
- @Test
- public void unmodifiableMap() {
- Map<Object, Object> modifiableMap = new HashMap<>();
- assertNotSame(modifiableMap, _CollectionUtil.unmodifiableMap(modifiableMap));
-
- Map<Object, Object> wrappedModifiableMap = Collections.unmodifiableMap(modifiableMap);
- assertSame(wrappedModifiableMap, _CollectionUtil.unmodifiableMap(wrappedModifiableMap));
-
- assertSame(Collections.emptyMap(), _CollectionUtil.unmodifiableMap(Collections.emptyMap()));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilsTest.java
new file mode 100644
index 0000000..652d5b2
--- /dev/null
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/CollectionUtilsTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import static org.junit.Assert.*;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Test;
+
+public class CollectionUtilsTest {
+
+ @Test
+ public void unmodifiableMap() {
+ Map<Object, Object> modifiableMap = new HashMap<>();
+ assertNotSame(modifiableMap, _CollectionUtils.unmodifiableMap(modifiableMap));
+
+ Map<Object, Object> wrappedModifiableMap = Collections.unmodifiableMap(modifiableMap);
+ assertSame(wrappedModifiableMap, _CollectionUtils.unmodifiableMap(wrappedModifiableMap));
+
+ assertSame(Collections.emptyMap(), _CollectionUtils.unmodifiableMap(Collections.emptyMap()));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilTest.java
deleted file mode 100644
index 0cd8fc0..0000000
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilTest.java
+++ /dev/null
@@ -1,1085 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-import java.util.TimeZone;
-
-import javax.xml.datatype.DatatypeConfigurationException;
-import javax.xml.datatype.DatatypeFactory;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-import org.apache.freemarker.core.util._DateUtil.CalendarFieldsToDateConverter;
-import org.apache.freemarker.core.util._DateUtil.DateParseException;
-import org.apache.freemarker.core.util._DateUtil.DateToISO8601CalendarFactory;
-import org.apache.freemarker.core.util._DateUtil.TrivialCalendarFieldsToDateConverter;
-
-import junit.framework.TestCase;
-
-public class DateUtilTest extends TestCase {
-
- private final TimeZone originalDefaultTZ = TimeZone.getDefault();
-
- @Override
- protected void setUp() throws Exception {
- TimeZone.setDefault(TimeZone.getTimeZone("Europe/Prague"));
- }
-
- @Override
- protected void tearDown() throws Exception {
- TimeZone.setDefault(originalDefaultTZ);
- }
-
- private final DateFormat df
- = new SimpleDateFormat("G yyyy-MM-dd HH:mm:ss:S Z", Locale.US);
- {
- df.setTimeZone(_DateUtil.UTC);
- }
-
- private CalendarFieldsToDateConverter cf2dc = new TrivialCalendarFieldsToDateConverter();
-
- private DateToISO8601CalendarFactory calendarFactory
- = new _DateUtil.TrivialDateToISO8601CalendarFactory();
-
- public DateUtilTest(String name) {
- super(name);
- }
-
- public void testDateToUTCString() throws ParseException {
- assertEquals(
- "1998-10-30T15:30:00.512Z",
- dateToISO8601UTCDateTimeMSString(
- df.parse("AD 1998-10-30 19:30:00:512 +0400"), true));
- assertEquals(
- "1998-10-30T15:30:00.5Z",
- dateToISO8601UTCDateTimeMSString(
- df.parse("AD 1998-10-30 19:30:00:500 +0400"), true));
- assertEquals(
- "1998-10-30T15:30:00.51Z",
- dateToISO8601UTCDateTimeMSString(
- df.parse("AD 1998-10-30 19:30:00:510 +0400"), true));
- assertEquals(
- "1998-10-30T15:30:00.1Z",
- dateToISO8601UTCDateTimeMSString(
- df.parse("AD 1998-10-30 19:30:00:100 +0400"), true));
- assertEquals(
- "1998-10-30T15:30:00.01Z",
- dateToISO8601UTCDateTimeMSString(
- df.parse("AD 1998-10-30 19:30:00:10 +0400"), true));
- assertEquals(
- "1998-10-30T15:30:00.001Z",
- dateToISO8601UTCDateTimeMSString(
- df.parse("AD 1998-10-30 19:30:00:1 +0400"), true));
- assertEquals(
- "2000-02-08T06:05:04Z",
- dateToISO8601UTCDateTimeMSString(
- df.parse("AD 2000-02-08 09:05:04:0 +0300"), true));
- assertEquals(
- "0099-02-28T06:15:24Z",
- dateToISO8601UTCDateTimeString(
- df.parse(
- "AD 0099-03-02 09:15:24:0 +0300"), true));
- assertEquals(
- "0010-02-28T06:15:24Z",
- dateToISO8601UTCDateTimeString(
- df.parse("AD 0010-03-02 09:15:24:0 +0300"), true));
- assertEquals(
- "0001-02-28T06:15:24Z",
- dateToISO8601UTCDateTimeString(
- df.parse("AD 0001-03-02 09:15:24:0 +0300"), true));
- assertEquals(
- "0000-02-29T06:15:24Z",
- dateToISO8601UTCDateTimeString(
- df.parse("BC 0001-03-02 09:15:24:0 +0300"), true));
- assertEquals(
- "-1-02-28T06:15:24Z",
- dateToISO8601UTCDateTimeString(
- df.parse("BC 2-03-02 09:15:24:0 +0300"), true));
- assertEquals(
- "10000-02-28T06:15:24Z",
- dateToISO8601UTCDateTimeString(
- df.parse("AD 10000-02-28 09:15:24:0 +0300"), true));
-
- Date d = df.parse("AD 1998-10-30 19:30:00:512 +0400");
- assertEquals(
- "1998-10-30",
- dateToISO8601UTCDateString(d));
- assertEquals(
- "15:30:00.512Z",
- dateToISO8601UTCTimeMSString(d, true));
- assertEquals(
- "15:30:00.512",
- dateToISO8601UTCTimeMSString(d, false));
- assertEquals(
- "1998-10-30",
- dateToISO8601UTCDateString(
- new java.sql.Date(d.getTime())));
- assertEquals(
- "15:30:00.512Z",
- dateToISO8601UTCTimeMSString(
- new java.sql.Time(d.getTime()), true));
- }
-
- public void testLocalTime() throws ParseException {
- Date dsum = df.parse("AD 2010-05-09 20:00:00:0 UTC");
- Date dwin = df.parse("AD 2010-01-01 20:00:00:0 UTC");
-
- TimeZone tzRome = TimeZone.getTimeZone("Europe/Rome");
- if (tzRome.getOffset(0) == 0) {
- throw new RuntimeException(
- "Can't get time zone for Europe/Rome!");
- }
- assertEquals(
- "2010-05-09T22:00:00+02:00",
- dateToISO8601DateTimeString(dsum, tzRome));
- assertEquals(
- "2010-01-01T21:00:00+01:00",
- dateToISO8601DateTimeString(dwin, tzRome));
- assertEquals(
- "2010-05-09",
- dateToISO8601DateString(dsum, tzRome));
- assertEquals(
- "2010-01-01",
- dateToISO8601DateString(dwin, tzRome));
- assertEquals(
- "22:00:00+02:00",
- dateToISO8601TimeString(dsum, tzRome));
- assertEquals(
- "21:00:00+01:00",
- dateToISO8601TimeString(dwin, tzRome));
-
- TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
- if (tzNY.getOffset(0) == 0) {
- throw new RuntimeException(
- "Can't get time zone for America/New_York!");
- }
- assertEquals(
- "2010-05-09T16:00:00-04:00",
- dateToISO8601DateTimeString(dsum, tzNY));
- assertEquals(
- "2010-01-01T15:00:00-05:00",
- dateToISO8601DateTimeString(dwin, tzNY));
- assertEquals(
- "2010-05-09",
- dateToISO8601DateString(dsum, tzNY));
- assertEquals(
- "2010-01-01",
- dateToISO8601DateString(dwin, tzNY));
- assertEquals(
- "16:00:00-04:00",
- dateToISO8601TimeString(dsum, tzNY));
- assertEquals(
- "15:00:00-05:00",
- dateToISO8601TimeString(dwin, tzNY));
-
- TimeZone tzFixed = TimeZone.getTimeZone("GMT+02:30");
- assertEquals(
- "2010-05-09T22:30:00+02:30",
- dateToISO8601DateTimeString(dsum, tzFixed));
- assertEquals(
- "2010-01-01T22:30:00+02:30",
- dateToISO8601DateTimeString(dwin, tzFixed));
- }
-
- public void testGetTimeZone() throws Exception {
- assertTrue(_DateUtil.getTimeZone("GMT") != _DateUtil.UTC);
- assertTrue(_DateUtil.getTimeZone("UT1") != _DateUtil.UTC);
- assertEquals(_DateUtil.getTimeZone("UTC"), _DateUtil.UTC);
-
- assertEquals(_DateUtil.getTimeZone("Europe/Rome"),
- TimeZone.getTimeZone("Europe/Rome"));
-
- assertEquals(_DateUtil.getTimeZone("Iceland"), // GMT and no DST
- TimeZone.getTimeZone("Iceland"));
-
- try {
- _DateUtil.getTimeZone("Europe/NoSuch");
- fail();
- } catch (UnrecognizedTimeZoneException e) {
- // good
- }
- }
-
- public void testTimeOnlyDate() throws UnrecognizedTimeZoneException {
- Date t = new Date(0L);
- SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
-
- tf.setTimeZone(_DateUtil.UTC);
- assertEquals("00:00:00", tf.format(t));
- assertEquals("00:00:00",
- dateToISO8601UTCTimeString(t, false));
-
- TimeZone gmt1 = _DateUtil.getTimeZone("GMT+01");
- tf.setTimeZone(gmt1);
- assertEquals("01:00:00", tf.format(t));
- assertEquals("01:00:00+01:00",
- dateToISO8601TimeString(t, gmt1));
- }
-
- public void testAccuracy() throws ParseException {
- Date d = df.parse("AD 2000-02-08 09:05:04:250 UTC");
- assertEquals("2000-02-08T09:05:04Z",
- dateToISO8601UTCDateTimeString(d, true));
- assertEquals("2000-02-08T09:05:04.25Z",
- dateToISO8601String(d, true, true, true,
- _DateUtil.ACCURACY_MILLISECONDS, null));
- assertEquals("2000-02-08T09:05:04Z",
- dateToISO8601String(d, true, true, true,
- _DateUtil.ACCURACY_SECONDS, null));
- assertEquals("2000-02-08T09:05Z",
- dateToISO8601String(d, true, true, true,
- _DateUtil.ACCURACY_MINUTES, null));
- assertEquals("2000-02-08T09Z",
- dateToISO8601String(d, true, true, true,
- _DateUtil.ACCURACY_HOURS, null));
-
- d = df.parse("AD 1998-10-30 19:30:00:000 +0400");
- assertEquals(
- "15:30:00Z",
- dateToISO8601UTCTimeMSString(d, true));
- assertEquals(
- "15:30:00.000Z",
- dateToISO8601UTCTimeMSFString(d, true));
- assertEquals(
- "1998-10-30T15:30:00Z",
- dateToISO8601UTCDateTimeMSString(d, true));
- assertEquals(
- "1998-10-30T15:30:00.000Z",
- dateToISO8601UTCDateTimeMSFString(d, true));
-
- d = df.parse("AD 1998-10-30 19:30:00:100 +0400");
- assertEquals(
- "15:30:00.1Z",
- dateToISO8601UTCTimeMSString(d, true));
- assertEquals(
- "15:30:00.100Z",
- dateToISO8601UTCTimeMSFString(d, true));
- assertEquals(
- "1998-10-30T15:30:00.1Z",
- dateToISO8601UTCDateTimeMSString(d, true));
- assertEquals(
- "1998-10-30T15:30:00.100Z",
- dateToISO8601UTCDateTimeMSFString(d, true));
-
- d = df.parse("AD 1998-10-30 19:30:00:010 +0400");
- assertEquals(
- "15:30:00.01Z",
- dateToISO8601UTCTimeMSString(d, true));
- assertEquals(
- "15:30:00.010Z",
- dateToISO8601UTCTimeMSFString(d, true));
- assertEquals(
- "1998-10-30T15:30:00.01Z",
- dateToISO8601UTCDateTimeMSString(d, true));
- assertEquals(
- "1998-10-30T15:30:00.010Z",
- dateToISO8601UTCDateTimeMSFString(d, true));
-
- d = df.parse("AD 1998-10-30 19:30:00:001 +0400");
- assertEquals(
- "15:30:00.001Z",
- dateToISO8601UTCTimeMSString(d, true));
- assertEquals(
- "15:30:00.001Z",
- dateToISO8601UTCTimeMSFString(d, true));
- assertEquals(
- "1998-10-30T15:30:00.001Z",
- dateToISO8601UTCDateTimeMSString(d, true));
- assertEquals(
- "1998-10-30T15:30:00.001Z",
- dateToISO8601UTCDateTimeMSFString(d, true));
- }
-
- public void testXSFormatISODeviations() throws ParseException, UnrecognizedTimeZoneException {
- Date dsum = df.parse("AD 2010-05-09 20:00:00:0 UTC");
- Date dwin = df.parse("AD 2010-01-01 20:00:00:0 UTC");
-
- TimeZone tzRome = _DateUtil.getTimeZone("Europe/Rome");
-
- assertEquals(
- "2010-01-01T21:00:00+01:00",
- _DateUtil.dateToXSString(dwin, true, true, true, _DateUtil.ACCURACY_SECONDS, tzRome, calendarFactory));
- assertEquals(
- "2010-05-09T22:00:00+02:00",
- _DateUtil.dateToXSString(dsum, true, true, true, _DateUtil.ACCURACY_SECONDS, tzRome, calendarFactory));
- assertEquals(
- "2010-01-01+01:00", // ISO doesn't allow date-only with TZ
- _DateUtil.dateToXSString(dwin, true, false, true, _DateUtil.ACCURACY_SECONDS, tzRome, calendarFactory));
- assertEquals(
- "2010-05-09+02:00", // ISO doesn't allow date-only with TZ
- _DateUtil.dateToXSString(dsum, true, false, true, _DateUtil.ACCURACY_SECONDS, tzRome, calendarFactory));
- assertEquals(
- "21:00:00+01:00",
- _DateUtil.dateToXSString(dwin, false, true, true, _DateUtil.ACCURACY_SECONDS, tzRome, calendarFactory));
- assertEquals(
- "22:00:00+02:00",
- _DateUtil.dateToXSString(dsum, false, true, true, _DateUtil.ACCURACY_SECONDS, tzRome, calendarFactory));
-
- assertEquals(
- "-1-02-29T06:15:24Z", // ISO uses 0 for BC 1
- _DateUtil.dateToXSString(
- df.parse("BC 0001-03-02 09:15:24:0 +0300"),
- true, true, true, _DateUtil.ACCURACY_SECONDS, _DateUtil.UTC, calendarFactory));
- assertEquals(
- "-2-02-28T06:15:24Z", // ISO uses -1 for BC 2
- _DateUtil.dateToXSString(
- df.parse("BC 2-03-02 09:15:24:0 +0300"),
- true, true, true, _DateUtil.ACCURACY_SECONDS, _DateUtil.UTC, calendarFactory));
- }
-
- private String dateToISO8601DateTimeString(
- Date date, TimeZone tz) {
- return dateToISO8601String(date, true, true, true,
- _DateUtil.ACCURACY_SECONDS, tz);
- }
-
- private String dateToISO8601UTCDateTimeString(
- Date date, boolean offsetPart) {
- return dateToISO8601String(date, true, true, offsetPart,
- _DateUtil.ACCURACY_SECONDS, _DateUtil.UTC);
- }
-
- private String dateToISO8601UTCDateTimeMSString(
- Date date, boolean offsetPart) {
- return dateToISO8601String(date, true, true, offsetPart,
- _DateUtil.ACCURACY_MILLISECONDS, _DateUtil.UTC);
- }
-
- private String dateToISO8601UTCDateTimeMSFString(
- Date date, boolean offsetPart) {
- return dateToISO8601String(date, true, true, offsetPart,
- _DateUtil.ACCURACY_MILLISECONDS_FORCED, _DateUtil.UTC);
- }
-
- private String dateToISO8601DateString(Date date, TimeZone tz) {
- return dateToISO8601String(date, true, false, false,
- _DateUtil.ACCURACY_SECONDS, tz);
- }
-
- private String dateToISO8601UTCDateString(Date date) {
- return dateToISO8601String(date, true, false, false,
- _DateUtil.ACCURACY_SECONDS, _DateUtil.UTC);
- }
-
- private String dateToISO8601TimeString(
- Date date, TimeZone tz) {
- return dateToISO8601String(date, false, true, true,
- _DateUtil.ACCURACY_SECONDS, tz);
- }
-
- private String dateToISO8601UTCTimeString(
- Date date, boolean offsetPart) {
- return dateToISO8601String(date, false, true, offsetPart,
- _DateUtil.ACCURACY_SECONDS, _DateUtil.UTC);
- }
-
- private String dateToISO8601UTCTimeMSString(
- Date date, boolean offsetPart) {
- return dateToISO8601String(date, false, true, offsetPart,
- _DateUtil.ACCURACY_MILLISECONDS, _DateUtil.UTC);
- }
-
- private String dateToISO8601UTCTimeMSFString(
- Date date, boolean offsetPart) {
- return dateToISO8601String(date, false, true, offsetPart,
- _DateUtil.ACCURACY_MILLISECONDS_FORCED, _DateUtil.UTC);
- }
-
- private String dateToISO8601String(
- Date date,
- boolean datePart, boolean timePart, boolean offsetPart,
- int accuracy,
- TimeZone timeZone) {
- return _DateUtil.dateToISO8601String(
- date,
- datePart, timePart, offsetPart,
- accuracy,
- timeZone,
- calendarFactory);
- }
-
- public void testParseDate() throws DateParseException {
- assertDateParsing(
- "AD 1998-10-29 20:00:00:0 +0000",
- null,
- "1998-10-30+04:00", _DateUtil.UTC);
- assertDateParsing(
- "AD 1998-10-30 02:00:00:0 +0000",
- null,
- "1998-10-30-02:00", _DateUtil.UTC);
- assertDateParsing(
- "AD 1998-10-30 02:00:00:0 +0000",
- "1998-10-30", _DateUtil.parseXSTimeZone("-02:00"));
- assertDateParsing(
- null,
- "AD 1998-10-30 02:00:00:0 +0000",
- "19981030", _DateUtil.parseXSTimeZone("-02:00"));
- assertDateParsing(
- "AD 1998-10-30 00:00:00:0 +0000",
- null,
- "1998-10-30Z", _DateUtil.UTC);
- assertDateParsing(
- "AD 1998-10-30 00:00:00:0 +0000",
- "1998-10-30", _DateUtil.UTC);
- assertDateParsing(
- null,
- "AD 1998-10-30 00:00:00:0 +0000",
- "19981030", _DateUtil.UTC);
-
- assertDateParsing(
- "AD 1998-10-29 20:00:00:0 +0000",
- null,
- "1998-10-30+04:00", _DateUtil.UTC);
- assertDateParsing(
- "AD 1998-10-30 04:00:00:0 +0000",
- null,
- "1998-10-30-04:00", _DateUtil.UTC);
- assertDateParsing(
- "AD 1998-10-30 00:00:00:0 +0000",
- null,
- "1998-10-30Z", _DateUtil.UTC);
-
- try {
- // XS doesn't have year 0
- assertDateParsing(
- "BC 0000-02-05 00:00:00:0 +0000",
- null,
- "0000-02-03Z", _DateUtil.UTC);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- assertDateParsing(
- null,
- "BC 0001-02-05 00:00:00:0 +0000",
- "0000-02-03", _DateUtil.UTC);
- assertDateParsing(
- null,
- "BC 0001-02-05 00:00:00:0 +0000",
- "00000203", _DateUtil.UTC);
-
- assertDateParsing(
- "BC 0001-02-05 00:00:00:0 +0000", // Julian
- "BC 0002-02-05 00:00:00:0 +0000", // Julian
- "-0001-02-03", _DateUtil.UTC); // Proleptic Gregorian
- assertDateParsing(
- null,
- "BC 0002-02-05 00:00:00:0 +0000", // Julian
- "-00010203", _DateUtil.UTC); // Proleptic Gregorian
-
- assertDateParsing(
- "AD 0001-02-05 00:00:00:0 +0000", // Julian
- null,
- "0001-02-03Z", _DateUtil.UTC); // Proleptic Gregorian
- assertDateParsing(
- "AD 0001-02-05 00:00:00:0 +0000", // Julian
- "0001-02-03", _DateUtil.UTC); // Proleptic Gregorian
- assertDateParsing(
- null,
- "AD 0001-02-05 00:00:00:0 +0000", // Julian
- "00010203", _DateUtil.UTC); // Proleptic Gregorian
- assertDateParsing(
- "AD 1001-12-07 00:00:00:0 +0000", // Julian
- null,
- "1001-12-13Z", _DateUtil.UTC); // Proleptic Gregorian
- assertDateParsing(
- "AD 1001-12-07 00:00:00:0 +0000", // Julian
- "1001-12-13", _DateUtil.UTC); // Proleptic Gregorian
-
- assertDateParsing(
- "AD 2006-12-31 00:00:00:0 +0000",
- null,
- "2006-12-31Z", _DateUtil.UTC);
- assertDateParsing(
- "AD 2006-12-31 00:00:00:0 +0000",
- "2006-12-31", _DateUtil.UTC);
- assertDateParsing(
- "AD 2006-01-01 00:00:00:0 +0000",
- null,
- "2006-01-01Z", _DateUtil.UTC);
- assertDateParsing(
- "AD 2006-01-01 00:00:00:0 +0000",
- "2006-01-01", _DateUtil.UTC);
- assertDateParsing(
- "AD 12006-01-01 00:00:00:0 +0000",
- "12006-01-01", _DateUtil.UTC);
- assertDateParsing(
- null,
- "AD 12006-01-01 00:00:00:0 +0000",
- "120060101", _DateUtil.UTC);
- }
-
- public void testParseDateMalformed() {
- assertDateMalformed("1998-10-30x");
- assertDateMalformed("+1998-10-30");
- assertDateMalformed("1998-10-");
- assertDateMalformed("1998-1-30");
- assertDateMalformed("1998-10-30+01");
- assertDateMalformed("1998-00-01");
- assertDateMalformed("1998-13-01");
- assertDateMalformed("1998-10-00");
- assertDateMalformed("1998-10-32");
- assertDateMalformed("1998-02-31");
-
- assertISO8601DateMalformed("2100103");
- assertISO8601DateMalformed("210-01-03");
- assertISO8601DateMalformed("2012-0301");
- assertISO8601DateMalformed("201203-01");
- assertISO8601DateMalformed("2012-01-01+01:00");
- }
-
- public void testParseTime() throws DateParseException {
- assertTimeParsing(
- "AD 1970-01-01 17:30:05:0 +0000",
- "17:30:05", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 17:30:05:0 +0000",
- "173005", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 07:30:00:100 +0000",
- "07:30:00.1", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 07:30:00:120 +0000",
- "07:30:00.12", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 07:30:00:123 +0000",
- "07:30:00.123", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 07:30:00:123 +0000",
- "07:30:00.1235", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 07:30:00:123 +0000",
- "07:30:00.12346", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 07:30:00:123 +0000",
- "073000.12346", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 07:30:00:123 +0000",
- "073000,12346", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 07:30:00:120 +0000",
- "07:30:00.12", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 07:30:00:500 +0000",
- "07:30:00.5", _DateUtil.UTC);
-
- assertTimeParsing(
- "AD 1970-01-01 16:30:05:0 +0000",
- "17:30:05+01:00", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 16:30:05:0 +0000",
- "173005+01", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 19:00:05:0 +0000",
- "17:30:05-01:30", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 19:00:05:0 +0000",
- "173005-0130", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-01 16:30:05:500 +0000",
- "17:30:05.5+01:00", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 16:30:05:500 +0000",
- "173005.5+0100", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 16:30:05:500 +0000",
- "173005.5+01", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 16:00:00:0 +0000",
- "170000+01", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 16:00:00:0 +0000",
- "1700+01", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-01 16:00:00:0 +0000",
- "17+01", _DateUtil.UTC);
-
- assertTimeParsing(
- "AD 1970-01-01 00:00:00:0 +0000",
- "00:00:00", _DateUtil.UTC);
- assertTimeParsing(
- "AD 1970-01-02 00:00:00:0 +0000",
- "24:00:00", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-02 00:00:00:0 +0000",
- "240000", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-02 00:00:00:0 +0000",
- "2400", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-02 00:00:00:0 +0000",
- "24:00", _DateUtil.UTC);
- assertTimeParsing(
- null,
- "AD 1970-01-02 00:00:00:0 +0000",
- "24", _DateUtil.UTC);
-
- assertTimeParsing(
- "AD 1970-01-01 23:59:59:999 +0000",
- "23:59:59.999", _DateUtil.UTC);
- }
-
- public void testParseTimeMalformed() {
- assertTimeMalformed("00:0000");
- assertTimeMalformed("00:00:00-01:60");
- assertTimeMalformed("24:00:01");
- assertTimeMalformed("00:00:61");
- assertTimeMalformed("00:60:00");
- assertTimeMalformed("25:00:00");
- assertTimeMalformed("2:00:00");
- assertTimeMalformed("02:0:00");
- assertTimeMalformed("02:00:0");
-
- assertISO8601TimeMalformed("1010101");
- assertISO8601TimeMalformed("10101");
- assertISO8601TimeMalformed("101");
- assertISO8601TimeMalformed("1");
- assertISO8601TimeMalformed("101010-1");
- assertISO8601TimeMalformed("101010-100");
- assertISO8601TimeMalformed("101010-10000");
- assertISO8601TimeMalformed("101010+1");
- assertISO8601TimeMalformed("101010+100");
- assertISO8601TimeMalformed("101010+10000");
- }
-
- public void testParseDateTime() throws DateParseException {
- assertDateTimeParsing(
- "AD 1998-10-30 11:30:00:0 +0000",
- "1998-10-30T15:30:00+04:00", _DateUtil.UTC);
- assertDateTimeParsing(
- null,
- "AD 1998-10-30 11:30:00:0 +0000",
- "19981030T153000+0400", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 11:30:00:500 +0000",
- "1998-10-30T15:30:00.5+04:00", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 15:30:00:0 +0000",
- "1998-10-30T15:30:00Z", _DateUtil.UTC);
- assertDateTimeParsing(
- null,
- "AD 1998-10-30 15:30:00:0 +0000",
- "19981030T1530Z", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 15:30:00:500 +0000",
- "1998-10-30T15:30:00.5Z", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 11:30:00:0 +0000",
- "1998-10-30T15:30:00+04:00", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 15:30:00:0 +0000",
- "1998-10-30T15:30:00Z", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 15:30:00:0 +0000",
- "1998-10-30T15:30:00", _DateUtil.UTC);
- assertDateTimeParsing(
- null,
- "AD 1998-10-30 15:30:00:0 +0000",
- "1998-10-30T15:30", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "AD 1998-10-29 20:00:00:0 +0000",
- "1998-10-30T00:00:00+04:00", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 02:00:00:0 +0000",
- "1998-10-30T00:00:00-02:00", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 00:00:00:0 +0000",
- "1998-10-30T00:00:00Z", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "AD 1998-10-29 20:00:00:0 +0000",
- "1998-10-30T00:00:00+04:00", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1998-10-30 00:00:00:0 +0000",
- "1998-10-30T00:00:00Z", _DateUtil.UTC);
- assertDateTimeParsing(
- null,
- "AD 1998-10-30 00:00:00:0 +0000",
- "1998-10-30T00:00Z", _DateUtil.UTC);
- assertDateTimeParsing(
- null,
- "AD 1998-10-30 00:00:00:0 +0000",
- "1998-10-30T00:00", _DateUtil.UTC);
- assertDateTimeParsing(
- null,
- "AD 1998-10-30 00:00:00:0 +0000",
- "19981030T00Z", _DateUtil.UTC);
-
- // BC years
- try {
- assertDateTimeParsing(
- "",
- null,
- "0000-02-03T00:00:00Z", _DateUtil.UTC);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- assertDateTimeParsing(
- null,
- "BC 0001-02-05 00:00:00:0 +0000",
- "0000-02-03T00:00:00Z", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "BC 0001-02-05 00:00:00:0 +0000", // Julian
- "BC 0002-02-05 00:00:00:0 +0000", // Julian
- "-0001-02-03T00:00:00Z", _DateUtil.UTC); // Proleptic Gregorian
-
- assertDateTimeParsing(
- "AD 0001-02-05 00:00:00:0 +0000", // Julian
- "0001-02-03T00:00:00Z", _DateUtil.UTC); // Proleptic Gregorian
- assertDateTimeParsing(
- "AD 1001-12-07 00:00:00:0 +0000", // Julian
- "1001-12-13T00:00:00Z", _DateUtil.UTC); // Proleptic Gregorian
- assertDateTimeParsing(
- "AD 11001-12-13 00:00:00:0 +0000",
- "11001-12-13T00:00:00Z", _DateUtil.UTC);
- assertDateTimeParsing(
- null,
- "AD 11001-12-13 00:00:00:0 +0000",
- "110011213T00Z", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "AD 2006-12-31 00:00:00:0 +0000",
- "2006-12-31T00:00:00Z", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 2006-01-01 00:00:00:0 +0000",
- "2006-01-01T00:00:00Z", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "AD 1970-01-01 07:30:00:123 +0000",
- "1970-01-01T07:30:00.123", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1970-01-01 07:30:00:123 +0000",
- "1970-01-01T07:30:00.1235", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1970-01-01 07:30:00:123 +0000",
- "1970-01-01T07:30:00.12346", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1970-01-01 07:30:00:120 +0000",
- "1970-01-01T07:30:00.12", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1970-01-01 07:30:00:500 +0000",
- "1970-01-01T07:30:00.5", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "AD 1970-01-01 16:30:05:0 +0000",
- "1970-01-01T17:30:05+01:00", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1970-01-01 16:30:05:500 +0000",
- "1970-01-01T17:30:05.5+01:00", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "AD 1970-01-01 00:00:00:0 +0000",
- "1970-01-01T00:00:00", _DateUtil.UTC);
- assertDateTimeParsing(
- "AD 1970-01-02 00:00:00:0 +0000",
- "1970-01-01T24:00:00", _DateUtil.UTC);
-
- assertDateTimeParsing(
- "AD 1970-01-01 23:59:59:999 +0000",
- "1970-01-01T23:59:59.999", _DateUtil.UTC);
- }
-
- public void testParseDateTimeMalformed() throws DateParseException {
- assertDateTimeMalformed("1998-00-01T00:00:00");
- assertDateTimeMalformed("1998-13-01T00:00:00");
- assertDateTimeMalformed("1998-10-00T00:00:00");
- assertDateTimeMalformed("1998-10-32T00:00:00");
- assertDateTimeMalformed("1998-02-31T00:00:00");
- assertDateTimeMalformed("1970-01-02T24:00:01");
- assertDateTimeMalformed("1970-01-01T00:00:61");
- assertDateTimeMalformed("1970-01-01T00:60:00");
- assertDateTimeMalformed("1970-01-01T25:00:00");
-
- assertISO8601DateTimeMalformed("197-01-01T20:00:00");
- }
-
- public void testParseXSTimeZone() throws DateParseException {
- assertEquals(0,
- _DateUtil.parseXSTimeZone("Z").getOffset(0));
- assertEquals(0,
- _DateUtil.parseXSTimeZone("-00:00").getOffset(0));
- assertEquals(0,
- _DateUtil.parseXSTimeZone("+00:00").getOffset(0));
- assertEquals(90 * 60 * 1000,
- _DateUtil.parseXSTimeZone("+01:30").getOffset(0));
- assertEquals(-4 * 60 * 60 * 1000,
- _DateUtil.parseXSTimeZone("-04:00").getOffset(0));
- assertEquals(((-23 * 60) - 59) * 60 * 1000,
- _DateUtil.parseXSTimeZone("-23:59").getOffset(0));
- assertEquals(((23 * 60) + 59) * 60 * 1000,
- _DateUtil.parseXSTimeZone("+23:59").getOffset(0));
- }
-
- public void testParseXSTimeZoneWrong() {
- try {
- _DateUtil.parseXSTimeZone("04:00").getOffset(0);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- try {
- _DateUtil.parseXSTimeZone("-04:00x").getOffset(0);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- try {
- _DateUtil.parseXSTimeZone("-04").getOffset(0);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- try {
- _DateUtil.parseXSTimeZone("+24:00").getOffset(0);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- try {
- _DateUtil.parseXSTimeZone("-24:00").getOffset(0);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- try {
- _DateUtil.parseXSTimeZone("-01:60").getOffset(0);
- fail();
- } catch (DateParseException e) {
- echo(e);
- }
- }
-
- public void testParseXSDateTimeFTLAndJavax() throws DateParseException {
- // Explicit time zone:
- assertJavaxAndFTLXSDateTimesSame("2014-01-01T13:35:08Z");
- assertJavaxAndFTLXSDateTimesSame("2014-01-01T13:35:08+02:00");
-
- // Default time zone:
- assertJavaxAndFTLXSDateTimesSame("2014-01-01T13:35:08"); // winter
- assertJavaxAndFTLXSDateTimesSame("2014-07-01T13:35:08"); // summer
-
- // Proleptic Gregorian
- assertJavaxAndFTLXSDateTimesSame("1500-01-01T13:35:08Z");
- assertJavaxAndFTLXSDateTimesSame("0200-01-01T13:35:08Z");
- assertJavaxAndFTLXSDateTimesSame("0001-01-01T00:00:00+05:00");
-
- // BC
- assertJavaxAndFTLXSDateTimesSame("0001-01-01T13:35:08Z");
- assertJavaxAndFTLXSDateTimesSame("-0001-01-01T13:35:08Z");
-
- // Hour 24
- assertJavaxAndFTLXSDateTimesSame("2014-01-01T23:59:59");
- if (isAtLeastJava6()) { // Java 5 has broken parser that doesn't allow 24.
- assertJavaxAndFTLXSDateTimesSame("2014-01-31T24:00:00");
- assertJavaxAndFTLXSDateTimesSame("2014-01-01T24:00:00");
- }
- assertJavaxAndFTLXSDateTimesSame("2014-01-02T00:00:00"); // same as the previous
- assertJavaxAndFTLXSDateTimesSame("2014-02-01T00:00:00"); // same as the previous
-
- // Under ms
- assertJavaxAndFTLXSDateTimesSame("2014-01-01T23:59:59.123456789");
- assertJavaxAndFTLXSDateTimesSame("2014-01-01T23:59:59.1235");
- }
-
- private boolean isAtLeastJava6() {
- try {
- Class.forName("java.lang.management.LockInfo");
- } catch (ClassNotFoundException e) {
- return false;
- }
- return true;
- }
-
- private final DatatypeFactory datetypeFactory;
- {
- try {
- datetypeFactory = DatatypeFactory.newInstance();
- } catch (DatatypeConfigurationException e) {
- throw new RuntimeException(e);
- }
- }
-
- private void assertJavaxAndFTLXSDateTimesSame(String s) throws DateParseException {
- XMLGregorianCalendar xgc = datetypeFactory.newXMLGregorianCalendar(s);
- Date javaxDate = xgc.toGregorianCalendar().getTime();
- Date ftlDate = _DateUtil.parseXSDateTime(s, TimeZone.getDefault(), cf2dc);
- assertEquals(javaxDate, ftlDate);
- }
-
- private void assertDateParsing(String expected, String parsed, TimeZone tz) throws DateParseException {
- assertDateParsing(expected, expected, parsed, tz);
- }
-
- private void assertDateParsing(String expectedXS, String expectedISO8601, String parsed, TimeZone tz)
- throws DateParseException {
- if (expectedXS != null) {
- assertEquals(
- expectedXS,
- df.format(_DateUtil.parseXSDate(parsed, tz, cf2dc)));
- }
- if (expectedISO8601 != null) {
- assertEquals(
- expectedISO8601,
- df.format(_DateUtil.parseISO8601Date(parsed, tz, cf2dc)));
- }
- }
-
- private void assertDateTimeParsing(String expected, String parsed, TimeZone tz) throws DateParseException {
- assertDateTimeParsing(expected, expected, parsed, tz);
- }
-
- private void assertDateTimeParsing(String expectedXS, String expectedISO8601, String parsed, TimeZone tz)
- throws DateParseException {
- if (expectedXS != null) {
- assertEquals(
- expectedXS,
- df.format(_DateUtil.parseXSDateTime(parsed, tz, cf2dc)));
- }
- if (expectedISO8601 != null) {
- assertEquals(
- expectedISO8601,
- df.format(_DateUtil.parseISO8601DateTime(parsed, tz, cf2dc)));
- }
- }
-
- private void assertTimeParsing(String expected, String parsed, TimeZone tz) throws DateParseException {
- assertTimeParsing(expected, expected, parsed, tz);
- }
-
- private void assertTimeParsing(String expectedXS, String expectedISO8601, String parsed, TimeZone tz)
- throws DateParseException {
- if (expectedXS != null) {
- assertEquals(
- expectedXS,
- df.format(_DateUtil.parseXSTime(parsed, tz, cf2dc)));
- }
- if (expectedISO8601 != null) {
- assertEquals(
- expectedISO8601,
- df.format(_DateUtil.parseISO8601Time(parsed, tz, cf2dc)));
- }
- }
-
- private void assertDateMalformed(String parsed) {
- try {
- _DateUtil.parseXSDate(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- try {
- _DateUtil.parseISO8601Date(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- }
-
- private void assertTimeMalformed(String parsed) {
- try {
- _DateUtil.parseXSTime(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- try {
- _DateUtil.parseISO8601Time(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- }
-
- private void assertDateTimeMalformed(String parsed) {
- try {
- _DateUtil.parseXSDateTime(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- try {
- _DateUtil.parseISO8601DateTime(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- }
-
- private void assertISO8601DateMalformed(String parsed) {
- try {
- _DateUtil.parseISO8601Date(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- }
-
- private void assertISO8601TimeMalformed(String parsed) {
- try {
- _DateUtil.parseISO8601Time(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- }
-
- private void assertISO8601DateTimeMalformed(String parsed) {
- try {
- _DateUtil.parseISO8601DateTime(parsed, _DateUtil.UTC, cf2dc);
- fail();
- } catch (DateParseException e) {
- // Expected
- echo(e);
- }
- }
-
- private void echo(@SuppressWarnings("unused") DateParseException e) {
- // System.out.println(e);
- }
-
-}
\ No newline at end of file
[11/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtils.java
new file mode 100644
index 0000000..3ce73b8
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/MessageUtils.java
@@ -0,0 +1,344 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core;
+
+import java.util.ArrayList;
+
+import org.apache.freemarker.core.model.TemplateModel;
+import org.apache.freemarker.core.model.TemplateModelException;
+import org.apache.freemarker.core.util._StringUtils;
+import org.apache.freemarker.core.valueformat.TemplateDateFormat;
+import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
+import org.apache.freemarker.core.valueformat.TemplateValueFormatException;
+import org.apache.freemarker.core.valueformat.UnknownDateTypeFormattingUnsupportedException;
+
+/**
+ * Utilities for creating error messages (and other messages).
+ */
+class MessageUtils {
+
+ static final String UNKNOWN_DATE_TO_STRING_ERROR_MESSAGE
+ = "Can't convert the date-like value to string because it isn't "
+ + "known if it's a date (no time part), time or date-time value.";
+
+ static final String UNKNOWN_DATE_TYPE_ERROR_TIP =
+ "Use ?date, ?time, or ?dateTime to tell FreeMarker the exact type.";
+
+ static final Object[] UNKNOWN_DATE_TO_STRING_TIPS = {
+ UNKNOWN_DATE_TYPE_ERROR_TIP,
+ "If you need a particular format only once, use ?string(pattern), like ?string('dd.MM.yyyy HH:mm:ss'), "
+ + "to specify which fields to display. "
+ };
+
+ static final String FM3_SNAKE_CASE = "\nThe name contains '_' character, but since FreeMarker 3 names defined "
+ + "by the template language use camel case (e.g. someExampleName).";
+
+ static final String EMBEDDED_MESSAGE_BEGIN = "---begin-message---\n";
+
+ static final String EMBEDDED_MESSAGE_END = "\n---end-message---";
+
+ static final String ERROR_MESSAGE_HR = "----";
+
+ // Can't be instantiated
+ private MessageUtils() { }
+
+ static String formatLocationForSimpleParsingError(Template template, int line, int column) {
+ return formatLocation("in", template, line, column);
+ }
+
+ static String formatLocationForSimpleParsingError(String templateSourceOrLookupName, int line, int column) {
+ return formatLocation("in", templateSourceOrLookupName, line, column);
+ }
+
+ static String formatLocationForEvaluationError(Template template, int line, int column) {
+ return formatLocation("at", template, line, column);
+ }
+
+ static String formatLocationForEvaluationError(ASTDirMacroOrFunction macro, int line, int column) {
+ Template t = macro.getTemplate();
+ return formatLocation("at", t != null ? t.getSourceOrLookupName() : null, macro.getName(), macro.isFunction(),
+ line, column);
+ }
+
+ private static String formatLocation(String preposition, Template template, int line, int column) {
+ return formatLocation(preposition, template != null ? template.getSourceOrLookupName() : null, line, column);
+ }
+
+ private static String formatLocation(String preposition, String templateSourceName, int line, int column) {
+ return formatLocation(
+ preposition, templateSourceName,
+ null, false,
+ line, column);
+ }
+
+ private static String formatLocation(
+ String preposition, String templateSourceName,
+ String macroOrFuncName, boolean isFunction,
+ int line, int column) {
+ String templateDesc;
+ if (line < 0) {
+ templateDesc = "?eval-ed string";
+ macroOrFuncName = null;
+ } else {
+ templateDesc = templateSourceName != null
+ ? "template " + _StringUtils.jQuoteNoXSS(templateSourceName)
+ : "nameless template";
+ }
+ return "in " + templateDesc
+ + (macroOrFuncName != null
+ ? " in " + (isFunction ? "function " : "macro ") + _StringUtils.jQuote(macroOrFuncName)
+ : "")
+ + " "
+ + preposition + " " + formatPosition(line, column);
+ }
+
+ static String formatPosition(int line, int column) {
+ return "line " + (line >= 0 ? line : line - (ASTNode.RUNTIME_EVAL_LINE_DISPLACEMENT - 1))
+ + ", column " + column;
+ }
+
+ /**
+ * Returns a single line string that is no longer than {@code maxLength}.
+ * If will truncate the string at line-breaks too.
+ * The truncation is always signaled with a a {@code "..."} at the end of the result string.
+ */
+ static String shorten(String s, int maxLength) {
+ if (maxLength < 5) maxLength = 5;
+
+ boolean isTruncated = false;
+
+ int brIdx = s.indexOf('\n');
+ if (brIdx != -1) {
+ s = s.substring(0, brIdx);
+ isTruncated = true;
+ }
+ brIdx = s.indexOf('\r');
+ if (brIdx != -1) {
+ s = s.substring(0, brIdx);
+ isTruncated = true;
+ }
+
+ if (s.length() > maxLength) {
+ s = s.substring(0, maxLength - 3);
+ isTruncated = true;
+ }
+
+ if (!isTruncated) {
+ return s;
+ } else {
+ if (s.endsWith(".")) {
+ if (s.endsWith("..")) {
+ if (s.endsWith("...")) {
+ return s;
+ } else {
+ return s + ".";
+ }
+ } else {
+ return s + "..";
+ }
+ } else {
+ return s + "...";
+ }
+ }
+ }
+
+ static StringBuilder appendExpressionAsUntearable(StringBuilder sb, ASTExpression argExp) {
+ boolean needParen =
+ !(argExp instanceof ASTExpNumberLiteral)
+ && !(argExp instanceof ASTExpStringLiteral)
+ && !(argExp instanceof ASTExpBooleanLiteral)
+ && !(argExp instanceof ASTExpListLiteral)
+ && !(argExp instanceof ASTExpHashLiteral)
+ && !(argExp instanceof ASTExpVariable)
+ && !(argExp instanceof ASTExpDot)
+ && !(argExp instanceof ASTExpDynamicKeyName)
+ && !(argExp instanceof ASTExpFunctionCall)
+ && !(argExp instanceof ASTExpBuiltIn);
+ if (needParen) sb.append('(');
+ sb.append(argExp.getCanonicalForm());
+ if (needParen) sb.append(')');
+ return sb;
+ }
+
+ static TemplateModelException newArgCntError(String methodName, int argCnt, int expectedCnt) {
+ return newArgCntError(methodName, argCnt, expectedCnt, expectedCnt);
+ }
+
+ static TemplateModelException newArgCntError(String methodName, int argCnt, int minCnt, int maxCnt) {
+ ArrayList/*<Object>*/ desc = new ArrayList(20);
+
+ desc.add(methodName);
+
+ desc.add("(");
+ if (maxCnt != 0) desc.add("...");
+ desc.add(") expects ");
+
+ if (minCnt == maxCnt) {
+ if (maxCnt == 0) {
+ desc.add("no");
+ } else {
+ desc.add(Integer.valueOf(maxCnt));
+ }
+ } else if (maxCnt - minCnt == 1) {
+ desc.add(Integer.valueOf(minCnt));
+ desc.add(" or ");
+ desc.add(Integer.valueOf(maxCnt));
+ } else {
+ desc.add(Integer.valueOf(minCnt));
+ if (maxCnt != Integer.MAX_VALUE) {
+ desc.add(" to ");
+ desc.add(Integer.valueOf(maxCnt));
+ } else {
+ desc.add(" or more (unlimited)");
+ }
+ }
+ desc.add(" argument");
+ if (maxCnt > 1) desc.add("s");
+
+ desc.add(" but has received ");
+ if (argCnt == 0) {
+ desc.add("none");
+ } else {
+ desc.add(Integer.valueOf(argCnt));
+ }
+ desc.add(".");
+
+ return new _TemplateModelException(desc.toArray());
+ }
+
+ static TemplateModelException newMethodArgMustBeStringException(String methodName, int argIdx, TemplateModel arg) {
+ return newMethodArgUnexpectedTypeException(methodName, argIdx, "string", arg);
+ }
+
+ static TemplateModelException newMethodArgMustBeNumberException(String methodName, int argIdx, TemplateModel arg) {
+ return newMethodArgUnexpectedTypeException(methodName, argIdx, "number", arg);
+ }
+
+ static TemplateModelException newMethodArgMustBeBooleanException(String methodName, int argIdx, TemplateModel arg) {
+ return newMethodArgUnexpectedTypeException(methodName, argIdx, "boolean", arg);
+ }
+
+ static TemplateModelException newMethodArgMustBeExtendedHashException(
+ String methodName, int argIdx, TemplateModel arg) {
+ return newMethodArgUnexpectedTypeException(methodName, argIdx, "extended hash", arg);
+ }
+
+ static TemplateModelException newMethodArgMustBeSequenceException(
+ String methodName, int argIdx, TemplateModel arg) {
+ return newMethodArgUnexpectedTypeException(methodName, argIdx, "sequence", arg);
+ }
+
+ static TemplateModelException newMethodArgMustBeSequenceOrCollectionException(
+ String methodName, int argIdx, TemplateModel arg) {
+ return newMethodArgUnexpectedTypeException(methodName, argIdx, "sequence or collection", arg);
+ }
+
+ static TemplateModelException newMethodArgUnexpectedTypeException(
+ String methodName, int argIdx, String expectedType, TemplateModel arg) {
+ return new _TemplateModelException(
+ methodName, "(...) expects ", new _DelayedAOrAn(expectedType), " as argument #", Integer.valueOf(argIdx + 1),
+ ", but received ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(arg)), ".");
+ }
+
+ /**
+ * The type of the argument was good, but it's value wasn't.
+ */
+ static TemplateModelException newMethodArgInvalidValueException(
+ String methodName, int argIdx, Object... details) {
+ return new _TemplateModelException(
+ methodName, "(...) argument #", Integer.valueOf(argIdx + 1),
+ " had invalid value: ", details);
+ }
+
+ /**
+ * The type of the argument was good, but the values of two or more arguments are inconsistent with each other.
+ */
+ static TemplateModelException newMethodArgsInvalidValueException(
+ String methodName, Object... details) {
+ return new _TemplateModelException(methodName, "(...) arguments have invalid value: ", details);
+ }
+
+ static TemplateException newInstantiatingClassNotAllowedException(String className, Environment env) {
+ return new _MiscTemplateException(env,
+ "Instantiating ", className, " is not allowed in the template for security reasons.");
+ }
+
+ static TemplateModelException newCantFormatUnknownTypeDateException(
+ ASTExpression dateSourceExpr, UnknownDateTypeFormattingUnsupportedException cause) {
+ return new _TemplateModelException(cause, null, new _ErrorDescriptionBuilder(
+ MessageUtils.UNKNOWN_DATE_TO_STRING_ERROR_MESSAGE)
+ .blame(dateSourceExpr)
+ .tips(MessageUtils.UNKNOWN_DATE_TO_STRING_TIPS));
+ }
+
+ static TemplateException newCantFormatDateException(TemplateDateFormat format, ASTExpression dataSrcExp,
+ TemplateValueFormatException e, boolean useTempModelExc) {
+ _ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
+ "Failed to format date/time/dateTime with format ", new _DelayedJQuote(format.getDescription()), ": ",
+ e.getMessage())
+ .blame(dataSrcExp);
+ return useTempModelExc
+ ? new _TemplateModelException(e, null, desc)
+ : new _MiscTemplateException(e, null, desc);
+ }
+
+ static TemplateException newCantFormatNumberException(TemplateNumberFormat format, ASTExpression dataSrcExp,
+ TemplateValueFormatException e, boolean useTempModelExc) {
+ _ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
+ "Failed to format number with format ", new _DelayedJQuote(format.getDescription()), ": ",
+ e.getMessage())
+ .blame(dataSrcExp);
+ return useTempModelExc
+ ? new _TemplateModelException(e, null, desc)
+ : new _MiscTemplateException(e, null, desc);
+ }
+
+ /**
+ * @return "a" or "an" or "a(n)" (or "" for empty string) for an FTL type name
+ */
+ static String getAOrAn(String s) {
+ if (s == null) return null;
+ if (s.length() == 0) return "";
+
+ char fc = Character.toLowerCase(s.charAt(0));
+ if (fc == 'a' || fc == 'e' || fc == 'i') {
+ return "an";
+ } else if (fc == 'h') {
+ String ls = s.toLowerCase();
+ if (ls.startsWith("has") || ls.startsWith("hi")) {
+ return "a";
+ } else if (ls.startsWith("ht")) {
+ return "an";
+ } else {
+ return "a(n)";
+ }
+ } else if (fc == 'u' || fc == 'o') {
+ return "a(n)";
+ } else {
+ char sc = (s.length() > 1) ? s.charAt(1) : '\0';
+ if (fc == 'x' && !(sc == 'a' || sc == 'e' || sc == 'i' || sc == 'a' || sc == 'o' || sc == 'u')) {
+ return "an";
+ } else {
+ return "a";
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/MiscUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/MiscUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/MiscUtil.java
deleted file mode 100644
index 35d5943..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/MiscUtil.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Utilities that didn't fit elsewhere.
- */
-class MiscUtil {
-
- // Can't be instatiated
- private MiscUtil() { }
-
- static final String C_FALSE = "false";
- static final String C_TRUE = "true";
-
- /**
- * Returns the map entries in source code order of the ASTExpression values.
- */
- static List/*Map.Entry*/ sortMapOfExpressions(Map/*<?, ASTExpression>*/ map) {
- ArrayList res = new ArrayList(map.entrySet());
- Collections.sort(res,
- new Comparator() { // for sorting to source code order
- @Override
- public int compare(Object o1, Object o2) {
- Map.Entry ent1 = (Map.Entry) o1;
- ASTExpression exp1 = (ASTExpression) ent1.getValue();
-
- Map.Entry ent2 = (Map.Entry) o2;
- ASTExpression exp2 = (ASTExpression) ent2.getValue();
-
- int res = exp1.beginLine - exp2.beginLine;
- if (res != 0) return res;
- res = exp1.beginColumn - exp2.beginColumn;
- if (res != 0) return res;
-
- if (ent1 == ent2) return 0;
-
- // Should never reach this
- return ((String) ent1.getKey()).compareTo((String) ent1.getKey());
- }
-
- });
- return res;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/MutableParsingAndProcessingConfiguration.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/MutableParsingAndProcessingConfiguration.java b/freemarker-core/src/main/java/org/apache/freemarker/core/MutableParsingAndProcessingConfiguration.java
index 9339c62..0c845b7 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/MutableParsingAndProcessingConfiguration.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/MutableParsingAndProcessingConfiguration.java
@@ -28,7 +28,7 @@ import org.apache.freemarker.core.outputformat.impl.UndefinedOutputFormat;
import org.apache.freemarker.core.templateresolver.TemplateLoader;
import org.apache.freemarker.core.util._NullArgumentException;
import org.apache.freemarker.core.util._SortedArraySet;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.util._UnmodifiableCompositeSet;
public abstract class MutableParsingAndProcessingConfiguration<
@@ -92,7 +92,7 @@ public abstract class MutableParsingAndProcessingConfiguration<
value, OutputFormat.class, true, _SettingEvaluationEnvironment.getCurrent()));
}
} else if (WHITESPACE_STRIPPING_KEY.equals(name)) {
- setWhitespaceStripping(_StringUtil.getYesNo(value));
+ setWhitespaceStripping(_StringUtils.getYesNo(value));
} else if (AUTO_ESCAPING_POLICY_KEY.equals(name)) {
if ("enableIfDefault".equals(value)) {
setAutoEscapingPolicy(AutoEscapingPolicy.ENABLE_IF_DEFAULT);
@@ -110,7 +110,7 @@ public abstract class MutableParsingAndProcessingConfiguration<
if (value.equalsIgnoreCase(DEFAULT_VALUE)) {
unsetRecognizeStandardFileExtensions();
} else {
- setRecognizeStandardFileExtensions(_StringUtil.getYesNo(value));
+ setRecognizeStandardFileExtensions(_StringUtils.getYesNo(value));
}
} else if (TEMPLATE_LANGUAGE_KEY.equals(name)) {
if ("FTL".equals(value)) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/MutableProcessingConfiguration.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/MutableProcessingConfiguration.java b/freemarker-core/src/main/java/org/apache/freemarker/core/MutableProcessingConfiguration.java
index d119bbc..d1684d3 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/MutableProcessingConfiguration.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/MutableProcessingConfiguration.java
@@ -61,12 +61,12 @@ import org.apache.freemarker.core.templateresolver.impl.DefaultTemplateNameForma
import org.apache.freemarker.core.util.FTLUtil;
import org.apache.freemarker.core.util.GenericParseException;
import org.apache.freemarker.core.util.OptInTemplateClassResolver;
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._CollectionUtils;
import org.apache.freemarker.core.util._KeyValuePair;
import org.apache.freemarker.core.util._NullArgumentException;
import org.apache.freemarker.core.util._SortedArraySet;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory;
@@ -367,7 +367,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
if (customNumberFormats == this.customNumberFormats) {
return;
}
- _CollectionUtil.safeCastMap("customNumberFormats", customNumberFormats,
+ _CollectionUtils.safeCastMap("customNumberFormats", customNumberFormats,
String.class, false,
TemplateNumberFormatFactory.class, false);
validateFormatNames(customNumberFormats.keySet());
@@ -638,7 +638,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
if (customDateFormats == this.customDateFormats) {
return;
}
- _CollectionUtil.safeCastMap("customDateFormats", customDateFormats,
+ _CollectionUtils.safeCastMap("customDateFormats", customDateFormats,
String.class, false,
TemplateDateFormatFactory.class, false);
validateFormatNames(customDateFormats.keySet());
@@ -1150,7 +1150,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
if (autoImports == this.autoImports) {
return;
}
- _CollectionUtil.safeCastMap("autoImports", autoImports, String.class, false, String.class, false);
+ _CollectionUtils.safeCastMap("autoImports", autoImports, String.class, false, String.class, false);
this.autoImports = Collections.unmodifiableMap(new LinkedHashMap<>(autoImports));
} else {
this.autoImports = autoImports;
@@ -1209,7 +1209,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
if (autoIncludes == this.autoIncludes) {
return;
}
- _CollectionUtil.safeCastList("autoIncludes", autoIncludes, String.class, false);
+ _CollectionUtils.safeCastList("autoIncludes", autoIncludes, String.class, false);
Set<String> uniqueItems = new LinkedHashSet<>(autoIncludes.size() * 4 / 3, 1f);
for (String templateName : autoIncludes) {
if (!uniqueItems.add(templateName)) {
@@ -1653,7 +1653,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
if (JVM_DEFAULT_VALUE.equalsIgnoreCase(value)) {
setLocale(Locale.getDefault());
} else {
- setLocale(_StringUtil.deduceLocale(value));
+ setLocale(_StringUtils.deduceLocale(value));
}
} else if (NUMBER_FORMAT_KEY.equals(name)) {
setNumberFormat(value);
@@ -1752,11 +1752,11 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
} else if (URL_ESCAPING_CHARSET_KEY.equals(name)) {
setURLEscapingCharset(Charset.forName(value));
} else if (AUTO_FLUSH_KEY.equals(name)) {
- setAutoFlush(_StringUtil.getYesNo(value));
+ setAutoFlush(_StringUtils.getYesNo(value));
} else if (SHOW_ERROR_TIPS_KEY.equals(name)) {
- setShowErrorTips(_StringUtil.getYesNo(value));
+ setShowErrorTips(_StringUtils.getYesNo(value));
} else if (API_BUILTIN_ENABLED_KEY.equals(name)) {
- setAPIBuiltinEnabled(_StringUtil.getYesNo(value));
+ setAPIBuiltinEnabled(_StringUtils.getYesNo(value));
} else if (NEW_BUILTIN_CLASS_RESOLVER_KEY.equals(name)) {
if ("unrestricted".equals(value)) {
setNewBuiltinClassResolver(TemplateClassResolver.UNRESTRICTED);
@@ -1775,7 +1775,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
trustedTemplates = segmentValue;
} else {
throw new InvalidSettingValueException(name, value,
- "Unrecognized list segment key: " + _StringUtil.jQuote(segmentKey) +
+ "Unrecognized list segment key: " + _StringUtils.jQuote(segmentKey) +
". Supported keys are: \"" + ALLOWED_CLASSES + "\", \"" +
TRUSTED_TEMPLATES + "\"");
}
@@ -1796,9 +1796,9 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
+ "looks like class name");
}
} else if (LAZY_AUTO_IMPORTS_KEY.equals(name)) {
- setLazyAutoImports(value.equals(NULL_VALUE) ? null : Boolean.valueOf(_StringUtil.getYesNo(value)));
+ setLazyAutoImports(value.equals(NULL_VALUE) ? null : Boolean.valueOf(_StringUtils.getYesNo(value)));
} else if (LAZY_IMPORTS_KEY.equals(name)) {
- setLazyImports(_StringUtil.getYesNo(value));
+ setLazyImports(_StringUtils.getYesNo(value));
} else if (AUTO_INCLUDES_KEY.equals(name)) {
setAutoIncludes(parseAsList(value));
} else if (AUTO_IMPORTS_KEY.equals(name)) {
@@ -1834,8 +1834,8 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
for (Object value : values) {
if (!expectedClass.isInstance(value)) {
throw new IllegalArgumentException(somethingsSentenceStart + " must be instances of "
- + _ClassUtil.getShortClassName(expectedClass) + ", but one of them was a(n) "
- + _ClassUtil.getShortClassNameOfObject(value) + ".");
+ + _ClassUtils.getShortClassName(expectedClass) + ", but one of them was a(n) "
+ + _ClassUtils.getShortClassNameOfObject(value) + ".");
}
}
}
@@ -2017,7 +2017,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
// When there's no need for inheritance:
customSettingsModifiable = false; // Copy-on-write on next modification
- return _CollectionUtil.unmodifiableMap(customSettings);
+ return _CollectionUtils.unmodifiableMap(customSettings);
}
/**
@@ -2185,7 +2185,7 @@ public abstract class MutableProcessingConfiguration<SelfT extends MutableProces
"Unexpected end of text: expected \"as\"");
String s = fetchKeyword();
if (!s.equalsIgnoreCase("as")) throw new GenericParseException(
- "Expected \"as\", but found " + _StringUtil.jQuote(s));
+ "Expected \"as\", but found " + _StringUtils.jQuote(s));
c = skipWS();
if (c == ' ') throw new GenericParseException(
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/NonSequenceOrCollectionException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/NonSequenceOrCollectionException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/NonSequenceOrCollectionException.java
index 2836230..c229808 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/NonSequenceOrCollectionException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/NonSequenceOrCollectionException.java
@@ -23,7 +23,7 @@ import org.apache.freemarker.core.model.TemplateCollectionModel;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateSequenceModel;
import org.apache.freemarker.core.model.WrapperTemplateModel;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
/**
* Indicates that a {@link TemplateSequenceModel} or {@link TemplateCollectionModel} value was expected, but the value
@@ -53,7 +53,7 @@ public class NonSequenceOrCollectionException extends UnexpectedTypeException {
NonSequenceOrCollectionException(
ASTExpression blamed, TemplateModel model, Environment env)
throws InvalidReferenceException {
- this(blamed, model, _CollectionUtil.EMPTY_OBJECT_ARRAY, env);
+ this(blamed, model, _CollectionUtils.EMPTY_OBJECT_ARRAY, env);
}
NonSequenceOrCollectionException(
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ParseException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ParseException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ParseException.java
index 2b87cfe..9480562 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ParseException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ParseException.java
@@ -25,8 +25,8 @@ import java.util.Iterator;
import java.util.Set;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._SecurityUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._SecurityUtils;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Parsing-time exception in a template (as opposed to a runtime exception, a {@link TemplateException}). This usually
@@ -76,7 +76,7 @@ public class ParseException extends IOException implements FMParserConstants {
/**
* The end of line string for this machine.
*/
- protected String eol = _SecurityUtil.getSystemProperty("line.separator", "\n");
+ protected String eol = _SecurityUtils.getSystemProperty("line.separator", "\n");
private String templateSourceName;
private String templateLookupName;
@@ -287,7 +287,7 @@ public class ParseException extends IOException implements FMParserConstants {
String prefix;
if (!isInJBossToolsMode()) {
prefix = "Syntax error "
- + MessageUtil.formatLocationForSimpleParsingError(getTemplateSourceOrLookupName(), lineNumber,
+ + MessageUtils.formatLocationForSimpleParsingError(getTemplateSourceOrLookupName(), lineNumber,
columnNumber)
+ ":\n";
} else {
@@ -437,7 +437,7 @@ public class ParseException extends IOException implements FMParserConstants {
+ "Check if you have a valid #if-#elseIf-#else or #list-#else structure.";
} else if (kind == END_IF || kind == ELSE_IF) {
return "Unexpected directive, "
- + _StringUtil.jQuote(nextToken)
+ + _StringUtils.jQuote(nextToken)
+ ". Check if you have a valid #if-#elseIf-#else structure.";
}
return null;
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/RegexpHelper.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/RegexpHelper.java b/freemarker-core/src/main/java/org/apache/freemarker/core/RegexpHelper.java
index d564d31..37b5fd5 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/RegexpHelper.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/RegexpHelper.java
@@ -24,7 +24,7 @@ import java.util.regex.PatternSyntaxException;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.templateresolver.impl.MruCacheStorage;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -145,7 +145,7 @@ final class RegexpHelper {
// [FM3] Should be an error
RegexpHelper.logFlagWarning(
"Unrecognized regular expression flag: "
- + _StringUtil.jQuote(String.valueOf(c)) + ".");
+ + _StringUtils.jQuote(String.valueOf(c)) + ".");
}
} // switch
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/Template.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/Template.java b/freemarker-core/src/main/java/org/apache/freemarker/core/Template.java
index fde11d9..9384b9e 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/Template.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/Template.java
@@ -55,7 +55,7 @@ import org.apache.freemarker.core.templateresolver.TemplateLookupStrategy;
import org.apache.freemarker.core.templateresolver.impl.DefaultTemplateResolver;
import org.apache.freemarker.core.templateresolver.impl.FileTemplateLoader;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
import org.apache.freemarker.core.util._NullArgumentException;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory;
@@ -332,8 +332,8 @@ public class Template implements ProcessingConfiguration, CustomStateScope {
ltbReader.throwFailure();
_DebuggerService.registerTemplate(this);
- namespaceURIToPrefixLookup = _CollectionUtil.unmodifiableMap(namespaceURIToPrefixLookup);
- prefixToNamespaceURILookup = _CollectionUtil.unmodifiableMap(prefixToNamespaceURILookup);
+ namespaceURIToPrefixLookup = _CollectionUtils.unmodifiableMap(namespaceURIToPrefixLookup);
+ prefixToNamespaceURILookup = _CollectionUtils.unmodifiableMap(prefixToNamespaceURILookup);
finishConstruction();
}
@@ -343,8 +343,8 @@ public class Template implements ProcessingConfiguration, CustomStateScope {
* protected when construction is done.
*/
private void finishConstruction() {
- headerCustomSettings = _CollectionUtil.unmodifiableMap(headerCustomSettings);
- tcAndHeaderCustomSettings = _CollectionUtil.unmodifiableMap(tcAndHeaderCustomSettings);
+ headerCustomSettings = _CollectionUtils.unmodifiableMap(headerCustomSettings);
+ tcAndHeaderCustomSettings = _CollectionUtils.unmodifiableMap(tcAndHeaderCustomSettings);
writeProtected = true;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateBooleanFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateBooleanFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateBooleanFormat.java
index 240b81e..b2de905 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateBooleanFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateBooleanFormat.java
@@ -19,13 +19,15 @@
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.TemplateValueFormat;
// TODO Should be public and moved over to core.valueformat?
final class TemplateBooleanFormat extends TemplateValueFormat {
- static final String C_TRUE_FALSE = "true,false";
+ static final String C_FALSE = "false";
+ static final String C_TRUE = "true";
+ static final String C_TRUE_FALSE = C_TRUE + "," + C_FALSE;
static final TemplateBooleanFormat C_TRUE_FALSE_FORMAT = new TemplateBooleanFormat();
static TemplateBooleanFormat getInstance(String format) {
@@ -85,7 +87,7 @@ final class TemplateBooleanFormat extends TemplateValueFormat {
@Override
public String getDescription() {
- return _StringUtil.jQuote(formatString);
+ return _StringUtils.jQuote(formatString);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateClassResolver.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateClassResolver.java b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateClassResolver.java
index 415c66c..0e04b4f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateClassResolver.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateClassResolver.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
/**
* Used by built-ins and other template language features that get a class
@@ -34,7 +34,7 @@ import org.apache.freemarker.core.util._ClassUtil;
public interface TemplateClassResolver {
/**
- * Simply calls {@link _ClassUtil#forName(String)}.
+ * Simply calls {@link _ClassUtils#forName(String)}.
*/
TemplateClassResolver UNRESTRICTED = new TemplateClassResolver() {
@@ -42,7 +42,7 @@ public interface TemplateClassResolver {
public Class resolve(String className, Environment env, Template template)
throws TemplateException {
try {
- return _ClassUtil.forName(className);
+ return _ClassUtils.forName(className);
} catch (ClassNotFoundException e) {
throw new _MiscTemplateException(e, env);
}
@@ -58,7 +58,7 @@ public interface TemplateClassResolver {
@Override
public Class resolve(String className, Environment env, Template template)
throws TemplateException {
- throw MessageUtil.newInstantiatingClassNotAllowedException(className, env);
+ throw MessageUtils.newInstantiatingClassNotAllowedException(className, env);
}
};
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateConfiguration.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateConfiguration.java b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateConfiguration.java
index 3e77e2c..901c4f4 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateConfiguration.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateConfiguration.java
@@ -29,7 +29,7 @@ import java.util.TimeZone;
import org.apache.freemarker.core.arithmetic.ArithmeticEngine;
import org.apache.freemarker.core.outputformat.OutputFormat;
import org.apache.freemarker.core.util.CommonBuilder;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory;
@@ -779,13 +779,13 @@ public final class TemplateConfiguration implements ParsingAndProcessingConfigur
setBooleanFormat(tc.getBooleanFormat());
}
if (tc.isCustomDateFormatsSet()) {
- setCustomDateFormats(_CollectionUtil.mergeImmutableMaps(
+ setCustomDateFormats(_CollectionUtils.mergeImmutableMaps(
isCustomDateFormatsSet() ? getCustomDateFormats() : null, tc.getCustomDateFormats(), false),
true
);
}
if (tc.isCustomNumberFormatsSet()) {
- setCustomNumberFormats(_CollectionUtil.mergeImmutableMaps(
+ setCustomNumberFormats(_CollectionUtils.mergeImmutableMaps(
isCustomNumberFormatsSet() ? getCustomNumberFormats() : null, tc.getCustomNumberFormats(), false),
true);
}
@@ -856,21 +856,21 @@ public final class TemplateConfiguration implements ParsingAndProcessingConfigur
setLazyAutoImports(tc.getLazyAutoImports());
}
if (tc.isAutoImportsSet()) {
- setAutoImports(_CollectionUtil.mergeImmutableMaps(
+ setAutoImports(_CollectionUtils.mergeImmutableMaps(
isAutoImportsSet() ? getAutoImports() : null,
tc.isAutoImportsSet() ? tc.getAutoImports() : null,
true),
true);
}
if (tc.isAutoIncludesSet()) {
- setAutoIncludes(_CollectionUtil.mergeImmutableLists(
+ setAutoIncludes(_CollectionUtils.mergeImmutableLists(
isAutoIncludesSet() ? getAutoIncludes() : null,
tc.isAutoIncludesSet() ? tc.getAutoIncludes() : null,
true),
true);
}
- setCustomSettingsMap(_CollectionUtil.mergeImmutableMaps(
+ setCustomSettingsMap(_CollectionUtils.mergeImmutableMaps(
getCustomSettings(false),
tc.getCustomSettings(false),
false));
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateElementArrayBuilder.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateElementArrayBuilder.java b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateElementArrayBuilder.java
index 3b8f40f..4bc9a4f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateElementArrayBuilder.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateElementArrayBuilder.java
@@ -18,7 +18,7 @@
*/
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
/**
* Holds an buffer (array) of {@link ASTElement}-s with the count of the utilized items in it. The un-utilized tail
@@ -70,7 +70,7 @@ class TemplateElements {
*/
ASTElement asSingleElement() {
if (count == 0) {
- return new ASTStaticText(_CollectionUtil.EMPTY_CHAR_ARRAY, false);
+ return new ASTStaticText(_CollectionUtils.EMPTY_CHAR_ARRAY, false);
} else {
ASTElement first = buffer[0];
if (count == 1) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateException.java
index fb54f82..e7f387f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateException.java
@@ -27,7 +27,7 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
/**
* Runtime exception in a template (as opposed to a parsing-time exception: {@link ParseException}).
@@ -170,10 +170,10 @@ public class TemplateException extends Exception {
String stackTopFew = getFTLInstructionStackTopFew();
if (stackTopFew != null) {
message = messageWithoutStackTop + "\n\n"
- + MessageUtil.ERROR_MESSAGE_HR + "\n"
+ + MessageUtils.ERROR_MESSAGE_HR + "\n"
+ FTL_INSTRUCTION_STACK_TRACE_TITLE + "\n"
+ stackTopFew
- + MessageUtil.ERROR_MESSAGE_HR;
+ + MessageUtils.ERROR_MESSAGE_HR;
messageWithoutStackTop = message.substring(0, messageWithoutStackTop.length()); // to reuse backing char[]
} else {
message = messageWithoutStackTop;
@@ -339,10 +339,10 @@ public class TemplateException extends Exception {
if (stackTrace != null) {
out.println(getMessageWithoutStackTop()); // Not getMessage()!
out.println();
- out.println(MessageUtil.ERROR_MESSAGE_HR);
+ out.println(MessageUtils.ERROR_MESSAGE_HR);
out.println(FTL_INSTRUCTION_STACK_TRACE_TITLE);
out.print(stackTrace);
- out.println(MessageUtil.ERROR_MESSAGE_HR);
+ out.println(MessageUtils.ERROR_MESSAGE_HR);
} else {
ftlStackTrace = false;
javaStackTrace = true;
@@ -353,7 +353,7 @@ public class TemplateException extends Exception {
if (ftlStackTrace) { // We are after an FTL stack trace
out.println();
out.println("Java stack trace (for programmers):");
- out.println(MessageUtil.ERROR_MESSAGE_HR);
+ out.println(MessageUtils.ERROR_MESSAGE_HR);
synchronized (lock) {
if (messageWasAlreadyPrintedForThisTrace == null) {
messageWasAlreadyPrintedForThisTrace = new ThreadLocal();
@@ -376,8 +376,8 @@ public class TemplateException extends Exception {
if (causeCause == null) {
try {
// Reflection is used to prevent dependency on Servlet classes.
- Method m = getCause().getClass().getMethod("getRootCause", _CollectionUtil.EMPTY_CLASS_ARRAY);
- Throwable rootCause = (Throwable) m.invoke(getCause(), _CollectionUtil.EMPTY_OBJECT_ARRAY);
+ Method m = getCause().getClass().getMethod("getRootCause", _CollectionUtils.EMPTY_CLASS_ARRAY);
+ Throwable rootCause = (Throwable) m.invoke(getCause(), _CollectionUtils.EMPTY_OBJECT_ARRAY);
if (rootCause != null) {
out.println("ServletException root cause: ");
out.printStandardStackTrace(rootCause);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateExceptionHandler.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateExceptionHandler.java b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateExceptionHandler.java
index 477cbf6..1269053 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateExceptionHandler.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateExceptionHandler.java
@@ -23,7 +23,7 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Used for the {@code templateExceptionHandler} configuration setting;
@@ -134,7 +134,7 @@ public interface TemplateExceptionHandler {
te.printStackTrace(stackPW, false, true, true);
stackPW.close();
pw.println();
- pw.println(_StringUtil.XMLEncNQG(stackTraceSW.toString()));
+ pw.println(_StringUtils.XMLEncNQG(stackTraceSW.toString()));
pw.println("</pre></div></html>");
pw.flush(); // To commit the HTTP response
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateLanguage.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateLanguage.java b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateLanguage.java
index 205fa8c..02ccb47 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateLanguage.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/TemplateLanguage.java
@@ -24,7 +24,7 @@ import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents a template language. Currently this class is not mature, so it can't be implemented outside FreeMarker,
@@ -105,7 +105,7 @@ public abstract class TemplateLanguage {
@Override
public final String toString() {
- return "TemplateLanguage(" + _StringUtil.jQuote(name) + ")";
+ return "TemplateLanguage(" + _StringUtils.jQuote(name) + ")";
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/Version.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/Version.java b/freemarker-core/src/main/java/org/apache/freemarker/core/Version.java
index 3a542d1..da7e1fc 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/Version.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/Version.java
@@ -22,7 +22,7 @@ package org.apache.freemarker.core;
import java.io.Serializable;
import java.util.Date;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Represents a version number plus the further qualifiers and build info. This is
@@ -71,14 +71,14 @@ public final class Version implements Serializable {
} else {
if (i == 0) {
throw new IllegalArgumentException(
- "The version number string " + _StringUtil.jQuote(stringValue)
+ "The version number string " + _StringUtils.jQuote(stringValue)
+ " doesn't start with a number.");
}
if (c == '.') {
char nextC = i + 1 >= stringValue.length() ? 0 : stringValue.charAt(i + 1);
if (nextC == '.') {
throw new IllegalArgumentException(
- "The version number string " + _StringUtil.jQuote(stringValue)
+ "The version number string " + _StringUtils.jQuote(stringValue)
+ " contains multiple dots after a number.");
}
if (partIdx == 2 || !isNumber(nextC)) {
@@ -100,7 +100,7 @@ public final class Version implements Serializable {
extraInfoTmp = extraInfoTmp.substring(1);
if (extraInfoTmp.length() == 0) {
throw new IllegalArgumentException(
- "The version number string " + _StringUtil.jQuote(stringValue)
+ "The version number string " + _StringUtils.jQuote(stringValue)
+ " has an extra info section opened with \"" + firstChar + "\", but it's empty.");
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_CallableUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_CallableUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_CallableUtils.java
index b1e02ab..81a5aa0 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_CallableUtils.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_CallableUtils.java
@@ -36,7 +36,7 @@ import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.TemplateSequenceModel;
import org.apache.freemarker.core.util.FTLUtil;
import org.apache.freemarker.core.util.StringToIndexMap;
-import org.apache.freemarker.core.util._CollectionUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
/**
* For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
@@ -161,7 +161,7 @@ public final class _CallableUtils {
TemplateModel argValue, String argName, int argIndex,
boolean optional) throws TemplateException {
if (argValue instanceof TemplateScalarModel) {
- return _EvalUtil.modelToString((TemplateScalarModel) argValue, null, null);
+ return _EvalUtils.modelToString((TemplateScalarModel) argValue, null, null);
}
if (argValue == null) {
if (optional) {
@@ -255,7 +255,7 @@ public final class _CallableUtils {
(!validPredefNames.isEmpty()
? new Object[] { " The supported parameter names are:\n",
new _DelayedJQuotedListing(validPredefNames)}
- : _CollectionUtil.EMPTY_OBJECT_ARRAY)}
+ : _CollectionUtils.EMPTY_OBJECT_ARRAY)}
: "")
);
if (callableValue instanceof Environment.TemplateLanguageDirective
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedAOrAn.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedAOrAn.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedAOrAn.java
index 630fa26..1c5bc09 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedAOrAn.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedAOrAn.java
@@ -29,7 +29,7 @@ public class _DelayedAOrAn extends _DelayedConversionToString {
@Override
protected String doConversion(Object obj) {
String s = obj.toString();
- return MessageUtil.getAOrAn(s) + " " + s;
+ return MessageUtils.getAOrAn(s) + " " + s;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuote.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuote.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuote.java
index 4caf71b..0d04574 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuote.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuote.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/** Don't use this; used internally by FreeMarker, might changes without notice. */
public class _DelayedJQuote extends _DelayedConversionToString {
@@ -30,7 +30,7 @@ public class _DelayedJQuote extends _DelayedConversionToString {
@Override
protected String doConversion(Object obj) {
- return _StringUtil.jQuote(_ErrorDescriptionBuilder.toString(obj));
+ return _StringUtils.jQuote(_ErrorDescriptionBuilder.toString(obj));
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuotedListing.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuotedListing.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuotedListing.java
index e809a92..d251281 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuotedListing.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedJQuotedListing.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core;
import java.util.Collection;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/** Don't use this; used internally by FreeMarker, might changes without notice. */
public class _DelayedJQuotedListing extends _DelayedConversionToString {
@@ -37,7 +37,7 @@ public class _DelayedJQuotedListing extends _DelayedConversionToString {
if (sb.length() != 0) {
sb.append(", ");
}
- sb.append(_StringUtil.jQuote(element));
+ sb.append(_StringUtils.jQuote(element));
}
return sb.toString();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedShortClassName.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedShortClassName.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedShortClassName.java
index d9769b9..9a141c2 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedShortClassName.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_DelayedShortClassName.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
public class _DelayedShortClassName extends _DelayedConversionToString {
@@ -29,7 +29,7 @@ public class _DelayedShortClassName extends _DelayedConversionToString {
@Override
protected String doConversion(Object obj) {
- return _ClassUtil.getShortClassName((Class) obj, true);
+ return _ClassUtils.getShortClassName((Class) obj, true);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_ErrorDescriptionBuilder.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_ErrorDescriptionBuilder.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_ErrorDescriptionBuilder.java
index 13cadcd..48a48fc 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_ErrorDescriptionBuilder.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_ErrorDescriptionBuilder.java
@@ -23,9 +23,9 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
-import org.apache.freemarker.core.model.impl._MethodUtil;
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.model.impl._MethodUtils;
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -150,7 +150,7 @@ public class _ErrorDescriptionBuilder {
sb.append("\n\n");
for (int i = 0; i < allTips.length; i++) {
if (i != 0) sb.append('\n');
- sb.append(MessageUtil.ERROR_MESSAGE_HR).append('\n');
+ sb.append(MessageUtils.ERROR_MESSAGE_HR).append('\n');
sb.append("Tip: ");
Object tip = allTips[i];
if (!(tip instanceof Object[])) {
@@ -159,7 +159,7 @@ public class _ErrorDescriptionBuilder {
appendParts(sb, (Object[]) tip);
}
}
- sb.append('\n').append(MessageUtil.ERROR_MESSAGE_HR);
+ sb.append('\n').append(MessageUtils.ERROR_MESSAGE_HR);
}
}
@@ -262,19 +262,19 @@ public class _ErrorDescriptionBuilder {
if (partObj == null) {
return null;
} else if (partObj instanceof Class) {
- partStr = _ClassUtil.getShortClassName((Class) partObj);
+ partStr = _ClassUtils.getShortClassName((Class) partObj);
} else if (partObj instanceof Method || partObj instanceof Constructor) {
- partStr = _MethodUtil.toString((Member) partObj);
+ partStr = _MethodUtils.toString((Member) partObj);
} else {
- partStr = suppressToStringException ? _StringUtil.tryToString(partObj) : partObj.toString();
+ partStr = suppressToStringException ? _StringUtils.tryToString(partObj) : partObj.toString();
}
return partStr;
}
private String[] splitToLines(String s) {
- s = _StringUtil.replace(s, "\r\n", "\n");
- s = _StringUtil.replace(s, "\r", "\n");
- return _StringUtil.split(s, '\n');
+ s = _StringUtils.replace(s, "\r\n", "\n");
+ s = _StringUtils.replace(s, "\r", "\n");
+ return _StringUtils.split(s, '\n');
}
/**
[16/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilTest.java
deleted file mode 100644
index 37e4726..0000000
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilTest.java
+++ /dev/null
@@ -1,585 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.model.impl;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("boxing")
-public class OverloadedNumberUtilTest extends TestCase {
-
- public OverloadedNumberUtilTest(String name) {
- super(name);
- }
-
- public void testIntegerCoercions() {
- cipEqu(Byte.valueOf(Byte.MAX_VALUE));
- cipEqu(Byte.valueOf((byte) 0));
- cipEqu(Byte.valueOf(Byte.MIN_VALUE));
-
- cipEqu(Short.valueOf(Byte.MAX_VALUE),
- new OverloadedNumberUtil.ShortOrByte((short) Byte.MAX_VALUE, Byte.MAX_VALUE));
- cipEqu(Short.valueOf((short) 0),
- new OverloadedNumberUtil.ShortOrByte((short) 0, (byte) 0));
- cipEqu(Short.valueOf(Byte.MIN_VALUE),
- new OverloadedNumberUtil.ShortOrByte((short) Byte.MIN_VALUE, Byte.MIN_VALUE));
-
- cipEqu(Short.valueOf((short) (Byte.MAX_VALUE + 1)));
- cipEqu(Short.valueOf((short) (Byte.MIN_VALUE - 1)));
- cipEqu(Short.valueOf(Short.MAX_VALUE));
- cipEqu(Short.valueOf(Short.MIN_VALUE));
-
- cipEqu(Integer.valueOf(Byte.MAX_VALUE),
- new OverloadedNumberUtil.IntegerOrByte((int) Byte.MAX_VALUE, Byte.MAX_VALUE));
- cipEqu(Integer.valueOf(0),
- new OverloadedNumberUtil.IntegerOrByte(0, (byte) 0));
- cipEqu(Integer.valueOf(Byte.MIN_VALUE),
- new OverloadedNumberUtil.IntegerOrByte((int) Byte.MIN_VALUE, Byte.MIN_VALUE));
-
- cipEqu(Integer.valueOf(Byte.MAX_VALUE + 1),
- new OverloadedNumberUtil.IntegerOrShort(Byte.MAX_VALUE + 1, (short) (Byte.MAX_VALUE + 1)));
- cipEqu(Integer.valueOf(Byte.MIN_VALUE - 1),
- new OverloadedNumberUtil.IntegerOrShort(Byte.MIN_VALUE - 1, (short) (Byte.MIN_VALUE - 1)));
- cipEqu(Integer.valueOf(Short.MAX_VALUE),
- new OverloadedNumberUtil.IntegerOrShort((int) Short.MAX_VALUE, Short.MAX_VALUE));
- cipEqu(Integer.valueOf(Short.MIN_VALUE),
- new OverloadedNumberUtil.IntegerOrShort((int) Short.MIN_VALUE, Short.MIN_VALUE));
-
- cipEqu(Integer.valueOf(Short.MAX_VALUE + 1));
- cipEqu(Integer.valueOf(Short.MIN_VALUE - 1));
- cipEqu(Integer.valueOf(Integer.MAX_VALUE));
- cipEqu(Integer.valueOf(Integer.MIN_VALUE));
-
- cipEqu(Long.valueOf(Byte.MAX_VALUE),
- new OverloadedNumberUtil.LongOrByte((long) Byte.MAX_VALUE, Byte.MAX_VALUE));
- cipEqu(Long.valueOf(0),
- new OverloadedNumberUtil.LongOrByte((long) 0, (byte) 0));
- cipEqu(Long.valueOf(Byte.MIN_VALUE),
- new OverloadedNumberUtil.LongOrByte((long) Byte.MIN_VALUE, Byte.MIN_VALUE));
-
- cipEqu(Long.valueOf(Byte.MAX_VALUE + 1),
- new OverloadedNumberUtil.LongOrShort((long) (Byte.MAX_VALUE + 1), (short) (Byte.MAX_VALUE + 1)));
- cipEqu(Long.valueOf(Byte.MIN_VALUE - 1),
- new OverloadedNumberUtil.LongOrShort((long) (Byte.MIN_VALUE - 1), (short) (Byte.MIN_VALUE - 1)));
- cipEqu(Long.valueOf(Short.MAX_VALUE),
- new OverloadedNumberUtil.LongOrShort((long) Short.MAX_VALUE, Short.MAX_VALUE));
- cipEqu(Long.valueOf(Short.MIN_VALUE),
- new OverloadedNumberUtil.LongOrShort((long) Short.MIN_VALUE, Short.MIN_VALUE));
-
- cipEqu(Long.valueOf(Short.MAX_VALUE + 1),
- new OverloadedNumberUtil.LongOrInteger((long) Short.MAX_VALUE + 1, Short.MAX_VALUE + 1));
- cipEqu(Long.valueOf(Short.MIN_VALUE - 1),
- new OverloadedNumberUtil.LongOrInteger((long) Short.MIN_VALUE - 1, Short.MIN_VALUE - 1));
- cipEqu(Long.valueOf(Integer.MAX_VALUE),
- new OverloadedNumberUtil.LongOrInteger((long) Integer.MAX_VALUE, Integer.MAX_VALUE));
- cipEqu(Long.valueOf(Integer.MIN_VALUE),
- new OverloadedNumberUtil.LongOrInteger((long) Integer.MIN_VALUE, Integer.MIN_VALUE));
-
- cipEqu(Long.valueOf(Integer.MAX_VALUE + 1L));
- cipEqu(Long.valueOf(Integer.MIN_VALUE - 1L));
- cipEqu(Long.valueOf(Long.MAX_VALUE));
- cipEqu(Long.valueOf(Long.MIN_VALUE));
- }
-
- public void testIntegerNoCoercions() {
- cipEqu(Integer.valueOf(Byte.MAX_VALUE), Integer.valueOf(Byte.MAX_VALUE), 0);
- cipEqu(Integer.valueOf(0), Integer.valueOf(0), 0);
- cipEqu(Integer.valueOf(Byte.MIN_VALUE), Integer.valueOf(Byte.MIN_VALUE), 0);
- }
-
- public void testIntegerLimitedCoercions() {
- cipEqu(Integer.valueOf(Byte.MAX_VALUE), Integer.valueOf(Byte.MAX_VALUE), TypeFlags.INTEGER);
- cipEqu(Integer.valueOf(0), Integer.valueOf(0), TypeFlags.INTEGER);
- cipEqu(Integer.valueOf(Byte.MIN_VALUE), Integer.valueOf(Byte.MIN_VALUE), TypeFlags.INTEGER);
-
- cipEqu(Long.valueOf(Integer.MAX_VALUE + 1L), Long.valueOf(Integer.MAX_VALUE + 1L), TypeFlags.INTEGER);
-
- for (int n = -1; n < 2; n++) {
- final Long longN = Long.valueOf(n);
- cipEqu(longN, new OverloadedNumberUtil.LongOrInteger(longN, n), TypeFlags.INTEGER);
- cipEqu(longN, new OverloadedNumberUtil.LongOrShort(longN, (short) n), TypeFlags.SHORT);
- cipEqu(longN, new OverloadedNumberUtil.LongOrByte(longN, (byte) n), TypeFlags.BYTE);
- cipEqu(longN, new OverloadedNumberUtil.LongOrShort(longN, (short) n),
- TypeFlags.SHORT | TypeFlags.INTEGER);
- }
- }
-
- public void testBigDecimalCoercions() {
- cipEqu(new BigDecimal(123), new OverloadedNumberUtil.IntegerBigDecimal(new BigDecimal(123)));
- cipEqu(new BigDecimal(123), new OverloadedNumberUtil.IntegerBigDecimal(new BigDecimal(123)),
- TypeFlags.DOUBLE | TypeFlags.INTEGER);
- cipEqu(new BigDecimal(123), TypeFlags.INTEGER);
- cipEqu(new BigDecimal(123), TypeFlags.INTEGER | TypeFlags.LONG);
- cipEqu(new BigDecimal(123), TypeFlags.DOUBLE);
- cipEqu(new BigDecimal(123), TypeFlags.DOUBLE | TypeFlags.FLOAT);
-
- cipEqu(new BigDecimal(123.5));
- // Not wasting time with check if it's a whole number if we only have integer-only or non-integer-only targets:
- cipEqu(new BigDecimal(123.5), TypeFlags.INTEGER | TypeFlags.LONG);
- cipEqu(new BigDecimal(123.5), TypeFlags.DOUBLE | TypeFlags.FLOAT);
-
- cipEqu(new BigDecimal("0.01"));
- cipEqu(new BigDecimal("-0.01"));
- cipEqu(BigDecimal.ZERO, new OverloadedNumberUtil.IntegerBigDecimal(BigDecimal.ZERO));
- }
-
- public void testUnknownNumberCoercion() {
- cipEqu(new RationalNumber(2, 3));
- }
-
- @SuppressWarnings("boxing")
- public void testDoubleCoercion() {
- cipEqu(Double.valueOf(1.5), new OverloadedNumberUtil.DoubleOrFloat(1.5));
- cipEqu(Double.valueOf(-0.125), new OverloadedNumberUtil.DoubleOrFloat(-0.125));
- cipEqu(Double.valueOf(Float.MAX_VALUE), new OverloadedNumberUtil.DoubleOrFloat((double) Float.MAX_VALUE));
- cipEqu(Double.valueOf(-Float.MAX_VALUE), new OverloadedNumberUtil.DoubleOrFloat((double) -Float.MAX_VALUE));
- cipEqu(Double.valueOf(Float.MAX_VALUE * 10.0));
- cipEqu(Double.valueOf(-Float.MAX_VALUE * 10.0));
-
- cipEqu(Double.valueOf(0), new OverloadedNumberUtil.DoubleOrByte(0.0, (byte) 0));
- cipEqu(Double.valueOf(Byte.MAX_VALUE), new OverloadedNumberUtil.DoubleOrByte((double) Byte.MAX_VALUE, Byte.MAX_VALUE));
- cipEqu(Double.valueOf(Byte.MIN_VALUE), new OverloadedNumberUtil.DoubleOrByte((double) Byte.MIN_VALUE, Byte.MIN_VALUE));
-
- cipEqu(Double.valueOf(Byte.MAX_VALUE + 1), new OverloadedNumberUtil.DoubleOrShort((double)
- (Byte.MAX_VALUE + 1), (short) (Byte.MAX_VALUE + 1)));
- cipEqu(Double.valueOf(Byte.MIN_VALUE - 1), new OverloadedNumberUtil.DoubleOrShort((double)
- (Byte.MIN_VALUE - 1), (short) (Byte.MIN_VALUE - 1)));
-
- cipEqu(Double.valueOf(Short.MAX_VALUE + 1),
- new OverloadedNumberUtil.DoubleOrIntegerOrFloat((double) Short.MAX_VALUE + 1, Short.MAX_VALUE + 1));
- cipEqu(Double.valueOf(Short.MIN_VALUE - 1),
- new OverloadedNumberUtil.DoubleOrIntegerOrFloat((double) Short.MIN_VALUE - 1, Short.MIN_VALUE - 1));
- cipEqu(Double.valueOf(16777216), new OverloadedNumberUtil.DoubleOrIntegerOrFloat(16777216.0, 16777216));
- cipEqu(Double.valueOf(-16777216), new OverloadedNumberUtil.DoubleOrIntegerOrFloat(-16777216.0, -16777216));
-
- cipEqu(Double.valueOf(Integer.MAX_VALUE),
- new OverloadedNumberUtil.DoubleOrInteger((double) Integer.MAX_VALUE, Integer.MAX_VALUE));
- cipEqu(Double.valueOf(Integer.MIN_VALUE),
- new OverloadedNumberUtil.DoubleOrInteger((double) Integer.MIN_VALUE, Integer.MIN_VALUE));
-
- cipEqu(Double.valueOf(Integer.MAX_VALUE + 1L),
- new OverloadedNumberUtil.DoubleOrLong(Double.valueOf(Integer.MAX_VALUE + 1L), Integer.MAX_VALUE + 1L));
- cipEqu(Double.valueOf(Integer.MIN_VALUE - 1L),
- new OverloadedNumberUtil.DoubleOrLong(Double.valueOf(Integer.MIN_VALUE - 1L), Integer.MIN_VALUE - 1L));
- cipEqu(Double.valueOf(Long.MAX_VALUE),
- new OverloadedNumberUtil.DoubleOrFloat((double) Long.MAX_VALUE));
- cipEqu(Double.valueOf(Long.MIN_VALUE),
- new OverloadedNumberUtil.DoubleOrFloat((double) Long.MIN_VALUE));
-
- // When only certain target types are present:
- cipEqu(Double.valueOf(5), new OverloadedNumberUtil.DoubleOrByte(5.0, (byte) 5), TypeFlags.BYTE);
- cipEqu(Double.valueOf(5), new OverloadedNumberUtil.DoubleOrByte(5.0, (byte) 5), TypeFlags.BYTE | TypeFlags.SHORT);
- cipEqu(Double.valueOf(-129), TypeFlags.BYTE);
- cipEqu(Double.valueOf(5), new OverloadedNumberUtil.DoubleOrShort(5.0, (short) 5), TypeFlags.SHORT);
- cipEqu(Double.valueOf(5), new OverloadedNumberUtil.DoubleOrInteger(5.0, 5), TypeFlags.INTEGER);
- cipEqu(Double.valueOf(5), new OverloadedNumberUtil.DoubleOrLong(5.0, 5), TypeFlags.LONG);
- cipEqu(Double.valueOf(5), new OverloadedNumberUtil.DoubleOrFloat(5.0), TypeFlags.FLOAT);
- cipEqu(Double.valueOf(5), Double.valueOf(5), TypeFlags.DOUBLE);
- cipEqu(Double.valueOf(5), new OverloadedNumberUtil.DoubleOrFloat(5.0),
- TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(Double.valueOf(5.9), new OverloadedNumberUtil.DoubleOrFloat(5.9),
- TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(Double.valueOf(5.9),
- TypeFlags.DOUBLE | TypeFlags.INTEGER);
- cipEqu(Double.valueOf(5.9), new OverloadedNumberUtil.DoubleOrFloat(5.9),
- TypeFlags.FLOAT | TypeFlags.INTEGER);
- cipEqu(Double.valueOf(5.9), TypeFlags.INTEGER);
- cipEqu(Double.valueOf(Long.MAX_VALUE),
- new OverloadedNumberUtil.DoubleOrFloat((double) Long.MAX_VALUE),
- TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(Double.valueOf(Long.MAX_VALUE),
- TypeFlags.DOUBLE | TypeFlags.LONG);
- cipEqu(Double.valueOf(Long.MIN_VALUE),
- new OverloadedNumberUtil.DoubleOrFloat((double) Long.MIN_VALUE),
- TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(Double.valueOf(Float.MAX_VALUE * 10),
- TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(Double.valueOf(-Float.MAX_VALUE * 10),
- TypeFlags.DOUBLE | TypeFlags.FLOAT);
-
- // Rounded values:
- cipEqu(Double.valueOf(0.0000009),
- new OverloadedNumberUtil.DoubleOrByte(0.0000009, (byte) 0));
- cipEqu(Double.valueOf(-0.0000009),
- new OverloadedNumberUtil.DoubleOrByte(-0.0000009, (byte) 0));
- cipEqu(Double.valueOf(0.9999991),
- new OverloadedNumberUtil.DoubleOrByte(0.9999991, (byte) 1));
- cipEqu(Double.valueOf(-0.9999991),
- new OverloadedNumberUtil.DoubleOrByte(-0.9999991, (byte) -1));
- cipEqu(Double.valueOf(0.0000009),
- new OverloadedNumberUtil.DoubleOrShort(0.0000009, (short) 0),
- TypeFlags.SHORT | TypeFlags.DOUBLE);
- cipEqu(Double.valueOf(0.0000009), new OverloadedNumberUtil.DoubleOrInteger(0.0000009, 0),
- TypeFlags.INTEGER | TypeFlags.DOUBLE);
- cipEqu(Double.valueOf(0.0000009), new OverloadedNumberUtil.DoubleOrLong(0.0000009, 0),
- TypeFlags.LONG | TypeFlags.DOUBLE);
- cipEqu(Double.valueOf(0.0000009),
- new OverloadedNumberUtil.DoubleOrByte(0.0000009, (byte) 0), TypeFlags.BYTE);
- cipEqu(Double.valueOf(0.0000009),
- new OverloadedNumberUtil.DoubleOrShort(0.0000009, (short) 0), TypeFlags.SHORT);
- cipEqu(Double.valueOf(0.0000009),
- new OverloadedNumberUtil.DoubleOrInteger(0.0000009, 0), TypeFlags.INTEGER);
- cipEqu(Double.valueOf(0.0000009),
- new OverloadedNumberUtil.DoubleOrLong(0.0000009, 0L), TypeFlags.LONG);
- cipEqu(Double.valueOf(0.9999999),
- new OverloadedNumberUtil.DoubleOrInteger(0.9999999, 1), TypeFlags.INTEGER);
- cipEqu(Double.valueOf(Byte.MAX_VALUE + 0.9e-6),
- new OverloadedNumberUtil.DoubleOrByte(Byte.MAX_VALUE + 0.9e-6, Byte.MAX_VALUE));
- cipEqu(Double.valueOf(Byte.MIN_VALUE - 0.9e-6),
- new OverloadedNumberUtil.DoubleOrByte(Byte.MIN_VALUE - 0.9e-6, Byte.MIN_VALUE));
- cipEqu(Double.valueOf(Byte.MAX_VALUE + 1.1e-6),
- new OverloadedNumberUtil.DoubleOrFloat(Byte.MAX_VALUE + 1.1e-6));
- cipEqu(Double.valueOf(Byte.MIN_VALUE - 1.1e-6),
- new OverloadedNumberUtil.DoubleOrFloat(Byte.MIN_VALUE - 1.1e-6));
- cipEqu(Double.valueOf(Byte.MAX_VALUE + 0.9999991),
- new OverloadedNumberUtil.DoubleOrShort(
- Byte.MAX_VALUE + 0.9999991, (short) (Byte.MAX_VALUE + 1)));
- cipEqu(Double.valueOf(Byte.MIN_VALUE - 0.9999991),
- new OverloadedNumberUtil.DoubleOrShort(
- Byte.MIN_VALUE - 0.9999991, (short) (Byte.MIN_VALUE - 1)));
-
- cipEqu(Double.valueOf(Byte.MAX_VALUE + 1), new OverloadedNumberUtil.DoubleOrShort((double)
- (Byte.MAX_VALUE + 1), (short) (Byte.MAX_VALUE + 1)));
- cipEqu(Double.valueOf(Byte.MIN_VALUE - 1), new OverloadedNumberUtil.DoubleOrShort((double)
- (Byte.MIN_VALUE - 1), (short) (Byte.MIN_VALUE - 1)));
-
- cipEqu(Short.MAX_VALUE + 0.9999991,
- new OverloadedNumberUtil.DoubleOrIntegerOrFloat(Short.MAX_VALUE + 0.9999991, Short.MAX_VALUE + 1));
- cipEqu(Short.MIN_VALUE - 0.9999991,
- new OverloadedNumberUtil.DoubleOrIntegerOrFloat(Short.MIN_VALUE - 0.9999991, Short.MIN_VALUE - 1));
- cipEqu(16777216 + 0.9e-6,
- new OverloadedNumberUtil.DoubleOrIntegerOrFloat(16777216 + 0.9e-6, 16777216));
- cipEqu(-16777216 - 0.9e-6,
- new OverloadedNumberUtil.DoubleOrIntegerOrFloat(-16777216 - 0.9e-6, -16777216));
-
- cipEqu(Integer.MAX_VALUE + 0.9e-6,
- new OverloadedNumberUtil.DoubleOrInteger(Integer.MAX_VALUE + 0.9e-6, Integer.MAX_VALUE));
- cipEqu(Integer.MIN_VALUE - 0.9e-6,
- new OverloadedNumberUtil.DoubleOrInteger(Integer.MIN_VALUE - 0.9e-6, Integer.MIN_VALUE));
-
- cipEqu(Integer.MAX_VALUE + 1L + 0.9e-6,
- new OverloadedNumberUtil.DoubleOrFloat(Integer.MAX_VALUE + 1L + 0.9e-6));
- cipEqu(Integer.MIN_VALUE - 1L - 0.9e-6,
- new OverloadedNumberUtil.DoubleOrFloat(Integer.MIN_VALUE - 1L - 0.9e-6));
- cipEqu(Long.MAX_VALUE + 0.9e-6,
- new OverloadedNumberUtil.DoubleOrFloat(Long.MAX_VALUE + 0.9e-6));
- cipEqu(Long.MIN_VALUE - 0.9e-6,
- new OverloadedNumberUtil.DoubleOrFloat(Long.MIN_VALUE - 0.9e-6));
- }
-
- @SuppressWarnings("boxing")
- public void testFloatCoercion() {
- cipEqu(1.00002f);
- cipEqu(-1.00002f);
- cipEqu(1.999989f);
- cipEqu(-1.999989f);
- cipEqu(16777218f);
- cipEqu(-16777218f);
-
- cipEqu(1f, new OverloadedNumberUtil.FloatOrByte(1f, (byte) 1));
- cipEqu(-1f, new OverloadedNumberUtil.FloatOrByte(-1f, (byte) -1));
- cipEqu(1.000009f, new OverloadedNumberUtil.FloatOrByte(1.000009f, (byte) 1));
- cipEqu(-1.000009f, new OverloadedNumberUtil.FloatOrByte(-1.000009f, (byte) -1));
- cipEqu(1.999991f, new OverloadedNumberUtil.FloatOrByte(1.999991f, (byte) 2));
- cipEqu(-1.999991f, new OverloadedNumberUtil.FloatOrByte(-1.999991f, (byte) -2));
-
- cipEqu(1000f, new OverloadedNumberUtil.FloatOrShort(1000f, (short) 1000));
- cipEqu(-1000f, new OverloadedNumberUtil.FloatOrShort(-1000f, (short) -1000));
- cipEqu(1000.00006f);
-
- cipEqu(60000f, new OverloadedNumberUtil.FloatOrInteger(60000f, 60000));
- cipEqu(-60000f, new OverloadedNumberUtil.FloatOrInteger(-60000f, -60000));
- cipEqu(60000.004f);
-
- cipEqu(100f, new OverloadedNumberUtil.FloatOrByte(100f, (byte) 100), TypeFlags.MASK_KNOWN_INTEGERS);
- cipEqu(1000f, new OverloadedNumberUtil.FloatOrShort(1000f, (short) 1000), TypeFlags.MASK_KNOWN_INTEGERS);
- cipEqu(60000f, new OverloadedNumberUtil.FloatOrInteger(60000f, 60000), TypeFlags.MASK_KNOWN_INTEGERS);
- cipEqu(60000f, new OverloadedNumberUtil.FloatOrInteger(60000f, 60000), TypeFlags.LONG);
- cipEqu((float) Integer.MAX_VALUE, (float) Integer.MAX_VALUE, TypeFlags.LONG);
- cipEqu((float) -Integer.MAX_VALUE, (float) -Integer.MAX_VALUE);
-
- cipEqu(0.5f, 0.5f, TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(0.5f, 0.5f, TypeFlags.DOUBLE);
- }
-
- public void testBigIntegerCoercion() {
- BigInteger bi;
-
- cipEqu(BigInteger.ZERO, new OverloadedNumberUtil.BigIntegerOrByte(BigInteger.ZERO));
- bi = new BigInteger(String.valueOf(Byte.MAX_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrByte(bi));
- bi = new BigInteger(String.valueOf(Byte.MIN_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrByte(bi));
-
- bi = new BigInteger(String.valueOf(Byte.MAX_VALUE + 1));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
- bi = new BigInteger(String.valueOf(Byte.MIN_VALUE - 1));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
- bi = new BigInteger(String.valueOf(Short.MAX_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
- bi = new BigInteger(String.valueOf(Short.MIN_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
-
- bi = new BigInteger(String.valueOf(Short.MAX_VALUE + 1));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
- bi = new BigInteger(String.valueOf(Short.MIN_VALUE - 1));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
- bi = new BigInteger(String.valueOf(Integer.MAX_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
- bi = new BigInteger(String.valueOf(Integer.MIN_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
-
- bi = new BigInteger(String.valueOf(Integer.MAX_VALUE + 1L));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
- bi = new BigInteger(String.valueOf(Integer.MIN_VALUE - 1L));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
- bi = new BigInteger(String.valueOf(Long.MAX_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
- bi = new BigInteger(String.valueOf(Long.MIN_VALUE));
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
-
- cipEqu(new BigInteger(String.valueOf(Long.MAX_VALUE)).add(BigInteger.ONE));
- cipEqu(new BigInteger(String.valueOf(Long.MIN_VALUE)).subtract(BigInteger.ONE));
-
- bi = new BigInteger("0");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi),
- TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi),
- TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi),
- TypeFlags.FLOAT);
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi),
- TypeFlags.DOUBLE);
-
- bi = new BigInteger("16777215");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- bi = new BigInteger("-16777215");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
-
- bi = new BigInteger("16777216");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- bi = new BigInteger("-16777216");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
-
- bi = new BigInteger("16777217");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, TypeFlags.FLOAT);
- bi = new BigInteger("-16777217");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, TypeFlags.FLOAT);
-
- bi = new BigInteger("9007199254740991");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
- bi = new BigInteger("-9007199254740991");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
-
- bi = new BigInteger("9007199254740992");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
- bi = new BigInteger("-9007199254740992");
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
-
- bi = new BigInteger("9007199254740993");
- cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(bi, TypeFlags.FLOAT);
- cipEqu(bi, TypeFlags.DOUBLE);
- bi = new BigInteger("-9007199254740993");
- cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
- cipEqu(bi, TypeFlags.DOUBLE | TypeFlags.FLOAT);
- cipEqu(bi, TypeFlags.FLOAT);
- cipEqu(bi, TypeFlags.DOUBLE);
-
- bi = new BigInteger("9007199254740994");
- cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
- bi = new BigInteger("-9007199254740994");
- cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
- }
-
- private void cipEqu(Number actualAndExpected) {
- cipEqu(actualAndExpected, actualAndExpected, -1);
- }
-
- private void cipEqu(Number actual, Number expected) {
- cipEqu(actual, expected, -1);
- }
-
- private void cipEqu(Number actualAndExpected, int flags) {
- cipEqu(actualAndExpected, actualAndExpected, flags);
- }
-
- @SuppressWarnings("boxing")
- private void cipEqu(Number actual, Number expected, int flags) {
- Number res = OverloadedNumberUtil.addFallbackType(actual, flags);
- assertEquals(expected.getClass(), res.getClass());
- assertEquals(expected, res);
-
- // Some number types wrap the number with multiple types and equals() only compares one of them. So we try to
- // catch any inconsistency:
- assertEquals(expected.byteValue(), res.byteValue());
- assertEquals(expected.shortValue(), res.shortValue());
- assertEquals(expected.intValue(), res.intValue());
- assertEquals(expected.longValue(), res.longValue());
- assertEquals(expected.floatValue(), res.floatValue());
- assertEquals(expected.doubleValue(), res.doubleValue());
- }
-
- public void testGetArgumentConversionPrice() {
- // Unknown number types:
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- RationalNumber.class, Integer.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, RationalNumber.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- RationalNumber.class, Float.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- Float.class, RationalNumber.class));
- assertEquals(0, OverloadedNumberUtil.getArgumentConversionPrice(
- RationalNumber.class, RationalNumber.class));
-
- // Fully check some rows (not all of them; the code is generated anyways):
-
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, Byte.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, Short.class));
- assertEquals(0, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, Integer.class));
- assertEquals(10004, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, Long.class));
- assertEquals(10005, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, BigInteger.class));
- assertEquals(30006, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, Float.class));
- assertEquals(20007, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, Double.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, BigDecimal.class));
-
- assertEquals(45001, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, Byte.class));
- assertEquals(44002, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, Short.class));
- assertEquals(41003, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, Integer.class));
- assertEquals(41004, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, Long.class));
- assertEquals(40005, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, BigInteger.class));
- assertEquals(33006, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, Float.class));
- assertEquals(32007, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, Double.class));
- assertEquals(0, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, BigDecimal.class));
-
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, Byte.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, Short.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, Integer.class));
- assertEquals(21004, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, Long.class));
- assertEquals(21005, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, BigInteger.class));
- assertEquals(40006, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, Float.class));
- assertEquals(0, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, Double.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, BigDecimal.class));
-
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, Byte.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, Short.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, Integer.class));
- assertEquals(Integer.MAX_VALUE, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, Long.class));
- assertEquals(0, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, BigInteger.class));
- assertEquals(40006, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, Float.class));
- assertEquals(20007, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, Double.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, BigDecimal.class));
-
- // Check if all fromC is present:
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- Byte.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- Short.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- Integer.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- Long.class, BigDecimal.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- BigInteger.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- Float.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- Double.class, BigDecimal.class));
- assertEquals(0, OverloadedNumberUtil.getArgumentConversionPrice(
- BigDecimal.class, BigDecimal.class));
- assertEquals(0, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.IntegerBigDecimal.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrFloat.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.FloatOrByte.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrShort.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.FloatOrByte.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.FloatOrShort.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.FloatOrInteger.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrByte.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrIntegerOrFloat.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrInteger.class, BigDecimal.class));
- assertEquals(20008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.DoubleOrLong.class, BigDecimal.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrByte.class, BigDecimal.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrShort.class, BigDecimal.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrInteger.class, BigDecimal.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrLong.class, BigDecimal.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrFloat.class, BigDecimal.class));
- assertEquals(10008, OverloadedNumberUtil.getArgumentConversionPrice(
- OverloadedNumberUtil.BigIntegerOrDouble.class, BigDecimal.class));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilsTest.java
new file mode 100644
index 0000000..679ede6
--- /dev/null
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/OverloadedNumberUtilsTest.java
@@ -0,0 +1,585 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.model.impl;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import junit.framework.TestCase;
+
+@SuppressWarnings("boxing")
+public class OverloadedNumberUtilsTest extends TestCase {
+
+ public OverloadedNumberUtilsTest(String name) {
+ super(name);
+ }
+
+ public void testIntegerCoercions() {
+ cipEqu(Byte.valueOf(Byte.MAX_VALUE));
+ cipEqu(Byte.valueOf((byte) 0));
+ cipEqu(Byte.valueOf(Byte.MIN_VALUE));
+
+ cipEqu(Short.valueOf(Byte.MAX_VALUE),
+ new OverloadedNumberUtils.ShortOrByte((short) Byte.MAX_VALUE, Byte.MAX_VALUE));
+ cipEqu(Short.valueOf((short) 0),
+ new OverloadedNumberUtils.ShortOrByte((short) 0, (byte) 0));
+ cipEqu(Short.valueOf(Byte.MIN_VALUE),
+ new OverloadedNumberUtils.ShortOrByte((short) Byte.MIN_VALUE, Byte.MIN_VALUE));
+
+ cipEqu(Short.valueOf((short) (Byte.MAX_VALUE + 1)));
+ cipEqu(Short.valueOf((short) (Byte.MIN_VALUE - 1)));
+ cipEqu(Short.valueOf(Short.MAX_VALUE));
+ cipEqu(Short.valueOf(Short.MIN_VALUE));
+
+ cipEqu(Integer.valueOf(Byte.MAX_VALUE),
+ new OverloadedNumberUtils.IntegerOrByte((int) Byte.MAX_VALUE, Byte.MAX_VALUE));
+ cipEqu(Integer.valueOf(0),
+ new OverloadedNumberUtils.IntegerOrByte(0, (byte) 0));
+ cipEqu(Integer.valueOf(Byte.MIN_VALUE),
+ new OverloadedNumberUtils.IntegerOrByte((int) Byte.MIN_VALUE, Byte.MIN_VALUE));
+
+ cipEqu(Integer.valueOf(Byte.MAX_VALUE + 1),
+ new OverloadedNumberUtils.IntegerOrShort(Byte.MAX_VALUE + 1, (short) (Byte.MAX_VALUE + 1)));
+ cipEqu(Integer.valueOf(Byte.MIN_VALUE - 1),
+ new OverloadedNumberUtils.IntegerOrShort(Byte.MIN_VALUE - 1, (short) (Byte.MIN_VALUE - 1)));
+ cipEqu(Integer.valueOf(Short.MAX_VALUE),
+ new OverloadedNumberUtils.IntegerOrShort((int) Short.MAX_VALUE, Short.MAX_VALUE));
+ cipEqu(Integer.valueOf(Short.MIN_VALUE),
+ new OverloadedNumberUtils.IntegerOrShort((int) Short.MIN_VALUE, Short.MIN_VALUE));
+
+ cipEqu(Integer.valueOf(Short.MAX_VALUE + 1));
+ cipEqu(Integer.valueOf(Short.MIN_VALUE - 1));
+ cipEqu(Integer.valueOf(Integer.MAX_VALUE));
+ cipEqu(Integer.valueOf(Integer.MIN_VALUE));
+
+ cipEqu(Long.valueOf(Byte.MAX_VALUE),
+ new OverloadedNumberUtils.LongOrByte((long) Byte.MAX_VALUE, Byte.MAX_VALUE));
+ cipEqu(Long.valueOf(0),
+ new OverloadedNumberUtils.LongOrByte((long) 0, (byte) 0));
+ cipEqu(Long.valueOf(Byte.MIN_VALUE),
+ new OverloadedNumberUtils.LongOrByte((long) Byte.MIN_VALUE, Byte.MIN_VALUE));
+
+ cipEqu(Long.valueOf(Byte.MAX_VALUE + 1),
+ new OverloadedNumberUtils.LongOrShort((long) (Byte.MAX_VALUE + 1), (short) (Byte.MAX_VALUE + 1)));
+ cipEqu(Long.valueOf(Byte.MIN_VALUE - 1),
+ new OverloadedNumberUtils.LongOrShort((long) (Byte.MIN_VALUE - 1), (short) (Byte.MIN_VALUE - 1)));
+ cipEqu(Long.valueOf(Short.MAX_VALUE),
+ new OverloadedNumberUtils.LongOrShort((long) Short.MAX_VALUE, Short.MAX_VALUE));
+ cipEqu(Long.valueOf(Short.MIN_VALUE),
+ new OverloadedNumberUtils.LongOrShort((long) Short.MIN_VALUE, Short.MIN_VALUE));
+
+ cipEqu(Long.valueOf(Short.MAX_VALUE + 1),
+ new OverloadedNumberUtils.LongOrInteger((long) Short.MAX_VALUE + 1, Short.MAX_VALUE + 1));
+ cipEqu(Long.valueOf(Short.MIN_VALUE - 1),
+ new OverloadedNumberUtils.LongOrInteger((long) Short.MIN_VALUE - 1, Short.MIN_VALUE - 1));
+ cipEqu(Long.valueOf(Integer.MAX_VALUE),
+ new OverloadedNumberUtils.LongOrInteger((long) Integer.MAX_VALUE, Integer.MAX_VALUE));
+ cipEqu(Long.valueOf(Integer.MIN_VALUE),
+ new OverloadedNumberUtils.LongOrInteger((long) Integer.MIN_VALUE, Integer.MIN_VALUE));
+
+ cipEqu(Long.valueOf(Integer.MAX_VALUE + 1L));
+ cipEqu(Long.valueOf(Integer.MIN_VALUE - 1L));
+ cipEqu(Long.valueOf(Long.MAX_VALUE));
+ cipEqu(Long.valueOf(Long.MIN_VALUE));
+ }
+
+ public void testIntegerNoCoercions() {
+ cipEqu(Integer.valueOf(Byte.MAX_VALUE), Integer.valueOf(Byte.MAX_VALUE), 0);
+ cipEqu(Integer.valueOf(0), Integer.valueOf(0), 0);
+ cipEqu(Integer.valueOf(Byte.MIN_VALUE), Integer.valueOf(Byte.MIN_VALUE), 0);
+ }
+
+ public void testIntegerLimitedCoercions() {
+ cipEqu(Integer.valueOf(Byte.MAX_VALUE), Integer.valueOf(Byte.MAX_VALUE), TypeFlags.INTEGER);
+ cipEqu(Integer.valueOf(0), Integer.valueOf(0), TypeFlags.INTEGER);
+ cipEqu(Integer.valueOf(Byte.MIN_VALUE), Integer.valueOf(Byte.MIN_VALUE), TypeFlags.INTEGER);
+
+ cipEqu(Long.valueOf(Integer.MAX_VALUE + 1L), Long.valueOf(Integer.MAX_VALUE + 1L), TypeFlags.INTEGER);
+
+ for (int n = -1; n < 2; n++) {
+ final Long longN = Long.valueOf(n);
+ cipEqu(longN, new OverloadedNumberUtils.LongOrInteger(longN, n), TypeFlags.INTEGER);
+ cipEqu(longN, new OverloadedNumberUtils.LongOrShort(longN, (short) n), TypeFlags.SHORT);
+ cipEqu(longN, new OverloadedNumberUtils.LongOrByte(longN, (byte) n), TypeFlags.BYTE);
+ cipEqu(longN, new OverloadedNumberUtils.LongOrShort(longN, (short) n),
+ TypeFlags.SHORT | TypeFlags.INTEGER);
+ }
+ }
+
+ public void testBigDecimalCoercions() {
+ cipEqu(new BigDecimal(123), new OverloadedNumberUtils.IntegerBigDecimal(new BigDecimal(123)));
+ cipEqu(new BigDecimal(123), new OverloadedNumberUtils.IntegerBigDecimal(new BigDecimal(123)),
+ TypeFlags.DOUBLE | TypeFlags.INTEGER);
+ cipEqu(new BigDecimal(123), TypeFlags.INTEGER);
+ cipEqu(new BigDecimal(123), TypeFlags.INTEGER | TypeFlags.LONG);
+ cipEqu(new BigDecimal(123), TypeFlags.DOUBLE);
+ cipEqu(new BigDecimal(123), TypeFlags.DOUBLE | TypeFlags.FLOAT);
+
+ cipEqu(new BigDecimal(123.5));
+ // Not wasting time with check if it's a whole number if we only have integer-only or non-integer-only targets:
+ cipEqu(new BigDecimal(123.5), TypeFlags.INTEGER | TypeFlags.LONG);
+ cipEqu(new BigDecimal(123.5), TypeFlags.DOUBLE | TypeFlags.FLOAT);
+
+ cipEqu(new BigDecimal("0.01"));
+ cipEqu(new BigDecimal("-0.01"));
+ cipEqu(BigDecimal.ZERO, new OverloadedNumberUtils.IntegerBigDecimal(BigDecimal.ZERO));
+ }
+
+ public void testUnknownNumberCoercion() {
+ cipEqu(new RationalNumber(2, 3));
+ }
+
+ @SuppressWarnings("boxing")
+ public void testDoubleCoercion() {
+ cipEqu(Double.valueOf(1.5), new OverloadedNumberUtils.DoubleOrFloat(1.5));
+ cipEqu(Double.valueOf(-0.125), new OverloadedNumberUtils.DoubleOrFloat(-0.125));
+ cipEqu(Double.valueOf(Float.MAX_VALUE), new OverloadedNumberUtils.DoubleOrFloat((double) Float.MAX_VALUE));
+ cipEqu(Double.valueOf(-Float.MAX_VALUE), new OverloadedNumberUtils.DoubleOrFloat((double) -Float.MAX_VALUE));
+ cipEqu(Double.valueOf(Float.MAX_VALUE * 10.0));
+ cipEqu(Double.valueOf(-Float.MAX_VALUE * 10.0));
+
+ cipEqu(Double.valueOf(0), new OverloadedNumberUtils.DoubleOrByte(0.0, (byte) 0));
+ cipEqu(Double.valueOf(Byte.MAX_VALUE), new OverloadedNumberUtils.DoubleOrByte((double) Byte.MAX_VALUE, Byte.MAX_VALUE));
+ cipEqu(Double.valueOf(Byte.MIN_VALUE), new OverloadedNumberUtils.DoubleOrByte((double) Byte.MIN_VALUE, Byte.MIN_VALUE));
+
+ cipEqu(Double.valueOf(Byte.MAX_VALUE + 1), new OverloadedNumberUtils.DoubleOrShort((double)
+ (Byte.MAX_VALUE + 1), (short) (Byte.MAX_VALUE + 1)));
+ cipEqu(Double.valueOf(Byte.MIN_VALUE - 1), new OverloadedNumberUtils.DoubleOrShort((double)
+ (Byte.MIN_VALUE - 1), (short) (Byte.MIN_VALUE - 1)));
+
+ cipEqu(Double.valueOf(Short.MAX_VALUE + 1),
+ new OverloadedNumberUtils.DoubleOrIntegerOrFloat((double) Short.MAX_VALUE + 1, Short.MAX_VALUE + 1));
+ cipEqu(Double.valueOf(Short.MIN_VALUE - 1),
+ new OverloadedNumberUtils.DoubleOrIntegerOrFloat((double) Short.MIN_VALUE - 1, Short.MIN_VALUE - 1));
+ cipEqu(Double.valueOf(16777216), new OverloadedNumberUtils.DoubleOrIntegerOrFloat(16777216.0, 16777216));
+ cipEqu(Double.valueOf(-16777216), new OverloadedNumberUtils.DoubleOrIntegerOrFloat(-16777216.0, -16777216));
+
+ cipEqu(Double.valueOf(Integer.MAX_VALUE),
+ new OverloadedNumberUtils.DoubleOrInteger((double) Integer.MAX_VALUE, Integer.MAX_VALUE));
+ cipEqu(Double.valueOf(Integer.MIN_VALUE),
+ new OverloadedNumberUtils.DoubleOrInteger((double) Integer.MIN_VALUE, Integer.MIN_VALUE));
+
+ cipEqu(Double.valueOf(Integer.MAX_VALUE + 1L),
+ new OverloadedNumberUtils.DoubleOrLong(Double.valueOf(Integer.MAX_VALUE + 1L), Integer.MAX_VALUE + 1L));
+ cipEqu(Double.valueOf(Integer.MIN_VALUE - 1L),
+ new OverloadedNumberUtils.DoubleOrLong(Double.valueOf(Integer.MIN_VALUE - 1L), Integer.MIN_VALUE - 1L));
+ cipEqu(Double.valueOf(Long.MAX_VALUE),
+ new OverloadedNumberUtils.DoubleOrFloat((double) Long.MAX_VALUE));
+ cipEqu(Double.valueOf(Long.MIN_VALUE),
+ new OverloadedNumberUtils.DoubleOrFloat((double) Long.MIN_VALUE));
+
+ // When only certain target types are present:
+ cipEqu(Double.valueOf(5), new OverloadedNumberUtils.DoubleOrByte(5.0, (byte) 5), TypeFlags.BYTE);
+ cipEqu(Double.valueOf(5), new OverloadedNumberUtils.DoubleOrByte(5.0, (byte) 5), TypeFlags.BYTE | TypeFlags.SHORT);
+ cipEqu(Double.valueOf(-129), TypeFlags.BYTE);
+ cipEqu(Double.valueOf(5), new OverloadedNumberUtils.DoubleOrShort(5.0, (short) 5), TypeFlags.SHORT);
+ cipEqu(Double.valueOf(5), new OverloadedNumberUtils.DoubleOrInteger(5.0, 5), TypeFlags.INTEGER);
+ cipEqu(Double.valueOf(5), new OverloadedNumberUtils.DoubleOrLong(5.0, 5), TypeFlags.LONG);
+ cipEqu(Double.valueOf(5), new OverloadedNumberUtils.DoubleOrFloat(5.0), TypeFlags.FLOAT);
+ cipEqu(Double.valueOf(5), Double.valueOf(5), TypeFlags.DOUBLE);
+ cipEqu(Double.valueOf(5), new OverloadedNumberUtils.DoubleOrFloat(5.0),
+ TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(Double.valueOf(5.9), new OverloadedNumberUtils.DoubleOrFloat(5.9),
+ TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(Double.valueOf(5.9),
+ TypeFlags.DOUBLE | TypeFlags.INTEGER);
+ cipEqu(Double.valueOf(5.9), new OverloadedNumberUtils.DoubleOrFloat(5.9),
+ TypeFlags.FLOAT | TypeFlags.INTEGER);
+ cipEqu(Double.valueOf(5.9), TypeFlags.INTEGER);
+ cipEqu(Double.valueOf(Long.MAX_VALUE),
+ new OverloadedNumberUtils.DoubleOrFloat((double) Long.MAX_VALUE),
+ TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(Double.valueOf(Long.MAX_VALUE),
+ TypeFlags.DOUBLE | TypeFlags.LONG);
+ cipEqu(Double.valueOf(Long.MIN_VALUE),
+ new OverloadedNumberUtils.DoubleOrFloat((double) Long.MIN_VALUE),
+ TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(Double.valueOf(Float.MAX_VALUE * 10),
+ TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(Double.valueOf(-Float.MAX_VALUE * 10),
+ TypeFlags.DOUBLE | TypeFlags.FLOAT);
+
+ // Rounded values:
+ cipEqu(Double.valueOf(0.0000009),
+ new OverloadedNumberUtils.DoubleOrByte(0.0000009, (byte) 0));
+ cipEqu(Double.valueOf(-0.0000009),
+ new OverloadedNumberUtils.DoubleOrByte(-0.0000009, (byte) 0));
+ cipEqu(Double.valueOf(0.9999991),
+ new OverloadedNumberUtils.DoubleOrByte(0.9999991, (byte) 1));
+ cipEqu(Double.valueOf(-0.9999991),
+ new OverloadedNumberUtils.DoubleOrByte(-0.9999991, (byte) -1));
+ cipEqu(Double.valueOf(0.0000009),
+ new OverloadedNumberUtils.DoubleOrShort(0.0000009, (short) 0),
+ TypeFlags.SHORT | TypeFlags.DOUBLE);
+ cipEqu(Double.valueOf(0.0000009), new OverloadedNumberUtils.DoubleOrInteger(0.0000009, 0),
+ TypeFlags.INTEGER | TypeFlags.DOUBLE);
+ cipEqu(Double.valueOf(0.0000009), new OverloadedNumberUtils.DoubleOrLong(0.0000009, 0),
+ TypeFlags.LONG | TypeFlags.DOUBLE);
+ cipEqu(Double.valueOf(0.0000009),
+ new OverloadedNumberUtils.DoubleOrByte(0.0000009, (byte) 0), TypeFlags.BYTE);
+ cipEqu(Double.valueOf(0.0000009),
+ new OverloadedNumberUtils.DoubleOrShort(0.0000009, (short) 0), TypeFlags.SHORT);
+ cipEqu(Double.valueOf(0.0000009),
+ new OverloadedNumberUtils.DoubleOrInteger(0.0000009, 0), TypeFlags.INTEGER);
+ cipEqu(Double.valueOf(0.0000009),
+ new OverloadedNumberUtils.DoubleOrLong(0.0000009, 0L), TypeFlags.LONG);
+ cipEqu(Double.valueOf(0.9999999),
+ new OverloadedNumberUtils.DoubleOrInteger(0.9999999, 1), TypeFlags.INTEGER);
+ cipEqu(Double.valueOf(Byte.MAX_VALUE + 0.9e-6),
+ new OverloadedNumberUtils.DoubleOrByte(Byte.MAX_VALUE + 0.9e-6, Byte.MAX_VALUE));
+ cipEqu(Double.valueOf(Byte.MIN_VALUE - 0.9e-6),
+ new OverloadedNumberUtils.DoubleOrByte(Byte.MIN_VALUE - 0.9e-6, Byte.MIN_VALUE));
+ cipEqu(Double.valueOf(Byte.MAX_VALUE + 1.1e-6),
+ new OverloadedNumberUtils.DoubleOrFloat(Byte.MAX_VALUE + 1.1e-6));
+ cipEqu(Double.valueOf(Byte.MIN_VALUE - 1.1e-6),
+ new OverloadedNumberUtils.DoubleOrFloat(Byte.MIN_VALUE - 1.1e-6));
+ cipEqu(Double.valueOf(Byte.MAX_VALUE + 0.9999991),
+ new OverloadedNumberUtils.DoubleOrShort(
+ Byte.MAX_VALUE + 0.9999991, (short) (Byte.MAX_VALUE + 1)));
+ cipEqu(Double.valueOf(Byte.MIN_VALUE - 0.9999991),
+ new OverloadedNumberUtils.DoubleOrShort(
+ Byte.MIN_VALUE - 0.9999991, (short) (Byte.MIN_VALUE - 1)));
+
+ cipEqu(Double.valueOf(Byte.MAX_VALUE + 1), new OverloadedNumberUtils.DoubleOrShort((double)
+ (Byte.MAX_VALUE + 1), (short) (Byte.MAX_VALUE + 1)));
+ cipEqu(Double.valueOf(Byte.MIN_VALUE - 1), new OverloadedNumberUtils.DoubleOrShort((double)
+ (Byte.MIN_VALUE - 1), (short) (Byte.MIN_VALUE - 1)));
+
+ cipEqu(Short.MAX_VALUE + 0.9999991,
+ new OverloadedNumberUtils.DoubleOrIntegerOrFloat(Short.MAX_VALUE + 0.9999991, Short.MAX_VALUE + 1));
+ cipEqu(Short.MIN_VALUE - 0.9999991,
+ new OverloadedNumberUtils.DoubleOrIntegerOrFloat(Short.MIN_VALUE - 0.9999991, Short.MIN_VALUE - 1));
+ cipEqu(16777216 + 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrIntegerOrFloat(16777216 + 0.9e-6, 16777216));
+ cipEqu(-16777216 - 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrIntegerOrFloat(-16777216 - 0.9e-6, -16777216));
+
+ cipEqu(Integer.MAX_VALUE + 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrInteger(Integer.MAX_VALUE + 0.9e-6, Integer.MAX_VALUE));
+ cipEqu(Integer.MIN_VALUE - 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrInteger(Integer.MIN_VALUE - 0.9e-6, Integer.MIN_VALUE));
+
+ cipEqu(Integer.MAX_VALUE + 1L + 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrFloat(Integer.MAX_VALUE + 1L + 0.9e-6));
+ cipEqu(Integer.MIN_VALUE - 1L - 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrFloat(Integer.MIN_VALUE - 1L - 0.9e-6));
+ cipEqu(Long.MAX_VALUE + 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrFloat(Long.MAX_VALUE + 0.9e-6));
+ cipEqu(Long.MIN_VALUE - 0.9e-6,
+ new OverloadedNumberUtils.DoubleOrFloat(Long.MIN_VALUE - 0.9e-6));
+ }
+
+ @SuppressWarnings("boxing")
+ public void testFloatCoercion() {
+ cipEqu(1.00002f);
+ cipEqu(-1.00002f);
+ cipEqu(1.999989f);
+ cipEqu(-1.999989f);
+ cipEqu(16777218f);
+ cipEqu(-16777218f);
+
+ cipEqu(1f, new OverloadedNumberUtils.FloatOrByte(1f, (byte) 1));
+ cipEqu(-1f, new OverloadedNumberUtils.FloatOrByte(-1f, (byte) -1));
+ cipEqu(1.000009f, new OverloadedNumberUtils.FloatOrByte(1.000009f, (byte) 1));
+ cipEqu(-1.000009f, new OverloadedNumberUtils.FloatOrByte(-1.000009f, (byte) -1));
+ cipEqu(1.999991f, new OverloadedNumberUtils.FloatOrByte(1.999991f, (byte) 2));
+ cipEqu(-1.999991f, new OverloadedNumberUtils.FloatOrByte(-1.999991f, (byte) -2));
+
+ cipEqu(1000f, new OverloadedNumberUtils.FloatOrShort(1000f, (short) 1000));
+ cipEqu(-1000f, new OverloadedNumberUtils.FloatOrShort(-1000f, (short) -1000));
+ cipEqu(1000.00006f);
+
+ cipEqu(60000f, new OverloadedNumberUtils.FloatOrInteger(60000f, 60000));
+ cipEqu(-60000f, new OverloadedNumberUtils.FloatOrInteger(-60000f, -60000));
+ cipEqu(60000.004f);
+
+ cipEqu(100f, new OverloadedNumberUtils.FloatOrByte(100f, (byte) 100), TypeFlags.MASK_KNOWN_INTEGERS);
+ cipEqu(1000f, new OverloadedNumberUtils.FloatOrShort(1000f, (short) 1000), TypeFlags.MASK_KNOWN_INTEGERS);
+ cipEqu(60000f, new OverloadedNumberUtils.FloatOrInteger(60000f, 60000), TypeFlags.MASK_KNOWN_INTEGERS);
+ cipEqu(60000f, new OverloadedNumberUtils.FloatOrInteger(60000f, 60000), TypeFlags.LONG);
+ cipEqu((float) Integer.MAX_VALUE, (float) Integer.MAX_VALUE, TypeFlags.LONG);
+ cipEqu((float) -Integer.MAX_VALUE, (float) -Integer.MAX_VALUE);
+
+ cipEqu(0.5f, 0.5f, TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(0.5f, 0.5f, TypeFlags.DOUBLE);
+ }
+
+ public void testBigIntegerCoercion() {
+ BigInteger bi;
+
+ cipEqu(BigInteger.ZERO, new OverloadedNumberUtils.BigIntegerOrByte(BigInteger.ZERO));
+ bi = new BigInteger(String.valueOf(Byte.MAX_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrByte(bi));
+ bi = new BigInteger(String.valueOf(Byte.MIN_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrByte(bi));
+
+ bi = new BigInteger(String.valueOf(Byte.MAX_VALUE + 1));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrShort(bi));
+ bi = new BigInteger(String.valueOf(Byte.MIN_VALUE - 1));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrShort(bi));
+ bi = new BigInteger(String.valueOf(Short.MAX_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrShort(bi));
+ bi = new BigInteger(String.valueOf(Short.MIN_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrShort(bi));
+
+ bi = new BigInteger(String.valueOf(Short.MAX_VALUE + 1));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrInteger(bi));
+ bi = new BigInteger(String.valueOf(Short.MIN_VALUE - 1));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrInteger(bi));
+ bi = new BigInteger(String.valueOf(Integer.MAX_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrInteger(bi));
+ bi = new BigInteger(String.valueOf(Integer.MIN_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrInteger(bi));
+
+ bi = new BigInteger(String.valueOf(Integer.MAX_VALUE + 1L));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrLong(bi));
+ bi = new BigInteger(String.valueOf(Integer.MIN_VALUE - 1L));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrLong(bi));
+ bi = new BigInteger(String.valueOf(Long.MAX_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrLong(bi));
+ bi = new BigInteger(String.valueOf(Long.MIN_VALUE));
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrLong(bi));
+
+ cipEqu(new BigInteger(String.valueOf(Long.MAX_VALUE)).add(BigInteger.ONE));
+ cipEqu(new BigInteger(String.valueOf(Long.MIN_VALUE)).subtract(BigInteger.ONE));
+
+ bi = new BigInteger("0");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrFloat(bi),
+ TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrFloat(bi),
+ TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrFloat(bi),
+ TypeFlags.FLOAT);
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi),
+ TypeFlags.DOUBLE);
+
+ bi = new BigInteger("16777215");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ bi = new BigInteger("-16777215");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+
+ bi = new BigInteger("16777216");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ bi = new BigInteger("-16777216");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+
+ bi = new BigInteger("16777217");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, TypeFlags.FLOAT);
+ bi = new BigInteger("-16777217");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, TypeFlags.FLOAT);
+
+ bi = new BigInteger("9007199254740991");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
+ bi = new BigInteger("-9007199254740991");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
+
+ bi = new BigInteger("9007199254740992");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
+ bi = new BigInteger("-9007199254740992");
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, new OverloadedNumberUtils.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
+
+ bi = new BigInteger("9007199254740993");
+ cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(bi, TypeFlags.FLOAT);
+ cipEqu(bi, TypeFlags.DOUBLE);
+ bi = new BigInteger("-9007199254740993");
+ cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
+ cipEqu(bi, TypeFlags.DOUBLE | TypeFlags.FLOAT);
+ cipEqu(bi, TypeFlags.FLOAT);
+ cipEqu(bi, TypeFlags.DOUBLE);
+
+ bi = new BigInteger("9007199254740994");
+ cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
+ bi = new BigInteger("-9007199254740994");
+ cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
+ }
+
+ private void cipEqu(Number actualAndExpected) {
+ cipEqu(actualAndExpected, actualAndExpected, -1);
+ }
+
+ private void cipEqu(Number actual, Number expected) {
+ cipEqu(actual, expected, -1);
+ }
+
+ private void cipEqu(Number actualAndExpected, int flags) {
+ cipEqu(actualAndExpected, actualAndExpected, flags);
+ }
+
+ @SuppressWarnings("boxing")
+ private void cipEqu(Number actual, Number expected, int flags) {
+ Number res = OverloadedNumberUtils.addFallbackType(actual, flags);
+ assertEquals(expected.getClass(), res.getClass());
+ assertEquals(expected, res);
+
+ // Some number types wrap the number with multiple types and equals() only compares one of them. So we try to
+ // catch any inconsistency:
+ assertEquals(expected.byteValue(), res.byteValue());
+ assertEquals(expected.shortValue(), res.shortValue());
+ assertEquals(expected.intValue(), res.intValue());
+ assertEquals(expected.longValue(), res.longValue());
+ assertEquals(expected.floatValue(), res.floatValue());
+ assertEquals(expected.doubleValue(), res.doubleValue());
+ }
+
+ public void testGetArgumentConversionPrice() {
+ // Unknown number types:
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ RationalNumber.class, Integer.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, RationalNumber.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ RationalNumber.class, Float.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ Float.class, RationalNumber.class));
+ assertEquals(0, OverloadedNumberUtils.getArgumentConversionPrice(
+ RationalNumber.class, RationalNumber.class));
+
+ // Fully check some rows (not all of them; the code is generated anyways):
+
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, Byte.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, Short.class));
+ assertEquals(0, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, Integer.class));
+ assertEquals(10004, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, Long.class));
+ assertEquals(10005, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, BigInteger.class));
+ assertEquals(30006, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, Float.class));
+ assertEquals(20007, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, Double.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, BigDecimal.class));
+
+ assertEquals(45001, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, Byte.class));
+ assertEquals(44002, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, Short.class));
+ assertEquals(41003, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, Integer.class));
+ assertEquals(41004, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, Long.class));
+ assertEquals(40005, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, BigInteger.class));
+ assertEquals(33006, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, Float.class));
+ assertEquals(32007, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, Double.class));
+ assertEquals(0, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, BigDecimal.class));
+
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, Byte.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, Short.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, Integer.class));
+ assertEquals(21004, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, Long.class));
+ assertEquals(21005, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, BigInteger.class));
+ assertEquals(40006, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, Float.class));
+ assertEquals(0, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, Double.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, BigDecimal.class));
+
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, Byte.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, Short.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, Integer.class));
+ assertEquals(Integer.MAX_VALUE, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, Long.class));
+ assertEquals(0, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, BigInteger.class));
+ assertEquals(40006, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, Float.class));
+ assertEquals(20007, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, Double.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, BigDecimal.class));
+
+ // Check if all fromC is present:
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ Byte.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ Short.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ Integer.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ Long.class, BigDecimal.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigInteger.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ Float.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ Double.class, BigDecimal.class));
+ assertEquals(0, OverloadedNumberUtils.getArgumentConversionPrice(
+ BigDecimal.class, BigDecimal.class));
+ assertEquals(0, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.IntegerBigDecimal.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrFloat.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.FloatOrByte.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrShort.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.FloatOrByte.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.FloatOrShort.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.FloatOrInteger.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrByte.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrIntegerOrFloat.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrInteger.class, BigDecimal.class));
+ assertEquals(20008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.DoubleOrLong.class, BigDecimal.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrByte.class, BigDecimal.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrShort.class, BigDecimal.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrInteger.class, BigDecimal.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrLong.class, BigDecimal.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrFloat.class, BigDecimal.class));
+ assertEquals(10008, OverloadedNumberUtils.getArgumentConversionPrice(
+ OverloadedNumberUtils.BigIntegerOrDouble.class, BigDecimal.class));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ParameterListPreferabilityTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ParameterListPreferabilityTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ParameterListPreferabilityTest.java
index 3e6c2ed..54461d4 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ParameterListPreferabilityTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ParameterListPreferabilityTest.java
@@ -27,7 +27,7 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
-import org.apache.freemarker.core.util._NumberUtil;
+import org.apache.freemarker.core.util._NumberUtils;
import junit.framework.TestCase;
@@ -84,7 +84,7 @@ public class ParameterListPreferabilityTest extends TestCase {
new Class[] { Serializable.class },
new Class[] { Object.class },
},
- new Object[] { new OverloadedNumberUtil.IntegerBigDecimal(new BigDecimal("1")) });
+ new Object[] { new OverloadedNumberUtils.IntegerBigDecimal(new BigDecimal("1")) });
testAllCmpPermutationsInc(
new Class[][] {
@@ -128,7 +128,7 @@ public class ParameterListPreferabilityTest extends TestCase {
new Class[] { Serializable.class },
new Class[] { Object.class },
},
- new Object[] { new OverloadedNumberUtil.FloatOrByte(1f, (byte) 1) });
+ new Object[] { new OverloadedNumberUtils.FloatOrByte(1f, (byte) 1) });
testAllCmpPermutationsInc(
new Class[][] {
@@ -153,7 +153,7 @@ public class ParameterListPreferabilityTest extends TestCase {
new Class[] { Serializable.class },
new Class[] { Object.class }
},
- new Object[] { new OverloadedNumberUtil.IntegerOrShort(1, (short) 1) });
+ new Object[] { new OverloadedNumberUtils.IntegerOrShort(1, (short) 1) });
testAllCmpPermutationsInc(
new Class[][] {
@@ -422,9 +422,9 @@ public class ParameterListPreferabilityTest extends TestCase {
for (int i = 0; i < sortedSignatures.length; i++) {
for (int j = 0; j < sortedSignatures.length; j++) {
assertEquals("sortedSignatures[" + i + "] <==> sortedSignatures [" + j + "]",
- _NumberUtil.getSignum(
+ _NumberUtils.getSignum(
Integer.valueOf(j).compareTo(i)),
- _NumberUtil.getSignum(
+ _NumberUtils.getSignum(
argTs.compareParameterListPreferability(
sortedSignatures[i], sortedSignatures[j], varargs)));
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/JavaObjectInfo.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/JavaObjectInfo.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/JavaObjectInfo.java
index aa6d618..a82665b 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/JavaObjectInfo.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/templatesuite/models/JavaObjectInfo.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core.templatesuite.models;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
public class JavaObjectInfo {
@@ -29,7 +29,7 @@ public class JavaObjectInfo {
public String info(Object o) {
if (o == null) return "null";
- return o.getClass().getName() + " " + _StringUtil.jQuote(o.toString());
+ return o.getClass().getName() + " " + _StringUtils.jQuote(o.toString());
}
}
[13/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilsTest.java
new file mode 100644
index 0000000..a4d57a8
--- /dev/null
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilsTest.java
@@ -0,0 +1,416 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import static junit.framework.TestCase.assertNull;
+import static org.junit.Assert.*;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.regex.Pattern;
+
+import org.hamcrest.Matchers;
+import org.junit.Test;
+
+public class StringUtilsTest {
+
+ @Test
+ public void testV2319() {
+ assertEquals("\\n\\r\\f\\b\\t\\x00\\x19", _StringUtils.javaScriptStringEnc("\n\r\f\b\t\u0000\u0019"));
+ }
+
+ @Test
+ public void testControlChars() {
+ assertEsc(
+ "\n\r\f\b\t \u0000\u0019\u001F \u007F\u0080\u009F \u2028\u2029",
+ "\\n\\r\\f\\b\\t \\x00\\x19\\x1F \\x7F\\x80\\x9F \\u2028\\u2029",
+ "\\n\\r\\f\\b\\t \\u0000\\u0019\\u001F \\u007F\\u0080\\u009F \\u2028\\u2029");
+ }
+
+ @Test
+ public void testHtmlChars() {
+ assertEsc(
+ "<safe>/>->]> </foo> <!-- --> <![CDATA[ ]]> <?php?>",
+ "<safe>/>->]> <\\/foo> \\x3C!-- --\\> \\x3C![CDATA[ ]]\\> \\x3C?php?>",
+ "<safe>/>->]> <\\/foo> \\u003C!-- --\\u003E \\u003C![CDATA[ ]]\\u003E \\u003C?php?>");
+ assertEsc("<!c", "\\x3C!c", "\\u003C!c");
+ assertEsc("c<!", "c\\x3C!", "c\\u003C!");
+ assertEsc("c<", "c\\x3C", "c\\u003C");
+ assertEsc("c<c", "c<c", "c<c");
+ assertEsc("<c", "<c", "<c");
+ assertEsc(">", "\\>", "\\u003E");
+ assertEsc("->", "-\\>", "-\\u003E");
+ assertEsc("-->", "--\\>", "--\\u003E");
+ assertEsc("c-->", "c--\\>", "c--\\u003E");
+ assertEsc("-->c", "--\\>c", "--\\u003Ec");
+ assertEsc("]>", "]\\>", "]\\u003E");
+ assertEsc("]]>", "]]\\>", "]]\\u003E");
+ assertEsc("c]]>", "c]]\\>", "c]]\\u003E");
+ assertEsc("]]>c", "]]\\>c", "]]\\u003Ec");
+ assertEsc("c->", "c->", "c->");
+ assertEsc("c>", "c>", "c>");
+ assertEsc("-->", "--\\>", "--\\u003E");
+ assertEsc("/", "\\/", "\\/");
+ assertEsc("/c", "\\/c", "\\/c");
+ assertEsc("</", "<\\/", "<\\/");
+ assertEsc("</c", "<\\/c", "<\\/c");
+ assertEsc("c/", "c/", "c/");
+ }
+
+ @Test
+ public void testJSChars() {
+ assertEsc("\"", "\\\"", "\\\"");
+ assertEsc("'", "\\'", "'");
+ assertEsc("\\", "\\\\", "\\\\");
+ }
+
+ @Test
+ public void testSameStringsReturned() {
+ String s = "==> I/m <safe>!";
+ assertTrue(s == _StringUtils.jsStringEnc(s, false)); // "==" because is must return the same object
+ assertTrue(s == _StringUtils.jsStringEnc(s, true));
+
+ s = "";
+ assertTrue(s == _StringUtils.jsStringEnc(s, false));
+ assertTrue(s == _StringUtils.jsStringEnc(s, true));
+
+ s = "\u00E1rv\u00EDzt\u0171r\u0151 \u3020";
+ assertEquals(s, _StringUtils.jsStringEnc(s, false));
+ assertTrue(s == _StringUtils.jsStringEnc(s, false));
+ assertTrue(s == _StringUtils.jsStringEnc(s, true));
+ }
+
+ @Test
+ public void testOneOffs() {
+ assertEsc("c\"c\"cc\"\"c", "c\\\"c\\\"cc\\\"\\\"c", "c\\\"c\\\"cc\\\"\\\"c");
+ assertEsc("\"c\"cc\"", "\\\"c\\\"cc\\\"", "\\\"c\\\"cc\\\"");
+ assertEsc("c/c/cc//c", "c/c/cc//c", "c/c/cc//c");
+ assertEsc("c<c<cc<<c", "c<c<cc<<c", "c<c<cc<<c");
+ assertEsc("/<", "\\/\\x3C", "\\/\\u003C");
+ assertEsc(">", "\\>", "\\u003E");
+ assertEsc("]>", "]\\>", "]\\u003E");
+ assertEsc("->", "-\\>", "-\\u003E");
+ }
+
+ private void assertEsc(String s, String javaScript, String json) {
+ assertEquals(javaScript, _StringUtils.jsStringEnc(s, false));
+ assertEquals(json, _StringUtils.jsStringEnc(s, true));
+ }
+
+ @Test
+ public void testTrim() {
+ assertSame(_CollectionUtils.EMPTY_CHAR_ARRAY, _StringUtils.trim(_CollectionUtils.EMPTY_CHAR_ARRAY));
+ assertSame(_CollectionUtils.EMPTY_CHAR_ARRAY, _StringUtils.trim(" \t\u0001 ".toCharArray()));
+ {
+ char[] cs = "foo".toCharArray();
+ assertSame(cs, cs);
+ }
+ assertArrayEquals("foo".toCharArray(), _StringUtils.trim("foo ".toCharArray()));
+ assertArrayEquals("foo".toCharArray(), _StringUtils.trim(" foo".toCharArray()));
+ assertArrayEquals("foo".toCharArray(), _StringUtils.trim(" foo ".toCharArray()));
+ assertArrayEquals("foo".toCharArray(), _StringUtils.trim("\t\tfoo \r\n".toCharArray()));
+ assertArrayEquals("x".toCharArray(), _StringUtils.trim(" x ".toCharArray()));
+ assertArrayEquals("x y z".toCharArray(), _StringUtils.trim(" x y z ".toCharArray()));
+ }
+
+ @Test
+ public void testIsTrimmedToEmpty() {
+ assertTrue(_StringUtils.isTrimmableToEmpty("".toCharArray()));
+ assertTrue(_StringUtils.isTrimmableToEmpty("\r\r\n\u0001".toCharArray()));
+ assertFalse(_StringUtils.isTrimmableToEmpty("x".toCharArray()));
+ assertFalse(_StringUtils.isTrimmableToEmpty(" x ".toCharArray()));
+ }
+
+ @Test
+ public void testJQuote() {
+ assertEquals("null", _StringUtils.jQuote(null));
+ assertEquals("\"foo\"", _StringUtils.jQuote("foo"));
+ assertEquals("\"123\"", _StringUtils.jQuote(Integer.valueOf(123)));
+ assertEquals("\"foo's \\\"bar\\\"\"",
+ _StringUtils.jQuote("foo's \"bar\""));
+ assertEquals("\"\\n\\r\\t\\u0001\"",
+ _StringUtils.jQuote("\n\r\t\u0001"));
+ assertEquals("\"<\\nb\\rc\\td\\u0001>\"",
+ _StringUtils.jQuote("<\nb\rc\td\u0001>"));
+ }
+
+ @Test
+ public void testJQuoteNoXSS() {
+ assertEquals("null", _StringUtils.jQuoteNoXSS(null));
+ assertEquals("\"foo\"", _StringUtils.jQuoteNoXSS("foo"));
+ assertEquals("\"123\"", _StringUtils.jQuoteNoXSS(Integer.valueOf(123)));
+ assertEquals("\"foo's \\\"bar\\\"\"",
+ _StringUtils.jQuoteNoXSS("foo's \"bar\""));
+ assertEquals("\"\\n\\r\\t\\u0001\"",
+ _StringUtils.jQuoteNoXSS("\n\r\t\u0001"));
+ assertEquals("\"\\u003C\\nb\\rc\\td\\u0001>\"",
+ _StringUtils.jQuoteNoXSS("<\nb\rc\td\u0001>"));
+ assertEquals("\"\\u003C\\nb\\rc\\td\\u0001>\"",
+ _StringUtils.jQuoteNoXSS((Object) "<\nb\rc\td\u0001>"));
+ }
+
+ @Test
+ public void testGlobToRegularExpression() {
+ assertGlobMatches("a/b/c.ftl", "a/b/c.ftl");
+ assertGlobDoesNotMatch("/a/b/cxftl", "/a/b/c.ftl", "a/b/C.ftl");
+
+ assertGlobMatches("a/b/*.ftl", "a/b/.ftl", "a/b/x.ftl", "a/b/xx.ftl");
+ assertGlobDoesNotMatch("a/b/*.ftl", "a/c/x.ftl", "a/b/c/x.ftl", "/a/b/x.ftl", "a/b/xxftl");
+
+ assertGlobMatches("a/b/?.ftl", "a/b/x.ftl");
+ assertGlobDoesNotMatch("a/b/?.ftl", "a/c/x.ftl", "a/b/.ftl", "a/b/xx.ftl", "a/b/xxftl");
+
+ assertGlobMatches("a/**/c.ftl", "a/b/c.ftl", "a/c.ftl", "a/b/b2/b3/c.ftl", "a//c.ftl");
+ assertGlobDoesNotMatch("a/**/c.ftl", "x/b/c.ftl", "a/b/x.ftl");
+
+ assertGlobMatches("**/c.ftl", "a/b/c.ftl", "c.ftl", "/c.ftl", "///c.ftl");
+ assertGlobDoesNotMatch("**/c.ftl", "a/b/x.ftl");
+
+ assertGlobMatches("a/b/**", "a/b/c.ftl", "a/b/c2/c.ftl", "a/b/", "a/b/c/");
+ assertGlobDoesNotMatch("a/b.ftl");
+
+ assertGlobMatches("**", "a/b/c.ftl", "");
+
+ assertGlobMatches("\\[\\{\\*\\?\\}\\]\\\\", "[{*?}]\\");
+ assertGlobDoesNotMatch("\\[\\{\\*\\?\\}\\]\\\\", "[{xx}]\\");
+
+ assertGlobMatches("a/b/\\?.ftl", "a/b/?.ftl");
+ assertGlobDoesNotMatch("a/b/\\?.ftl", "a/b/x.ftl");
+
+ assertGlobMatches("\\?\\?.ftl", "??.ftl");
+ assertGlobMatches("\\\\\\\\", "\\\\");
+ assertGlobMatches("\\\\\\\\?", "\\\\x");
+ assertGlobMatches("x\\", "x");
+
+ assertGlobMatches("???*", "123", "1234", "12345");
+ assertGlobDoesNotMatch("???*", "12", "1", "");
+
+ assertGlobMatches("**/a??/b*.ftl", "a11/b1.ftl", "x/a11/b123.ftl", "x/y/a11/b.ftl");
+ assertGlobDoesNotMatch("**/a??/b*.ftl", "a1/b1.ftl", "x/a11/c123.ftl");
+
+ assertFalse(_StringUtils.globToRegularExpression("ab*").matcher("aBc").matches());
+ assertTrue(_StringUtils.globToRegularExpression("ab*", true).matcher("aBc").matches());
+ assertTrue(_StringUtils.globToRegularExpression("ab", true).matcher("aB").matches());
+ assertTrue(_StringUtils.globToRegularExpression("\u00E1b*", true).matcher("\u00C1bc").matches());
+
+ try {
+ _StringUtils.globToRegularExpression("x**/y");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e.getMessage(), Matchers.containsString("**"));
+ }
+
+ try {
+ _StringUtils.globToRegularExpression("**y");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e.getMessage(), Matchers.containsString("**"));
+ }
+
+ try {
+ _StringUtils.globToRegularExpression("[ab]c");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e.getMessage(), Matchers.containsString("unsupported"));
+ }
+
+ try {
+ _StringUtils.globToRegularExpression("{aa,bb}c");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e.getMessage(), Matchers.containsString("unsupported"));
+ }
+ }
+
+ private void assertGlobMatches(String glob, String... ss) {
+ Pattern pattern = _StringUtils.globToRegularExpression(glob);
+ for (String s : ss) {
+ if (!pattern.matcher(s).matches()) {
+ fail("Glob " + glob + " (regexp: " + pattern + ") doesn't match " + s);
+ }
+ }
+ }
+
+ private void assertGlobDoesNotMatch(String glob, String... ss) {
+ Pattern pattern = _StringUtils.globToRegularExpression(glob);
+ for (String s : ss) {
+ if (pattern.matcher(s).matches()) {
+ fail("Glob " + glob + " (regexp: " + pattern + ") matches " + s);
+ }
+ }
+ }
+
+ @Test
+ public void testHTMLEnc() {
+ String s = "";
+ assertSame(s, _StringUtils.XMLEncNA(s));
+
+ s = "asd";
+ assertSame(s, _StringUtils.XMLEncNA(s));
+
+ assertEquals("a&b<c>d"e'f", _StringUtils.XMLEncNA("a&b<c>d\"e'f"));
+ assertEquals("<", _StringUtils.XMLEncNA("<"));
+ assertEquals("<a", _StringUtils.XMLEncNA("<a"));
+ assertEquals("<a>", _StringUtils.XMLEncNA("<a>"));
+ assertEquals("a>", _StringUtils.XMLEncNA("a>"));
+ assertEquals("<>", _StringUtils.XMLEncNA("<>"));
+ assertEquals("a<>b", _StringUtils.XMLEncNA("a<>b"));
+ }
+
+ @Test
+ public void testXHTMLEnc() throws IOException {
+ String s = "";
+ assertSame(s, _StringUtils.XHTMLEnc(s));
+
+ s = "asd";
+ assertSame(s, _StringUtils.XHTMLEnc(s));
+
+ testXHTMLEnc("a&b<c>d"e'f", "a&b<c>d\"e'f");
+ testXHTMLEnc("<", "<");
+ testXHTMLEnc("<a", "<a");
+ testXHTMLEnc("<a>", "<a>");
+ testXHTMLEnc("a>", "a>");
+ testXHTMLEnc("<>", "<>");
+ testXHTMLEnc("a<>b", "a<>b");
+ }
+
+ private void testXHTMLEnc(String expected, String in) throws IOException {
+ assertEquals(expected, _StringUtils.XHTMLEnc(in));
+
+ StringWriter sw = new StringWriter();
+ _StringUtils.XHTMLEnc(in, sw);
+ assertEquals(expected, sw.toString());
+ }
+
+ @Test
+ public void testXMLEnc() throws IOException {
+ String s = "";
+ assertSame(s, _StringUtils.XMLEnc(s));
+
+ s = "asd";
+ assertSame(s, _StringUtils.XMLEnc(s));
+
+ testXMLEnc("a&b<c>d"e'f", "a&b<c>d\"e'f");
+ testXMLEnc("<", "<");
+ testXMLEnc("<a", "<a");
+ testXMLEnc("<a>", "<a>");
+ testXMLEnc("a>", "a>");
+ testXMLEnc("<>", "<>");
+ testXMLEnc("a<>b", "a<>b");
+ }
+
+ private void testXMLEnc(String expected, String in) throws IOException {
+ assertEquals(expected, _StringUtils.XMLEnc(in));
+
+ StringWriter sw = new StringWriter();
+ _StringUtils.XMLEnc(in, sw);
+ assertEquals(expected, sw.toString());
+ }
+
+ @Test
+ public void testXMLEncQAttr() throws IOException {
+ String s = "";
+ assertSame(s, _StringUtils.XMLEncQAttr(s));
+
+ s = "asd";
+ assertSame(s, _StringUtils.XMLEncQAttr(s));
+
+ assertEquals("a&b<c>d"e'f", _StringUtils.XMLEncQAttr("a&b<c>d\"e'f"));
+ assertEquals("<", _StringUtils.XMLEncQAttr("<"));
+ assertEquals("<a", _StringUtils.XMLEncQAttr("<a"));
+ assertEquals("<a>", _StringUtils.XMLEncQAttr("<a>"));
+ assertEquals("a>", _StringUtils.XMLEncQAttr("a>"));
+ assertEquals("<>", _StringUtils.XMLEncQAttr("<>"));
+ assertEquals("a<>b", _StringUtils.XMLEncQAttr("a<>b"));
+ }
+
+ @Test
+ public void testXMLEncNQG() throws IOException {
+ String s = "";
+ assertSame(s, _StringUtils.XMLEncNQG(s));
+
+ s = "asd";
+ assertSame(s, _StringUtils.XMLEncNQG(s));
+
+ assertEquals("a&b<c>d\"e'f", _StringUtils.XMLEncNQG("a&b<c>d\"e'f"));
+ assertEquals("<", _StringUtils.XMLEncNQG("<"));
+ assertEquals("<a", _StringUtils.XMLEncNQG("<a"));
+ assertEquals("<a>", _StringUtils.XMLEncNQG("<a>"));
+ assertEquals("a>", _StringUtils.XMLEncNQG("a>"));
+ assertEquals("<>", _StringUtils.XMLEncNQG("<>"));
+ assertEquals("a<>b", _StringUtils.XMLEncNQG("a<>b"));
+
+ assertEquals(">", _StringUtils.XMLEncNQG(">"));
+ assertEquals("]>", _StringUtils.XMLEncNQG("]>"));
+ assertEquals("]]>", _StringUtils.XMLEncNQG("]]>"));
+ assertEquals("x]]>", _StringUtils.XMLEncNQG("x]]>"));
+ assertEquals("x]>", _StringUtils.XMLEncNQG("x]>"));
+ assertEquals("]x>", _StringUtils.XMLEncNQG("]x>"));
+ }
+
+ @Test
+ public void testRTFEnc() throws IOException {
+ String s = "";
+ assertSame(s, _StringUtils.RTFEnc(s));
+
+ s = "asd";
+ assertSame(s, _StringUtils.RTFEnc(s));
+
+ testRTFEnc("a\\{b\\}c\\\\d", "a{b}c\\d");
+ testRTFEnc("\\{", "{");
+ testRTFEnc("\\{a", "{a");
+ testRTFEnc("\\{a\\}", "{a}");
+ testRTFEnc("a\\}", "a}");
+ testRTFEnc("\\{\\}", "{}");
+ testRTFEnc("a\\{\\}b", "a{}b");
+ }
+
+ private void testRTFEnc(String expected, String in) throws IOException {
+ assertEquals(expected, _StringUtils.RTFEnc(in));
+
+ StringWriter sw = new StringWriter();
+ _StringUtils.RTFEnc(in, sw);
+ assertEquals(expected, sw.toString());
+ }
+
+ @Test
+ public void testNormalizeEOLs() {
+ assertNull(_StringUtils.normalizeEOLs(null));
+ assertEquals("", _StringUtils.normalizeEOLs(""));
+ assertEquals("x", _StringUtils.normalizeEOLs("x"));
+ assertEquals("x\ny", _StringUtils.normalizeEOLs("x\ny"));
+ assertEquals("x\ny", _StringUtils.normalizeEOLs("x\r\ny"));
+ assertEquals("x\ny", _StringUtils.normalizeEOLs("x\ry"));
+ assertEquals("\n\n\n\n\n\n", _StringUtils.normalizeEOLs("\n\r\r\r\n\r\n\r"));
+ }
+
+ @Test
+ public void snakeCaseToCamelCase() {
+ assertNull(_StringUtils.snakeCaseToCamelCase(null));
+ assertEquals("", _StringUtils.snakeCaseToCamelCase(""));
+ assertEquals("x", _StringUtils.snakeCaseToCamelCase("x"));
+ assertEquals("xxx", _StringUtils.snakeCaseToCamelCase("xXx"));
+ assertEquals("fooBar", _StringUtils.snakeCaseToCamelCase("foo_bar"));
+ assertEquals("fooBar", _StringUtils.snakeCaseToCamelCase("FOO_BAR"));
+ assertEquals("fooBar", _StringUtils.snakeCaseToCamelCase("_foo__bar_"));
+ assertEquals("aBC", _StringUtils.snakeCaseToCamelCase("a_b_c"));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTComment.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTComment.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTComment.java
index 2efd4f7..8a16965 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTComment.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTComment.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST comment node
@@ -43,7 +43,7 @@ final class ASTComment extends ASTElement {
if (canonical) {
return "<#--" + text + "-->";
} else {
- return "comment " + _StringUtil.jQuote(text.trim());
+ return "comment " + _StringUtils.jQuote(text.trim());
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirAssignment.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirAssignment.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirAssignment.java
index db548cf..09bf4ea 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirAssignment.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirAssignment.java
@@ -22,7 +22,7 @@ package org.apache.freemarker.core;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: An instruction that makes a single assignment, like {@code <#local x=1>}, {@code <#global x=1>},
@@ -154,7 +154,7 @@ final class ASTDirAssignment extends ASTDirective {
} else { // Numerical operation
Number lhoNumber;
if (lhoValue instanceof TemplateNumberModel) {
- lhoNumber = _EvalUtil.modelToNumber((TemplateNumberModel) lhoValue, null);
+ lhoNumber = _EvalUtils.modelToNumber((TemplateNumberModel) lhoValue, null);
} else if (lhoValue == null) {
throw InvalidReferenceException.getInstance(variableName, getOperatorTypeAsString(), env);
} else {
@@ -191,7 +191,7 @@ final class ASTDirAssignment extends ASTDirective {
buf.append(' ');
}
- buf.append(_StringUtil.toFTLTopLevelTragetIdentifier(variableName));
+ buf.append(_StringUtils.toFTLTopLevelTragetIdentifier(variableName));
if (valueExp != null) {
buf.append(' ');
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirEscape.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirEscape.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirEscape.java
index 56414e4..7a324cd 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirEscape.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirEscape.java
@@ -22,7 +22,7 @@ package org.apache.freemarker.core;
import java.io.IOException;
import org.apache.freemarker.core.ASTExpression.ReplacemenetState;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: {@code #escape}.
@@ -60,7 +60,7 @@ class ASTDirEscape extends ASTDirective {
StringBuilder sb = new StringBuilder();
if (canonical) sb.append('<');
sb.append(getASTNodeDescriptor())
- .append(' ').append(_StringUtil.toFTLTopLevelIdentifierReference(variable))
+ .append(' ').append(_StringUtils.toFTLTopLevelIdentifierReference(variable))
.append(" as ").append(expr.getCanonicalForm());
if (canonical) {
sb.append('>');
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirImport.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirImport.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirImport.java
index db95913..79b320a 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirImport.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirImport.java
@@ -22,7 +22,7 @@ package org.apache.freemarker.core;
import java.io.IOException;
import org.apache.freemarker.core.templateresolver.MalformedTemplateNameException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: {@code #import}
@@ -75,7 +75,7 @@ final class ASTDirImport extends ASTDirective {
buf.append(' ');
buf.append(importedTemplateNameExp.getCanonicalForm());
buf.append(" as ");
- buf.append(_StringUtil.toFTLTopLevelTragetIdentifier(targetNsVarName));
+ buf.append(_StringUtils.toFTLTopLevelTragetIdentifier(targetNsVarName));
if (canonical) buf.append("/>");
return buf.toString();
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirInclude.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirInclude.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirInclude.java
index b458537..169541b 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirInclude.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirInclude.java
@@ -23,7 +23,7 @@ import java.io.IOException;
import org.apache.freemarker.core.templateresolver.MalformedTemplateNameException;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: {@code #include}
@@ -147,7 +147,7 @@ final class ASTDirInclude extends ASTDirective {
private boolean getYesNo(ASTExpression exp, String s) throws TemplateException {
try {
- return _StringUtil.getYesNo(s);
+ return _StringUtils.getYesNo(s);
} catch (IllegalArgumentException iae) {
throw new _MiscTemplateException(exp,
"Value must be boolean (or one of these strings: "
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirItems.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirItems.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirItems.java
index 7290153..0f2508b 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirItems.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirItems.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core;
import java.io.IOException;
import org.apache.freemarker.core.ASTDirList.IterationContext;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: {@code #items}
@@ -66,10 +66,10 @@ class ASTDirItems extends ASTDirective {
if (canonical) sb.append('<');
sb.append(getASTNodeDescriptor());
sb.append(" as ");
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(nestedContentParamName));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(nestedContentParamName));
if (nestedContentParam2Name != null) {
sb.append(", ");
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(nestedContentParam2Name));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(nestedContentParam2Name));
}
if (canonical) {
sb.append('>');
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirList.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirList.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirList.java
index 14c7189..40da397 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirList.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirList.java
@@ -35,7 +35,7 @@ import org.apache.freemarker.core.model.TemplateModelIterator;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.TemplateSequenceModel;
import org.apache.freemarker.core.model.impl.SimpleNumber;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: {@code #list} element, or pre-{@code #else} section of it inside a
@@ -130,10 +130,10 @@ final class ASTDirList extends ASTDirective {
buf.append(listedExp.getCanonicalForm());
if (nestedContentParamName != null) {
buf.append(" as ");
- buf.append(_StringUtil.toFTLTopLevelIdentifierReference(nestedContentParamName));
+ buf.append(_StringUtils.toFTLTopLevelIdentifierReference(nestedContentParamName));
if (nestedContentParam2Name != null) {
buf.append(", ");
- buf.append(_StringUtil.toFTLTopLevelIdentifierReference(nestedContentParam2Name));
+ buf.append(_StringUtils.toFTLTopLevelIdentifierReference(nestedContentParam2Name));
}
}
if (canonical) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirMacroOrFunction.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirMacroOrFunction.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirMacroOrFunction.java
index 6aecfff..344f86f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirMacroOrFunction.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirMacroOrFunction.java
@@ -28,7 +28,7 @@ import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateModelIterator;
import org.apache.freemarker.core.util.StringToIndexMap;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: {@code #macro} or {@code #function}
@@ -143,7 +143,7 @@ final class ASTDirMacroOrFunction extends ASTDirective implements TemplateModel
if (canonical) sb.append('<');
sb.append(getASTNodeDescriptor());
sb.append(' ');
- sb.append(_StringUtil.toFTLTopLevelTragetIdentifier(name));
+ sb.append(_StringUtils.toFTLTopLevelTragetIdentifier(name));
if (function) sb.append('(');
@@ -160,7 +160,7 @@ final class ASTDirMacroOrFunction extends ASTDirective implements TemplateModel
ParameterDefinition paramDef = paramDefsByArgArrayIdx[idx];
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(paramDef.name));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(paramDef.name));
if (!function) {
sb.append("{").append(POSITIONAL_PARAMETER_OPTION_NAME).append("}");
}
@@ -179,7 +179,7 @@ final class ASTDirMacroOrFunction extends ASTDirective implements TemplateModel
firstParam = false;
}
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(paramDefsByArgArrayIdx[posVarargsArgIdx].name));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(paramDefsByArgArrayIdx[posVarargsArgIdx].name));
if (!function) {
sb.append("{").append(POSITIONAL_PARAMETER_OPTION_NAME).append("}");
}
@@ -201,7 +201,7 @@ final class ASTDirMacroOrFunction extends ASTDirective implements TemplateModel
ParameterDefinition paramDef = paramDefsByArgArrayIdx[idx];
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(paramDef.name));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(paramDef.name));
if (function) {
sb.append("{").append(NAMED_PARAMETER_OPTION_NAME).append("}");
}
@@ -224,7 +224,7 @@ final class ASTDirMacroOrFunction extends ASTDirective implements TemplateModel
firstParam = false;
}
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(paramDefsByArgArrayIdx[namedVarargsArgIdx].name));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(paramDefsByArgArrayIdx[namedVarargsArgIdx].name));
if (function) {
sb.append("{").append(NAMED_PARAMETER_OPTION_NAME).append("}");
}
@@ -360,7 +360,7 @@ final class ASTDirMacroOrFunction extends ASTDirective implements TemplateModel
@Override
public String toString() {
return "ParameterDefinition(" +
- "name=" + _StringUtil.jQuote(name)
+ "name=" + _StringUtils.jQuote(name)
+ (defaultExpression != null ? ", default=" + defaultExpression.getCanonicalForm() : "")
+ ')';
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSetting.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSetting.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSetting.java
index 576b05a..2217a18 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSetting.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSetting.java
@@ -26,7 +26,7 @@ import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.util._SortedArraySet;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST directive node: {@code #setting}.
@@ -60,12 +60,12 @@ final class ASTDirSetting extends ASTDirective {
+ "supported.");
} else {
sb.append("Unknown setting name: ");
- sb.append(_StringUtil.jQuote(key)).append(".");
+ sb.append(_StringUtils.jQuote(key)).append(".");
String correctedKey;
if (key.indexOf('_') != -1) {
- sb.append(MessageUtil.FM3_SNAKE_CASE);
- correctedKey = _StringUtil.snakeCaseToCamelCase(key);
+ sb.append(MessageUtils.FM3_SNAKE_CASE);
+ correctedKey = _StringUtils.snakeCaseToCamelCase(key);
if (!SETTING_NAMES.contains(correctedKey)) {
if (key.equals("datetime_format")) {
correctedKey = "dateTimeFormat";
@@ -130,7 +130,7 @@ final class ASTDirSetting extends ASTDirective {
if (canonical) sb.append('<');
sb.append(getASTNodeDescriptor());
sb.append(' ');
- sb.append(_StringUtil.toFTLTopLevelTragetIdentifier(key));
+ sb.append(_StringUtils.toFTLTopLevelTragetIdentifier(key));
sb.append('=');
sb.append(value.getCanonicalForm());
if (canonical) sb.append("/>");
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSwitch.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSwitch.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSwitch.java
index 97d58c3..1d5d6ea 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSwitch.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDirSwitch.java
@@ -66,9 +66,9 @@ final class ASTDirSwitch extends ASTDirective {
processCase = true;
} else if (cas.condition != null) {
// Otherwise, if this case isn't the default, test it.
- processCase = _EvalUtil.compare(
+ processCase = _EvalUtils.compare(
searched,
- _EvalUtil.CMP_OP_EQUALS, "case==", cas.condition, cas.condition, env);
+ _EvalUtils.CMP_OP_EQUALS, "case==", cas.condition, cas.condition, env);
}
if (processCase) {
env.visit(cas);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDollarInterpolation.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDollarInterpolation.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDollarInterpolation.java
index a2c68e4..9003b07 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDollarInterpolation.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDollarInterpolation.java
@@ -95,7 +95,7 @@ final class ASTDollarInterpolation extends ASTInterpolation {
@Override
protected Object calculateInterpolatedStringOrMarkup(Environment env) throws TemplateException {
- return _EvalUtil.coerceModelToStringOrMarkup(escapedExpression.eval(env), escapedExpression, null, env);
+ return _EvalUtils.coerceModelToStringOrMarkup(escapedExpression.eval(env), escapedExpression, null, env);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDynamicTopLevelCall.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDynamicTopLevelCall.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDynamicTopLevelCall.java
index 7bf4737..7250620 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDynamicTopLevelCall.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTDynamicTopLevelCall.java
@@ -32,7 +32,7 @@ import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.util.BugException;
import org.apache.freemarker.core.util.CommonSupplier;
import org.apache.freemarker.core.util.StringToIndexMap;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@@ -149,7 +149,7 @@ class ASTDynamicTopLevelCall extends ASTDirective implements CallPlace {
StringBuilder sb = new StringBuilder();
if (canonical) sb.append('<');
sb.append('@');
- MessageUtil.appendExpressionAsUntearable(sb, callableValueExp);
+ MessageUtils.appendExpressionAsUntearable(sb, callableValueExp);
boolean nameIsInParen = sb.charAt(sb.length() - 1) == ')';
if (positionalArgs != null) {
for (int i = 0; i < positionalArgs.length; i++) {
@@ -163,7 +163,7 @@ class ASTDynamicTopLevelCall extends ASTDirective implements CallPlace {
if (namedArgs != null) {
for (NamedArgument namedArg : namedArgs) {
sb.append(' ');
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(namedArg.getName()));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(namedArg.getName()));
sb.append('=');
sb.append(namedArg.getValue().getCanonicalForm());
}
@@ -177,7 +177,7 @@ class ASTDynamicTopLevelCall extends ASTDirective implements CallPlace {
} else {
first = false;
}
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(nestedContentParamName));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(nestedContentParamName));
}
}
if (canonical) {
@@ -360,8 +360,8 @@ class ASTDynamicTopLevelCall extends ASTDirective implements CallPlace {
} catch (Exception e) {
throw new CallPlaceCustomDataInitializationException(
"Failed to initialize custom data for provider identity "
- + _StringUtil.tryToString(providerIdentity) + " via factory "
- + _StringUtil.tryToString(supplier), e);
+ + _StringUtils.tryToString(providerIdentity) + " via factory "
+ + _StringUtils.tryToString(supplier), e);
}
if (customData == null) {
throw new NullPointerException("CommonSupplier.get() has returned null");
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpAddOrConcat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpAddOrConcat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpAddOrConcat.java
index c303daa..4385dac 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpAddOrConcat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpAddOrConcat.java
@@ -68,8 +68,8 @@ final class ASTExpAddOrConcat extends ASTExpression {
ASTExpression rightExp, TemplateModel rightModel)
throws TemplateException {
if (leftModel instanceof TemplateNumberModel && rightModel instanceof TemplateNumberModel) {
- Number first = _EvalUtil.modelToNumber((TemplateNumberModel) leftModel, leftExp);
- Number second = _EvalUtil.modelToNumber((TemplateNumberModel) rightModel, rightExp);
+ Number first = _EvalUtils.modelToNumber((TemplateNumberModel) leftModel, leftExp);
+ Number second = _EvalUtils.modelToNumber((TemplateNumberModel) rightModel, rightExp);
return _evalOnNumbers(env, parent, first, second);
} else if (leftModel instanceof TemplateSequenceModel && rightModel instanceof TemplateSequenceModel) {
return new ConcatenatedSequence((TemplateSequenceModel) leftModel, (TemplateSequenceModel) rightModel);
@@ -80,7 +80,7 @@ final class ASTExpAddOrConcat extends ASTExpression {
// We try string addition first. If hash addition is possible, then instead of throwing exception
// we return null and do hash addition instead. (We can't simply give hash addition a priority, like
// with sequence addition above, as FTL strings are often also FTL hashes.)
- Object leftOMOrStr = _EvalUtil.coerceModelToStringOrMarkup(
+ Object leftOMOrStr = _EvalUtils.coerceModelToStringOrMarkup(
leftModel, leftExp, /* returnNullOnNonCoercableType = */ hashConcatPossible, null,
env);
if (leftOMOrStr == null) {
@@ -88,7 +88,7 @@ final class ASTExpAddOrConcat extends ASTExpression {
}
// Same trick with null return as above.
- Object rightOMOrStr = _EvalUtil.coerceModelToStringOrMarkup(
+ Object rightOMOrStr = _EvalUtils.coerceModelToStringOrMarkup(
rightModel, rightExp, /* returnNullOnNonCoercableType = */ hashConcatPossible, null,
env);
if (rightOMOrStr == null) {
@@ -100,18 +100,18 @@ final class ASTExpAddOrConcat extends ASTExpression {
return new SimpleScalar(((String) leftOMOrStr).concat((String) rightOMOrStr));
} else { // rightOMOrStr instanceof TemplateMarkupOutputModel
TemplateMarkupOutputModel<?> rightMO = (TemplateMarkupOutputModel<?>) rightOMOrStr;
- return _EvalUtil.concatMarkupOutputs(parent,
+ return _EvalUtils.concatMarkupOutputs(parent,
rightMO.getOutputFormat().fromPlainTextByEscaping((String) leftOMOrStr),
rightMO);
}
} else { // leftOMOrStr instanceof TemplateMarkupOutputModel
TemplateMarkupOutputModel<?> leftMO = (TemplateMarkupOutputModel<?>) leftOMOrStr;
if (rightOMOrStr instanceof String) { // markup output
- return _EvalUtil.concatMarkupOutputs(parent,
+ return _EvalUtils.concatMarkupOutputs(parent,
leftMO,
leftMO.getOutputFormat().fromPlainTextByEscaping((String) rightOMOrStr));
} else { // rightOMOrStr instanceof TemplateMarkupOutputModel
- return _EvalUtil.concatMarkupOutputs(parent,
+ return _EvalUtils.concatMarkupOutputs(parent,
leftMO,
(TemplateMarkupOutputModel<?>) rightOMOrStr);
}
@@ -148,7 +148,7 @@ final class ASTExpAddOrConcat extends ASTExpression {
static TemplateModel _evalOnNumbers(Environment env, ASTNode parent, Number first, Number second)
throws TemplateException {
- ArithmeticEngine ae = _EvalUtil.getArithmeticEngine(env, parent);
+ ArithmeticEngine ae = _EvalUtils.getArithmeticEngine(env, parent);
return new SimpleNumber(ae.add(first, second));
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpArithmetic.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpArithmetic.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpArithmetic.java
index 99fd7f0..e05a72c 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpArithmetic.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpArithmetic.java
@@ -53,7 +53,7 @@ final class ASTExpArithmetic extends ASTExpression {
static TemplateModel _eval(Environment env, ASTNode parent, Number lhoNumber, int operator, Number rhoNumber)
throws TemplateException {
- ArithmeticEngine ae = _EvalUtil.getArithmeticEngine(env, parent);
+ ArithmeticEngine ae = _EvalUtils.getArithmeticEngine(env, parent);
switch (operator) {
case TYPE_SUBSTRACTION :
return new SimpleNumber(ae.subtract(lhoNumber, rhoNumber));
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBooleanLiteral.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBooleanLiteral.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBooleanLiteral.java
index 8525ea3..0cb9c50 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBooleanLiteral.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBooleanLiteral.java
@@ -44,7 +44,7 @@ final class ASTExpBooleanLiteral extends ASTExpression {
@Override
public String getCanonicalForm() {
- return val ? MiscUtil.C_TRUE : MiscUtil.C_FALSE;
+ return val ? TemplateBooleanFormat.C_TRUE : TemplateBooleanFormat.C_FALSE;
}
@Override
@@ -54,7 +54,7 @@ final class ASTExpBooleanLiteral extends ASTExpression {
@Override
public String toString() {
- return val ? MiscUtil.C_TRUE : MiscUtil.C_FALSE;
+ return val ? TemplateBooleanFormat.C_TRUE : TemplateBooleanFormat.C_FALSE;
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltIn.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltIn.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltIn.java
index c69c297..7e93646 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltIn.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltIn.java
@@ -66,8 +66,8 @@ import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateNumberModel;
import org.apache.freemarker.core.model.TemplateScalarModel;
-import org.apache.freemarker.core.util._DateUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._DateUtils;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST expression node: {@code exp?name}
@@ -151,66 +151,66 @@ abstract class ASTExpBuiltIn extends ASTExpression implements Cloneable {
putBI("isTime", new BuiltInsForMultipleTypes.is_dateOfTypeBI(TemplateDateModel.TIME));
putBI("isoUtc", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_SECONDS, /* useUTC = */ true));
+ /* showOffset = */ null, _DateUtils.ACCURACY_SECONDS, /* useUTC = */ true));
putBI("isoUtcFZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.TRUE, _DateUtil.ACCURACY_SECONDS, /* useUTC = */ true));
+ /* showOffset = */ Boolean.TRUE, _DateUtils.ACCURACY_SECONDS, /* useUTC = */ true));
putBI("isoUtcNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_SECONDS, /* useUTC = */ true));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_SECONDS, /* useUTC = */ true));
putBI("isoUtcMs", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_MILLISECONDS, /* useUTC = */ true));
+ /* showOffset = */ null, _DateUtils.ACCURACY_MILLISECONDS, /* useUTC = */ true));
putBI("isoUtcMsNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_MILLISECONDS, /* useUTC = */ true));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_MILLISECONDS, /* useUTC = */ true));
putBI("isoUtcM", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_MINUTES, /* useUTC = */ true));
+ /* showOffset = */ null, _DateUtils.ACCURACY_MINUTES, /* useUTC = */ true));
putBI("isoUtcMNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_MINUTES, /* useUTC = */ true));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_MINUTES, /* useUTC = */ true));
putBI("isoUtcH", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_HOURS, /* useUTC = */ true));
+ /* showOffset = */ null, _DateUtils.ACCURACY_HOURS, /* useUTC = */ true));
putBI("isoUtcHNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_HOURS, /* useUTC = */ true));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_HOURS, /* useUTC = */ true));
putBI("isoLocal", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_SECONDS, /* useUTC = */ false));
+ /* showOffset = */ null, _DateUtils.ACCURACY_SECONDS, /* useUTC = */ false));
putBI("isoLocalNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_SECONDS, /* useUTC = */ false));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_SECONDS, /* useUTC = */ false));
putBI("isoLocalMs", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_MILLISECONDS, /* useUTC = */ false));
+ /* showOffset = */ null, _DateUtils.ACCURACY_MILLISECONDS, /* useUTC = */ false));
putBI("isoLocalMsNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_MILLISECONDS, /* useUTC = */ false));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_MILLISECONDS, /* useUTC = */ false));
putBI("isoLocalM", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_MINUTES, /* useUTC = */ false));
+ /* showOffset = */ null, _DateUtils.ACCURACY_MINUTES, /* useUTC = */ false));
putBI("isoLocalMNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_MINUTES, /* useUTC = */ false));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_MINUTES, /* useUTC = */ false));
putBI("isoLocalH", new iso_utc_or_local_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_HOURS, /* useUTC = */ false));
+ /* showOffset = */ null, _DateUtils.ACCURACY_HOURS, /* useUTC = */ false));
putBI("isoLocalHNZ", new iso_utc_or_local_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_HOURS, /* useUTC = */ false));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_HOURS, /* useUTC = */ false));
putBI("iso", new iso_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_SECONDS));
+ /* showOffset = */ null, _DateUtils.ACCURACY_SECONDS));
putBI("isoNZ", new iso_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_SECONDS));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_SECONDS));
putBI("isoMs", new iso_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_MILLISECONDS));
+ /* showOffset = */ null, _DateUtils.ACCURACY_MILLISECONDS));
putBI("isoMsNZ", new iso_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_MILLISECONDS));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_MILLISECONDS));
putBI("isoM", new iso_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_MINUTES));
+ /* showOffset = */ null, _DateUtils.ACCURACY_MINUTES));
putBI("isoMNZ", new iso_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_MINUTES));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_MINUTES));
putBI("isoH", new iso_BI(
- /* showOffset = */ null, _DateUtil.ACCURACY_HOURS));
+ /* showOffset = */ null, _DateUtils.ACCURACY_HOURS));
putBI("isoHNZ", new iso_BI(
- /* showOffset = */ Boolean.FALSE, _DateUtil.ACCURACY_HOURS));
+ /* showOffset = */ Boolean.FALSE, _DateUtils.ACCURACY_HOURS));
putBI("jString", new BuiltInsForStringsEncoding.j_stringBI());
putBI("join", new BuiltInsForSequences.joinBI());
@@ -301,12 +301,12 @@ abstract class ASTExpBuiltIn extends ASTExpression implements Cloneable {
String key = keyTk.image;
ASTExpBuiltIn bi = BUILT_INS_BY_NAME.get(key);
if (bi == null) {
- StringBuilder sb = new StringBuilder("Unknown built-in: ").append(_StringUtil.jQuote(key)).append(".");
+ StringBuilder sb = new StringBuilder("Unknown built-in: ").append(_StringUtils.jQuote(key)).append(".");
String correctedKey;
if (key.indexOf("_") != -1) {
- sb.append(MessageUtil.FM3_SNAKE_CASE);
- correctedKey = _StringUtil.snakeCaseToCamelCase(key);
+ sb.append(MessageUtils.FM3_SNAKE_CASE);
+ correctedKey = _StringUtils.snakeCaseToCamelCase(key);
if (!BUILT_INS_BY_NAME.containsKey(correctedKey)) {
if (correctedKey.length() > 1) {
correctedKey = correctedKey.substring(0, correctedKey.length() - 2)
@@ -397,7 +397,7 @@ abstract class ASTExpBuiltIn extends ASTExpression implements Cloneable {
protected final void checkMethodArgCount(int argCnt, int expectedCnt) throws TemplateModelException {
if (argCnt != expectedCnt) {
- throw MessageUtil.newArgCntError("?" + key, argCnt, expectedCnt);
+ throw MessageUtils.newArgCntError("?" + key, argCnt, expectedCnt);
}
}
@@ -412,7 +412,7 @@ abstract class ASTExpBuiltIn extends ASTExpression implements Cloneable {
protected final void checkMethodArgCount(int argCnt, int minCnt, int maxCnt) throws TemplateModelException {
if (argCnt < minCnt || argCnt > maxCnt) {
- throw MessageUtil.newArgCntError("?" + key, argCnt, minCnt, maxCnt);
+ throw MessageUtils.newArgCntError("?" + key, argCnt, minCnt, maxCnt);
}
}
@@ -440,9 +440,9 @@ abstract class ASTExpBuiltIn extends ASTExpression implements Cloneable {
if (optional && arg == null) {
return null;
}
- throw MessageUtil.newMethodArgMustBeStringException("?" + key, argIdx, arg);
+ throw MessageUtils.newMethodArgMustBeStringException("?" + key, argIdx, arg);
} else {
- return _EvalUtil.modelToString((TemplateScalarModel) arg, null, null);
+ return _EvalUtils.modelToString((TemplateScalarModel) arg, null, null);
}
}
@@ -471,18 +471,18 @@ abstract class ASTExpBuiltIn extends ASTExpression implements Cloneable {
if (optional && arg == null) {
return null;
}
- throw MessageUtil.newMethodArgMustBeNumberException("?" + key, argIdx, arg);
+ throw MessageUtils.newMethodArgMustBeNumberException("?" + key, argIdx, arg);
} else {
- return _EvalUtil.modelToNumber((TemplateNumberModel) arg, null);
+ return _EvalUtils.modelToNumber((TemplateNumberModel) arg, null);
}
}
protected final TemplateModelException newMethodArgInvalidValueException(int argIdx, Object[] details) {
- return MessageUtil.newMethodArgInvalidValueException("?" + key, argIdx, details);
+ return MessageUtils.newMethodArgInvalidValueException("?" + key, argIdx, details);
}
protected final TemplateModelException newMethodArgsInvalidValueException(Object[] details) {
- return MessageUtil.newMethodArgsInvalidValueException("?" + key, details);
+ return MessageUtils.newMethodArgsInvalidValueException("?" + key, details);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltInVariable.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltInVariable.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltInVariable.java
index ab50470..d48135e 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltInVariable.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpBuiltInVariable.java
@@ -30,7 +30,7 @@ import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.impl.SimpleDate;
import org.apache.freemarker.core.model.impl.SimpleScalar;
import org.apache.freemarker.core.util._SortedArraySet;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST expression node: {@code .name}
@@ -94,12 +94,12 @@ final class ASTExpBuiltInVariable extends ASTExpression {
if (!BUILT_IN_VARIABLE_NAMES.contains(name)) {
StringBuilder sb = new StringBuilder();
sb.append("Unknown special variable name: ");
- sb.append(_StringUtil.jQuote(name)).append(".");
+ sb.append(_StringUtils.jQuote(name)).append(".");
String correctedName;
if (name.indexOf('_') != -1) {
- sb.append(MessageUtil.FM3_SNAKE_CASE);
- correctedName = _StringUtil.snakeCaseToCamelCase(name);
+ sb.append(MessageUtils.FM3_SNAKE_CASE);
+ correctedName = _StringUtils.snakeCaseToCamelCase(name);
if (!BUILT_IN_VARIABLE_NAMES.contains(correctedName)) {
correctedName = null;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpComparison.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpComparison.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpComparison.java
index 7629a94..4f429ac 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpComparison.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpComparison.java
@@ -37,17 +37,17 @@ final class ASTExpComparison extends ASTExpBoolean {
opString = opString.intern();
this.opString = opString;
if (opString == "==") {
- operation = _EvalUtil.CMP_OP_EQUALS;
+ operation = _EvalUtils.CMP_OP_EQUALS;
} else if (opString == "!=") {
- operation = _EvalUtil.CMP_OP_NOT_EQUALS;
+ operation = _EvalUtils.CMP_OP_NOT_EQUALS;
} else if (opString == "gt" || opString == "\\gt" || opString == ">" || opString == ">") {
- operation = _EvalUtil.CMP_OP_GREATER_THAN;
+ operation = _EvalUtils.CMP_OP_GREATER_THAN;
} else if (opString == "gte" || opString == "\\gte" || opString == ">=" || opString == ">=") {
- operation = _EvalUtil.CMP_OP_GREATER_THAN_EQUALS;
+ operation = _EvalUtils.CMP_OP_GREATER_THAN_EQUALS;
} else if (opString == "lt" || opString == "\\lt" || opString == "<" || opString == "<") {
- operation = _EvalUtil.CMP_OP_LESS_THAN;
+ operation = _EvalUtils.CMP_OP_LESS_THAN;
} else if (opString == "lte" || opString == "\\lte" || opString == "<=" || opString == "<=") {
- operation = _EvalUtil.CMP_OP_LESS_THAN_EQUALS;
+ operation = _EvalUtils.CMP_OP_LESS_THAN_EQUALS;
} else {
throw new BugException("Unknown comparison operator " + opString);
}
@@ -59,7 +59,7 @@ final class ASTExpComparison extends ASTExpBoolean {
*/
@Override
boolean evalToBoolean(Environment env) throws TemplateException {
- return _EvalUtil.compare(left, operation, opString, right, this, env);
+ return _EvalUtils.compare(left, operation, opString, right, this, env);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDot.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDot.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDot.java
index 8fc6a82..c1da34e 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDot.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDot.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core;
import org.apache.freemarker.core.model.TemplateHashModel;
import org.apache.freemarker.core.model.TemplateModel;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST expression node: {@code .} operator.
@@ -46,7 +46,7 @@ final class ASTExpDot extends ASTExpression {
@Override
public String getCanonicalForm() {
- return target.getCanonicalForm() + getASTNodeDescriptor() + _StringUtil.toFTLIdentifierReferenceAfterDot(key);
+ return target.getCanonicalForm() + getASTNodeDescriptor() + _StringUtils.toFTLIdentifierReferenceAfterDot(key);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDynamicKeyName.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDynamicKeyName.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDynamicKeyName.java
index 416019c..c69972f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDynamicKeyName.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpDynamicKeyName.java
@@ -52,7 +52,7 @@ final class ASTExpDynamicKeyName extends ASTExpression {
return dealWithNumericalKey(targetModel, index, env);
}
if (keyModel instanceof TemplateScalarModel) {
- String key = _EvalUtil.modelToString((TemplateScalarModel) keyModel, keyExpression, env);
+ String key = _EvalUtils.modelToString((TemplateScalarModel) keyModel, keyExpression, env);
return dealWithStringKey(targetModel, key, env);
}
if (keyModel instanceof RangeModel) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpFunctionCall.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpFunctionCall.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpFunctionCall.java
index 5101db7..391e5a7 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpFunctionCall.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpFunctionCall.java
@@ -30,7 +30,7 @@ import org.apache.freemarker.core._CallableUtils.NamedArgument;
import org.apache.freemarker.core.model.TemplateFunctionModel;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.util.CommonSupplier;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
@@ -97,7 +97,7 @@ final class ASTExpFunctionCall extends ASTExpression implements CallPlace {
} else {
first = false;
}
- sb.append(_StringUtil.toFTLTopLevelIdentifierReference(namedArg.getName()));
+ sb.append(_StringUtils.toFTLTopLevelIdentifierReference(namedArg.getName()));
sb.append('=');
sb.append(namedArg.getValue().getCanonicalForm());
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpStringLiteral.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpStringLiteral.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpStringLiteral.java
index b66eb1d..0dbcfb1 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpStringLiteral.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpStringLiteral.java
@@ -105,7 +105,7 @@ final class ASTExpStringLiteral extends ASTExpression implements TemplateScalarM
TemplateMarkupOutputModel<?> partMO = calcedPart instanceof String
? markupResult.getOutputFormat().fromPlainTextByEscaping((String) calcedPart)
: (TemplateMarkupOutputModel<?>) calcedPart;
- markupResult = _EvalUtil.concatMarkupOutputs(this, markupResult, partMO);
+ markupResult = _EvalUtils.concatMarkupOutputs(this, markupResult, partMO);
} else { // We are using `plainTextOutput` (or nothing yet)
if (calcedPart instanceof String) {
String partStr = (String) calcedPart;
@@ -119,7 +119,7 @@ final class ASTExpStringLiteral extends ASTExpression implements TemplateScalarM
if (plainTextResult != null) {
TemplateMarkupOutputModel<?> leftHandMO = moPart.getOutputFormat()
.fromPlainTextByEscaping(plainTextResult.toString());
- markupResult = _EvalUtil.concatMarkupOutputs(this, leftHandMO, moPart);
+ markupResult = _EvalUtils.concatMarkupOutputs(this, leftHandMO, moPart);
plainTextResult = null;
} else {
markupResult = moPart;
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpVariable.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpVariable.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpVariable.java
index e4a2327..890563f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpVariable.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpVariable.java
@@ -20,7 +20,7 @@
package org.apache.freemarker.core;
import org.apache.freemarker.core.model.TemplateModel;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST expression node: Reference to a "top-level" (local, current namespace, global, data-model) variable
@@ -50,7 +50,7 @@ final class ASTExpVariable extends ASTExpression {
@Override
public String getCanonicalForm() {
- return _StringUtil.toFTLTopLevelIdentifierReference(name);
+ return _StringUtils.toFTLTopLevelIdentifierReference(name);
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpression.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpression.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpression.java
index be00f66..97f82a5 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpression.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTExpression.java
@@ -72,36 +72,36 @@ abstract class ASTExpression extends ASTNode {
}
String evalAndCoerceToPlainText(Environment env) throws TemplateException {
- return _EvalUtil.coerceModelToPlainText(eval(env), this, null, env);
+ return _EvalUtils.coerceModelToPlainText(eval(env), this, null, env);
}
/**
* @param seqTip Tip to display if the value type is not coercable, but it's sequence or collection.
*/
String evalAndCoerceToPlainText(Environment env, String seqTip) throws TemplateException {
- return _EvalUtil.coerceModelToPlainText(eval(env), this, seqTip, env);
+ return _EvalUtils.coerceModelToPlainText(eval(env), this, seqTip, env);
}
Object evalAndCoerceToStringOrMarkup(Environment env) throws TemplateException {
- return _EvalUtil.coerceModelToStringOrMarkup(eval(env), this, null, env);
+ return _EvalUtils.coerceModelToStringOrMarkup(eval(env), this, null, env);
}
/**
* @param seqTip Tip to display if the value type is not coercable, but it's sequence or collection.
*/
Object evalAndCoerceToStringOrMarkup(Environment env, String seqTip) throws TemplateException {
- return _EvalUtil.coerceModelToStringOrMarkup(eval(env), this, seqTip, env);
+ return _EvalUtils.coerceModelToStringOrMarkup(eval(env), this, seqTip, env);
}
String evalAndCoerceToStringOrUnsupportedMarkup(Environment env) throws TemplateException {
- return _EvalUtil.coerceModelToStringOrUnsupportedMarkup(eval(env), this, null, env);
+ return _EvalUtils.coerceModelToStringOrUnsupportedMarkup(eval(env), this, null, env);
}
/**
* @param seqTip Tip to display if the value type is not coercable, but it's sequence or collection.
*/
String evalAndCoerceToStringOrUnsupportedMarkup(Environment env, String seqTip) throws TemplateException {
- return _EvalUtil.coerceModelToStringOrUnsupportedMarkup(eval(env), this, seqTip, env);
+ return _EvalUtils.coerceModelToStringOrUnsupportedMarkup(eval(env), this, seqTip, env);
}
Number evalToNumber(Environment env) throws TemplateException {
@@ -111,7 +111,7 @@ abstract class ASTExpression extends ASTNode {
Number modelToNumber(TemplateModel model, Environment env) throws TemplateException {
if (model instanceof TemplateNumberModel) {
- return _EvalUtil.modelToNumber((TemplateNumberModel) model, this);
+ return _EvalUtils.modelToNumber((TemplateNumberModel) model, this);
} else {
throw new NonNumericalException(this, model, env);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTNode.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTNode.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTNode.java
index 6a2ce15..4ca9b7f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTNode.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTNode.java
@@ -88,7 +88,7 @@ abstract class ASTNode {
* where in the template source, this object is.
*/
public String getStartLocation() {
- return MessageUtil.formatLocationForEvaluationError(template, beginLine, beginColumn);
+ return MessageUtils.formatLocationForEvaluationError(template, beginLine, beginColumn);
}
/**
@@ -100,7 +100,7 @@ abstract class ASTNode {
}
public String getEndLocation() {
- return MessageUtil.formatLocationForEvaluationError(template, endLine, endColumn);
+ return MessageUtils.formatLocationForEvaluationError(template, endLine, endColumn);
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/ASTStaticText.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTStaticText.java b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTStaticText.java
index eceb412..76f1019 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/ASTStaticText.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/ASTStaticText.java
@@ -21,8 +21,8 @@ package org.apache.freemarker.core;
import java.io.IOException;
-import org.apache.freemarker.core.util._CollectionUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
+import org.apache.freemarker.core.util._StringUtils;
/**
* AST node representing static text.
@@ -76,7 +76,7 @@ final class ASTStaticText extends ASTElement {
}
return text;
} else {
- return "text " + _StringUtil.jQuote(new String(text));
+ return "text " + _StringUtils.jQuote(new String(text));
}
}
@@ -155,7 +155,7 @@ final class ASTStaticText extends ASTElement {
if (lastNewLineIndex >= 0 || beginColumn == 1) {
char[] firstPart = substring(text, 0, lastNewLineIndex + 1);
char[] lastLine = substring(text, 1 + lastNewLineIndex);
- if (_StringUtil.isTrimmableToEmpty(lastLine)) {
+ if (_StringUtils.isTrimmableToEmpty(lastLine)) {
text = firstPart;
endColumn = 0;
} else {
@@ -200,7 +200,7 @@ final class ASTStaticText extends ASTElement {
}
char[] trailingPart = substring(text, firstLineIndex);
char[] openingPart = substring(text, 0, firstLineIndex);
- if (_StringUtil.isTrimmableToEmpty(openingPart)) {
+ if (_StringUtils.isTrimmableToEmpty(openingPart)) {
text = trailingPart;
beginLine++;
beginColumn = 1;
@@ -210,7 +210,7 @@ final class ASTStaticText extends ASTElement {
lastNonWS--;
}
char[] printablePart = substring(text, 0, lastNonWS + 1);
- if (_StringUtil.isTrimmableToEmpty(trailingPart)) {
+ if (_StringUtils.isTrimmableToEmpty(trailingPart)) {
// THIS BLOCK IS HEINOUS! THERE MUST BE A BETTER WAY! REVISIT (JR)
boolean trimTrailingPart = true;
for (ASTElement te = nextTerminalNode();
@@ -224,7 +224,7 @@ final class ASTStaticText extends ASTElement {
break;
}
}
- if (trimTrailingPart) trailingPart = _CollectionUtil.EMPTY_CHAR_ARRAY;
+ if (trimTrailingPart) trailingPart = _CollectionUtils.EMPTY_CHAR_ARRAY;
}
text = concat(printablePart, trailingPart);
}
@@ -271,7 +271,7 @@ final class ASTStaticText extends ASTElement {
++newlineIndex;
}
}
- if (!_StringUtil.isTrimmableToEmpty(text, 0, newlineIndex)) {
+ if (!_StringUtils.isTrimmableToEmpty(text, 0, newlineIndex)) {
return 0;
}
// We look at the preceding elements on the line to see if we should
@@ -295,7 +295,7 @@ final class ASTStaticText extends ASTElement {
if (lastNewlineIndex == -1 && beginColumn != 1) {
return 0;
}
- if (!_StringUtil.isTrimmableToEmpty(text, lastNewlineIndex + 1)) {
+ if (!_StringUtils.isTrimmableToEmpty(text, lastNewlineIndex + 1)) {
return 0;
}
// We look at the elements afterward on the same line to see if we should
@@ -349,7 +349,7 @@ final class ASTStaticText extends ASTElement {
return true;
}
if (stripWhitespace) {
- if (!_StringUtil.isTrimmableToEmpty(text)) {
+ if (!_StringUtils.isTrimmableToEmpty(text)) {
return false;
}
ASTElement parentElement = getParent();
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForDate.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForDate.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForDate.java
index 33971f5..44fda23 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForDate.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForDate.java
@@ -31,7 +31,7 @@ abstract class BuiltInForDate extends ASTExpBuiltIn {
TemplateModel model = target.eval(env);
if (model instanceof TemplateDateModel) {
TemplateDateModel tdm = (TemplateDateModel) model;
- return calculateResult(_EvalUtil.modelToDate(tdm, target), tdm.getDateType(), env);
+ return calculateResult(_EvalUtils.modelToDate(tdm, target), tdm.getDateType(), env);
} else {
throw newNonDateException(env, model, target);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForLegacyEscaping.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForLegacyEscaping.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForLegacyEscaping.java
index 8cdcbf6..e1f46d1 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForLegacyEscaping.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInForLegacyEscaping.java
@@ -31,7 +31,7 @@ abstract class BuiltInForLegacyEscaping extends BuiltInBannedWhenAutoEscaping {
TemplateModel _eval(Environment env)
throws TemplateException {
TemplateModel tm = target.eval(env);
- Object moOrStr = _EvalUtil.coerceModelToStringOrMarkup(tm, target, null, env);
+ Object moOrStr = _EvalUtils.coerceModelToStringOrMarkup(tm, target, null, env);
if (moOrStr instanceof String) {
return calculateResult((String) moOrStr, env);
} else {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForDates.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForDates.java b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForDates.java
index 3760c77..829c5fa 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForDates.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/BuiltInsForDates.java
@@ -31,7 +31,7 @@ import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.impl.SimpleDate;
import org.apache.freemarker.core.model.impl.SimpleScalar;
import org.apache.freemarker.core.util.UnrecognizedTimeZoneException;
-import org.apache.freemarker.core.util._DateUtil;
+import org.apache.freemarker.core.util._DateUtils;
/**
* A holder for built-ins that operate exclusively on date left-hand values.
@@ -56,7 +56,7 @@ class BuiltInsForDates {
if (tdmDateType != TemplateDateModel.UNKNOWN) {
return tdm;
}
- return new SimpleDate(_EvalUtil.modelToDate(tdm, target), dateType);
+ return new SimpleDate(_EvalUtils.modelToDate(tdm, target), dateType);
} else {
throw BuiltInForDate.newNonDateException(env, model, target);
}
@@ -94,9 +94,9 @@ class BuiltInsForDates {
instanceof TimeZone) {
tzArg = (TimeZone) adaptedObj;
} else if (tzArgTM instanceof TemplateScalarModel) {
- String tzName = _EvalUtil.modelToString((TemplateScalarModel) tzArgTM, null, null);
+ String tzName = _EvalUtils.modelToString((TemplateScalarModel) tzArgTM, null, null);
try {
- tzArg = _DateUtil.getTimeZone(tzName);
+ tzArg = _DateUtils.getTimeZone(tzName);
} catch (UnrecognizedTimeZoneException e) {
throw new _TemplateModelException(
"The time zone string specified for ?", key,
@@ -104,11 +104,11 @@ class BuiltInsForDates {
new _DelayedJQuote(tzName));
}
} else {
- throw MessageUtil.newMethodArgUnexpectedTypeException(
+ throw MessageUtils.newMethodArgUnexpectedTypeException(
"?" + key, 0, "string or java.util.TimeZone", tzArgTM);
}
- return new SimpleScalar(_DateUtil.dateToISO8601String(
+ return new SimpleScalar(_DateUtils.dateToISO8601String(
date,
dateType != TemplateDateModel.TIME,
dateType != TemplateDateModel.DATE,
@@ -157,14 +157,14 @@ class BuiltInsForDates {
Date date, int dateType, Environment env)
throws TemplateException {
checkDateTypeNotUnknown(dateType);
- return new SimpleScalar(_DateUtil.dateToISO8601String(
+ return new SimpleScalar(_DateUtils.dateToISO8601String(
date,
dateType != TemplateDateModel.TIME,
dateType != TemplateDateModel.DATE,
shouldShowOffset(date, dateType, env),
accuracy,
useUTC
- ? _DateUtil.UTC
+ ? _DateUtils.UTC
: env.shouldUseSQLDTTZ(date.getClass())
? env.getSQLDateAndTimeTimeZone()
: env.getTimeZone(),
@@ -191,7 +191,7 @@ class BuiltInsForDates {
throw new _MiscTemplateException(new _ErrorDescriptionBuilder(
"The value of the following has unknown date type, but ?", key,
" needs a value where it's known if it's a date (no time part), time, or date-time value:"
- ).blame(target).tip(MessageUtil.UNKNOWN_DATE_TYPE_ERROR_TIP));
+ ).blame(target).tip(MessageUtils.UNKNOWN_DATE_TYPE_ERROR_TIP));
}
}
[17/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
Renamed XxxUtil classes to XxxUtils, as this convention is more widespread nowadays.
Project: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/commit/ebb39b84
Tree: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/tree/ebb39b84
Diff: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/diff/ebb39b84
Branch: refs/heads/3
Commit: ebb39b8457918dcf58211edeb45e6eaaf6e0b0dc
Parents: cfd3796
Author: ddekany <dd...@apache.org>
Authored: Tue Aug 8 19:56:35 2017 +0200
Committer: ddekany <dd...@apache.org>
Committed: Tue Aug 8 19:56:35 2017 +0200
----------------------------------------------------------------------
.../core/FM2ASTToFM3SourceConverter.java | 22 +-
.../core/UnexpectedNodeContentException.java | 6 +-
.../apache/freemarker/converter/Converter.java | 4 +-
.../freemarker/converter/ConverterUtilTest.java | 24 -
.../org/apache/freemarker/core/ASTPrinter.java | 10 +-
.../org/apache/freemarker/core/ASTTest.java | 8 +-
.../freemarker/core/ConfigurationTest.java | 10 +-
.../freemarker/core/CoreLocaleUtilsTest.java | 22 +-
...leParsingAndProcessingConfigurationTest.java | 4 +-
.../MutableProcessingConfigurationTest.java | 30 +-
.../core/ParsingErrorMessagesTest.java | 6 +-
.../apache/freemarker/core/SQLTimeZoneTest.java | 10 +-
.../core/TagSyntaxVariationsTest.java | 6 +-
.../DefaultObjectWrapperSingletonsTest.java | 4 +-
.../core/model/impl/IsApplicableTest.java | 2 +-
.../impl/IsMoreSpecificParameterTypeTest.java | 100 +-
.../model/impl/MiscNumericalOperationsTest.java | 2 +-
.../model/impl/ModelAPINewInstanceTest.java | 6 +-
.../model/impl/OverloadedNumberUtilTest.java | 585 -------
.../model/impl/OverloadedNumberUtilsTest.java | 585 +++++++
.../impl/ParameterListPreferabilityTest.java | 12 +-
.../templatesuite/models/JavaObjectInfo.java | 4 +-
.../models/OverloadedMethods2.java | 146 +-
.../BaseNTemplateNumberFormatFactory.java | 10 +-
.../core/userpkg/CustomHTMLOutputFormat.java | 4 +-
...EpochMillisDivTemplateDateFormatFactory.java | 4 +-
.../HTMLISOTemplateDateFormatFactory.java | 18 +-
.../userpkg/HexTemplateNumberFormatFactory.java | 4 +-
.../PrintfGTemplateNumberFormatFactory.java | 4 +-
.../core/userpkg/TestTemplateCallableModel.java | 4 +-
.../core/util/CollectionUtilTest.java | 43 -
.../core/util/CollectionUtilsTest.java | 43 +
.../freemarker/core/util/DateUtilTest.java | 1085 ------------
.../freemarker/core/util/DateUtilsTest.java | 1085 ++++++++++++
.../freemarker/core/util/NumberUtilTest.java | 215 ---
.../freemarker/core/util/NumberUtilsTest.java | 215 +++
.../freemarker/core/util/StringUtilTest.java | 416 -----
.../freemarker/core/util/StringUtilsTest.java | 416 +++++
.../org/apache/freemarker/core/ASTComment.java | 4 +-
.../freemarker/core/ASTDirAssignment.java | 6 +-
.../apache/freemarker/core/ASTDirEscape.java | 4 +-
.../apache/freemarker/core/ASTDirImport.java | 4 +-
.../apache/freemarker/core/ASTDirInclude.java | 4 +-
.../org/apache/freemarker/core/ASTDirItems.java | 6 +-
.../org/apache/freemarker/core/ASTDirList.java | 6 +-
.../freemarker/core/ASTDirMacroOrFunction.java | 14 +-
.../apache/freemarker/core/ASTDirSetting.java | 10 +-
.../apache/freemarker/core/ASTDirSwitch.java | 4 +-
.../freemarker/core/ASTDollarInterpolation.java | 2 +-
.../freemarker/core/ASTDynamicTopLevelCall.java | 12 +-
.../freemarker/core/ASTExpAddOrConcat.java | 16 +-
.../freemarker/core/ASTExpArithmetic.java | 2 +-
.../freemarker/core/ASTExpBooleanLiteral.java | 4 +-
.../apache/freemarker/core/ASTExpBuiltIn.java | 76 +-
.../freemarker/core/ASTExpBuiltInVariable.java | 8 +-
.../freemarker/core/ASTExpComparison.java | 14 +-
.../org/apache/freemarker/core/ASTExpDot.java | 4 +-
.../freemarker/core/ASTExpDynamicKeyName.java | 2 +-
.../freemarker/core/ASTExpFunctionCall.java | 4 +-
.../freemarker/core/ASTExpStringLiteral.java | 4 +-
.../apache/freemarker/core/ASTExpVariable.java | 4 +-
.../apache/freemarker/core/ASTExpression.java | 14 +-
.../org/apache/freemarker/core/ASTNode.java | 4 +-
.../apache/freemarker/core/ASTStaticText.java | 20 +-
.../apache/freemarker/core/BuiltInForDate.java | 2 +-
.../core/BuiltInForLegacyEscaping.java | 2 +-
.../freemarker/core/BuiltInsForDates.java | 18 +-
.../core/BuiltInsForMultipleTypes.java | 18 +-
.../freemarker/core/BuiltInsForNodes.java | 4 +-
.../freemarker/core/BuiltInsForNumbers.java | 16 +-
.../core/BuiltInsForOutputFormatRelated.java | 2 +-
.../freemarker/core/BuiltInsForSequences.java | 16 +-
.../core/BuiltInsForStringsBasic.java | 20 +-
.../core/BuiltInsForStringsEncoding.java | 22 +-
.../freemarker/core/BuiltInsForStringsMisc.java | 20 +-
.../core/BuiltInsForStringsRegexp.java | 4 +-
.../core/BuiltInsWithParseTimeParameters.java | 4 +-
.../apache/freemarker/core/Configuration.java | 48 +-
.../core/CoreSettingValueNotSetException.java | 4 +-
.../core/CustomSettingValueNotSetException.java | 4 +-
.../org/apache/freemarker/core/Environment.java | 62 +-
.../core/InvalidSettingNameException.java | 8 +-
.../core/InvalidSettingValueException.java | 6 +-
.../org/apache/freemarker/core/MessageUtil.java | 344 ----
.../apache/freemarker/core/MessageUtils.java | 344 ++++
.../org/apache/freemarker/core/MiscUtil.java | 69 -
...utableParsingAndProcessingConfiguration.java | 6 +-
.../core/MutableProcessingConfiguration.java | 36 +-
.../core/NonSequenceOrCollectionException.java | 4 +-
.../apache/freemarker/core/ParseException.java | 10 +-
.../apache/freemarker/core/RegexpHelper.java | 4 +-
.../org/apache/freemarker/core/Template.java | 10 +-
.../freemarker/core/TemplateBooleanFormat.java | 8 +-
.../freemarker/core/TemplateClassResolver.java | 8 +-
.../freemarker/core/TemplateConfiguration.java | 12 +-
.../core/TemplateElementArrayBuilder.java | 4 +-
.../freemarker/core/TemplateException.java | 16 +-
.../core/TemplateExceptionHandler.java | 4 +-
.../freemarker/core/TemplateLanguage.java | 4 +-
.../org/apache/freemarker/core/Version.java | 8 +-
.../apache/freemarker/core/_CallableUtils.java | 6 +-
.../apache/freemarker/core/_DelayedAOrAn.java | 2 +-
.../apache/freemarker/core/_DelayedJQuote.java | 4 +-
.../freemarker/core/_DelayedJQuotedListing.java | 4 +-
.../freemarker/core/_DelayedShortClassName.java | 4 +-
.../core/_ErrorDescriptionBuilder.java | 22 +-
.../org/apache/freemarker/core/_EvalUtil.java | 545 ------
.../org/apache/freemarker/core/_EvalUtils.java | 545 ++++++
...ObjectBuilderSettingEvaluationException.java | 4 +-
.../core/_ObjectBuilderSettingEvaluator.java | 32 +-
.../core/_TemplateModelException.java | 4 +-
.../impl/BigDecimalArithmeticEngine.java | 28 +-
.../impl/ConservativeArithmeticEngine.java | 26 +-
.../freemarker/core/debug/DebuggerServer.java | 6 +-
.../freemarker/core/debug/_DebuggerService.java | 4 +-
.../core/model/impl/ArgumentTypes.java | 36 +-
.../freemarker/core/model/impl/BeanModel.java | 4 +-
.../core/model/impl/ClassBasedModelFactory.java | 4 +-
.../core/model/impl/ClassIntrospector.java | 2 +-
.../core/model/impl/DefaultObjectWrapper.java | 38 +-
.../DefaultObjectWrapperTCCLSingletonUtil.java | 129 --
.../DefaultObjectWrapperTCCLSingletonUtils.java | 129 ++
.../model/impl/OverloadedJavaMethodModel.java | 2 +-
.../core/model/impl/OverloadedMethods.java | 6 +-
.../model/impl/OverloadedMethodsSubset.java | 14 +-
.../core/model/impl/OverloadedNumberUtil.java | 1289 --------------
.../core/model/impl/OverloadedNumberUtils.java | 1289 ++++++++++++++
.../ReflectionCallableMemberDescriptor.java | 4 +-
.../model/impl/RestrictedObjectWrapper.java | 4 +-
.../core/model/impl/SimpleJavaMethodModel.java | 2 +-
.../core/model/impl/SimpleMethod.java | 16 +-
.../core/model/impl/UnsafeMethods.java | 6 +-
.../freemarker/core/model/impl/_MethodUtil.java | 319 ----
.../core/model/impl/_MethodUtils.java | 319 ++++
.../freemarker/core/model/impl/_ModelAPI.java | 8 +-
.../core/outputformat/OutputFormat.java | 8 +-
.../outputformat/impl/HTMLOutputFormat.java | 8 +-
.../core/outputformat/impl/RTFOutputFormat.java | 8 +-
.../outputformat/impl/XHTMLOutputFormat.java | 8 +-
.../core/outputformat/impl/XMLOutputFormat.java | 8 +-
.../templateresolver/FileNameGlobMatcher.java | 6 +-
.../FirstMatchTemplateConfigurationFactory.java | 4 +-
.../MalformedTemplateNameException.java | 4 +-
.../core/templateresolver/PathGlobMatcher.java | 8 +-
.../core/templateresolver/PathRegexMatcher.java | 4 +-
.../impl/ByteArrayTemplateLoader.java | 4 +-
.../impl/ClassTemplateLoader.java | 6 +-
.../impl/DefaultTemplateNameFormat.java | 4 +-
.../impl/DefaultTemplateResolver.java | 16 +-
.../impl/FileTemplateLoader.java | 10 +-
.../impl/StringTemplateLoader.java | 4 +-
.../core/util/DuplicateStringKeyException.java | 2 +-
.../apache/freemarker/core/util/FTLUtil.java | 4 +-
.../core/util/OptInTemplateClassResolver.java | 14 +-
.../freemarker/core/util/StringToIndexMap.java | 2 +-
.../util/UnrecognizedTimeZoneException.java | 2 +-
.../apache/freemarker/core/util/_ClassUtil.java | 168 --
.../freemarker/core/util/_ClassUtils.java | 168 ++
.../freemarker/core/util/_CollectionUtil.java | 220 ---
.../freemarker/core/util/_CollectionUtils.java | 220 +++
.../apache/freemarker/core/util/_DateUtil.java | 914 ----------
.../apache/freemarker/core/util/_DateUtils.java | 914 ++++++++++
.../freemarker/core/util/_JavaVersions.java | 2 +-
.../freemarker/core/util/_LocaleUtil.java | 43 -
.../freemarker/core/util/_LocaleUtils.java | 43 +
.../freemarker/core/util/_NumberUtil.java | 224 ---
.../freemarker/core/util/_NumberUtils.java | 224 +++
.../freemarker/core/util/_SecurityUtil.java | 87 -
.../freemarker/core/util/_SecurityUtils.java | 87 +
.../freemarker/core/util/_StringUtil.java | 1625 ------------------
.../freemarker/core/util/_StringUtils.java | 1625 ++++++++++++++++++
.../core/valueformat/TemplateFormatUtil.java | 6 +-
.../impl/AliasTemplateDateFormatFactory.java | 8 +-
.../impl/AliasTemplateNumberFormatFactory.java | 8 +-
.../impl/ExtendedDecimalFormatParser.java | 8 +-
.../impl/ISOLikeTemplateDateFormat.java | 28 +-
.../impl/ISOLikeTemplateDateFormatFactory.java | 8 +-
.../valueformat/impl/ISOTemplateDateFormat.java | 16 +-
.../valueformat/impl/XSTemplateDateFormat.java | 16 +-
freemarker-core/src/main/javacc/FTL.jj | 12 +-
.../apache/freemarker/dom/DocumentModel.java | 2 +-
.../apache/freemarker/dom/DomStringUtil.java | 67 -
.../apache/freemarker/dom/DomStringUtils.java | 67 +
.../org/apache/freemarker/dom/ElementModel.java | 8 +-
.../apache/freemarker/dom/NodeListModel.java | 4 +-
.../apache/freemarker/dom/NodeOutputter.java | 8 +-
.../apache/freemarker/dom/test/DOMLoader.java | 6 +-
.../BaseNTemplateNumberFormatFactory.java | 10 +-
.../examples/TemplateConfigurationExamples.java | 4 +-
.../freemarker/servlet/FreemarkerServlet.java | 52 +-
.../freemarker/servlet/InitParamParser.java | 6 +-
.../servlet/WebAppTemplateLoader.java | 16 +-
.../jsp/FreeMarkerJspApplicationContext.java | 4 +-
.../freemarker/servlet/jsp/JspTagModelBase.java | 4 +-
.../servlet/jsp/JspWriterAdapter.java | 4 +-
.../freemarker/servlet/jsp/TaglibFactory.java | 62 +-
.../servlet/jsp/TaglibMethodUtil.java | 117 --
.../servlet/jsp/TaglibMethodUtils.java | 117 ++
.../servlet/jsp/_FreeMarkerPageContext21.java | 4 +-
.../servlet/jsp/TaglibMethodUtilTest.java | 108 --
.../servlet/jsp/TaglibMethodUtilsTest.java | 107 ++
.../jsp/taglibmembers/AttributeAccessorTag.java | 4 +-
.../jsp/taglibmembers/AttributeInfoTag.java | 8 +-
.../servlet/test/Model2TesterServlet.java | 4 +-
.../freemarker/servlet/test/WebAppTestCase.java | 4 +-
.../CopyrightCommentRemoverTemplateLoader.java | 4 +-
.../apache/freemarker/test/FileTestCase.java | 10 +-
.../freemarker/test/ResourcesExtractor.java | 14 +-
.../apache/freemarker/test/TemplateTest.java | 10 +-
.../freemarker/test/TemplateTestCase.java | 10 +-
.../freemarker/test/TemplateTestSuite.java | 14 +-
.../org/apache/freemarker/test/TestUtil.java | 244 ---
.../org/apache/freemarker/test/TestUtils.java | 244 +++
.../templateutil/AssertEqualsDirective.java | 4 +-
.../test/templateutil/AssertFailsDirective.java | 16 +-
.../templateutil/BadParameterTypeException.java | 6 +-
.../MissingRequiredParameterException.java | 6 +-
.../UnsupportedParameterException.java | 6 +-
218 files changed, 9777 insertions(+), 9869 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-converter/src/main/java/freemarker/core/FM2ASTToFM3SourceConverter.java
----------------------------------------------------------------------
diff --git a/freemarker-converter/src/main/java/freemarker/core/FM2ASTToFM3SourceConverter.java b/freemarker-converter/src/main/java/freemarker/core/FM2ASTToFM3SourceConverter.java
index 6d9b25c..1b171bd 100644
--- a/freemarker-converter/src/main/java/freemarker/core/FM2ASTToFM3SourceConverter.java
+++ b/freemarker-converter/src/main/java/freemarker/core/FM2ASTToFM3SourceConverter.java
@@ -36,10 +36,10 @@ import org.apache.freemarker.converter.ConverterException;
import org.apache.freemarker.converter.ConverterUtils;
import org.apache.freemarker.converter.UnconvertableLegacyFeatureException;
import org.apache.freemarker.core.util.FTLUtil;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
import org.apache.freemarker.core.util._NullArgumentException;
import org.apache.freemarker.core.util._ObjectHolder;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@@ -232,7 +232,7 @@ public class FM2ASTToFM3SourceConverter {
}
private String convertFtlHeaderParamName(String name) throws ConverterException {
- String converted = name.indexOf('_') == -1 ? name : _StringUtil.snakeCaseToCamelCase(name);
+ String converted = name.indexOf('_') == -1 ? name : _StringUtils.snakeCaseToCamelCase(name);
if (converted.equals("attributes")) {
converted = "customSettings";
}
@@ -246,7 +246,7 @@ public class FM2ASTToFM3SourceConverter {
printExp((Expression) node);
} else {
throw new UnexpectedNodeContentException(node, "Unhandled node class",
- _ClassUtil.getShortClassNameOfObject(node));
+ _ClassUtils.getShortClassNameOfObject(node));
}
}
@@ -606,7 +606,7 @@ public class FM2ASTToFM3SourceConverter {
}
private String convertSettingName(String name, TemplateObject node) throws ConverterException {
- String converted = name.indexOf('_') == -1 ? name : _StringUtil.snakeCaseToCamelCase(name);
+ String converted = name.indexOf('_') == -1 ? name : _StringUtils.snakeCaseToCamelCase(name);
if (converted.equals("classicCompatible")) {
throw new UnconvertableLegacyFeatureException("There \"classicCompatible\" setting doesn't exist in "
@@ -1327,7 +1327,7 @@ public class FM2ASTToFM3SourceConverter {
pos = printSeparatorAndWSAndExpComments(pos, beforeFirstNestedContParam ? ";" : ",");
String nestedContParamName = getParam(node, paramIdx, ParameterRole.TARGET_LOOP_VARIABLE, String.class);
- print(_StringUtil.toFTLTopLevelIdentifierReference(nestedContParamName));
+ print(_StringUtils.toFTLTopLevelIdentifierReference(nestedContParamName));
String identifierInSrc = readIdentifier(pos);
assertNodeContent(identifierInSrc.length() != 0, node,
"Can't find nested content parameter name in the source");
@@ -1485,7 +1485,7 @@ public class FM2ASTToFM3SourceConverter {
printWithConvertedExpComments(src.substring(wsStartPos, opPos));
String operatorInSrc = src.substring(opPos, opPos + operator.length());
assertNodeContent(operatorInSrc.equals(operator), node,
- "Expected " + _StringUtil.jQuote(operator) + ", found {}", operatorInSrc);
+ "Expected " + _StringUtils.jQuote(operator) + ", found {}", operatorInSrc);
print(operator);
}
@@ -1600,7 +1600,7 @@ public class FM2ASTToFM3SourceConverter {
}
private String convertBuiltInVariableName(String name) throws ConverterException {
- String converted = name.indexOf('_') == -1 ? name : _StringUtil.snakeCaseToCamelCase(name);
+ String converted = name.indexOf('_') == -1 ? name : _StringUtils.snakeCaseToCamelCase(name);
if (converted.equals("currentNode")) {
converted = "node";
@@ -1638,7 +1638,7 @@ public class FM2ASTToFM3SourceConverter {
static {
Map<String, String> domKeyMapping = new HashMap<>();
for (String atAtKey : AtAtKeyAccessor.getAtAtKeys()) {
- String atAtKeyCC = _StringUtil.snakeCaseToCamelCase(atAtKey);
+ String atAtKeyCC = _StringUtils.snakeCaseToCamelCase(atAtKey);
if (!atAtKeyCC.equals(atAtKey)) {
domKeyMapping.put(atAtKey, atAtKeyCC);
}
@@ -1956,7 +1956,7 @@ public class FM2ASTToFM3SourceConverter {
private String convertBuiltInName(String name) throws ConverterException {
String converted = IRREGULAR_BUILT_IN_NAME_CONVERSIONS.get(name);
if (converted == null) {
- converted = name.indexOf('_') == -1 ? name : _StringUtil.snakeCaseToCamelCase(name);
+ converted = name.indexOf('_') == -1 ? name : _StringUtils.snakeCaseToCamelCase(name);
}
if (!fm3BuiltInNames.contains(converted)) {
@@ -2413,7 +2413,7 @@ public class FM2ASTToFM3SourceConverter {
if (pos == src.length() || !src.startsWith(separatorSymbol, pos)) {
if (!separatorOptional) {
throw new ConverterException(
- "Expected separator " + _StringUtil.jQuote(separatorSymbol) + " at position " + pos + ".");
+ "Expected separator " + _StringUtils.jQuote(separatorSymbol) + " at position " + pos + ".");
}
if (separatorPosInOutput != null) {
separatorPosInOutput.set(null);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-converter/src/main/java/freemarker/core/UnexpectedNodeContentException.java
----------------------------------------------------------------------
diff --git a/freemarker-converter/src/main/java/freemarker/core/UnexpectedNodeContentException.java b/freemarker-converter/src/main/java/freemarker/core/UnexpectedNodeContentException.java
index f7c7408..090f18e 100644
--- a/freemarker-converter/src/main/java/freemarker/core/UnexpectedNodeContentException.java
+++ b/freemarker-converter/src/main/java/freemarker/core/UnexpectedNodeContentException.java
@@ -20,11 +20,11 @@
package freemarker.core;
import org.apache.freemarker.converter.ConverterException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
public class UnexpectedNodeContentException extends ConverterException {
public UnexpectedNodeContentException(TemplateObject node, String errorMessage, Object msgParam) {
- super("Unexpected AST content for " + _StringUtil.jQuote(node.getNodeTypeSymbol()) + " node (class: "
+ super("Unexpected AST content for " + _StringUtils.jQuote(node.getNodeTypeSymbol()) + " node (class: "
+ node.getClass().getName() + "):\n"
+ renderMessage(errorMessage, msgParam),
node.getBeginLine(), node.getBeginColumn());
@@ -43,7 +43,7 @@ public class UnexpectedNodeContentException extends ConverterException {
return "null";
}
if (param instanceof String || param instanceof Character) {
- return _StringUtil.jQuote(param);
+ return _StringUtils.jQuote(param);
}
return param.toString();
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-converter/src/main/java/org/apache/freemarker/converter/Converter.java
----------------------------------------------------------------------
diff --git a/freemarker-converter/src/main/java/org/apache/freemarker/converter/Converter.java b/freemarker-converter/src/main/java/org/apache/freemarker/converter/Converter.java
index c0527f9..b3dd1b7 100644
--- a/freemarker-converter/src/main/java/org/apache/freemarker/converter/Converter.java
+++ b/freemarker-converter/src/main/java/org/apache/freemarker/converter/Converter.java
@@ -34,7 +34,7 @@ import java.util.Set;
import java.util.regex.Pattern;
import org.apache.freemarker.core.util._NullArgumentException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -260,7 +260,7 @@ public abstract class Converter {
storeConversionMarkers(ctx.getConversionMarkers(), ctx);
convertedFileCount++;
} catch (IOException e) {
- throw new ConverterException("I/O exception while converting " + _StringUtil.jQuote(src) + ".", e);
+ throw new ConverterException("I/O exception while converting " + _StringUtils.jQuote(src) + ".", e);
} finally {
try {
if (ctx != null && ctx.outputStream != null) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-converter/src/test/java/org/freemarker/converter/ConverterUtilTest.java
----------------------------------------------------------------------
diff --git a/freemarker-converter/src/test/java/org/freemarker/converter/ConverterUtilTest.java b/freemarker-converter/src/test/java/org/freemarker/converter/ConverterUtilTest.java
deleted file mode 100644
index 3646834..0000000
--- a/freemarker-converter/src/test/java/org/freemarker/converter/ConverterUtilTest.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.freemarker.converter;
-
-public class ConverterUtilTest {
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTPrinter.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTPrinter.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTPrinter.java
index 299c70f..2bc1eea 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTPrinter.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTPrinter.java
@@ -41,8 +41,8 @@ import java.util.regex.PatternSyntaxException;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.util.FTLUtil;
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.test.TestConfigurationBuilder;
/**
@@ -109,7 +109,7 @@ public class ASTPrinter {
try {
fnPattern = Pattern.compile(args[2]);
} catch (PatternSyntaxException e) {
- p(_StringUtil.jQuote(args[2]) + " is not a valid regular expression");
+ p(_StringUtils.jQuote(args[2]) + " is not a valid regular expression");
System.exit(-1);
return;
}
@@ -352,7 +352,7 @@ public class ASTPrinter {
}
} else {
printNodeLineStart(paramRole, ind, out);
- out.write(_StringUtil.jQuote(node));
+ out.write(_StringUtils.jQuote(node));
printNodeLineEnd(node, out, opts);
}
}
@@ -362,7 +362,7 @@ public class ASTPrinter {
if (opts.getShowJavaClass()) {
out.write(" // ");
commentStared = true;
- out.write(_ClassUtil.getShortClassNameOfObject(node, true));
+ out.write(_ClassUtils.getShortClassNameOfObject(node, true));
}
if (opts.getShowLocation() && node instanceof ASTNode) {
if (!commentStared) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTTest.java
index 7379e28..217b7ff 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ASTTest.java
@@ -23,8 +23,8 @@ import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.freemarker.core.ASTPrinter.Options;
-import org.apache.freemarker.core.util._StringUtil;
-import org.apache.freemarker.test.TestUtil;
+import org.apache.freemarker.core.util._StringUtils;
+import org.apache.freemarker.test.TestUtils;
import org.apache.freemarker.test.FileTestCase;
public class ASTTest extends FileTestCase {
@@ -88,7 +88,7 @@ public class ASTTest extends FileTestCase {
assertExpectedFileEqualsString(
testName + ".ast",
ASTPrinter.getASTAsString(templateName,
- TestUtil.removeFTLCopyrightComment(
+ TestUtils.removeFTLCopyrightComment(
normalizeLineBreaks(
loadTestTextResource(
getTestFileURL(
@@ -97,7 +97,7 @@ public class ASTTest extends FileTestCase {
}
private String normalizeLineBreaks(final String s) throws FileNotFoundException, IOException {
- return _StringUtil.replace(s, "\r\n", "\n").replace('\r', '\n');
+ return _StringUtils.replace(s, "\r\n", "\n").replace('\r', '\n');
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java
index 2f7af7b..dab1460 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java
@@ -82,8 +82,8 @@ import org.apache.freemarker.core.userpkg.EpochMillisTemplateDateFormatFactory;
import org.apache.freemarker.core.userpkg.HexTemplateNumberFormatFactory;
import org.apache.freemarker.core.userpkg.NameClashingDummyOutputFormat;
import org.apache.freemarker.core.userpkg.SeldomEscapedOutputFormat;
-import org.apache.freemarker.core.util._CollectionUtil;
-import org.apache.freemarker.core.util._DateUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
+import org.apache.freemarker.core.util._DateUtils;
import org.apache.freemarker.core.util._NullWriter;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory;
@@ -530,7 +530,7 @@ public class ConfigurationTest {
{
Template t = cfg.getTemplate("Stat/t.de.ftlx");
assertEquals("TODO,XML", t.getBooleanFormat());
- assertEquals(_DateUtil.UTC, t.getTimeZone());
+ assertEquals(_DateUtils.UTC, t.getTimeZone());
}
assertNotNull(cfgB.getTemplateConfigurations());
@@ -848,13 +848,13 @@ public class ConfigurationTest {
public void testCollectionSettingMutability() throws IOException {
Builder cb = new Builder(VERSION_3_0_0);
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(cb.getSharedVariables()));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(cb.getSharedVariables()));
Map<String, Object> mutableValue = new HashMap<>();
mutableValue.put("x", "v1");
cb.setSharedVariables(mutableValue);
Map<String, Object> immutableValue = cb.getSharedVariables();
assertNotSame(mutableValue, immutableValue); // Must be a copy
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(immutableValue));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(immutableValue));
assertEquals(mutableValue, immutableValue);
mutableValue.put("y", "v2");
assertNotEquals(mutableValue, immutableValue); // No aliasing
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/CoreLocaleUtilsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/CoreLocaleUtilsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/CoreLocaleUtilsTest.java
index 6714fc3..ce7922f 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/CoreLocaleUtilsTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/CoreLocaleUtilsTest.java
@@ -22,7 +22,7 @@ import static org.junit.Assert.*;
import java.util.Locale;
-import org.apache.freemarker.core.util._LocaleUtil;
+import org.apache.freemarker.core.util._LocaleUtils;
import org.junit.Test;
public class CoreLocaleUtilsTest {
@@ -33,40 +33,40 @@ public class CoreLocaleUtilsTest {
locale = new Locale("ru", "RU", "Linux");
assertEquals("ru_RU_Linux", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertEquals("ru_RU", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertEquals("ru", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertNull(locale);
locale = new Locale("ch", "CH");
assertEquals("ch_CH", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertEquals("ch", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertNull(locale);
locale = new Locale("ja");
assertEquals("ja", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertNull(locale);
locale = new Locale("ja", "", "");
assertEquals("ja", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertNull(locale);
locale = new Locale("");
assertEquals("", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertNull(locale);
locale = new Locale("hu", "", "Linux");
assertEquals("hu__Linux", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertEquals("hu", locale.toString());
- locale = _LocaleUtil.getLessSpecificLocale(locale);
+ locale = _LocaleUtils.getLessSpecificLocale(locale);
assertNull(locale);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java
index 54ce6b1..cbdcbe4 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java
@@ -32,7 +32,7 @@ import java.util.TimeZone;
import org.apache.freemarker.core.outputformat.impl.HTMLOutputFormat;
import org.apache.freemarker.core.outputformat.impl.UndefinedOutputFormat;
import org.apache.freemarker.core.outputformat.impl.XMLOutputFormat;
-import org.apache.freemarker.core.util._DateUtil;
+import org.apache.freemarker.core.util._DateUtils;
import org.apache.freemarker.core.util._NullArgumentException;
import org.junit.Test;
@@ -261,7 +261,7 @@ public class MutableParsingAndProcessingConfigurationTest {
assertEquals(TimeZone.getDefault(), cfgB.getTimeZone());
assertFalse(cfgB.isTimeZoneSet());
- TimeZone nonDefault = TimeZone.getDefault().equals(_DateUtil.UTC) ? TimeZone.getTimeZone("PST") : _DateUtil.UTC;
+ TimeZone nonDefault = TimeZone.getDefault().equals(_DateUtils.UTC) ? TimeZone.getTimeZone("PST") : _DateUtils.UTC;
cfgB.setTimeZone(nonDefault);
assertTrue(cfgB.isTimeZoneSet());
assertEquals(nonDefault, cfgB.getTimeZone());
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java
index 5db5dd9..0d764be 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java
@@ -36,8 +36,8 @@ import org.apache.freemarker.core.userpkg.BaseNTemplateNumberFormatFactory;
import org.apache.freemarker.core.userpkg.EpochMillisDivTemplateDateFormatFactory;
import org.apache.freemarker.core.userpkg.EpochMillisTemplateDateFormatFactory;
import org.apache.freemarker.core.userpkg.HexTemplateNumberFormatFactory;
-import org.apache.freemarker.core.util._CollectionUtil;
-import org.apache.freemarker.core.util._DateUtil;
+import org.apache.freemarker.core.util._CollectionUtils;
+import org.apache.freemarker.core.util._DateUtils;
import org.apache.freemarker.core.util._NullWriter;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory;
@@ -80,52 +80,52 @@ public class MutableProcessingConfigurationTest {
MutableProcessingConfiguration<?> mpc = new Configuration.Builder(Configuration.VERSION_3_0_0);
{
- assertTrue(_CollectionUtil.isListKnownToBeUnmodifiable(mpc.getAutoIncludes()));
+ assertTrue(_CollectionUtils.isListKnownToBeUnmodifiable(mpc.getAutoIncludes()));
List<String> mutableValue = new ArrayList<>();
mutableValue.add("x");
mpc.setAutoIncludes(mutableValue);
List<String> immutableValue = mpc.getAutoIncludes();
assertNotSame(mutableValue, immutableValue); // Must be a copy
- assertTrue(_CollectionUtil.isListKnownToBeUnmodifiable(immutableValue));
+ assertTrue(_CollectionUtils.isListKnownToBeUnmodifiable(immutableValue));
assertEquals(mutableValue, immutableValue);
mutableValue.add("y");
assertNotEquals(mutableValue, immutableValue); // No aliasing
}
{
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(mpc.getAutoImports()));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(mpc.getAutoImports()));
Map<String, String> mutableValue = new HashMap<>();
mutableValue.put("x", "x.ftl");
mpc.setAutoImports(mutableValue);
Map<String, String> immutableValue = mpc.getAutoImports();
assertNotSame(mutableValue, immutableValue); // Must be a copy
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(immutableValue));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(immutableValue));
assertEquals(mutableValue, immutableValue);
mutableValue.put("y", "y.ftl");
assertNotEquals(mutableValue, immutableValue); // No aliasing
}
{
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(mpc.getCustomDateFormats()));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(mpc.getCustomDateFormats()));
Map<String, TemplateDateFormatFactory> mutableValue = new HashMap<>();
mutableValue.put("x", EpochMillisTemplateDateFormatFactory.INSTANCE);
mpc.setCustomDateFormats(mutableValue);
Map<String, TemplateDateFormatFactory> immutableValue = mpc.getCustomDateFormats();
assertNotSame(mutableValue, immutableValue); // Must be a copy
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(immutableValue));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(immutableValue));
assertEquals(mutableValue, immutableValue);
mutableValue.put("y", EpochMillisDivTemplateDateFormatFactory.INSTANCE);
assertNotEquals(mutableValue, immutableValue); // No aliasing
}
{
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(mpc.getCustomNumberFormats()));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(mpc.getCustomNumberFormats()));
Map<String, TemplateNumberFormatFactory> mutableValue = new HashMap<>();
mutableValue.put("x", BaseNTemplateNumberFormatFactory.INSTANCE);
mpc.setCustomNumberFormats(mutableValue);
Map<String, TemplateNumberFormatFactory> immutableValue = mpc.getCustomNumberFormats();
assertNotSame(mutableValue, immutableValue); // Must be a copy
- assertTrue(_CollectionUtil.isMapKnownToBeUnmodifiable(immutableValue));
+ assertTrue(_CollectionUtils.isMapKnownToBeUnmodifiable(immutableValue));
assertEquals(mutableValue, immutableValue);
mutableValue.put("y", HexTemplateNumberFormatFactory.INSTANCE);
assertNotEquals(mutableValue, immutableValue); // No aliasing
@@ -202,13 +202,13 @@ public class MutableProcessingConfigurationTest {
assertEquals(TimeZone.getDefault(), env2.getTimeZone());
assertNull(env2.getSQLDateAndTimeTimeZone());
- env1.setSQLDateAndTimeTimeZone(_DateUtil.UTC);
+ env1.setSQLDateAndTimeTimeZone(_DateUtils.UTC);
// cfg:
assertEquals(TimeZone.getDefault(), cfg.getTimeZone());
assertNull(cfg.getSQLDateAndTimeTimeZone());
// env:
assertEquals(TimeZone.getDefault(), env1.getTimeZone());
- assertEquals(_DateUtil.UTC, env1.getSQLDateAndTimeTimeZone());
+ assertEquals(_DateUtils.UTC, env1.getSQLDateAndTimeTimeZone());
env1.setTimeZone(localTZ);
// cfg:
@@ -216,7 +216,7 @@ public class MutableProcessingConfigurationTest {
assertNull(cfg.getSQLDateAndTimeTimeZone());
// env:
assertEquals(localTZ, env1.getTimeZone());
- assertEquals(_DateUtil.UTC, env1.getSQLDateAndTimeTimeZone());
+ assertEquals(_DateUtils.UTC, env1.getSQLDateAndTimeTimeZone());
// env 2:
assertEquals(TimeZone.getDefault(), env2.getTimeZone());
assertNull(env2.getSQLDateAndTimeTimeZone());
@@ -235,14 +235,14 @@ public class MutableProcessingConfigurationTest {
Environment env2 = t.createProcessingEnvironment(null, new StringWriter());
env1.setTimeZone(localTZ);
- env1.setSQLDateAndTimeTimeZone(_DateUtil.UTC);
+ env1.setSQLDateAndTimeTimeZone(_DateUtils.UTC);
// cfg:
assertEquals(otherTZ1, cfg.getTimeZone());
assertEquals(otherTZ2, cfg.getSQLDateAndTimeTimeZone());
// env:
assertEquals(localTZ, env1.getTimeZone());
- assertEquals(_DateUtil.UTC, env1.getSQLDateAndTimeTimeZone());
+ assertEquals(_DateUtils.UTC, env1.getSQLDateAndTimeTimeZone());
// env 2:
assertEquals(otherTZ1, env2.getTimeZone());
assertEquals(otherTZ2, env2.getSQLDateAndTimeTimeZone());
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/ParsingErrorMessagesTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ParsingErrorMessagesTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ParsingErrorMessagesTest.java
index 3189615..731a063 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ParsingErrorMessagesTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ParsingErrorMessagesTest.java
@@ -23,7 +23,7 @@ import static org.junit.Assert.*;
import java.io.IOException;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.test.TestConfigurationBuilder;
import org.junit.Test;
@@ -190,10 +190,10 @@ public class ParsingErrorMessagesTest {
if (needle.startsWith("\\!")) {
String netNeedle = needle.substring(2);
if (msg.contains(netNeedle)) {
- fail("The message shouldn't contain substring " + _StringUtil.jQuote(netNeedle) + ":\n" + msg);
+ fail("The message shouldn't contain substring " + _StringUtils.jQuote(netNeedle) + ":\n" + msg);
}
} else if (!msg.contains(needle)) {
- fail("The message didn't contain substring " + _StringUtil.jQuote(needle) + ":\n" + msg);
+ fail("The message didn't contain substring " + _StringUtils.jQuote(needle) + ":\n" + msg);
}
}
showError(e);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/SQLTimeZoneTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/SQLTimeZoneTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/SQLTimeZoneTest.java
index 3939a15..869167b 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/SQLTimeZoneTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/SQLTimeZoneTest.java
@@ -30,7 +30,7 @@ import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
-import org.apache.freemarker.core.util._DateUtil;
+import org.apache.freemarker.core.util._DateUtils;
import org.apache.freemarker.test.TemplateTest;
import org.junit.Test;
@@ -42,7 +42,7 @@ public class SQLTimeZoneTest extends TemplateTest {
private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
{
- df.setTimeZone(_DateUtil.UTC);
+ df.setTimeZone(_DateUtils.UTC);
}
// Values that JDBC in GMT+02 would produce
@@ -266,7 +266,7 @@ public class SQLTimeZoneTest extends TemplateTest {
private Configuration.ExtendableBuilder<?> testCacheFlushing_createBuilder() {
return createConfigurationBuilder()
- .timeZone(_DateUtil.UTC)
+ .timeZone(_DateUtils.UTC)
.sqlDateAndTimeTimeZone(null) // Default from FM2...
.dateFormat("yyyy-MM-dd E")
.timeFormat("HH:mm:ss E")
@@ -276,7 +276,7 @@ public class SQLTimeZoneTest extends TemplateTest {
@Test
public void testDateAndTimeBuiltInsHasNoEffect() throws Exception {
setConfiguration(createConfigurationBuilder()
- .timeZone(_DateUtil.UTC)
+ .timeZone(_DateUtils.UTC)
.sqlDateAndTimeTimeZone(GMT_P02)
.build());
@@ -297,7 +297,7 @@ public class SQLTimeZoneTest extends TemplateTest {
@Test
public void testChangeSettingInTemplate() throws Exception {
setConfiguration(createConfigurationBuilder()
- .timeZone(_DateUtil.UTC)
+ .timeZone(_DateUtils.UTC)
.sqlDateAndTimeTimeZone(null)
.build());
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/TagSyntaxVariationsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/TagSyntaxVariationsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/TagSyntaxVariationsTest.java
index ee521d9..51286b4 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/TagSyntaxVariationsTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/TagSyntaxVariationsTest.java
@@ -26,7 +26,7 @@ import java.util.Collections;
import java.util.Map;
import org.apache.freemarker.core.userpkg.UpperCaseDirective;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.test.TestConfigurationBuilder;
import junit.framework.TestCase;
@@ -179,13 +179,13 @@ public class TagSyntaxVariationsTest extends TestCase {
} catch (ParseException e) {
if (expected != null) {
fail("Couldn't invoke Template from "
- + _StringUtil.jQuote(template) + ": " + e);
+ + _StringUtils.jQuote(template) + ": " + e);
} else {
return;
}
}
if (expected == null) fail("Template parsing should have fail for "
- + _StringUtil.jQuote(template));
+ + _StringUtils.jQuote(template));
StringWriter out = new StringWriter();
t.process(new Object(), out);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperSingletonsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperSingletonsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperSingletonsTest.java
index be2c6a2..dd7581c 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperSingletonsTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/DefaultObjectWrapperSingletonsTest.java
@@ -34,7 +34,7 @@ import org.apache.freemarker.core.model.TemplateDateModel;
import org.apache.freemarker.core.model.TemplateHashModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.model.TemplateScalarModel;
-import org.apache.freemarker.test.TestUtil;
+import org.apache.freemarker.test.TestUtils;
import junit.framework.TestCase;
@@ -52,7 +52,7 @@ public class DefaultObjectWrapperSingletonsTest extends TestCase {
public void testBuilderEqualsAndHash() throws Exception {
assertEquals(Configuration.VERSION_3_0_0, new DefaultObjectWrapper.Builder(Configuration.VERSION_3_0_0).getIncompatibleImprovements());
try {
- new DefaultObjectWrapper.Builder(TestUtil.getClosestFutureVersion());
+ new DefaultObjectWrapper.Builder(TestUtils.getClosestFutureVersion());
fail("Maybe you need to update this test for the new FreeMarker version");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("upgrade"));
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsApplicableTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsApplicableTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsApplicableTest.java
index 599e6f2..fbf62a6 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsApplicableTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsApplicableTest.java
@@ -65,7 +65,7 @@ public class IsApplicableTest extends TestCase {
assertApplicable(ats, BigDecimal.class);
assertApplicable(ats, BigInteger.class);
- ats = new ArgumentTypes(new Object[] { new OverloadedNumberUtil.IntegerOrByte(1, (byte) 1) });
+ ats = new ArgumentTypes(new Object[] { new OverloadedNumberUtils.IntegerOrByte(1, (byte) 1) });
assertApplicable(ats, Object.class);
assertNotApplicable(ats, CharSequence.class);
assertNotApplicable(ats, String.class);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsMoreSpecificParameterTypeTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsMoreSpecificParameterTypeTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsMoreSpecificParameterTypeTest.java
index 3de3f13..4195ab4 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsMoreSpecificParameterTypeTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/IsMoreSpecificParameterTypeTest.java
@@ -32,67 +32,67 @@ public class IsMoreSpecificParameterTypeTest extends TestCase {
}
public void testFixed() {
- assertEquals(1, _MethodUtil.isMoreOrSameSpecificParameterType(String.class, String.class, true, 0));
- assertEquals(1, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, int.class, true, 0));
+ assertEquals(1, _MethodUtils.isMoreOrSameSpecificParameterType(String.class, String.class, true, 0));
+ assertEquals(1, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, int.class, true, 0));
- assertEquals(2, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Integer.class, true, 0));
- assertEquals(2, _MethodUtil.isMoreOrSameSpecificParameterType(boolean.class, Boolean.class, true, 0));
+ assertEquals(2, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Integer.class, true, 0));
+ assertEquals(2, _MethodUtils.isMoreOrSameSpecificParameterType(boolean.class, Boolean.class, true, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, long.class, true, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, double.class, true, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Long.class, true, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Double.class, true, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, Long.class, true, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, Double.class, true, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, long.class, true, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, double.class, true, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Long.class, true, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Double.class, true, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, Long.class, true, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, Double.class, true, 0));
- assertEquals(4, _MethodUtil.isMoreOrSameSpecificParameterType(HashMap.class, Map.class, true, 0));
- assertEquals(4, _MethodUtil.isMoreOrSameSpecificParameterType(String.class, CharSequence.class, true, 0));
- assertEquals(4, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, Number.class, true, 0));
- assertEquals(4, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Number.class, true, 0));
+ assertEquals(4, _MethodUtils.isMoreOrSameSpecificParameterType(HashMap.class, Map.class, true, 0));
+ assertEquals(4, _MethodUtils.isMoreOrSameSpecificParameterType(String.class, CharSequence.class, true, 0));
+ assertEquals(4, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, Number.class, true, 0));
+ assertEquals(4, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Number.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Map.class, String.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, int.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Boolean.class, boolean.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, boolean.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Boolean.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, String.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, BigDecimal.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Long.class, Integer.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(long.class, Integer.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Long.class, int.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, BigDecimal.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Map.class, String.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, int.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Boolean.class, boolean.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, boolean.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Boolean.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, String.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, BigDecimal.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Long.class, Integer.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(long.class, Integer.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Long.class, int.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, BigDecimal.class, true, 0));
}
public void testBuggy() {
- assertEquals(1, _MethodUtil.isMoreOrSameSpecificParameterType(String.class, String.class, false, 0));
- assertEquals(1, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, int.class, false, 0));
+ assertEquals(1, _MethodUtils.isMoreOrSameSpecificParameterType(String.class, String.class, false, 0));
+ assertEquals(1, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, int.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Integer.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(boolean.class, Boolean.class, false, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Integer.class, false, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(boolean.class, Boolean.class, false, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, long.class, false, 0));
- assertEquals(3, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, double.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Long.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Double.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, Long.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, Double.class, false, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, long.class, false, 0));
+ assertEquals(3, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, double.class, false, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Long.class, false, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Double.class, false, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, Long.class, false, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, Double.class, false, 0));
- assertEquals(4, _MethodUtil.isMoreOrSameSpecificParameterType(HashMap.class, Map.class, false, 0));
- assertEquals(4, _MethodUtil.isMoreOrSameSpecificParameterType(String.class, CharSequence.class, false, 0));
- assertEquals(4, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, Number.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Number.class, false, 0));
+ assertEquals(4, _MethodUtils.isMoreOrSameSpecificParameterType(HashMap.class, Map.class, false, 0));
+ assertEquals(4, _MethodUtils.isMoreOrSameSpecificParameterType(String.class, CharSequence.class, false, 0));
+ assertEquals(4, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, Number.class, false, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Number.class, false, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Map.class, String.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, int.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Boolean.class, boolean.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, boolean.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, Boolean.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, String.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(int.class, BigDecimal.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Long.class, Integer.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(long.class, Integer.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Long.class, int.class, true, 0));
- assertEquals(0, _MethodUtil.isMoreOrSameSpecificParameterType(Integer.class, BigDecimal.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Map.class, String.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, int.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Boolean.class, boolean.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, boolean.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, Boolean.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, String.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(int.class, BigDecimal.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Long.class, Integer.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(long.class, Integer.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Long.class, int.class, true, 0));
+ assertEquals(0, _MethodUtils.isMoreOrSameSpecificParameterType(Integer.class, BigDecimal.class, true, 0));
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/MiscNumericalOperationsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/MiscNumericalOperationsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/MiscNumericalOperationsTest.java
index 9e175e5..dab5372 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/MiscNumericalOperationsTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/MiscNumericalOperationsTest.java
@@ -61,7 +61,7 @@ public class MiscNumericalOperationsTest extends TestCase {
BigInteger bi = new BigInteger("123");
assertEquals(DefaultObjectWrapper.forceUnwrappedNumberToType(new BigDecimal("123.6"), BigInteger.class), bi);
assertEquals(DefaultObjectWrapper.forceUnwrappedNumberToType(
- new OverloadedNumberUtil.IntegerBigDecimal(new BigDecimal("123")), BigInteger.class), bi);
+ new OverloadedNumberUtils.IntegerBigDecimal(new BigDecimal("123")), BigInteger.class), bi);
assertTrue(DefaultObjectWrapper.forceUnwrappedNumberToType(bi, BigInteger.class) == bi);
assertEquals(DefaultObjectWrapper.forceUnwrappedNumberToType(Long.valueOf(123), BigInteger.class), bi);
assertEquals(DefaultObjectWrapper.forceUnwrappedNumberToType(Double.valueOf(123.6), BigInteger.class), bi);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ModelAPINewInstanceTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ModelAPINewInstanceTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ModelAPINewInstanceTest.java
index 0b0a614..b6be7f1 100644
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ModelAPINewInstanceTest.java
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/model/impl/ModelAPINewInstanceTest.java
@@ -20,7 +20,7 @@
package org.apache.freemarker.core.model.impl;
import org.apache.freemarker.core.Configuration;
-import org.apache.freemarker.test.TestUtil;
+import org.apache.freemarker.test.TestUtils;
import junit.framework.TestCase;
@@ -111,8 +111,8 @@ public class ModelAPINewInstanceTest extends TestCase {
public Constructors(Integer x, Integer y) { s = "Integer " + x + ", Integer " + y; }
public Constructors(Object x, Object y) { s = "Object " + x + ", Object " + y; }
- public Constructors(int... xs) { s = "int... " + TestUtil.arrayToString(xs); }
- public Constructors(Object x, int... ys) { s = "Object " + x + ", int... " + TestUtil.arrayToString(ys); }
+ public Constructors(int... xs) { s = "int... " + TestUtils.arrayToString(xs); }
+ public Constructors(Object x, int... ys) { s = "Object " + x + ", int... " + TestUtils.arrayToString(ys); }
@Override
public String toString() {
[03/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtils.java
new file mode 100644
index 0000000..9218005
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/util/_StringUtils.java
@@ -0,0 +1,1625 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.regex.Pattern;
+
+import org.apache.freemarker.core.Environment;
+import org.apache.freemarker.core.Template;
+import org.apache.freemarker.core.Version;
+
+/** Don't use this; used internally by FreeMarker, might changes without notice. */
+public class _StringUtils {
+
+ private static final char[] LT = new char[] { '&', 'l', 't', ';' };
+ private static final char[] GT = new char[] { '&', 'g', 't', ';' };
+ private static final char[] AMP = new char[] { '&', 'a', 'm', 'p', ';' };
+ private static final char[] QUOT = new char[] { '&', 'q', 'u', 'o', 't', ';' };
+ private static final char[] HTML_APOS = new char[] { '&', '#', '3', '9', ';' };
+ private static final char[] XML_APOS = new char[] { '&', 'a', 'p', 'o', 's', ';' };
+
+ /**
+ * XML Encoding.
+ * Replaces all '>' '<' '&', "'" and '"' with entity reference
+ */
+ public static String XMLEnc(String s) {
+ return XMLOrHTMLEnc(s, true, true, XML_APOS);
+ }
+
+ /**
+ * Like {@link #XMLEnc(String)}, but writes the result into a {@link Writer}.
+ */
+ public static void XMLEnc(String s, Writer out) throws IOException {
+ XMLOrHTMLEnc(s, XML_APOS, out);
+ }
+
+ /**
+ * XHTML Encoding.
+ * Replaces all '>' '<' '&', "'" and '"' with entity reference
+ * suitable for XHTML decoding in common user agents (including legacy
+ * user agents, which do not decode "&apos;" to "'", so "&#39;" is used
+ * instead [see http://www.w3.org/TR/xhtml1/#C_16])
+ */
+ public static String XHTMLEnc(String s) {
+ return XMLOrHTMLEnc(s, true, true, HTML_APOS);
+ }
+
+ /**
+ * Like {@link #XHTMLEnc(String)}, but writes the result into a {@link Writer}.
+ */
+ public static void XHTMLEnc(String s, Writer out) throws IOException {
+ XMLOrHTMLEnc(s, HTML_APOS, out);
+ }
+
+ private static String XMLOrHTMLEnc(String s, boolean escGT, boolean escQuot, char[] apos) {
+ final int ln = s.length();
+
+ // First we find out if we need to escape, and if so, what the length of the output will be:
+ int firstEscIdx = -1;
+ int lastEscIdx = 0;
+ int plusOutLn = 0;
+ for (int i = 0; i < ln; i++) {
+ escape: do {
+ final char c = s.charAt(i);
+ switch (c) {
+ case '<':
+ plusOutLn += LT.length - 1;
+ break;
+ case '>':
+ if (!(escGT || maybeCDataEndGT(s, i))) {
+ break escape;
+ }
+ plusOutLn += GT.length - 1;
+ break;
+ case '&':
+ plusOutLn += AMP.length - 1;
+ break;
+ case '"':
+ if (!escQuot) {
+ break escape;
+ }
+ plusOutLn += QUOT.length - 1;
+ break;
+ case '\'': // apos
+ if (apos == null) {
+ break escape;
+ }
+ plusOutLn += apos.length - 1;
+ break;
+ default:
+ break escape;
+ }
+
+ if (firstEscIdx == -1) {
+ firstEscIdx = i;
+ }
+ lastEscIdx = i;
+ } while (false);
+ }
+
+ if (firstEscIdx == -1) {
+ return s; // Nothing to escape
+ } else {
+ final char[] esced = new char[ln + plusOutLn];
+ if (firstEscIdx != 0) {
+ s.getChars(0, firstEscIdx, esced, 0);
+ }
+ int dst = firstEscIdx;
+ scan: for (int i = firstEscIdx; i <= lastEscIdx; i++) {
+ final char c = s.charAt(i);
+ switch (c) {
+ case '<':
+ dst = shortArrayCopy(LT, esced, dst);
+ continue scan;
+ case '>':
+ if (!(escGT || maybeCDataEndGT(s, i))) {
+ break;
+ }
+ dst = shortArrayCopy(GT, esced, dst);
+ continue scan;
+ case '&':
+ dst = shortArrayCopy(AMP, esced, dst);
+ continue scan;
+ case '"':
+ if (!escQuot) {
+ break;
+ }
+ dst = shortArrayCopy(QUOT, esced, dst);
+ continue scan;
+ case '\'': // apos
+ if (apos == null) {
+ break;
+ }
+ dst = shortArrayCopy(apos, esced, dst);
+ continue scan;
+ }
+ esced[dst++] = c;
+ }
+ if (lastEscIdx != ln - 1) {
+ s.getChars(lastEscIdx + 1, ln, esced, dst);
+ }
+
+ return String.valueOf(esced);
+ }
+ }
+
+ private static boolean maybeCDataEndGT(String s, int i) {
+ if (i == 0) return true;
+ if (s.charAt(i - 1) != ']') return false;
+ return i == 1 || s.charAt(i - 2) == ']';
+ }
+
+ private static void XMLOrHTMLEnc(String s, char[] apos, Writer out) throws IOException {
+ int writtenEnd = 0; // exclusive end
+ int ln = s.length();
+ for (int i = 0; i < ln; i++) {
+ char c = s.charAt(i);
+ if (c == '<' || c == '>' || c == '&' || c == '"' || c == '\'') {
+ int flushLn = i - writtenEnd;
+ if (flushLn != 0) {
+ out.write(s, writtenEnd, flushLn);
+ }
+ writtenEnd = i + 1;
+
+ switch (c) {
+ case '<': out.write(LT); break;
+ case '>': out.write(GT); break;
+ case '&': out.write(AMP); break;
+ case '"': out.write(QUOT); break;
+ default: out.write(apos); break;
+ }
+ }
+ }
+ if (writtenEnd < ln) {
+ out.write(s, writtenEnd, ln - writtenEnd);
+ }
+ }
+
+ /**
+ * For efficiently copying very short char arrays.
+ */
+ private static int shortArrayCopy(char[] src, char[] dst, int dstOffset) {
+ for (char aSrc : src) {
+ dst[dstOffset++] = aSrc;
+ }
+ return dstOffset;
+ }
+
+ /**
+ * XML encoding without replacing apostrophes.
+ * @see #XMLEnc(String)
+ */
+ public static String XMLEncNA(String s) {
+ return XMLOrHTMLEnc(s, true, true, null);
+ }
+
+ /**
+ * XML encoding for attribute values quoted with <tt>"</tt> (not with <tt>'</tt>!).
+ * Also can be used for HTML attributes that are quoted with <tt>"</tt>.
+ * @see #XMLEnc(String)
+ */
+ public static String XMLEncQAttr(String s) {
+ return XMLOrHTMLEnc(s, false, true, null);
+ }
+
+ /**
+ * XML encoding without replacing apostrophes and quotation marks and
+ * greater-thans (except in {@code ]]>}).
+ * @see #XMLEnc(String)
+ */
+ public static String XMLEncNQG(String s) {
+ return XMLOrHTMLEnc(s, false, false, null);
+ }
+
+ /**
+ * Rich Text Format encoding (does not replace line breaks).
+ * Escapes all '\' '{' '}'.
+ */
+ public static String RTFEnc(String s) {
+ int ln = s.length();
+
+ // First we find out if we need to escape, and if so, what the length of the output will be:
+ int firstEscIdx = -1;
+ int lastEscIdx = 0;
+ int plusOutLn = 0;
+ for (int i = 0; i < ln; i++) {
+ char c = s.charAt(i);
+ if (c == '{' || c == '}' || c == '\\') {
+ if (firstEscIdx == -1) {
+ firstEscIdx = i;
+ }
+ lastEscIdx = i;
+ plusOutLn++;
+ }
+ }
+
+ if (firstEscIdx == -1) {
+ return s; // Nothing to escape
+ } else {
+ char[] esced = new char[ln + plusOutLn];
+ if (firstEscIdx != 0) {
+ s.getChars(0, firstEscIdx, esced, 0);
+ }
+ int dst = firstEscIdx;
+ for (int i = firstEscIdx; i <= lastEscIdx; i++) {
+ char c = s.charAt(i);
+ if (c == '{' || c == '}' || c == '\\') {
+ esced[dst++] = '\\';
+ }
+ esced[dst++] = c;
+ }
+ if (lastEscIdx != ln - 1) {
+ s.getChars(lastEscIdx + 1, ln, esced, dst);
+ }
+
+ return String.valueOf(esced);
+ }
+ }
+
+ /**
+ * Like {@link #RTFEnc(String)}, but writes the result into a {@link Writer}.
+ */
+ public static void RTFEnc(String s, Writer out) throws IOException {
+ int writtenEnd = 0; // exclusive end
+ int ln = s.length();
+ for (int i = 0; i < ln; i++) {
+ char c = s.charAt(i);
+ if (c == '{' || c == '}' || c == '\\') {
+ int flushLn = i - writtenEnd;
+ if (flushLn != 0) {
+ out.write(s, writtenEnd, flushLn);
+ }
+ out.write('\\');
+ writtenEnd = i; // Not i + 1, so c will be written out later
+ }
+ }
+ if (writtenEnd < ln) {
+ out.write(s, writtenEnd, ln - writtenEnd);
+ }
+ }
+
+
+ /**
+ * URL encoding (like%20this) for query parameter values, path <em>segments</em>, fragments; this encodes all
+ * characters that are reserved anywhere.
+ */
+ public static String URLEnc(String s, Charset charset) throws UnsupportedEncodingException {
+ return URLEnc(s, charset, false);
+ }
+
+ /**
+ * Like {@link #URLEnc(String, Charset)} but doesn't escape the slash character ({@code /}).
+ * This can be used to encode a path only if you know that no folder or file name will contain {@code /}
+ * character (not in the path, but in the name itself), which usually stands, as the commonly used OS-es don't
+ * allow that.
+ */
+ public static String URLPathEnc(String s, Charset charset) throws UnsupportedEncodingException {
+ return URLEnc(s, charset, true);
+ }
+
+ private static String URLEnc(String s, Charset charset, boolean keepSlash)
+ throws UnsupportedEncodingException {
+ int ln = s.length();
+ int i;
+ for (i = 0; i < ln; i++) {
+ char c = s.charAt(i);
+ if (!safeInURL(c, keepSlash)) {
+ break;
+ }
+ }
+ if (i == ln) {
+ // Nothing to escape
+ return s;
+ }
+
+ StringBuilder b = new StringBuilder(ln + ln / 3 + 2);
+ b.append(s.substring(0, i));
+
+ int encStart = i;
+ for (i++; i < ln; i++) {
+ char c = s.charAt(i);
+ if (safeInURL(c, keepSlash)) {
+ if (encStart != -1) {
+ byte[] o = s.substring(encStart, i).getBytes(charset);
+ for (byte bc : o) {
+ b.append('%');
+ int c1 = bc & 0x0F;
+ int c2 = (bc >> 4) & 0x0F;
+ b.append((char) (c2 < 10 ? c2 + '0' : c2 - 10 + 'A'));
+ b.append((char) (c1 < 10 ? c1 + '0' : c1 - 10 + 'A'));
+ }
+ encStart = -1;
+ }
+ b.append(c);
+ } else {
+ if (encStart == -1) {
+ encStart = i;
+ }
+ }
+ }
+ if (encStart != -1) {
+ byte[] o = s.substring(encStart, i).getBytes(charset);
+ for (byte bc : o) {
+ b.append('%');
+ int c1 = bc & 0x0F;
+ int c2 = (bc >> 4) & 0x0F;
+ b.append((char) (c2 < 10 ? c2 + '0' : c2 - 10 + 'A'));
+ b.append((char) (c1 < 10 ? c1 + '0' : c1 - 10 + 'A'));
+ }
+ }
+
+ return b.toString();
+ }
+
+ private static boolean safeInURL(char c, boolean keepSlash) {
+ return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
+ || c >= '0' && c <= '9'
+ || c == '_' || c == '-' || c == '.' || c == '!' || c == '~'
+ || c >= '\'' && c <= '*'
+ || keepSlash && c == '/';
+ }
+
+ public static Locale deduceLocale(String input) {
+ if (input == null) return null;
+ Locale locale = Locale.getDefault();
+ if (input.length() > 0 && input.charAt(0) == '"') input = input.substring(1, input.length() - 1);
+ StringTokenizer st = new StringTokenizer(input, ",_ ");
+ String lang = "", country = "";
+ if (st.hasMoreTokens()) {
+ lang = st.nextToken();
+ }
+ if (st.hasMoreTokens()) {
+ country = st.nextToken();
+ }
+ if (!st.hasMoreTokens()) {
+ locale = new Locale(lang, country);
+ } else {
+ locale = new Locale(lang, country, st.nextToken());
+ }
+ return locale;
+ }
+
+ public static String capitalize(String s) {
+ StringTokenizer st = new StringTokenizer(s, " \t\r\n", true);
+ StringBuilder buf = new StringBuilder(s.length());
+ while (st.hasMoreTokens()) {
+ String tok = st.nextToken();
+ buf.append(tok.substring(0, 1).toUpperCase());
+ buf.append(tok.substring(1).toLowerCase());
+ }
+ return buf.toString();
+ }
+
+ public static boolean getYesNo(String s) {
+ if (s.startsWith("\"")) {
+ s = s.substring(1, s.length() - 1);
+
+ }
+ if (s.equalsIgnoreCase("n")
+ || s.equalsIgnoreCase("no")
+ || s.equalsIgnoreCase("f")
+ || s.equalsIgnoreCase("false")) {
+ return false;
+ } else if (s.equalsIgnoreCase("y")
+ || s.equalsIgnoreCase("yes")
+ || s.equalsIgnoreCase("t")
+ || s.equalsIgnoreCase("true")) {
+ return true;
+ }
+ throw new IllegalArgumentException("Illegal boolean value: " + s);
+ }
+
+ /**
+ * Splits a string at the specified character.
+ */
+ public static String[] split(String s, char c) {
+ int i, b, e;
+ int cnt;
+ String res[];
+ int ln = s.length();
+
+ i = 0;
+ cnt = 1;
+ while ((i = s.indexOf(c, i)) != -1) {
+ cnt++;
+ i++;
+ }
+ res = new String[cnt];
+
+ i = 0;
+ b = 0;
+ while (b <= ln) {
+ e = s.indexOf(c, b);
+ if (e == -1) e = ln;
+ res[i++] = s.substring(b, e);
+ b = e + 1;
+ }
+ return res;
+ }
+
+ /**
+ * Splits a string at the specified string.
+ */
+ public static String[] split(String s, String sep, boolean caseInsensitive) {
+ String splitString = caseInsensitive ? sep.toLowerCase() : sep;
+ String input = caseInsensitive ? s.toLowerCase() : s;
+ int i, b, e;
+ int cnt;
+ String res[];
+ int ln = s.length();
+ int sln = sep.length();
+
+ if (sln == 0) throw new IllegalArgumentException(
+ "The separator string has 0 length");
+
+ i = 0;
+ cnt = 1;
+ while ((i = input.indexOf(splitString, i)) != -1) {
+ cnt++;
+ i += sln;
+ }
+ res = new String[cnt];
+
+ i = 0;
+ b = 0;
+ while (b <= ln) {
+ e = input.indexOf(splitString, b);
+ if (e == -1) e = ln;
+ res[i++] = s.substring(b, e);
+ b = e + sln;
+ }
+ return res;
+ }
+
+ /**
+ * Same as {@link #replace(String, String, String, boolean, boolean)} with two {@code false} parameters.
+ */
+ public static String replace(String text, String oldSub, String newSub) {
+ return replace(text, oldSub, newSub, false, false);
+ }
+
+ /**
+ * Replaces all occurrences of a sub-string in a string.
+ * @param text The string where it will replace <code>oldSub</code> with
+ * <code>newSub</code>.
+ * @return String The string after the replacements.
+ */
+ public static String replace(String text,
+ String oldSub,
+ String newSub,
+ boolean caseInsensitive,
+ boolean firstOnly) {
+ StringBuilder buf;
+ int tln;
+ int oln = oldSub.length();
+
+ if (oln == 0) {
+ int nln = newSub.length();
+ if (nln == 0) {
+ return text;
+ } else {
+ if (firstOnly) {
+ return newSub + text;
+ } else {
+ tln = text.length();
+ buf = new StringBuilder(tln + (tln + 1) * nln);
+ buf.append(newSub);
+ for (int i = 0; i < tln; i++) {
+ buf.append(text.charAt(i));
+ buf.append(newSub);
+ }
+ return buf.toString();
+ }
+ }
+ } else {
+ oldSub = caseInsensitive ? oldSub.toLowerCase() : oldSub;
+ String input = caseInsensitive ? text.toLowerCase() : text;
+ int e = input.indexOf(oldSub);
+ if (e == -1) {
+ return text;
+ }
+ int b = 0;
+ tln = text.length();
+ buf = new StringBuilder(
+ tln + Math.max(newSub.length() - oln, 0) * 3);
+ do {
+ buf.append(text.substring(b, e));
+ buf.append(newSub);
+ b = e + oln;
+ e = input.indexOf(oldSub, b);
+ } while (e != -1 && !firstOnly);
+ buf.append(text.substring(b));
+ return buf.toString();
+ }
+ }
+
+ /**
+ * Removes a line-break from the end of the string (if there's any).
+ */
+ public static String chomp(String s) {
+ if (s.endsWith("\r\n")) return s.substring(0, s.length() - 2);
+ if (s.endsWith("\r") || s.endsWith("\n"))
+ return s.substring(0, s.length() - 1);
+ return s;
+ }
+
+ /**
+ * Converts a 0-length string to null, leaves the string as is otherwise.
+ * @param s maybe {@code null}.
+ */
+ public static String emptyToNull(String s) {
+ if (s == null) return null;
+ return s.length() == 0 ? null : s;
+ }
+
+ /**
+ * Converts the parameter with <code>toString</code> (if it's not <code>null</code>) and passes it to
+ * {@link #jQuote(String)}.
+ */
+ public static String jQuote(Object obj) {
+ return jQuote(obj != null ? obj.toString() : null);
+ }
+
+ /**
+ * Quotes string as Java Language string literal.
+ * Returns string <code>"null"</code> if <code>s</code>
+ * is <code>null</code>.
+ */
+ public static String jQuote(String s) {
+ if (s == null) {
+ return "null";
+ }
+ int ln = s.length();
+ StringBuilder b = new StringBuilder(ln + 4);
+ b.append('"');
+ for (int i = 0; i < ln; i++) {
+ char c = s.charAt(i);
+ if (c == '"') {
+ b.append("\\\"");
+ } else if (c == '\\') {
+ b.append("\\\\");
+ } else if (c < 0x20) {
+ if (c == '\n') {
+ b.append("\\n");
+ } else if (c == '\r') {
+ b.append("\\r");
+ } else if (c == '\f') {
+ b.append("\\f");
+ } else if (c == '\b') {
+ b.append("\\b");
+ } else if (c == '\t') {
+ b.append("\\t");
+ } else {
+ b.append("\\u00");
+ int x = c / 0x10;
+ b.append(toHexDigit(x));
+ x = c & 0xF;
+ b.append(toHexDigit(x));
+ }
+ } else {
+ b.append(c);
+ }
+ } // for each characters
+ b.append('"');
+ return b.toString();
+ }
+
+ /**
+ * Converts the parameter with <code>toString</code> (if not
+ * <code>null</code>)and passes it to {@link #jQuoteNoXSS(String)}.
+ */
+ public static String jQuoteNoXSS(Object obj) {
+ return jQuoteNoXSS(obj != null ? obj.toString() : null);
+ }
+
+ /**
+ * Same as {@link #jQuote(String)} but also escapes <code>'<'</code>
+ * as <code>\</code><code>u003C</code>. This is used for log messages to prevent XSS
+ * on poorly written Web-based log viewers.
+ */
+ public static String jQuoteNoXSS(String s) {
+ if (s == null) {
+ return "null";
+ }
+ int ln = s.length();
+ StringBuilder b = new StringBuilder(ln + 4);
+ b.append('"');
+ for (int i = 0; i < ln; i++) {
+ char c = s.charAt(i);
+ if (c == '"') {
+ b.append("\\\"");
+ } else if (c == '\\') {
+ b.append("\\\\");
+ } else if (c == '<') {
+ b.append("\\u003C");
+ } else if (c < 0x20) {
+ if (c == '\n') {
+ b.append("\\n");
+ } else if (c == '\r') {
+ b.append("\\r");
+ } else if (c == '\f') {
+ b.append("\\f");
+ } else if (c == '\b') {
+ b.append("\\b");
+ } else if (c == '\t') {
+ b.append("\\t");
+ } else {
+ b.append("\\u00");
+ int x = c / 0x10;
+ b.append(toHexDigit(x));
+ x = c & 0xF;
+ b.append(toHexDigit(x));
+ }
+ } else {
+ b.append(c);
+ }
+ } // for each characters
+ b.append('"');
+ return b.toString();
+ }
+
+ /**
+ * Escapes the <code>String</code> with the escaping rules of Java language
+ * string literals, so it's safe to insert the value into a string literal.
+ * The resulting string will not be quoted.
+ *
+ * <p>All characters under UCS code point 0x20 will be escaped.
+ * Where they have no dedicated escape sequence in Java, they will
+ * be replaced with hexadecimal escape (<tt>\</tt><tt>u<i>XXXX</i></tt>).
+ *
+ * @see #jQuote(String)
+ */
+ public static String javaStringEnc(String s) {
+ int ln = s.length();
+ for (int i = 0; i < ln; i++) {
+ char c = s.charAt(i);
+ if (c == '"' || c == '\\' || c < 0x20) {
+ StringBuilder b = new StringBuilder(ln + 4);
+ b.append(s.substring(0, i));
+ while (true) {
+ if (c == '"') {
+ b.append("\\\"");
+ } else if (c == '\\') {
+ b.append("\\\\");
+ } else if (c < 0x20) {
+ if (c == '\n') {
+ b.append("\\n");
+ } else if (c == '\r') {
+ b.append("\\r");
+ } else if (c == '\f') {
+ b.append("\\f");
+ } else if (c == '\b') {
+ b.append("\\b");
+ } else if (c == '\t') {
+ b.append("\\t");
+ } else {
+ b.append("\\u00");
+ int x = c / 0x10;
+ b.append((char)
+ (x < 0xA ? x + '0' : x - 0xA + 'a'));
+ x = c & 0xF;
+ b.append((char)
+ (x < 0xA ? x + '0' : x - 0xA + 'a'));
+ }
+ } else {
+ b.append(c);
+ }
+ i++;
+ if (i >= ln) {
+ return b.toString();
+ }
+ c = s.charAt(i);
+ }
+ } // if has to be escaped
+ } // for each characters
+ return s;
+ }
+
+ /**
+ * Escapes a {@link String} to be safely insertable into a JavaScript string literal; for more see
+ * {@link #jsStringEnc(String, boolean) jsStringEnc(s, false)}.
+ */
+ public static String javaScriptStringEnc(String s) {
+ return jsStringEnc(s, false);
+ }
+
+ /**
+ * Escapes a {@link String} to be safely insertable into a JSON string literal; for more see
+ * {@link #jsStringEnc(String, boolean) jsStringEnc(s, true)}.
+ */
+ public static String jsonStringEnc(String s) {
+ return jsStringEnc(s, true);
+ }
+
+ private static final int NO_ESC = 0;
+ private static final int ESC_HEXA = 1;
+ private static final int ESC_BACKSLASH = 3;
+
+ /**
+ * Escapes a {@link String} to be safely insertable into a JavaScript or a JSON string literal.
+ * The resulting string will <em>not</em> be quoted; the caller must ensure that they are there in the final
+ * output. Note that for JSON, the quotation marks must be {@code "}, not {@code '}, because JSON doesn't escape
+ * {@code '}.
+ *
+ * <p>The escaping rules guarantee that if the inside of the JavaScript/JSON string literal is from one or more
+ * touching pieces that were escaped with this, no character sequence can occur that closes the
+ * JavaScript/JSON string literal, or has a meaning in HTML/XML that causes the HTML script section to be closed.
+ * (If, however, the escaped section is preceded by or followed by strings from other sources, this can't be
+ * guaranteed in some rare cases. Like <tt>x = "</${a?jsString}"</tt> might closes the "script"
+ * element if {@code a} is {@code "script>"}.)
+ *
+ * The escaped characters are:
+ *
+ * <table style="width: auto; border-collapse: collapse" border="1" summary="Characters escaped by jsStringEnc">
+ * <tr>
+ * <th>Input
+ * <th>Output
+ * <tr>
+ * <td><tt>"</tt>
+ * <td><tt>\"</tt>
+ * <tr>
+ * <td><tt>'</tt> if not in JSON-mode
+ * <td><tt>\'</tt>
+ * <tr>
+ * <td><tt>\</tt>
+ * <td><tt>\\</tt>
+ * <tr>
+ * <td><tt>/</tt> if the method can't know that it won't be directly after <tt><</tt>
+ * <td><tt>\/</tt>
+ * <tr>
+ * <td><tt>></tt> if the method can't know that it won't be directly after <tt>]]</tt> or <tt>--</tt>
+ * <td>JavaScript: <tt>\></tt>; JSON: <tt>\</tt><tt>u003E</tt>
+ * <tr>
+ * <td><tt><</tt> if the method can't know that it won't be directly followed by <tt>!</tt> or <tt>?</tt>
+ * <td><tt><tt>\</tt>u003C</tt>
+ * <tr>
+ * <td>
+ * u0000-u001f (UNICODE control characters - disallowed by JSON)<br>
+ * u007f-u009f (UNICODE control characters - disallowed by JSON)
+ * <td><tt>\n</tt>, <tt>\r</tt> and such, or if there's no such dedicated escape:
+ * JavaScript: <tt>\x<i>XX</i></tt>, JSON: <tt>\<tt>u</tt><i>XXXX</i></tt>
+ * <tr>
+ * <td>
+ * u2028 (Line separator - source code line-break in ECMAScript)<br>
+ * u2029 (Paragraph separator - source code line-break in ECMAScript)<br>
+ * <td><tt>\<tt>u</tt><i>XXXX</i></tt>
+ * </table>
+ */
+ public static String jsStringEnc(String s, boolean json) {
+ _NullArgumentException.check("s", s);
+
+ int ln = s.length();
+ StringBuilder sb = null;
+ for (int i = 0; i < ln; i++) {
+ final char c = s.charAt(i);
+ final int escapeType; //
+ if (!(c > '>' && c < 0x7F && c != '\\') && c != ' ' && !(c >= 0xA0 && c < 0x2028)) { // skip common chars
+ if (c <= 0x1F) { // control chars range 1
+ if (c == '\n') {
+ escapeType = 'n';
+ } else if (c == '\r') {
+ escapeType = 'r';
+ } else if (c == '\f') {
+ escapeType = 'f';
+ } else if (c == '\b') {
+ escapeType = 'b';
+ } else if (c == '\t') {
+ escapeType = 't';
+ } else {
+ escapeType = ESC_HEXA;
+ }
+ } else if (c == '"') {
+ escapeType = ESC_BACKSLASH;
+ } else if (c == '\'') {
+ escapeType = json ? NO_ESC : ESC_BACKSLASH;
+ } else if (c == '\\') {
+ escapeType = ESC_BACKSLASH;
+ } else if (c == '/' && (i == 0 || s.charAt(i - 1) == '<')) { // against closing elements
+ escapeType = ESC_BACKSLASH;
+ } else if (c == '>') { // against "]]> and "-->"
+ final boolean dangerous;
+ if (i == 0) {
+ dangerous = true;
+ } else {
+ final char prevC = s.charAt(i - 1);
+ if (prevC == ']' || prevC == '-') {
+ if (i == 1) {
+ dangerous = true;
+ } else {
+ final char prevPrevC = s.charAt(i - 2);
+ dangerous = prevPrevC == prevC;
+ }
+ } else {
+ dangerous = false;
+ }
+ }
+ escapeType = dangerous ? (json ? ESC_HEXA : ESC_BACKSLASH) : NO_ESC;
+ } else if (c == '<') { // against "<!"
+ final boolean dangerous;
+ if (i == ln - 1) {
+ dangerous = true;
+ } else {
+ char nextC = s.charAt(i + 1);
+ dangerous = nextC == '!' || nextC == '?';
+ }
+ escapeType = dangerous ? ESC_HEXA : NO_ESC;
+ } else if ((c >= 0x7F && c <= 0x9F) // control chars range 2
+ || (c == 0x2028 || c == 0x2029) // UNICODE line terminators
+ ) {
+ escapeType = ESC_HEXA;
+ } else {
+ escapeType = NO_ESC;
+ }
+
+ if (escapeType != NO_ESC) { // If needs escaping
+ if (sb == null) {
+ sb = new StringBuilder(ln + 6);
+ sb.append(s.substring(0, i));
+ }
+
+ sb.append('\\');
+ if (escapeType > 0x20) {
+ sb.append((char) escapeType);
+ } else if (escapeType == ESC_HEXA) {
+ if (!json && c < 0x100) {
+ sb.append('x');
+ sb.append(toHexDigit(c >> 4));
+ sb.append(toHexDigit(c & 0xF));
+ } else {
+ sb.append('u');
+ sb.append(toHexDigit((c >> 12) & 0xF));
+ sb.append(toHexDigit((c >> 8) & 0xF));
+ sb.append(toHexDigit((c >> 4) & 0xF));
+ sb.append(toHexDigit(c & 0xF));
+ }
+ } else { // escapeType == ESC_BACKSLASH
+ sb.append(c);
+ }
+ continue;
+ }
+ // Falls through when escapeType == NO_ESC
+ }
+ // Needs no escaping
+
+ if (sb != null) sb.append(c);
+ } // for each characters
+
+ return sb == null ? s : sb.toString();
+ }
+
+ private static char toHexDigit(int d) {
+ return (char) (d < 0xA ? d + '0' : d - 0xA + 'A');
+ }
+
+ /**
+ * Parses a name-value pair list, where the pairs are separated with comma,
+ * and the name and value is separated with colon.
+ * The keys and values can contain only letters, digits and <tt>_</tt>. They
+ * can't be quoted. White-space around the keys and values are ignored. The
+ * value can be omitted if <code>defaultValue</code> is not null. When a
+ * value is omitted, then the colon after the key must be omitted as well.
+ * The same key can't be used for multiple times.
+ *
+ * @param s the string to parse.
+ * For example: <code>"strong:100, soft:900"</code>.
+ * @param defaultValue the value used when the value is omitted in a
+ * key-value pair.
+ *
+ * @return the map that contains the name-value pairs.
+ *
+ * @throws java.text.ParseException if the string is not a valid name-value
+ * pair list.
+ */
+ public static Map parseNameValuePairList(String s, String defaultValue)
+ throws java.text.ParseException {
+ Map map = new HashMap();
+
+ char c = ' ';
+ int ln = s.length();
+ int p = 0;
+ int keyStart;
+ int valueStart;
+ String key;
+ String value;
+
+ fetchLoop: while (true) {
+ // skip ws
+ while (p < ln) {
+ c = s.charAt(p);
+ if (!Character.isWhitespace(c)) {
+ break;
+ }
+ p++;
+ }
+ if (p == ln) {
+ break fetchLoop;
+ }
+ keyStart = p;
+
+ // seek key end
+ while (p < ln) {
+ c = s.charAt(p);
+ if (!(Character.isLetterOrDigit(c) || c == '_')) {
+ break;
+ }
+ p++;
+ }
+ if (keyStart == p) {
+ throw new java.text.ParseException(
+ "Expecting letter, digit or \"_\" "
+ + "here, (the first character of the key) but found "
+ + jQuote(String.valueOf(c))
+ + " at position " + p + ".",
+ p);
+ }
+ key = s.substring(keyStart, p);
+
+ // skip ws
+ while (p < ln) {
+ c = s.charAt(p);
+ if (!Character.isWhitespace(c)) {
+ break;
+ }
+ p++;
+ }
+ if (p == ln) {
+ if (defaultValue == null) {
+ throw new java.text.ParseException(
+ "Expecting \":\", but reached "
+ + "the end of the string "
+ + " at position " + p + ".",
+ p);
+ }
+ value = defaultValue;
+ } else if (c != ':') {
+ if (defaultValue == null || c != ',') {
+ throw new java.text.ParseException(
+ "Expecting \":\" here, but found "
+ + jQuote(String.valueOf(c))
+ + " at position " + p + ".",
+ p);
+ }
+
+ // skip ","
+ p++;
+
+ value = defaultValue;
+ } else {
+ // skip ":"
+ p++;
+
+ // skip ws
+ while (p < ln) {
+ c = s.charAt(p);
+ if (!Character.isWhitespace(c)) {
+ break;
+ }
+ p++;
+ }
+ if (p == ln) {
+ throw new java.text.ParseException(
+ "Expecting the value of the key "
+ + "here, but reached the end of the string "
+ + " at position " + p + ".",
+ p);
+ }
+ valueStart = p;
+
+ // seek value end
+ while (p < ln) {
+ c = s.charAt(p);
+ if (!(Character.isLetterOrDigit(c) || c == '_')) {
+ break;
+ }
+ p++;
+ }
+ if (valueStart == p) {
+ throw new java.text.ParseException(
+ "Expecting letter, digit or \"_\" "
+ + "here, (the first character of the value) "
+ + "but found "
+ + jQuote(String.valueOf(c))
+ + " at position " + p + ".",
+ p);
+ }
+ value = s.substring(valueStart, p);
+
+ // skip ws
+ while (p < ln) {
+ c = s.charAt(p);
+ if (!Character.isWhitespace(c)) {
+ break;
+ }
+ p++;
+ }
+
+ // skip ","
+ if (p < ln) {
+ if (c != ',') {
+ throw new java.text.ParseException(
+ "Excpecting \",\" or the end "
+ + "of the string here, but found "
+ + jQuote(String.valueOf(c))
+ + " at position " + p + ".",
+ p);
+ } else {
+ p++;
+ }
+ }
+ }
+
+ // store the key-value pair
+ if (map.put(key, value) != null) {
+ throw new java.text.ParseException(
+ "Dublicated key: "
+ + jQuote(key), keyStart);
+ }
+ }
+
+ return map;
+ }
+
+ /**
+ * @return whether the qname matches the combination of nodeName, nsURI, and environment prefix settings.
+ */
+ static public boolean matchesQName(String qname, String nodeName, String nsURI, Environment env) {
+ String defaultNS = env.getDefaultNS();
+ if ((defaultNS != null) && defaultNS.equals(nsURI)) {
+ return qname.equals(nodeName)
+ || qname.equals(Template.DEFAULT_NAMESPACE_PREFIX + ":" + nodeName);
+ }
+ if ("".equals(nsURI)) {
+ if (defaultNS != null) {
+ return qname.equals(Template.NO_NS_PREFIX + ":" + nodeName);
+ } else {
+ return qname.equals(nodeName) || qname.equals(Template.NO_NS_PREFIX + ":" + nodeName);
+ }
+ }
+ String prefix = env.getPrefixForNamespace(nsURI);
+ if (prefix == null) {
+ return false; // Is this the right thing here???
+ }
+ return qname.equals(prefix + ":" + nodeName);
+ }
+
+ /**
+ * Pads the string at the left with spaces until it reaches the desired
+ * length. If the string is longer than this length, then it returns the
+ * unchanged string.
+ *
+ * @param s the string that will be padded.
+ * @param minLength the length to reach.
+ */
+ public static String leftPad(String s, int minLength) {
+ return leftPad(s, minLength, ' ');
+ }
+
+ /**
+ * Pads the string at the left with the specified character until it reaches
+ * the desired length. If the string is longer than this length, then it
+ * returns the unchanged string.
+ *
+ * @param s the string that will be padded.
+ * @param minLength the length to reach.
+ * @param filling the filling pattern.
+ */
+ public static String leftPad(String s, int minLength, char filling) {
+ int ln = s.length();
+ if (minLength <= ln) {
+ return s;
+ }
+
+ StringBuilder res = new StringBuilder(minLength);
+
+ int dif = minLength - ln;
+ for (int i = 0; i < dif; i++) {
+ res.append(filling);
+ }
+
+ res.append(s);
+
+ return res.toString();
+ }
+
+ /**
+ * Pads the string at the left with a filling pattern until it reaches the
+ * desired length. If the string is longer than this length, then it returns
+ * the unchanged string. For example: <code>leftPad('ABC', 9, '1234')</code>
+ * returns <code>"123412ABC"</code>.
+ *
+ * @param s the string that will be padded.
+ * @param minLength the length to reach.
+ * @param filling the filling pattern. Must be at least 1 characters long.
+ * Can't be <code>null</code>.
+ */
+ public static String leftPad(String s, int minLength, String filling) {
+ int ln = s.length();
+ if (minLength <= ln) {
+ return s;
+ }
+
+ StringBuilder res = new StringBuilder(minLength);
+
+ int dif = minLength - ln;
+ int fln = filling.length();
+ if (fln == 0) {
+ throw new IllegalArgumentException(
+ "The \"filling\" argument can't be 0 length string.");
+ }
+ int cnt = dif / fln;
+ for (int i = 0; i < cnt; i++) {
+ res.append(filling);
+ }
+ cnt = dif % fln;
+ for (int i = 0; i < cnt; i++) {
+ res.append(filling.charAt(i));
+ }
+
+ res.append(s);
+
+ return res.toString();
+ }
+
+ /**
+ * Pads the string at the right with spaces until it reaches the desired
+ * length. If the string is longer than this length, then it returns the
+ * unchanged string.
+ *
+ * @param s the string that will be padded.
+ * @param minLength the length to reach.
+ */
+ public static String rightPad(String s, int minLength) {
+ return rightPad(s, minLength, ' ');
+ }
+
+ /**
+ * Pads the string at the right with the specified character until it
+ * reaches the desired length. If the string is longer than this length,
+ * then it returns the unchanged string.
+ *
+ * @param s the string that will be padded.
+ * @param minLength the length to reach.
+ * @param filling the filling pattern.
+ */
+ public static String rightPad(String s, int minLength, char filling) {
+ int ln = s.length();
+ if (minLength <= ln) {
+ return s;
+ }
+
+ StringBuilder res = new StringBuilder(minLength);
+
+ res.append(s);
+
+ int dif = minLength - ln;
+ for (int i = 0; i < dif; i++) {
+ res.append(filling);
+ }
+
+ return res.toString();
+ }
+
+ /**
+ * Pads the string at the right with a filling pattern until it reaches the
+ * desired length. If the string is longer than this length, then it returns
+ * the unchanged string. For example: <code>rightPad('ABC', 9, '1234')</code>
+ * returns <code>"ABC412341"</code>. Note that the filling pattern is
+ * started as if you overlay <code>"123412341"</code> with the left-aligned
+ * <code>"ABC"</code>, so it starts with <code>"4"</code>.
+ *
+ * @param s the string that will be padded.
+ * @param minLength the length to reach.
+ * @param filling the filling pattern. Must be at least 1 characters long.
+ * Can't be <code>null</code>.
+ */
+ public static String rightPad(String s, int minLength, String filling) {
+ int ln = s.length();
+ if (minLength <= ln) {
+ return s;
+ }
+
+ StringBuilder res = new StringBuilder(minLength);
+
+ res.append(s);
+
+ int dif = minLength - ln;
+ int fln = filling.length();
+ if (fln == 0) {
+ throw new IllegalArgumentException(
+ "The \"filling\" argument can't be 0 length string.");
+ }
+ int start = ln % fln;
+ int end = fln - start <= dif
+ ? fln
+ : start + dif;
+ for (int i = start; i < end; i++) {
+ res.append(filling.charAt(i));
+ }
+ dif -= end - start;
+ int cnt = dif / fln;
+ for (int i = 0; i < cnt; i++) {
+ res.append(filling);
+ }
+ cnt = dif % fln;
+ for (int i = 0; i < cnt; i++) {
+ res.append(filling.charAt(i));
+ }
+
+ return res.toString();
+ }
+
+ /**
+ * Converts a version number string to an integer for easy comparison.
+ * The version number must start with numbers separated with
+ * dots. There can be any number of such dot-separated numbers, but only
+ * the first three will be considered. After the numbers arbitrary text can
+ * follow, and will be ignored.
+ *
+ * The string will be trimmed before interpretation.
+ *
+ * @return major * 1000000 + minor * 1000 + micro
+ */
+ public static int versionStringToInt(String version) {
+ return new Version(version).intValue();
+ }
+
+ /**
+ * Tries to run {@code toString()}, but if that fails, returns a
+ * {@code "[com.example.SomeClass.toString() failed: " + e + "]"} instead. Also, it returns {@code null} for
+ * {@code null} parameter.
+ */
+ public static String tryToString(Object object) {
+ if (object == null) return null;
+
+ try {
+ return object.toString();
+ } catch (Throwable e) {
+ return failedToStringSubstitute(object, e);
+ }
+ }
+
+ private static String failedToStringSubstitute(Object object, Throwable e) {
+ String eStr;
+ try {
+ eStr = e.toString();
+ } catch (Throwable e2) {
+ eStr = _ClassUtils.getShortClassNameOfObject(e);
+ }
+ return "[" + _ClassUtils.getShortClassNameOfObject(object) + ".toString() failed: " + eStr + "]";
+ }
+
+ /**
+ * Converts {@code 1}, {@code 2}, {@code 3} and so forth to {@code "A"}, {@code "B"}, {@code "C"} and so fort. When
+ * reaching {@code "Z"}, it continues like {@code "AA"}, {@code "AB"}, etc. The lowest supported number is 1, but
+ * there's no upper limit.
+ *
+ * @throws IllegalArgumentException
+ * If the argument is 0 or less.
+ */
+ public static String toUpperABC(int n) {
+ return toABC(n, 'A');
+ }
+
+ /**
+ * Same as {@link #toUpperABC(int)}, but produces lower case result, like {@code "ab"}.
+ */
+ public static String toLowerABC(int n) {
+ return toABC(n, 'a');
+ }
+
+ /**
+ * @param oneDigit
+ * The character that stands for the value 1.
+ */
+ private static String toABC(final int n, char oneDigit) {
+ if (n < 1) {
+ throw new IllegalArgumentException("Can't convert 0 or negative "
+ + "numbers to latin-number: " + n);
+ }
+
+ // First find out how many "digits" will we need. We start from A, then
+ // try AA, then AAA, etc. (Note that the smallest digit is "A", which is
+ // 1, not 0. Hence this isn't like a usual 26-based number-system):
+ int reached = 1;
+ int weight = 1;
+ while (true) {
+ int nextWeight = weight * 26;
+ int nextReached = reached + nextWeight;
+ if (nextReached <= n) {
+ // So we will have one more digit
+ weight = nextWeight;
+ reached = nextReached;
+ } else {
+ // No more digits
+ break;
+ }
+ }
+
+ // Increase the digits of the place values until we get as close
+ // to n as possible (but don't step over it).
+ StringBuilder sb = new StringBuilder();
+ while (weight != 0) {
+ // digitIncrease: how many we increase the digit which is already 1
+ final int digitIncrease = (n - reached) / weight;
+ sb.append((char) (oneDigit + digitIncrease));
+ reached += digitIncrease * weight;
+
+ weight /= 26;
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Behaves exactly like {@link String#trim()}, but works on arrays. If the resulting array would have the same
+ * content after trimming, it returns the original array instance. Otherwise it returns a new array instance (or
+ * {@link _CollectionUtils#EMPTY_CHAR_ARRAY}).
+ */
+ public static char[] trim(final char[] cs) {
+ if (cs.length == 0) {
+ return cs;
+ }
+
+ int start = 0;
+ int end = cs.length;
+ while (start < end && cs[start] <= ' ') {
+ start++;
+ }
+ while (start < end && cs[end - 1] <= ' ') {
+ end--;
+ }
+
+ if (start == 0 && end == cs.length) {
+ return cs;
+ }
+ if (start == end) {
+ return _CollectionUtils.EMPTY_CHAR_ARRAY;
+ }
+
+ char[] newCs = new char[end - start];
+ System.arraycopy(cs, start, newCs, 0, end - start);
+ return newCs;
+ }
+
+ /**
+ * Tells if {@link String#trim()} will return a 0-length string for the {@link String} equivalent of the argument.
+ */
+ public static boolean isTrimmableToEmpty(char[] text) {
+ return isTrimmableToEmpty(text, 0, text.length);
+ }
+
+ /**
+ * Like {@link #isTrimmableToEmpty(char[])}, but acts on a sub-array that starts at {@code start} (inclusive index).
+ */
+ public static boolean isTrimmableToEmpty(char[] text, int start) {
+ return isTrimmableToEmpty(text, start, text.length);
+ }
+
+ /**
+ * Like {@link #isTrimmableToEmpty(char[])}, but acts on a sub-array that starts at {@code start} (inclusive index)
+ * and ends at {@code end} (exclusive index).
+ */
+ public static boolean isTrimmableToEmpty(char[] text, int start, int end) {
+ for (int i = start; i < end; i++) {
+ // We follow Java's String.trim() here, which simply states that c <= ' ' is whitespace.
+ if (text[i] > ' ') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Same as {@link #globToRegularExpression(String, boolean)} with {@code caseInsensitive} argument {@code false}.
+ */
+ public static Pattern globToRegularExpression(String glob) {
+ return globToRegularExpression(glob, false);
+ }
+
+ /**
+ * Creates a regular expression from a glob. The glob must use {@code /} for as file separator, not {@code \}
+ * (backslash), and is always case sensitive.
+ *
+ * <p>This glob implementation recognizes these special characters:
+ * <ul>
+ * <li>{@code ?}: Wildcard that matches exactly one character, other than {@code /}
+ * <li>{@code *}: Wildcard that matches zero, one or multiple characters, other than {@code /}
+ * <li>{@code **}: Wildcard that matches zero, one or multiple directories. For example, {@code **}{@code /head.ftl}
+ * matches {@code foo/bar/head.ftl}, {@code foo/head.ftl} and {@code head.ftl} too. {@code **} must be either
+ * preceded by {@code /} or be at the beginning of the glob. {@code **} must be either followed by {@code /} or be
+ * at the end of the glob. When {@code **} is at the end of the glob, it also matches file names, like
+ * {@code a/**} matches {@code a/b/c.ftl}. If the glob only consist of a {@code **}, it will be a match for
+ * everything.
+ * <li>{@code \} (backslash): Makes the next character non-special (a literal). For example {@code How\?.ftl} will
+ * match {@code How?.ftl}, but not {@code HowX.ftl}. Naturally, two backslashes produce one literal backslash.
+ * <li>{@code [}: Reserved for future purposes; can't be used
+ * <li><code>{</code>: Reserved for future purposes; can't be used
+ * </ul>
+ */
+ public static Pattern globToRegularExpression(String glob, boolean caseInsensitive) {
+ StringBuilder regex = new StringBuilder();
+
+ int nextStart = 0;
+ boolean escaped = false;
+ int ln = glob.length();
+ for (int idx = 0; idx < ln; idx++) {
+ char c = glob.charAt(idx);
+ if (!escaped) {
+ if (c == '?') {
+ appendLiteralGlobSection(regex, glob, nextStart, idx);
+ regex.append("[^/]");
+ nextStart = idx + 1;
+ } else if (c == '*') {
+ appendLiteralGlobSection(regex, glob, nextStart, idx);
+ if (idx + 1 < ln && glob.charAt(idx + 1) == '*') {
+ if (!(idx == 0 || glob.charAt(idx - 1) == '/')) {
+ throw new IllegalArgumentException(
+ "The \"**\" wildcard must be directly after a \"/\" or it must be at the "
+ + "beginning, in this glob: " + glob);
+ }
+
+ if (idx + 2 == ln) { // trailing "**"
+ regex.append(".*");
+ idx++;
+ } else { // "**/"
+ if (!(idx + 2 < ln && glob.charAt(idx + 2) == '/')) {
+ throw new IllegalArgumentException(
+ "The \"**\" wildcard must be followed by \"/\", or must be at tehe end, "
+ + "in this glob: " + glob);
+ }
+ regex.append("(.*?/)*");
+ idx += 2; // "*/".length()
+ }
+ } else {
+ regex.append("[^/]*");
+ }
+ nextStart = idx + 1;
+ } else if (c == '\\') {
+ escaped = true;
+ } else if (c == '[' || c == '{') {
+ throw new IllegalArgumentException(
+ "The \"" + c + "\" glob operator is currently unsupported "
+ + "(precede it with \\ for literal matching), "
+ + "in this glob: " + glob);
+ }
+ } else {
+ escaped = false;
+ }
+ }
+ appendLiteralGlobSection(regex, glob, nextStart, glob.length());
+
+ return Pattern.compile(regex.toString(), caseInsensitive ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE : 0);
+ }
+
+ private static void appendLiteralGlobSection(StringBuilder regex, String glob, int start, int end) {
+ if (start == end) return;
+ String part = unescapeLiteralGlobSection(glob.substring(start, end));
+ regex.append(Pattern.quote(part));
+ }
+
+ private static String unescapeLiteralGlobSection(String s) {
+ int backslashIdx = s.indexOf('\\');
+ if (backslashIdx == -1) {
+ return s;
+ }
+ int ln = s.length();
+ StringBuilder sb = new StringBuilder(ln - 1);
+ int nextStart = 0;
+ do {
+ sb.append(s, nextStart, backslashIdx);
+ nextStart = backslashIdx + 1;
+ } while ((backslashIdx = s.indexOf('\\', nextStart + 1)) != -1);
+ if (nextStart < ln) {
+ sb.append(s, nextStart, ln);
+ }
+ return sb.toString();
+ }
+
+ public static String toFTLIdentifierReferenceAfterDot(String name) {
+ return FTLUtil.escapeIdentifier(name);
+ }
+
+ public static String toFTLTopLevelIdentifierReference(String name) {
+ return FTLUtil.escapeIdentifier(name);
+ }
+
+ public static String toFTLTopLevelTragetIdentifier(final String name) {
+ char quotationType = 0;
+ scanForQuotationType: for (int i = 0; i < name.length(); i++) {
+ final char c = name.charAt(i);
+ if (!(i == 0 ? FTLUtil.isNonEscapedIdentifierStart(c) : FTLUtil.isNonEscapedIdentifierPart(c)) && c != '@') {
+ if ((quotationType == 0 || quotationType == '\\') && (c == '-' || c == '.' || c == ':')) {
+ quotationType = '\\';
+ } else {
+ quotationType = '"';
+ break scanForQuotationType;
+ }
+ }
+ }
+ switch (quotationType) {
+ case 0:
+ return name;
+ case '"':
+ return FTLUtil.toStringLiteral(name);
+ case '\\':
+ return FTLUtil.escapeIdentifier(name);
+ default:
+ throw new BugException();
+ }
+ }
+
+ public static String snakeCaseToCamelCase(String s) {
+ if (s == null) {
+ return null;
+ }
+
+ int wordEndIdx = s.indexOf('_');
+ if (wordEndIdx == -1) {
+ return s.toLowerCase();
+ }
+
+ StringBuilder sb = new StringBuilder(s.length());
+ int wordStartIdx = 0;
+ do {
+ if (wordStartIdx < wordEndIdx) {
+ char wordStartC = s.charAt(wordStartIdx);
+ sb.append(sb.length() != 0 ? Character.toUpperCase(wordStartC) : Character.toLowerCase(wordStartC));
+ sb.append(s.substring(wordStartIdx + 1, wordEndIdx).toLowerCase());
+ }
+
+ wordStartIdx = wordEndIdx + 1;
+ wordEndIdx = s.indexOf('_', wordStartIdx);
+ if (wordEndIdx == -1) {
+ wordEndIdx = s.length();
+ }
+ } while (wordStartIdx < s.length());
+ return sb.toString();
+ }
+
+ public static boolean isASCIIDigit(char c) {
+ return c >= '0' && c <= '9';
+ }
+
+ public static boolean isUpperUSASCII(char c) {
+ return c >= 'A' && c <= 'Z';
+ }
+
+ private static final Pattern NORMALIZE_EOLS_REGEXP = Pattern.compile("\\r\\n?+");
+
+ /**
+ * Converts all non UN*X End-Of-Line character sequences (CR and CRLF) to UN*X format (LF).
+ * Returns {@code null} for {@code null} input.
+ */
+ public static String normalizeEOLs(String s) {
+ if (s == null) {
+ return null;
+ }
+ return NORMALIZE_EOLS_REGEXP.matcher(s).replaceAll("\n");
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/TemplateFormatUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/TemplateFormatUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/TemplateFormatUtil.java
index 366962a..a047e70 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/TemplateFormatUtil.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/TemplateFormatUtil.java
@@ -20,7 +20,7 @@ package org.apache.freemarker.core.valueformat;
import java.util.Date;
-import org.apache.freemarker.core._EvalUtil;
+import org.apache.freemarker.core._EvalUtils;
import org.apache.freemarker.core.model.ObjectWrapper;
import org.apache.freemarker.core.model.TemplateDateModel;
import org.apache.freemarker.core.model.TemplateModelException;
@@ -53,7 +53,7 @@ public final class TemplateFormatUtil {
throws TemplateModelException, UnformattableValueException {
Number number = numberModel.getAsNumber();
if (number == null) {
- throw _EvalUtil.newModelHasStoredNullException(Number.class, numberModel, null);
+ throw _EvalUtils.newModelHasStoredNullException(Number.class, numberModel, null);
}
return number;
}
@@ -67,7 +67,7 @@ public final class TemplateFormatUtil {
public static Date getNonNullDate(TemplateDateModel dateModel) throws TemplateModelException {
Date date = dateModel.getAsDate();
if (date == null) {
- throw _EvalUtil.newModelHasStoredNullException(Date.class, dateModel, null);
+ throw _EvalUtils.newModelHasStoredNullException(Date.class, dateModel, null);
}
return date;
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateDateFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateDateFormatFactory.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateDateFormatFactory.java
index eefb512..58331f3 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateDateFormatFactory.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateDateFormatFactory.java
@@ -23,8 +23,8 @@ import java.util.Map;
import java.util.TimeZone;
import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.util._LocaleUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._LocaleUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.TemplateDateFormat;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
import org.apache.freemarker.core.valueformat.TemplateFormatUtil;
@@ -76,7 +76,7 @@ public final class AliasTemplateDateFormatFactory extends TemplateDateFormatFact
Locale lookupLocale = locale;
targetFormatString = localizedTargetFormatStrings.get(lookupLocale);
while (targetFormatString == null
- && (lookupLocale = _LocaleUtil.getLessSpecificLocale(lookupLocale)) != null) {
+ && (lookupLocale = _LocaleUtils.getLessSpecificLocale(lookupLocale)) != null) {
targetFormatString = localizedTargetFormatStrings.get(lookupLocale);
}
} else {
@@ -88,7 +88,7 @@ public final class AliasTemplateDateFormatFactory extends TemplateDateFormatFact
return env.getTemplateDateFormat(targetFormatString, dateType, locale, timeZone, zonelessInput);
} catch (TemplateValueFormatException e) {
throw new AliasTargetTemplateValueFormatException("Failed to invoke format based on target format string, "
- + _StringUtil.jQuote(params) + ". Reason given: " + e.getMessage(), e);
+ + _StringUtils.jQuote(params) + ". Reason given: " + e.getMessage(), e);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateNumberFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateNumberFormatFactory.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateNumberFormatFactory.java
index 9d80ab8..9844c5c 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateNumberFormatFactory.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/AliasTemplateNumberFormatFactory.java
@@ -22,8 +22,8 @@ import java.util.Locale;
import java.util.Map;
import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.util._LocaleUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._LocaleUtils;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.TemplateFormatUtil;
import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory;
@@ -75,7 +75,7 @@ public final class AliasTemplateNumberFormatFactory extends TemplateNumberFormat
Locale lookupLocale = locale;
targetFormatString = localizedTargetFormatStrings.get(lookupLocale);
while (targetFormatString == null
- && (lookupLocale = _LocaleUtil.getLessSpecificLocale(lookupLocale)) != null) {
+ && (lookupLocale = _LocaleUtils.getLessSpecificLocale(lookupLocale)) != null) {
targetFormatString = localizedTargetFormatStrings.get(lookupLocale);
}
} else {
@@ -87,7 +87,7 @@ public final class AliasTemplateNumberFormatFactory extends TemplateNumberFormat
return env.getTemplateNumberFormat(targetFormatString, locale);
} catch (TemplateValueFormatException e) {
throw new AliasTargetTemplateValueFormatException("Failed to invoke format based on target format string, "
- + _StringUtil.jQuote(params) + ". Reason given: " + e.getMessage(), e);
+ + _StringUtils.jQuote(params) + ". Reason given: " + e.getMessage(), e);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ExtendedDecimalFormatParser.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ExtendedDecimalFormatParser.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ExtendedDecimalFormatParser.java
index dc1709c..cd4593d 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ExtendedDecimalFormatParser.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ExtendedDecimalFormatParser.java
@@ -28,7 +28,7 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.Set;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Parses a {@link DecimalFormat} pattern string to a {@link DecimalFormat} instance, with the pattern string extensions
@@ -324,14 +324,14 @@ class ExtendedDecimalFormatParser {
private ParseException newInvalidParameterValueException(String name, String value, int valuePos,
InvalidParameterValueException e) {
return new java.text.ParseException(
- _StringUtil.jQuote(value) + " is an invalid value for the \"" + name + "\" parameter: "
+ _StringUtils.jQuote(value) + " is an invalid value for the \"" + name + "\" parameter: "
+ e.message,
valuePos);
}
private ParseException newUnknownParameterException(String name, int namePos) throws ParseException {
StringBuilder sb = new StringBuilder(128);
- sb.append("Unsupported parameter name, ").append(_StringUtil.jQuote(name));
+ sb.append("Unsupported parameter name, ").append(_StringUtils.jQuote(name));
sb.append(". The supported names are: ");
Set<String> legalNames = PARAM_HANDLERS.keySet();
String[] legalNameArr = legalNames.toArray(new String[legalNames.size()]);
@@ -427,7 +427,7 @@ class ExtendedDecimalFormatParser {
}
private String unescape(String s, char openedQuot) {
- return openedQuot == '\'' ? _StringUtil.replace(s, "\'\'", "\'") : _StringUtil.replace(s, "\"\"", "\"");
+ return openedQuot == '\'' ? _StringUtils.replace(s, "\'\'", "\'") : _StringUtils.replace(s, "\"\"", "\"");
}
private String fetchStandardPattern() {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormat.java
index b76e7a3..1598518 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormat.java
@@ -26,11 +26,11 @@ import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.model.TemplateDateModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._DateUtil;
-import org.apache.freemarker.core.util._DateUtil.CalendarFieldsToDateConverter;
-import org.apache.freemarker.core.util._DateUtil.DateParseException;
-import org.apache.freemarker.core.util._DateUtil.DateToISO8601CalendarFactory;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._DateUtils;
+import org.apache.freemarker.core.util._DateUtils.CalendarFieldsToDateConverter;
+import org.apache.freemarker.core.util._DateUtils.DateParseException;
+import org.apache.freemarker.core.util._DateUtils.DateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._StringUtils;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.TemplateDateFormat;
import org.apache.freemarker.core.valueformat.TemplateFormatUtil;
@@ -75,7 +75,7 @@ abstract class ISOLikeTemplateDateFormat extends TemplateDateFormat {
final int ln = formatString.length();
boolean afterSeparator = false;
int i = parsingStart;
- int accuracy = _DateUtil.ACCURACY_MILLISECONDS;
+ int accuracy = _DateUtils.ACCURACY_MILLISECONDS;
Boolean showZoneOffset = null;
Boolean forceUTC = Boolean.FALSE;
while (i < ln) {
@@ -92,7 +92,7 @@ abstract class ISOLikeTemplateDateFormat extends TemplateDateFormat {
case 'h':
case 'm':
case 's':
- if (accuracy != _DateUtil.ACCURACY_MILLISECONDS) {
+ if (accuracy != _DateUtils.ACCURACY_MILLISECONDS) {
throw new InvalidFormatParametersException(
"Character \"" + c + "\" is unexpected as accuracy was already specified earlier "
+ "(at char pos. " + i + ").");
@@ -103,22 +103,22 @@ abstract class ISOLikeTemplateDateFormat extends TemplateDateFormat {
throw new InvalidFormatParametersException(
XS_LESS_THAN_SECONDS_ACCURACY_ERROR_MESSAGE);
}
- accuracy = _DateUtil.ACCURACY_HOURS;
+ accuracy = _DateUtils.ACCURACY_HOURS;
break;
case 'm':
if (i < ln && formatString.charAt(i) == 's') {
i++;
- accuracy = _DateUtil.ACCURACY_MILLISECONDS_FORCED;
+ accuracy = _DateUtils.ACCURACY_MILLISECONDS_FORCED;
} else {
if (isXSMode()) {
throw new InvalidFormatParametersException(
XS_LESS_THAN_SECONDS_ACCURACY_ERROR_MESSAGE);
}
- accuracy = _DateUtil.ACCURACY_MINUTES;
+ accuracy = _DateUtils.ACCURACY_MINUTES;
}
break;
case 's':
- accuracy = _DateUtil.ACCURACY_SECONDS;
+ accuracy = _DateUtils.ACCURACY_SECONDS;
break;
}
break;
@@ -163,7 +163,7 @@ abstract class ISOLikeTemplateDateFormat extends TemplateDateFormat {
break;
default:
throw new InvalidFormatParametersException(
- "Unexpected character, " + _StringUtil.jQuote(String.valueOf(c))
+ "Unexpected character, " + _StringUtils.jQuote(String.valueOf(c))
+ ". Expected the beginning of one of: h, m, s, ms, nz, fz, u"
+ " (at char pos. " + i + ").");
} // switch
@@ -195,7 +195,7 @@ abstract class ISOLikeTemplateDateFormat extends TemplateDateFormat {
? !zonelessInput
: showZoneOffset.booleanValue(),
accuracy,
- (forceUTC == null ? !zonelessInput : forceUTC.booleanValue()) ? _DateUtil.UTC : timeZone,
+ (forceUTC == null ? !zonelessInput : forceUTC.booleanValue()) ? _DateUtils.UTC : timeZone,
factory.getISOBuiltInCalendar(env));
}
@@ -210,7 +210,7 @@ abstract class ISOLikeTemplateDateFormat extends TemplateDateFormat {
justification = "Known to use the singleton Boolean-s only")
public final Date parse(String s, int dateType) throws UnparsableValueException {
CalendarFieldsToDateConverter calToDateConverter = factory.getCalendarFieldsToDateCalculator(env);
- TimeZone tz = forceUTC != Boolean.FALSE ? _DateUtil.UTC : timeZone;
+ TimeZone tz = forceUTC != Boolean.FALSE ? _DateUtils.UTC : timeZone;
try {
if (dateType == TemplateDateModel.DATE) {
return parseDate(s, tz, calToDateConverter);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormatFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormatFactory.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormatFactory.java
index 5db8f46..fe18a66 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormatFactory.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOLikeTemplateDateFormatFactory.java
@@ -21,10 +21,10 @@ package org.apache.freemarker.core.valueformat.impl;
import org.apache.freemarker.core.CustomStateKey;
import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.util._DateUtil.CalendarFieldsToDateConverter;
-import org.apache.freemarker.core.util._DateUtil.DateToISO8601CalendarFactory;
-import org.apache.freemarker.core.util._DateUtil.TrivialCalendarFieldsToDateConverter;
-import org.apache.freemarker.core.util._DateUtil.TrivialDateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._DateUtils.CalendarFieldsToDateConverter;
+import org.apache.freemarker.core.util._DateUtils.DateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._DateUtils.TrivialCalendarFieldsToDateConverter;
+import org.apache.freemarker.core.util._DateUtils.TrivialDateToISO8601CalendarFactory;
import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory;
abstract class ISOLikeTemplateDateFormatFactory extends TemplateDateFormatFactory {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOTemplateDateFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOTemplateDateFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOTemplateDateFormat.java
index 4856ee0..489e852 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOTemplateDateFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/ISOTemplateDateFormat.java
@@ -23,10 +23,10 @@ import java.util.Date;
import java.util.TimeZone;
import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.util._DateUtil;
-import org.apache.freemarker.core.util._DateUtil.CalendarFieldsToDateConverter;
-import org.apache.freemarker.core.util._DateUtil.DateParseException;
-import org.apache.freemarker.core.util._DateUtil.DateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._DateUtils;
+import org.apache.freemarker.core.util._DateUtils.CalendarFieldsToDateConverter;
+import org.apache.freemarker.core.util._DateUtils.DateParseException;
+import org.apache.freemarker.core.util._DateUtils.DateToISO8601CalendarFactory;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.UnknownDateTypeFormattingUnsupportedException;
@@ -45,26 +45,26 @@ class ISOTemplateDateFormat extends ISOLikeTemplateDateFormat {
@Override
protected String format(Date date, boolean datePart, boolean timePart, boolean offsetPart, int accuracy,
TimeZone timeZone, DateToISO8601CalendarFactory calendarFactory) {
- return _DateUtil.dateToISO8601String(
+ return _DateUtils.dateToISO8601String(
date, datePart, timePart, timePart && offsetPart, accuracy, timeZone, calendarFactory);
}
@Override
protected Date parseDate(String s, TimeZone tz, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
- return _DateUtil.parseISO8601Date(s, tz, calToDateConverter);
+ return _DateUtils.parseISO8601Date(s, tz, calToDateConverter);
}
@Override
protected Date parseTime(String s, TimeZone tz, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
- return _DateUtil.parseISO8601Time(s, tz, calToDateConverter);
+ return _DateUtils.parseISO8601Time(s, tz, calToDateConverter);
}
@Override
protected Date parseDateTime(String s, TimeZone tz,
CalendarFieldsToDateConverter calToDateConverter) throws DateParseException {
- return _DateUtil.parseISO8601DateTime(s, tz, calToDateConverter);
+ return _DateUtils.parseISO8601DateTime(s, tz, calToDateConverter);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/XSTemplateDateFormat.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/XSTemplateDateFormat.java b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/XSTemplateDateFormat.java
index 37d64dc..e5ea7ce 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/XSTemplateDateFormat.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/valueformat/impl/XSTemplateDateFormat.java
@@ -23,10 +23,10 @@ import java.util.Date;
import java.util.TimeZone;
import org.apache.freemarker.core.Environment;
-import org.apache.freemarker.core.util._DateUtil;
-import org.apache.freemarker.core.util._DateUtil.CalendarFieldsToDateConverter;
-import org.apache.freemarker.core.util._DateUtil.DateParseException;
-import org.apache.freemarker.core.util._DateUtil.DateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._DateUtils;
+import org.apache.freemarker.core.util._DateUtils.CalendarFieldsToDateConverter;
+import org.apache.freemarker.core.util._DateUtils.DateParseException;
+import org.apache.freemarker.core.util._DateUtils.DateToISO8601CalendarFactory;
import org.apache.freemarker.core.valueformat.InvalidFormatParametersException;
import org.apache.freemarker.core.valueformat.UnknownDateTypeFormattingUnsupportedException;
@@ -49,26 +49,26 @@ class XSTemplateDateFormat extends ISOLikeTemplateDateFormat {
@Override
protected String format(Date date, boolean datePart, boolean timePart, boolean offsetPart, int accuracy,
TimeZone timeZone, DateToISO8601CalendarFactory calendarFactory) {
- return _DateUtil.dateToXSString(
+ return _DateUtils.dateToXSString(
date, datePart, timePart, offsetPart, accuracy, timeZone, calendarFactory);
}
@Override
protected Date parseDate(String s, TimeZone tz, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
- return _DateUtil.parseXSDate(s, tz, calToDateConverter);
+ return _DateUtils.parseXSDate(s, tz, calToDateConverter);
}
@Override
protected Date parseTime(String s, TimeZone tz, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
- return _DateUtil.parseXSTime(s, tz, calToDateConverter);
+ return _DateUtils.parseXSTime(s, tz, calToDateConverter);
}
@Override
protected Date parseDateTime(String s, TimeZone tz,
CalendarFieldsToDateConverter calToDateConverter) throws DateParseException {
- return _DateUtil.parseXSDateTime(s, tz, calToDateConverter);
+ return _DateUtils.parseXSDateTime(s, tz, calToDateConverter);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/javacc/FTL.jj
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/javacc/FTL.jj b/freemarker-core/src/main/javacc/FTL.jj
index 2ae31c0..952f854 100644
--- a/freemarker-core/src/main/javacc/FTL.jj
+++ b/freemarker-core/src/main/javacc/FTL.jj
@@ -366,7 +366,7 @@ public class FMParser {
}
if (legacyCompat && tm instanceof TemplateScalarModel) {
try {
- return _StringUtil.getYesNo(((TemplateScalarModel) tm).getAsString());
+ return _StringUtils.getYesNo(((TemplateScalarModel) tm).getAsString());
} catch (Exception e) {
throw new ParseException(e.getMessage()
+ "\nExpecting boolean (true/false), found: " + exp.getCanonicalForm(),
@@ -3040,7 +3040,7 @@ ASTDirMacroOrFunction Macro() :
break;
default:
throw new ParseException(
- "Unsupported parameter option " + _StringUtil.jQuote(tk.image) + ". "
+ "Unsupported parameter option " + _StringUtils.jQuote(tk.image) + ". "
+ "The supported options are: \""
+ ASTDirMacroOrFunction.NAMED_PARAMETER_OPTION_NAME + "\", \""
+ ASTDirMacroOrFunction.POSITIONAL_PARAMETER_OPTION_NAME + "\".",
@@ -3207,7 +3207,7 @@ ASTDirMacroOrFunction Macro() :
children);
} catch (DuplicateStringKeyException e) {
throw new ParseException("The parameter list contains the parameter name "
- + _StringUtil.jQuote(e.getKey()) + " for multiple times.", template, start);
+ + _StringUtils.jQuote(e.getKey()) + " for multiple times.", template, start);
}
result.setLocation(template, start, end);
template.addMacro(result);
@@ -4013,7 +4013,7 @@ ASTElement OptionalBlock() :
tp = ASTImplicitParent()
]
{
- return tp != null ? tp : new ASTStaticText(_CollectionUtil.EMPTY_CHAR_ARRAY, false);
+ return tp != null ? tp : new ASTStaticText(_CollectionUtils.EMPTY_CHAR_ARRAY, false);
}
}
@@ -4204,7 +4204,7 @@ void HeaderElement() :
Object attValue = DeepUnwrap.unwrap(attributeMap.get(attName));
if (attValue != null && !(attValue instanceof Serializable)) {
throw new ParseException(
- "Value of custom setting " + _StringUtil.jQuote(attName)
+ "Value of custom setting " + _StringUtils.jQuote(attName)
+ " should implement java.io.Serializable.",
exp);
}
@@ -4217,7 +4217,7 @@ void HeaderElement() :
sb.append("Unknown header parameter: ").append(ks);
if (ks.indexOf('_') != -1) {
- sb.append(MessageUtil.FM3_SNAKE_CASE);
+ sb.append(MessageUtils.FM3_SNAKE_CASE);
}
String correctName;
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-dom/src/main/java/org/apache/freemarker/dom/DocumentModel.java
----------------------------------------------------------------------
diff --git a/freemarker-dom/src/main/java/org/apache/freemarker/dom/DocumentModel.java b/freemarker-dom/src/main/java/org/apache/freemarker/dom/DocumentModel.java
index 876b3cf..5a6f581 100644
--- a/freemarker-dom/src/main/java/org/apache/freemarker/dom/DocumentModel.java
+++ b/freemarker-dom/src/main/java/org/apache/freemarker/dom/DocumentModel.java
@@ -51,7 +51,7 @@ class DocumentModel extends NodeModel implements TemplateHashModel {
} else if (key.equals("**")) {
NodeList nl = ((Document) node).getElementsByTagName("*");
return new NodeListModel(nl, this);
- } else if (DomStringUtil.isXMLNameLike(key)) {
+ } else if (DomStringUtils.isXMLNameLike(key)) {
ElementModel em = (ElementModel) NodeModel.wrap(((Document) node).getDocumentElement());
if (em.matchesName(key, Environment.getCurrentEnvironment())) {
return em;
[10/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtil.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtil.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtil.java
deleted file mode 100644
index 727085f..0000000
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtil.java
+++ /dev/null
@@ -1,545 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core;
-
-import java.util.Date;
-
-import org.apache.freemarker.core.arithmetic.ArithmeticEngine;
-import org.apache.freemarker.core.arithmetic.impl.BigDecimalArithmeticEngine;
-import org.apache.freemarker.core.model.TemplateBooleanModel;
-import org.apache.freemarker.core.model.TemplateCollectionModel;
-import org.apache.freemarker.core.model.TemplateDateModel;
-import org.apache.freemarker.core.model.TemplateMarkupOutputModel;
-import org.apache.freemarker.core.model.TemplateModel;
-import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.model.TemplateNumberModel;
-import org.apache.freemarker.core.model.TemplateScalarModel;
-import org.apache.freemarker.core.model.TemplateSequenceModel;
-import org.apache.freemarker.core.outputformat.MarkupOutputFormat;
-import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.valueformat.TemplateDateFormat;
-import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
-import org.apache.freemarker.core.valueformat.TemplateValueFormat;
-import org.apache.freemarker.core.valueformat.TemplateValueFormatException;
-
-/**
- * Internally used static utilities for evaluation expressions.
- */
-public class _EvalUtil {
- static final int CMP_OP_EQUALS = 1;
- static final int CMP_OP_NOT_EQUALS = 2;
- static final int CMP_OP_LESS_THAN = 3;
- static final int CMP_OP_GREATER_THAN = 4;
- static final int CMP_OP_LESS_THAN_EQUALS = 5;
- static final int CMP_OP_GREATER_THAN_EQUALS = 6;
- // If you add a new operator here, update the "compare" and "cmpOpToString" methods!
-
- // Prevents instantination.
- private _EvalUtil() { }
-
- /**
- * @param expr {@code null} is allowed, but may results in less helpful error messages
- * @param env {@code null} is allowed
- */
- static String modelToString(TemplateScalarModel model, ASTExpression expr, Environment env)
- throws TemplateModelException {
- String value = model.getAsString();
- if (value == null) {
- throw newModelHasStoredNullException(String.class, model, expr);
- }
- return value;
- }
-
- /**
- * @param expr {@code null} is allowed, but may results in less helpful error messages
- */
- static Number modelToNumber(TemplateNumberModel model, ASTExpression expr)
- throws TemplateModelException {
- Number value = model.getAsNumber();
- if (value == null) throw newModelHasStoredNullException(Number.class, model, expr);
- return value;
- }
-
- /**
- * @param expr {@code null} is allowed, but may results in less helpful error messages
- */
- static Date modelToDate(TemplateDateModel model, ASTExpression expr)
- throws TemplateModelException {
- Date value = model.getAsDate();
- if (value == null) throw newModelHasStoredNullException(Date.class, model, expr);
- return value;
- }
-
- /** Signals the buggy case where we have a non-null model, but it wraps a null. */
- public static TemplateModelException newModelHasStoredNullException(
- Class expected, TemplateModel model, ASTExpression expr) {
- return new _TemplateModelException(expr,
- _TemplateModelException.modelHasStoredNullDescription(expected, model));
- }
-
- /**
- * Compares two expressions according the rules of the FTL comparator operators.
- *
- * @param leftExp not {@code null}
- * @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
- * @param operatorString can be null {@code null}; the actual operator used, used for more accurate error message.
- * @param rightExp not {@code null}
- * @param env {@code null} is tolerated, but should be avoided
- */
- static boolean compare(
- ASTExpression leftExp,
- int operator, String operatorString,
- ASTExpression rightExp,
- ASTExpression defaultBlamed,
- Environment env) throws TemplateException {
- TemplateModel ltm = leftExp.eval(env);
- TemplateModel rtm = rightExp.eval(env);
- return compare(
- ltm, leftExp,
- operator, operatorString,
- rtm, rightExp,
- defaultBlamed, false,
- false, false, false,
- env);
- }
-
- /**
- * Compares values according the rules of the FTL comparator operators; if the {@link ASTExpression}-s are
- * accessible, use {@link #compare(ASTExpression, int, String, ASTExpression, ASTExpression, Environment)} instead,
- * as that gives better error messages.
- *
- * @param leftValue maybe {@code null}, which will usually cause the appropriate {@link TemplateException}.
- * @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
- * @param rightValue maybe {@code null}, which will usually cause the appropriate {@link TemplateException}.
- * @param env {@code null} is tolerated, but should be avoided
- */
- static boolean compare(
- TemplateModel leftValue, int operator, TemplateModel rightValue,
- Environment env) throws TemplateException {
- return compare(
- leftValue, null,
- operator, null,
- rightValue, null,
- null, false,
- false, false, false,
- env);
- }
-
- /**
- * Same as {@link #compare(TemplateModel, int, TemplateModel, Environment)}, but if the two types are incompatible,
- * they are treated as non-equal instead of throwing an exception. Comparing dates of different types will
- * still throw an exception, however.
- */
- static boolean compareLenient(
- TemplateModel leftValue, int operator, TemplateModel rightValue,
- Environment env) throws TemplateException {
- return compare(
- leftValue, null,
- operator, null,
- rightValue, null,
- null, false,
- true, false, false,
- env);
- }
-
- private static final String VALUE_OF_THE_COMPARISON_IS_UNKNOWN_DATE_LIKE
- = "value of the comparison is a date-like value where "
- + "it's not known if it's a date (no time part), time, or date-time, "
- + "and thus can't be used in a comparison.";
-
- /**
- * @param leftExp {@code null} is allowed, but may results in less helpful error messages
- * @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
- * @param operatorString can be null {@code null}; the actual operator used, used for more accurate error message.
- * @param rightExp {@code null} is allowed, but may results in less helpful error messages
- * @param defaultBlamed {@code null} allowed; the expression to which the error will point to if something goes
- * wrong that is not specific to the left or right side expression, or if that expression is {@code null}.
- * @param typeMismatchMeansNotEqual If the two types are incompatible, they are treated as non-equal instead
- * of throwing an exception. Comparing dates of different types will still throw an exception, however.
- * @param leftNullReturnsFalse if {@code true}, a {@code null} left value will not cause exception, but make the
- * expression {@code false}.
- * @param rightNullReturnsFalse if {@code true}, a {@code null} right value will not cause exception, but make the
- * expression {@code false}.
- */
- static boolean compare(
- TemplateModel leftValue, ASTExpression leftExp,
- int operator, String operatorString,
- TemplateModel rightValue, ASTExpression rightExp,
- ASTExpression defaultBlamed, boolean quoteOperandsInErrors,
- boolean typeMismatchMeansNotEqual,
- boolean leftNullReturnsFalse, boolean rightNullReturnsFalse,
- Environment env) throws TemplateException {
- if (leftValue == null) {
- if (leftNullReturnsFalse) {
- return false;
- } else {
- if (leftExp != null) {
- throw InvalidReferenceException.getInstance(leftExp, env);
- } else {
- throw new _MiscTemplateException(defaultBlamed, env,
- "The left operand of the comparison was undefined or null.");
- }
- }
- }
-
- if (rightValue == null) {
- if (rightNullReturnsFalse) {
- return false;
- } else {
- if (rightExp != null) {
- throw InvalidReferenceException.getInstance(rightExp, env);
- } else {
- throw new _MiscTemplateException(defaultBlamed, env,
- "The right operand of the comparison was undefined or null.");
- }
- }
- }
-
- final int cmpResult;
- if (leftValue instanceof TemplateNumberModel && rightValue instanceof TemplateNumberModel) {
- Number leftNum = _EvalUtil.modelToNumber((TemplateNumberModel) leftValue, leftExp);
- Number rightNum = _EvalUtil.modelToNumber((TemplateNumberModel) rightValue, rightExp);
- ArithmeticEngine ae =
- env != null
- ? env.getArithmeticEngine()
- : (leftExp != null
- ? leftExp.getTemplate().getArithmeticEngine()
- : BigDecimalArithmeticEngine.INSTANCE);
- try {
- cmpResult = ae.compareNumbers(leftNum, rightNum);
- } catch (RuntimeException e) {
- throw new _MiscTemplateException(defaultBlamed, e, env,
- "Unexpected error while comparing two numbers: ", e);
- }
- } else if (leftValue instanceof TemplateDateModel && rightValue instanceof TemplateDateModel) {
- TemplateDateModel leftDateModel = (TemplateDateModel) leftValue;
- TemplateDateModel rightDateModel = (TemplateDateModel) rightValue;
-
- int leftDateType = leftDateModel.getDateType();
- int rightDateType = rightDateModel.getDateType();
-
- if (leftDateType == TemplateDateModel.UNKNOWN || rightDateType == TemplateDateModel.UNKNOWN) {
- String sideName;
- ASTExpression sideExp;
- if (leftDateType == TemplateDateModel.UNKNOWN) {
- sideName = "left";
- sideExp = leftExp;
- } else {
- sideName = "right";
- sideExp = rightExp;
- }
-
- throw new _MiscTemplateException(sideExp != null ? sideExp : defaultBlamed, env,
- "The ", sideName, " ", VALUE_OF_THE_COMPARISON_IS_UNKNOWN_DATE_LIKE);
- }
-
- if (leftDateType != rightDateType) {
- throw new _MiscTemplateException(defaultBlamed, env,
- "Can't compare dates of different types. Left date type is ",
- TemplateDateModel.TYPE_NAMES.get(leftDateType), ", right date type is ",
- TemplateDateModel.TYPE_NAMES.get(rightDateType), ".");
- }
-
- Date leftDate = _EvalUtil.modelToDate(leftDateModel, leftExp);
- Date rightDate = _EvalUtil.modelToDate(rightDateModel, rightExp);
- cmpResult = leftDate.compareTo(rightDate);
- } else if (leftValue instanceof TemplateScalarModel && rightValue instanceof TemplateScalarModel) {
- if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
- throw new _MiscTemplateException(defaultBlamed, env,
- "Can't use operator \"", cmpOpToString(operator, operatorString), "\" on string values.");
- }
- String leftString = _EvalUtil.modelToString((TemplateScalarModel) leftValue, leftExp, env);
- String rightString = _EvalUtil.modelToString((TemplateScalarModel) rightValue, rightExp, env);
- // FIXME NBC: Don't use the Collator here. That's locale-specific, but ==/!= should not be.
- cmpResult = env.getCollator().compare(leftString, rightString);
- } else if (leftValue instanceof TemplateBooleanModel && rightValue instanceof TemplateBooleanModel) {
- if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
- throw new _MiscTemplateException(defaultBlamed, env,
- "Can't use operator \"", cmpOpToString(operator, operatorString), "\" on boolean values.");
- }
- boolean leftBool = ((TemplateBooleanModel) leftValue).getAsBoolean();
- boolean rightBool = ((TemplateBooleanModel) rightValue).getAsBoolean();
- cmpResult = (leftBool ? 1 : 0) - (rightBool ? 1 : 0);
- } else {
- if (typeMismatchMeansNotEqual) {
- if (operator == CMP_OP_EQUALS) {
- return false;
- } else if (operator == CMP_OP_NOT_EQUALS) {
- return true;
- }
- // Falls through
- }
- throw new _MiscTemplateException(defaultBlamed, env,
- "Can't compare values of these types. ",
- "Allowed comparisons are between two numbers, two strings, two dates, or two booleans.\n",
- "Left hand operand ",
- (quoteOperandsInErrors && leftExp != null
- ? new Object[] { "(", new _DelayedGetCanonicalForm(leftExp), ") value " }
- : ""),
- "is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(leftValue)), ".\n",
- "Right hand operand ",
- (quoteOperandsInErrors && rightExp != null
- ? new Object[] { "(", new _DelayedGetCanonicalForm(rightExp), ") value " }
- : ""),
- "is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(rightValue)),
- ".");
- }
-
- switch (operator) {
- case CMP_OP_EQUALS: return cmpResult == 0;
- case CMP_OP_NOT_EQUALS: return cmpResult != 0;
- case CMP_OP_LESS_THAN: return cmpResult < 0;
- case CMP_OP_GREATER_THAN: return cmpResult > 0;
- case CMP_OP_LESS_THAN_EQUALS: return cmpResult <= 0;
- case CMP_OP_GREATER_THAN_EQUALS: return cmpResult >= 0;
- default: throw new BugException("Unsupported comparator operator code: " + operator);
- }
- }
-
- private static String cmpOpToString(int operator, String operatorString) {
- if (operatorString != null) {
- return operatorString;
- } else {
- switch (operator) {
- case CMP_OP_EQUALS: return "equals";
- case CMP_OP_NOT_EQUALS: return "not-equals";
- case CMP_OP_LESS_THAN: return "less-than";
- case CMP_OP_GREATER_THAN: return "greater-than";
- case CMP_OP_LESS_THAN_EQUALS: return "less-than-equals";
- case CMP_OP_GREATER_THAN_EQUALS: return "greater-than-equals";
- default: return "???";
- }
- }
- }
-
- /**
- * Converts a value to plain text {@link String}, or a {@link TemplateMarkupOutputModel} if that's what the
- * {@link TemplateValueFormat} involved produces.
- *
- * @param seqTip
- * Tip to display if the value type is not coercable, but it's sequence or collection.
- *
- * @return Never {@code null}
- */
- static Object coerceModelToStringOrMarkup(TemplateModel tm, ASTExpression exp, String seqTip, Environment env)
- throws TemplateException {
- return coerceModelToStringOrMarkup(tm, exp, false, seqTip, env);
- }
-
- /**
- * @return {@code null} if the {@code returnNullOnNonCoercableType} parameter is {@code true}, and the coercion is
- * not possible, because of the type is not right for it.
- *
- * @see #coerceModelToStringOrMarkup(TemplateModel, ASTExpression, String, Environment)
- */
- static Object coerceModelToStringOrMarkup(
- TemplateModel tm, ASTExpression exp, boolean returnNullOnNonCoercableType, String seqTip, Environment env)
- throws TemplateException {
- if (tm instanceof TemplateNumberModel) {
- TemplateNumberModel tnm = (TemplateNumberModel) tm;
- TemplateNumberFormat format = env.getTemplateNumberFormat(exp, false);
- try {
- return assertFormatResultNotNull(format.format(tnm));
- } catch (TemplateValueFormatException e) {
- throw MessageUtil.newCantFormatNumberException(format, exp, e, false);
- }
- } else if (tm instanceof TemplateDateModel) {
- TemplateDateModel tdm = (TemplateDateModel) tm;
- TemplateDateFormat format = env.getTemplateDateFormat(tdm, exp, false);
- try {
- return assertFormatResultNotNull(format.format(tdm));
- } catch (TemplateValueFormatException e) {
- throw MessageUtil.newCantFormatDateException(format, exp, e, false);
- }
- } else if (tm instanceof TemplateMarkupOutputModel) {
- return tm;
- } else {
- return coerceModelToTextualCommon(tm, exp, seqTip, true, returnNullOnNonCoercableType, env);
- }
- }
-
- /**
- * Like {@link #coerceModelToStringOrMarkup(TemplateModel, ASTExpression, String, Environment)}, but gives error
- * if the result is markup. This is what you normally use where markup results can't be used.
- *
- * @param seqTip
- * Tip to display if the value type is not coercable, but it's sequence or collection.
- *
- * @return Never {@code null}
- */
- static String coerceModelToStringOrUnsupportedMarkup(
- TemplateModel tm, ASTExpression exp, String seqTip, Environment env)
- throws TemplateException {
- if (tm instanceof TemplateNumberModel) {
- TemplateNumberModel tnm = (TemplateNumberModel) tm;
- TemplateNumberFormat format = env.getTemplateNumberFormat(exp, false);
- try {
- return ensureFormatResultString(format.format(tnm), exp, env);
- } catch (TemplateValueFormatException e) {
- throw MessageUtil.newCantFormatNumberException(format, exp, e, false);
- }
- } else if (tm instanceof TemplateDateModel) {
- TemplateDateModel tdm = (TemplateDateModel) tm;
- TemplateDateFormat format = env.getTemplateDateFormat(tdm, exp, false);
- try {
- return ensureFormatResultString(format.format(tdm), exp, env);
- } catch (TemplateValueFormatException e) {
- throw MessageUtil.newCantFormatDateException(format, exp, e, false);
- }
- } else {
- return coerceModelToTextualCommon(tm, exp, seqTip, false, false, env);
- }
- }
-
- /**
- * Converts a value to plain text {@link String}, even if the {@link TemplateValueFormat} involved normally produces
- * markup. This should be used rarely, where the user clearly intend to use the plain text variant of the format.
- *
- * @param seqTip
- * Tip to display if the value type is not coercable, but it's sequence or collection.
- *
- * @return Never {@code null}
- */
- static String coerceModelToPlainText(TemplateModel tm, ASTExpression exp, String seqTip,
- Environment env) throws TemplateException {
- if (tm instanceof TemplateNumberModel) {
- return assertFormatResultNotNull(env.formatNumberToPlainText((TemplateNumberModel) tm, exp, false));
- } else if (tm instanceof TemplateDateModel) {
- return assertFormatResultNotNull(env.formatDateToPlainText((TemplateDateModel) tm, exp, false));
- } else {
- return coerceModelToTextualCommon(tm, exp, seqTip, false, false, env);
- }
- }
-
- /**
- * @param tm
- * If {@code null} that's an exception
- *
- * @param supportsTOM
- * Whether the caller {@code coerceModelTo...} method could handle a {@link TemplateMarkupOutputModel}.
- *
- * @return Never {@code null}
- */
- private static String coerceModelToTextualCommon(
- TemplateModel tm, ASTExpression exp, String seqHint, boolean supportsTOM, boolean returnNullOnNonCoercableType,
- Environment env)
- throws TemplateException {
- if (tm instanceof TemplateScalarModel) {
- return modelToString((TemplateScalarModel) tm, exp, env);
- } else if (tm == null) {
- if (exp != null) {
- throw InvalidReferenceException.getInstance(exp, env);
- } else {
- throw new InvalidReferenceException(
- "Null/missing value (no more informatoin avilable)",
- env);
- }
- } else if (tm instanceof TemplateBooleanModel) {
- // [FM3] This should be before TemplateScalarModel, but automatic boolean-to-string is only non-error since
- // 2.3.20, so to keep backward compatibility we couldn't insert this before TemplateScalarModel.
- boolean booleanValue = ((TemplateBooleanModel) tm).getAsBoolean();
- return env.formatBoolean(booleanValue, false);
- } else {
- if (returnNullOnNonCoercableType) {
- return null;
- }
- if (seqHint != null && (tm instanceof TemplateSequenceModel || tm instanceof TemplateCollectionModel)) {
- if (supportsTOM) {
- throw new NonStringOrTemplateOutputException(exp, tm, seqHint, env);
- } else {
- throw new NonStringException(exp, tm, seqHint, env);
- }
- } else {
- if (supportsTOM) {
- throw new NonStringOrTemplateOutputException(exp, tm, env);
- } else {
- throw new NonStringException(exp, tm, env);
- }
- }
- }
- }
-
- private static String ensureFormatResultString(Object formatResult, ASTExpression exp, Environment env)
- throws NonStringException {
- if (formatResult instanceof String) {
- return (String) formatResult;
- }
-
- assertFormatResultNotNull(formatResult);
-
- TemplateMarkupOutputModel mo = (TemplateMarkupOutputModel) formatResult;
- _ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
- "Value was formatted to convert it to string, but the result was markup of ouput format ",
- new _DelayedJQuote(mo.getOutputFormat()), ".")
- .tip("Use value?string to force formatting to plain text.")
- .blame(exp);
- throw new NonStringException(null, desc);
- }
-
- static String assertFormatResultNotNull(String r) {
- if (r != null) {
- return r;
- }
- throw new NullPointerException("TemplateValueFormatter result can't be null");
- }
-
- static Object assertFormatResultNotNull(Object r) {
- if (r != null) {
- return r;
- }
- throw new NullPointerException("TemplateValueFormatter result can't be null");
- }
-
- static TemplateMarkupOutputModel concatMarkupOutputs(ASTNode parent, TemplateMarkupOutputModel leftMO,
- TemplateMarkupOutputModel rightMO) throws TemplateException {
- MarkupOutputFormat leftOF = leftMO.getOutputFormat();
- MarkupOutputFormat rightOF = rightMO.getOutputFormat();
- if (rightOF != leftOF) {
- String rightPT;
- String leftPT;
- if ((rightPT = rightOF.getSourcePlainText(rightMO)) != null) {
- return leftOF.concat(leftMO, leftOF.fromPlainTextByEscaping(rightPT));
- } else if ((leftPT = leftOF.getSourcePlainText(leftMO)) != null) {
- return rightOF.concat(rightOF.fromPlainTextByEscaping(leftPT), rightMO);
- } else {
- Object[] message = { "Concatenation left hand operand is in ", new _DelayedToString(leftOF),
- " format, while the right hand operand is in ", new _DelayedToString(rightOF),
- ". Conversion to common format wasn't possible." };
- if (parent instanceof ASTExpression) {
- throw new _MiscTemplateException((ASTExpression) parent, message);
- } else {
- throw new _MiscTemplateException(message);
- }
- }
- } else {
- return leftOF.concat(leftMO, rightMO);
- }
- }
-
- /**
- * Returns an {@link ArithmeticEngine} even if {@code env} is {@code null}, because we are in parsing phase.
- */
- static ArithmeticEngine getArithmeticEngine(Environment env, ASTNode tObj) {
- return env != null
- ? env.getArithmeticEngine()
- : tObj.getTemplate().getParsingConfiguration().getArithmeticEngine();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtils.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtils.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtils.java
new file mode 100644
index 0000000..199a88c
--- /dev/null
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_EvalUtils.java
@@ -0,0 +1,545 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core;
+
+import java.util.Date;
+
+import org.apache.freemarker.core.arithmetic.ArithmeticEngine;
+import org.apache.freemarker.core.arithmetic.impl.BigDecimalArithmeticEngine;
+import org.apache.freemarker.core.model.TemplateBooleanModel;
+import org.apache.freemarker.core.model.TemplateCollectionModel;
+import org.apache.freemarker.core.model.TemplateDateModel;
+import org.apache.freemarker.core.model.TemplateMarkupOutputModel;
+import org.apache.freemarker.core.model.TemplateModel;
+import org.apache.freemarker.core.model.TemplateModelException;
+import org.apache.freemarker.core.model.TemplateNumberModel;
+import org.apache.freemarker.core.model.TemplateScalarModel;
+import org.apache.freemarker.core.model.TemplateSequenceModel;
+import org.apache.freemarker.core.outputformat.MarkupOutputFormat;
+import org.apache.freemarker.core.util.BugException;
+import org.apache.freemarker.core.valueformat.TemplateDateFormat;
+import org.apache.freemarker.core.valueformat.TemplateNumberFormat;
+import org.apache.freemarker.core.valueformat.TemplateValueFormat;
+import org.apache.freemarker.core.valueformat.TemplateValueFormatException;
+
+/**
+ * Internally used static utilities for evaluation expressions.
+ */
+public class _EvalUtils {
+ static final int CMP_OP_EQUALS = 1;
+ static final int CMP_OP_NOT_EQUALS = 2;
+ static final int CMP_OP_LESS_THAN = 3;
+ static final int CMP_OP_GREATER_THAN = 4;
+ static final int CMP_OP_LESS_THAN_EQUALS = 5;
+ static final int CMP_OP_GREATER_THAN_EQUALS = 6;
+ // If you add a new operator here, update the "compare" and "cmpOpToString" methods!
+
+ // Prevents instantiation.
+ private _EvalUtils() { }
+
+ /**
+ * @param expr {@code null} is allowed, but may results in less helpful error messages
+ * @param env {@code null} is allowed
+ */
+ static String modelToString(TemplateScalarModel model, ASTExpression expr, Environment env)
+ throws TemplateModelException {
+ String value = model.getAsString();
+ if (value == null) {
+ throw newModelHasStoredNullException(String.class, model, expr);
+ }
+ return value;
+ }
+
+ /**
+ * @param expr {@code null} is allowed, but may results in less helpful error messages
+ */
+ static Number modelToNumber(TemplateNumberModel model, ASTExpression expr)
+ throws TemplateModelException {
+ Number value = model.getAsNumber();
+ if (value == null) throw newModelHasStoredNullException(Number.class, model, expr);
+ return value;
+ }
+
+ /**
+ * @param expr {@code null} is allowed, but may results in less helpful error messages
+ */
+ static Date modelToDate(TemplateDateModel model, ASTExpression expr)
+ throws TemplateModelException {
+ Date value = model.getAsDate();
+ if (value == null) throw newModelHasStoredNullException(Date.class, model, expr);
+ return value;
+ }
+
+ /** Signals the buggy case where we have a non-null model, but it wraps a null. */
+ public static TemplateModelException newModelHasStoredNullException(
+ Class expected, TemplateModel model, ASTExpression expr) {
+ return new _TemplateModelException(expr,
+ _TemplateModelException.modelHasStoredNullDescription(expected, model));
+ }
+
+ /**
+ * Compares two expressions according the rules of the FTL comparator operators.
+ *
+ * @param leftExp not {@code null}
+ * @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
+ * @param operatorString can be null {@code null}; the actual operator used, used for more accurate error message.
+ * @param rightExp not {@code null}
+ * @param env {@code null} is tolerated, but should be avoided
+ */
+ static boolean compare(
+ ASTExpression leftExp,
+ int operator, String operatorString,
+ ASTExpression rightExp,
+ ASTExpression defaultBlamed,
+ Environment env) throws TemplateException {
+ TemplateModel ltm = leftExp.eval(env);
+ TemplateModel rtm = rightExp.eval(env);
+ return compare(
+ ltm, leftExp,
+ operator, operatorString,
+ rtm, rightExp,
+ defaultBlamed, false,
+ false, false, false,
+ env);
+ }
+
+ /**
+ * Compares values according the rules of the FTL comparator operators; if the {@link ASTExpression}-s are
+ * accessible, use {@link #compare(ASTExpression, int, String, ASTExpression, ASTExpression, Environment)} instead,
+ * as that gives better error messages.
+ *
+ * @param leftValue maybe {@code null}, which will usually cause the appropriate {@link TemplateException}.
+ * @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
+ * @param rightValue maybe {@code null}, which will usually cause the appropriate {@link TemplateException}.
+ * @param env {@code null} is tolerated, but should be avoided
+ */
+ static boolean compare(
+ TemplateModel leftValue, int operator, TemplateModel rightValue,
+ Environment env) throws TemplateException {
+ return compare(
+ leftValue, null,
+ operator, null,
+ rightValue, null,
+ null, false,
+ false, false, false,
+ env);
+ }
+
+ /**
+ * Same as {@link #compare(TemplateModel, int, TemplateModel, Environment)}, but if the two types are incompatible,
+ * they are treated as non-equal instead of throwing an exception. Comparing dates of different types will
+ * still throw an exception, however.
+ */
+ static boolean compareLenient(
+ TemplateModel leftValue, int operator, TemplateModel rightValue,
+ Environment env) throws TemplateException {
+ return compare(
+ leftValue, null,
+ operator, null,
+ rightValue, null,
+ null, false,
+ true, false, false,
+ env);
+ }
+
+ private static final String VALUE_OF_THE_COMPARISON_IS_UNKNOWN_DATE_LIKE
+ = "value of the comparison is a date-like value where "
+ + "it's not known if it's a date (no time part), time, or date-time, "
+ + "and thus can't be used in a comparison.";
+
+ /**
+ * @param leftExp {@code null} is allowed, but may results in less helpful error messages
+ * @param operator one of the {@code COMP_OP_...} constants, like {@link #CMP_OP_EQUALS}.
+ * @param operatorString can be null {@code null}; the actual operator used, used for more accurate error message.
+ * @param rightExp {@code null} is allowed, but may results in less helpful error messages
+ * @param defaultBlamed {@code null} allowed; the expression to which the error will point to if something goes
+ * wrong that is not specific to the left or right side expression, or if that expression is {@code null}.
+ * @param typeMismatchMeansNotEqual If the two types are incompatible, they are treated as non-equal instead
+ * of throwing an exception. Comparing dates of different types will still throw an exception, however.
+ * @param leftNullReturnsFalse if {@code true}, a {@code null} left value will not cause exception, but make the
+ * expression {@code false}.
+ * @param rightNullReturnsFalse if {@code true}, a {@code null} right value will not cause exception, but make the
+ * expression {@code false}.
+ */
+ static boolean compare(
+ TemplateModel leftValue, ASTExpression leftExp,
+ int operator, String operatorString,
+ TemplateModel rightValue, ASTExpression rightExp,
+ ASTExpression defaultBlamed, boolean quoteOperandsInErrors,
+ boolean typeMismatchMeansNotEqual,
+ boolean leftNullReturnsFalse, boolean rightNullReturnsFalse,
+ Environment env) throws TemplateException {
+ if (leftValue == null) {
+ if (leftNullReturnsFalse) {
+ return false;
+ } else {
+ if (leftExp != null) {
+ throw InvalidReferenceException.getInstance(leftExp, env);
+ } else {
+ throw new _MiscTemplateException(defaultBlamed, env,
+ "The left operand of the comparison was undefined or null.");
+ }
+ }
+ }
+
+ if (rightValue == null) {
+ if (rightNullReturnsFalse) {
+ return false;
+ } else {
+ if (rightExp != null) {
+ throw InvalidReferenceException.getInstance(rightExp, env);
+ } else {
+ throw new _MiscTemplateException(defaultBlamed, env,
+ "The right operand of the comparison was undefined or null.");
+ }
+ }
+ }
+
+ final int cmpResult;
+ if (leftValue instanceof TemplateNumberModel && rightValue instanceof TemplateNumberModel) {
+ Number leftNum = _EvalUtils.modelToNumber((TemplateNumberModel) leftValue, leftExp);
+ Number rightNum = _EvalUtils.modelToNumber((TemplateNumberModel) rightValue, rightExp);
+ ArithmeticEngine ae =
+ env != null
+ ? env.getArithmeticEngine()
+ : (leftExp != null
+ ? leftExp.getTemplate().getArithmeticEngine()
+ : BigDecimalArithmeticEngine.INSTANCE);
+ try {
+ cmpResult = ae.compareNumbers(leftNum, rightNum);
+ } catch (RuntimeException e) {
+ throw new _MiscTemplateException(defaultBlamed, e, env,
+ "Unexpected error while comparing two numbers: ", e);
+ }
+ } else if (leftValue instanceof TemplateDateModel && rightValue instanceof TemplateDateModel) {
+ TemplateDateModel leftDateModel = (TemplateDateModel) leftValue;
+ TemplateDateModel rightDateModel = (TemplateDateModel) rightValue;
+
+ int leftDateType = leftDateModel.getDateType();
+ int rightDateType = rightDateModel.getDateType();
+
+ if (leftDateType == TemplateDateModel.UNKNOWN || rightDateType == TemplateDateModel.UNKNOWN) {
+ String sideName;
+ ASTExpression sideExp;
+ if (leftDateType == TemplateDateModel.UNKNOWN) {
+ sideName = "left";
+ sideExp = leftExp;
+ } else {
+ sideName = "right";
+ sideExp = rightExp;
+ }
+
+ throw new _MiscTemplateException(sideExp != null ? sideExp : defaultBlamed, env,
+ "The ", sideName, " ", VALUE_OF_THE_COMPARISON_IS_UNKNOWN_DATE_LIKE);
+ }
+
+ if (leftDateType != rightDateType) {
+ throw new _MiscTemplateException(defaultBlamed, env,
+ "Can't compare dates of different types. Left date type is ",
+ TemplateDateModel.TYPE_NAMES.get(leftDateType), ", right date type is ",
+ TemplateDateModel.TYPE_NAMES.get(rightDateType), ".");
+ }
+
+ Date leftDate = _EvalUtils.modelToDate(leftDateModel, leftExp);
+ Date rightDate = _EvalUtils.modelToDate(rightDateModel, rightExp);
+ cmpResult = leftDate.compareTo(rightDate);
+ } else if (leftValue instanceof TemplateScalarModel && rightValue instanceof TemplateScalarModel) {
+ if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
+ throw new _MiscTemplateException(defaultBlamed, env,
+ "Can't use operator \"", cmpOpToString(operator, operatorString), "\" on string values.");
+ }
+ String leftString = _EvalUtils.modelToString((TemplateScalarModel) leftValue, leftExp, env);
+ String rightString = _EvalUtils.modelToString((TemplateScalarModel) rightValue, rightExp, env);
+ // FIXME NBC: Don't use the Collator here. That's locale-specific, but ==/!= should not be.
+ cmpResult = env.getCollator().compare(leftString, rightString);
+ } else if (leftValue instanceof TemplateBooleanModel && rightValue instanceof TemplateBooleanModel) {
+ if (operator != CMP_OP_EQUALS && operator != CMP_OP_NOT_EQUALS) {
+ throw new _MiscTemplateException(defaultBlamed, env,
+ "Can't use operator \"", cmpOpToString(operator, operatorString), "\" on boolean values.");
+ }
+ boolean leftBool = ((TemplateBooleanModel) leftValue).getAsBoolean();
+ boolean rightBool = ((TemplateBooleanModel) rightValue).getAsBoolean();
+ cmpResult = (leftBool ? 1 : 0) - (rightBool ? 1 : 0);
+ } else {
+ if (typeMismatchMeansNotEqual) {
+ if (operator == CMP_OP_EQUALS) {
+ return false;
+ } else if (operator == CMP_OP_NOT_EQUALS) {
+ return true;
+ }
+ // Falls through
+ }
+ throw new _MiscTemplateException(defaultBlamed, env,
+ "Can't compare values of these types. ",
+ "Allowed comparisons are between two numbers, two strings, two dates, or two booleans.\n",
+ "Left hand operand ",
+ (quoteOperandsInErrors && leftExp != null
+ ? new Object[] { "(", new _DelayedGetCanonicalForm(leftExp), ") value " }
+ : ""),
+ "is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(leftValue)), ".\n",
+ "Right hand operand ",
+ (quoteOperandsInErrors && rightExp != null
+ ? new Object[] { "(", new _DelayedGetCanonicalForm(rightExp), ") value " }
+ : ""),
+ "is ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(rightValue)),
+ ".");
+ }
+
+ switch (operator) {
+ case CMP_OP_EQUALS: return cmpResult == 0;
+ case CMP_OP_NOT_EQUALS: return cmpResult != 0;
+ case CMP_OP_LESS_THAN: return cmpResult < 0;
+ case CMP_OP_GREATER_THAN: return cmpResult > 0;
+ case CMP_OP_LESS_THAN_EQUALS: return cmpResult <= 0;
+ case CMP_OP_GREATER_THAN_EQUALS: return cmpResult >= 0;
+ default: throw new BugException("Unsupported comparator operator code: " + operator);
+ }
+ }
+
+ private static String cmpOpToString(int operator, String operatorString) {
+ if (operatorString != null) {
+ return operatorString;
+ } else {
+ switch (operator) {
+ case CMP_OP_EQUALS: return "equals";
+ case CMP_OP_NOT_EQUALS: return "not-equals";
+ case CMP_OP_LESS_THAN: return "less-than";
+ case CMP_OP_GREATER_THAN: return "greater-than";
+ case CMP_OP_LESS_THAN_EQUALS: return "less-than-equals";
+ case CMP_OP_GREATER_THAN_EQUALS: return "greater-than-equals";
+ default: return "???";
+ }
+ }
+ }
+
+ /**
+ * Converts a value to plain text {@link String}, or a {@link TemplateMarkupOutputModel} if that's what the
+ * {@link TemplateValueFormat} involved produces.
+ *
+ * @param seqTip
+ * Tip to display if the value type is not coercable, but it's sequence or collection.
+ *
+ * @return Never {@code null}
+ */
+ static Object coerceModelToStringOrMarkup(TemplateModel tm, ASTExpression exp, String seqTip, Environment env)
+ throws TemplateException {
+ return coerceModelToStringOrMarkup(tm, exp, false, seqTip, env);
+ }
+
+ /**
+ * @return {@code null} if the {@code returnNullOnNonCoercableType} parameter is {@code true}, and the coercion is
+ * not possible, because of the type is not right for it.
+ *
+ * @see #coerceModelToStringOrMarkup(TemplateModel, ASTExpression, String, Environment)
+ */
+ static Object coerceModelToStringOrMarkup(
+ TemplateModel tm, ASTExpression exp, boolean returnNullOnNonCoercableType, String seqTip, Environment env)
+ throws TemplateException {
+ if (tm instanceof TemplateNumberModel) {
+ TemplateNumberModel tnm = (TemplateNumberModel) tm;
+ TemplateNumberFormat format = env.getTemplateNumberFormat(exp, false);
+ try {
+ return assertFormatResultNotNull(format.format(tnm));
+ } catch (TemplateValueFormatException e) {
+ throw MessageUtils.newCantFormatNumberException(format, exp, e, false);
+ }
+ } else if (tm instanceof TemplateDateModel) {
+ TemplateDateModel tdm = (TemplateDateModel) tm;
+ TemplateDateFormat format = env.getTemplateDateFormat(tdm, exp, false);
+ try {
+ return assertFormatResultNotNull(format.format(tdm));
+ } catch (TemplateValueFormatException e) {
+ throw MessageUtils.newCantFormatDateException(format, exp, e, false);
+ }
+ } else if (tm instanceof TemplateMarkupOutputModel) {
+ return tm;
+ } else {
+ return coerceModelToTextualCommon(tm, exp, seqTip, true, returnNullOnNonCoercableType, env);
+ }
+ }
+
+ /**
+ * Like {@link #coerceModelToStringOrMarkup(TemplateModel, ASTExpression, String, Environment)}, but gives error
+ * if the result is markup. This is what you normally use where markup results can't be used.
+ *
+ * @param seqTip
+ * Tip to display if the value type is not coercable, but it's sequence or collection.
+ *
+ * @return Never {@code null}
+ */
+ static String coerceModelToStringOrUnsupportedMarkup(
+ TemplateModel tm, ASTExpression exp, String seqTip, Environment env)
+ throws TemplateException {
+ if (tm instanceof TemplateNumberModel) {
+ TemplateNumberModel tnm = (TemplateNumberModel) tm;
+ TemplateNumberFormat format = env.getTemplateNumberFormat(exp, false);
+ try {
+ return ensureFormatResultString(format.format(tnm), exp, env);
+ } catch (TemplateValueFormatException e) {
+ throw MessageUtils.newCantFormatNumberException(format, exp, e, false);
+ }
+ } else if (tm instanceof TemplateDateModel) {
+ TemplateDateModel tdm = (TemplateDateModel) tm;
+ TemplateDateFormat format = env.getTemplateDateFormat(tdm, exp, false);
+ try {
+ return ensureFormatResultString(format.format(tdm), exp, env);
+ } catch (TemplateValueFormatException e) {
+ throw MessageUtils.newCantFormatDateException(format, exp, e, false);
+ }
+ } else {
+ return coerceModelToTextualCommon(tm, exp, seqTip, false, false, env);
+ }
+ }
+
+ /**
+ * Converts a value to plain text {@link String}, even if the {@link TemplateValueFormat} involved normally produces
+ * markup. This should be used rarely, where the user clearly intend to use the plain text variant of the format.
+ *
+ * @param seqTip
+ * Tip to display if the value type is not coercable, but it's sequence or collection.
+ *
+ * @return Never {@code null}
+ */
+ static String coerceModelToPlainText(TemplateModel tm, ASTExpression exp, String seqTip,
+ Environment env) throws TemplateException {
+ if (tm instanceof TemplateNumberModel) {
+ return assertFormatResultNotNull(env.formatNumberToPlainText((TemplateNumberModel) tm, exp, false));
+ } else if (tm instanceof TemplateDateModel) {
+ return assertFormatResultNotNull(env.formatDateToPlainText((TemplateDateModel) tm, exp, false));
+ } else {
+ return coerceModelToTextualCommon(tm, exp, seqTip, false, false, env);
+ }
+ }
+
+ /**
+ * @param tm
+ * If {@code null} that's an exception
+ *
+ * @param supportsTOM
+ * Whether the caller {@code coerceModelTo...} method could handle a {@link TemplateMarkupOutputModel}.
+ *
+ * @return Never {@code null}
+ */
+ private static String coerceModelToTextualCommon(
+ TemplateModel tm, ASTExpression exp, String seqHint, boolean supportsTOM, boolean returnNullOnNonCoercableType,
+ Environment env)
+ throws TemplateException {
+ if (tm instanceof TemplateScalarModel) {
+ return modelToString((TemplateScalarModel) tm, exp, env);
+ } else if (tm == null) {
+ if (exp != null) {
+ throw InvalidReferenceException.getInstance(exp, env);
+ } else {
+ throw new InvalidReferenceException(
+ "Null/missing value (no more informatoin avilable)",
+ env);
+ }
+ } else if (tm instanceof TemplateBooleanModel) {
+ // [FM3] This should be before TemplateScalarModel, but automatic boolean-to-string is only non-error since
+ // 2.3.20, so to keep backward compatibility we couldn't insert this before TemplateScalarModel.
+ boolean booleanValue = ((TemplateBooleanModel) tm).getAsBoolean();
+ return env.formatBoolean(booleanValue, false);
+ } else {
+ if (returnNullOnNonCoercableType) {
+ return null;
+ }
+ if (seqHint != null && (tm instanceof TemplateSequenceModel || tm instanceof TemplateCollectionModel)) {
+ if (supportsTOM) {
+ throw new NonStringOrTemplateOutputException(exp, tm, seqHint, env);
+ } else {
+ throw new NonStringException(exp, tm, seqHint, env);
+ }
+ } else {
+ if (supportsTOM) {
+ throw new NonStringOrTemplateOutputException(exp, tm, env);
+ } else {
+ throw new NonStringException(exp, tm, env);
+ }
+ }
+ }
+ }
+
+ private static String ensureFormatResultString(Object formatResult, ASTExpression exp, Environment env)
+ throws NonStringException {
+ if (formatResult instanceof String) {
+ return (String) formatResult;
+ }
+
+ assertFormatResultNotNull(formatResult);
+
+ TemplateMarkupOutputModel mo = (TemplateMarkupOutputModel) formatResult;
+ _ErrorDescriptionBuilder desc = new _ErrorDescriptionBuilder(
+ "Value was formatted to convert it to string, but the result was markup of ouput format ",
+ new _DelayedJQuote(mo.getOutputFormat()), ".")
+ .tip("Use value?string to force formatting to plain text.")
+ .blame(exp);
+ throw new NonStringException(null, desc);
+ }
+
+ static String assertFormatResultNotNull(String r) {
+ if (r != null) {
+ return r;
+ }
+ throw new NullPointerException("TemplateValueFormatter result can't be null");
+ }
+
+ static Object assertFormatResultNotNull(Object r) {
+ if (r != null) {
+ return r;
+ }
+ throw new NullPointerException("TemplateValueFormatter result can't be null");
+ }
+
+ static TemplateMarkupOutputModel concatMarkupOutputs(ASTNode parent, TemplateMarkupOutputModel leftMO,
+ TemplateMarkupOutputModel rightMO) throws TemplateException {
+ MarkupOutputFormat leftOF = leftMO.getOutputFormat();
+ MarkupOutputFormat rightOF = rightMO.getOutputFormat();
+ if (rightOF != leftOF) {
+ String rightPT;
+ String leftPT;
+ if ((rightPT = rightOF.getSourcePlainText(rightMO)) != null) {
+ return leftOF.concat(leftMO, leftOF.fromPlainTextByEscaping(rightPT));
+ } else if ((leftPT = leftOF.getSourcePlainText(leftMO)) != null) {
+ return rightOF.concat(rightOF.fromPlainTextByEscaping(leftPT), rightMO);
+ } else {
+ Object[] message = { "Concatenation left hand operand is in ", new _DelayedToString(leftOF),
+ " format, while the right hand operand is in ", new _DelayedToString(rightOF),
+ ". Conversion to common format wasn't possible." };
+ if (parent instanceof ASTExpression) {
+ throw new _MiscTemplateException((ASTExpression) parent, message);
+ } else {
+ throw new _MiscTemplateException(message);
+ }
+ }
+ } else {
+ return leftOF.concat(leftMO, rightMO);
+ }
+ }
+
+ /**
+ * Returns an {@link ArithmeticEngine} even if {@code env} is {@code null}, because we are in parsing phase.
+ */
+ static ArithmeticEngine getArithmeticEngine(Environment env, ASTNode tObj) {
+ return env != null
+ ? env.getArithmeticEngine()
+ : tObj.getTemplate().getParsingConfiguration().getArithmeticEngine();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluationException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluationException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluationException.java
index 620399a..6c8e700 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluationException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluationException.java
@@ -19,7 +19,7 @@
package org.apache.freemarker.core;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Don't use this; used internally by FreeMarker, might changes without notice.
@@ -38,7 +38,7 @@ public class _ObjectBuilderSettingEvaluationException extends Exception {
public _ObjectBuilderSettingEvaluationException(String expected, String src, int location) {
super("Expression syntax error: Expected a(n) " + expected + ", but "
+ (location < src.length()
- ? "found character " + _StringUtil.jQuote("" + src.charAt(location)) + " at position "
+ ? "found character " + _StringUtils.jQuote("" + src.charAt(location)) + " at position "
+ (location + 1) + "."
: "the end of the parsed string was reached.") );
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluator.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluator.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluator.java
index 89a6fe8..7be4511 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluator.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_ObjectBuilderSettingEvaluator.java
@@ -60,8 +60,8 @@ import org.apache.freemarker.core.templateresolver.PathRegexMatcher;
import org.apache.freemarker.core.util.BugException;
import org.apache.freemarker.core.util.FTLUtil;
import org.apache.freemarker.core.util.GenericParseException;
-import org.apache.freemarker.core.util._ClassUtil;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._ClassUtils;
+import org.apache.freemarker.core.util._StringUtils;
/**
* Don't use this; used internally by FreeMarker, might changes without notice.
@@ -634,7 +634,7 @@ public class _ObjectBuilderSettingEvaluator {
if (i != 0) {
sb.append(" or ");
}
- sb.append(_StringUtil.jQuote(expectedChars.substring(i, i + 1)));
+ sb.append(_StringUtils.jQuote(expectedChars.substring(i, i + 1)));
}
throw new _ObjectBuilderSettingEvaluationException(
sb.toString(),
@@ -739,13 +739,13 @@ public class _ObjectBuilderSettingEvaluator {
if (!beanPropSetters.containsKey(name)) {
throw new _ObjectBuilderSettingEvaluationException(
"The " + cl.getName() + " class has no writeable JavaBeans property called "
- + _StringUtil.jQuote(name) + ".");
+ + _StringUtils.jQuote(name) + ".");
}
Method beanPropSetter = beanPropSetters.put(name, null);
if (beanPropSetter == null) {
throw new _ObjectBuilderSettingEvaluationException(
- "JavaBeans property " + _StringUtil.jQuote(name) + " is set twice.");
+ "JavaBeans property " + _StringUtils.jQuote(name) + " is set twice.");
}
try {
@@ -765,7 +765,7 @@ public class _ObjectBuilderSettingEvaluator {
}
if (!(m instanceof JavaMethodModel)) {
throw new _ObjectBuilderSettingEvaluationException(
- _StringUtil.jQuote(beanPropSetter.getName()) + " wasn't a JavaMethodModel.");
+ _StringUtils.jQuote(beanPropSetter.getName()) + " wasn't a JavaMethodModel.");
}
List/*TemplateModel*/ args = new ArrayList();
((JavaMethodModel) m).execute(
@@ -773,7 +773,7 @@ public class _ObjectBuilderSettingEvaluator {
NonTemplateCallPlace.INSTANCE);
} catch (Exception e) {
throw new _ObjectBuilderSettingEvaluationException(
- "Failed to set " + _StringUtil.jQuote(name), e);
+ "Failed to set " + _StringUtils.jQuote(name), e);
}
}
}
@@ -877,16 +877,16 @@ public class _ObjectBuilderSettingEvaluator {
boolean clIsBuilderClass;
try {
- cl = _ClassUtil.forName(className + BUILDER_CLASS_POSTFIX_1);
+ cl = _ClassUtils.forName(className + BUILDER_CLASS_POSTFIX_1);
clIsBuilderClass = true;
} catch (ClassNotFoundException eIgnored) {
try {
- cl = _ClassUtil.forName(className + BUILDER_CLASS_POSTFIX_2);
+ cl = _ClassUtils.forName(className + BUILDER_CLASS_POSTFIX_2);
clIsBuilderClass = true;
} catch (ClassNotFoundException e) {
clIsBuilderClass = false;
try {
- cl = _ClassUtil.forName(className);
+ cl = _ClassUtils.forName(className);
} catch (Exception e2) {
boolean failedToGetAsStaticField;
if (canBeStaticField && className.indexOf('.') != -1) {
@@ -901,7 +901,7 @@ public class _ObjectBuilderSettingEvaluator {
failedToGetAsStaticField = false;
}
throw new _ObjectBuilderSettingEvaluationException(
- "Failed to get class " + _StringUtil.jQuote(className)
+ "Failed to get class " + _StringUtils.jQuote(className)
+ (failedToGetAsStaticField ? " (also failed to resolve name as static field)" : "")
+ ".",
e2);
@@ -920,7 +920,7 @@ public class _ObjectBuilderSettingEvaluator {
// Expected
} catch (Exception e) {
throw new _ObjectBuilderSettingEvaluationException(
- "Error when trying to access " + _StringUtil.jQuote(className) + "."
+ "Error when trying to access " + _StringUtils.jQuote(className) + "."
+ INSTANCE_FIELD_NAME, e);
}
}
@@ -944,10 +944,10 @@ public class _ObjectBuilderSettingEvaluator {
Class<?> cl;
try {
- cl = _ClassUtil.forName(className);
+ cl = _ClassUtils.forName(className);
} catch (Exception e) {
throw new _ObjectBuilderSettingEvaluationException(
- "Failed to get field's parent class, " + _StringUtil.jQuote(className) + ".",
+ "Failed to get field's parent class, " + _StringUtils.jQuote(className) + ".",
e);
}
@@ -956,8 +956,8 @@ public class _ObjectBuilderSettingEvaluator {
field = cl.getField(fieldName);
} catch (Exception e) {
throw new _ObjectBuilderSettingEvaluationException(
- "Failed to get field " + _StringUtil.jQuote(fieldName) + " from class "
- + _StringUtil.jQuote(className) + ".",
+ "Failed to get field " + _StringUtils.jQuote(fieldName) + " from class "
+ + _StringUtils.jQuote(className) + ".",
e);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/_TemplateModelException.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/_TemplateModelException.java b/freemarker-core/src/main/java/org/apache/freemarker/core/_TemplateModelException.java
index 76e9d2b..10ad99f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/_TemplateModelException.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/_TemplateModelException.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
public class _TemplateModelException extends TemplateModelException {
@@ -126,7 +126,7 @@ public class _TemplateModelException extends TemplateModelException {
return new Object[] {
"The FreeMarker value exists, but has nothing inside it; the TemplateModel object (class: ",
model.getClass().getName(), ") has returned a null",
- (expected != null ? new Object[] { " instead of a ", _ClassUtil.getShortClassName(expected) } : ""),
+ (expected != null ? new Object[] { " instead of a ", _ClassUtils.getShortClassName(expected) } : ""),
". This is possibly a bug in the non-FreeMarker code that builds the data-model." };
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/BigDecimalArithmeticEngine.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/BigDecimalArithmeticEngine.java b/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/BigDecimalArithmeticEngine.java
index 0d22656..d09d48f 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/BigDecimalArithmeticEngine.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/BigDecimalArithmeticEngine.java
@@ -21,7 +21,7 @@ package org.apache.freemarker.core.arithmetic.impl;
import java.math.BigDecimal;
import org.apache.freemarker.core.arithmetic.ArithmeticEngine;
-import org.apache.freemarker.core.util._NumberUtil;
+import org.apache.freemarker.core.util._NumberUtils;
/**
* Arithmetic engine that converts all numbers to {@link BigDecimal} and then operates on them, and also keeps the
@@ -40,37 +40,37 @@ public class BigDecimalArithmeticEngine extends ArithmeticEngine {
// We try to find the result based on the sign (+/-/0) first, because:
// - It's much faster than converting to BigDecial, and comparing to 0 is the most common comparison.
// - It doesn't require any type conversions, and thus things like "Infinity > 0" won't fail.
- int firstSignum = _NumberUtil.getSignum(first);
- int secondSignum = _NumberUtil.getSignum(second);
+ int firstSignum = _NumberUtils.getSignum(first);
+ int secondSignum = _NumberUtils.getSignum(second);
if (firstSignum != secondSignum) {
return firstSignum < secondSignum ? -1 : (firstSignum > secondSignum ? 1 : 0);
} else if (firstSignum == 0 && secondSignum == 0) {
return 0;
} else {
- BigDecimal left = _NumberUtil.toBigDecimal(first);
- BigDecimal right = _NumberUtil.toBigDecimal(second);
+ BigDecimal left = _NumberUtils.toBigDecimal(first);
+ BigDecimal right = _NumberUtils.toBigDecimal(second);
return left.compareTo(right);
}
}
@Override
public Number add(Number first, Number second) {
- BigDecimal left = _NumberUtil.toBigDecimal(first);
- BigDecimal right = _NumberUtil.toBigDecimal(second);
+ BigDecimal left = _NumberUtils.toBigDecimal(first);
+ BigDecimal right = _NumberUtils.toBigDecimal(second);
return left.add(right);
}
@Override
public Number subtract(Number first, Number second) {
- BigDecimal left = _NumberUtil.toBigDecimal(first);
- BigDecimal right = _NumberUtil.toBigDecimal(second);
+ BigDecimal left = _NumberUtils.toBigDecimal(first);
+ BigDecimal right = _NumberUtils.toBigDecimal(second);
return left.subtract(right);
}
@Override
public Number multiply(Number first, Number second) {
- BigDecimal left = _NumberUtil.toBigDecimal(first);
- BigDecimal right = _NumberUtil.toBigDecimal(second);
+ BigDecimal left = _NumberUtils.toBigDecimal(first);
+ BigDecimal right = _NumberUtils.toBigDecimal(second);
BigDecimal result = left.multiply(right);
if (result.scale() > maxScale) {
result = result.setScale(maxScale, roundingPolicy);
@@ -80,8 +80,8 @@ public class BigDecimalArithmeticEngine extends ArithmeticEngine {
@Override
public Number divide(Number first, Number second) {
- BigDecimal left = _NumberUtil.toBigDecimal(first);
- BigDecimal right = _NumberUtil.toBigDecimal(second);
+ BigDecimal left = _NumberUtils.toBigDecimal(first);
+ BigDecimal right = _NumberUtils.toBigDecimal(second);
return divide(left, right);
}
@@ -94,7 +94,7 @@ public class BigDecimalArithmeticEngine extends ArithmeticEngine {
@Override
public Number toNumber(String s) {
- return _NumberUtil.toBigDecimalOrDouble(s);
+ return _NumberUtils.toBigDecimalOrDouble(s);
}
private BigDecimal divide(BigDecimal left, BigDecimal right) {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/ConservativeArithmeticEngine.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/ConservativeArithmeticEngine.java b/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/ConservativeArithmeticEngine.java
index 12c27d9..16f58a2 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/ConservativeArithmeticEngine.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/arithmetic/impl/ConservativeArithmeticEngine.java
@@ -27,7 +27,7 @@ import org.apache.freemarker.core.TemplateException;
import org.apache.freemarker.core._MiscTemplateException;
import org.apache.freemarker.core.arithmetic.ArithmeticEngine;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._NumberUtil;
+import org.apache.freemarker.core.util._NumberUtils;
/**
* Arithmetic engine that uses (more-or-less) the widening conversions of
@@ -96,8 +96,8 @@ public class ConservativeArithmeticEngine extends ArithmeticEngine {
return n1.compareTo(n2);
}
case BIG_DECIMAL: {
- BigDecimal n1 = _NumberUtil.toBigDecimal(first);
- BigDecimal n2 = _NumberUtil.toBigDecimal(second);
+ BigDecimal n1 = _NumberUtils.toBigDecimal(first);
+ BigDecimal n2 = _NumberUtils.toBigDecimal(second);
return n1.compareTo(n2);
}
}
@@ -139,8 +139,8 @@ public class ConservativeArithmeticEngine extends ArithmeticEngine {
return n1.add(n2);
}
case BIG_DECIMAL: {
- BigDecimal n1 = _NumberUtil.toBigDecimal(first);
- BigDecimal n2 = _NumberUtil.toBigDecimal(second);
+ BigDecimal n1 = _NumberUtils.toBigDecimal(first);
+ BigDecimal n2 = _NumberUtils.toBigDecimal(second);
return n1.add(n2);
}
}
@@ -182,8 +182,8 @@ public class ConservativeArithmeticEngine extends ArithmeticEngine {
return n1.subtract(n2);
}
case BIG_DECIMAL: {
- BigDecimal n1 = _NumberUtil.toBigDecimal(first);
- BigDecimal n2 = _NumberUtil.toBigDecimal(second);
+ BigDecimal n1 = _NumberUtils.toBigDecimal(first);
+ BigDecimal n2 = _NumberUtils.toBigDecimal(second);
return n1.subtract(n2);
}
}
@@ -225,8 +225,8 @@ public class ConservativeArithmeticEngine extends ArithmeticEngine {
return n1.multiply(n2);
}
case BIG_DECIMAL: {
- BigDecimal n1 = _NumberUtil.toBigDecimal(first);
- BigDecimal n2 = _NumberUtil.toBigDecimal(second);
+ BigDecimal n1 = _NumberUtils.toBigDecimal(first);
+ BigDecimal n2 = _NumberUtils.toBigDecimal(second);
BigDecimal r = n1.multiply(n2);
return r.scale() > maxScale ? r.setScale(maxScale, roundingPolicy) : r;
}
@@ -274,8 +274,8 @@ public class ConservativeArithmeticEngine extends ArithmeticEngine {
}
}
case BIG_DECIMAL: {
- BigDecimal n1 = _NumberUtil.toBigDecimal(first);
- BigDecimal n2 = _NumberUtil.toBigDecimal(second);
+ BigDecimal n1 = _NumberUtils.toBigDecimal(first);
+ BigDecimal n2 = _NumberUtils.toBigDecimal(second);
int scale1 = n1.scale();
int scale2 = n2.scale();
int scale = Math.max(scale1, scale2);
@@ -319,8 +319,8 @@ public class ConservativeArithmeticEngine extends ArithmeticEngine {
@Override
public Number toNumber(String s) {
- Number n = _NumberUtil.toBigDecimalOrDouble(s);
- return n instanceof BigDecimal ? _NumberUtil.optimizeNumberRepresentation(n) : n;
+ Number n = _NumberUtils.toBigDecimalOrDouble(s);
+ return n instanceof BigDecimal ? _NumberUtils.optimizeNumberRepresentation(n) : n;
}
private static Map createClassCodesMap() {
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/debug/DebuggerServer.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/debug/DebuggerServer.java b/freemarker-core/src/main/java/org/apache/freemarker/core/debug/DebuggerServer.java
index c1428c1..4efc482 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/debug/DebuggerServer.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/debug/DebuggerServer.java
@@ -33,7 +33,7 @@ import java.util.Arrays;
import java.util.Random;
import org.apache.freemarker.core.util.UndeclaredThrowableException;
-import org.apache.freemarker.core.util._SecurityUtil;
+import org.apache.freemarker.core.util._SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -54,9 +54,9 @@ class DebuggerServer {
private ServerSocket serverSocket;
public DebuggerServer(Serializable debuggerStub) {
- port = _SecurityUtil.getSystemProperty("org.apache.freemarker.core.debug.port", Debugger.DEFAULT_PORT).intValue();
+ port = _SecurityUtils.getSystemProperty("org.apache.freemarker.core.debug.port", Debugger.DEFAULT_PORT).intValue();
try {
- password = _SecurityUtil.getSystemProperty("org.apache.freemarker.core.debug.password", "").getBytes(
+ password = _SecurityUtils.getSystemProperty("org.apache.freemarker.core.debug.password", "").getBytes(
StandardCharsets.UTF_8);
} catch (UnsupportedCharsetException e) {
throw new UndeclaredThrowableException(e);
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/debug/_DebuggerService.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/debug/_DebuggerService.java b/freemarker-core/src/main/java/org/apache/freemarker/core/debug/_DebuggerService.java
index 37d094c..4d37917 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/debug/_DebuggerService.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/debug/_DebuggerService.java
@@ -25,7 +25,7 @@ import java.util.List;
import org.apache.freemarker.core.Environment;
import org.apache.freemarker.core.Template;
-import org.apache.freemarker.core.util._SecurityUtil;
+import org.apache.freemarker.core.util._SecurityUtils;
/**
* Don't use this; used internally by FreeMarker, might changes without notice.
@@ -40,7 +40,7 @@ public abstract class _DebuggerService {
// off, this is a fast no-op service, otherwise it's the real-thing
// RMI service.
return
- _SecurityUtil.getSystemProperty("org.apache.freemarker.core.debug.password", null) == null
+ _SecurityUtils.getSystemProperty("org.apache.freemarker.core.debug.password", null) == null
? new NoOpDebuggerService()
: new RmiDebuggerService();
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ArgumentTypes.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ArgumentTypes.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ArgumentTypes.java
index 3b346e6..77d1790 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ArgumentTypes.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ArgumentTypes.java
@@ -27,7 +27,7 @@ import java.util.List;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
import org.apache.freemarker.core.util.BugException;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
/**
* The argument types of a method call; usable as cache key.
@@ -152,7 +152,7 @@ final class ArgumentTypes {
* specific than {@code Boolean}, because the former can't store {@code null}). The preferability decision gets
* trickier when there's a possibility of numerical conversion from the actual argument type to the type of some of
* the parameters. If such conversion is only possible for one of the competing parameter types, that parameter
- * automatically wins. If it's possible for both, {@link OverloadedNumberUtil#getArgumentConversionPrice} will
+ * automatically wins. If it's possible for both, {@link OverloadedNumberUtils#getArgumentConversionPrice} will
* be used to calculate the conversion "price", and the parameter type with lowest price wins. There are also
* a twist with array-to-list and list-to-array conversions; we try to avoid those, so the parameter where such
* conversion isn't needed will always win.
@@ -190,10 +190,10 @@ final class ArgumentTypes {
final boolean argIsNum = Number.class.isAssignableFrom(argType);
final int numConvPrice1;
- if (argIsNum && _ClassUtil.isNumerical(paramType1)) {
+ if (argIsNum && _ClassUtils.isNumerical(paramType1)) {
final Class<?> nonPrimParamType1 = paramType1.isPrimitive()
- ? _ClassUtil.primitiveClassToBoxingClass(paramType1) : paramType1;
- numConvPrice1 = OverloadedNumberUtil.getArgumentConversionPrice(argType, nonPrimParamType1);
+ ? _ClassUtils.primitiveClassToBoxingClass(paramType1) : paramType1;
+ numConvPrice1 = OverloadedNumberUtils.getArgumentConversionPrice(argType, nonPrimParamType1);
} else {
numConvPrice1 = Integer.MAX_VALUE;
}
@@ -202,10 +202,10 @@ final class ArgumentTypes {
// - FM doesn't know some of the numerical types, or the conversion between them is not allowed
final int numConvPrice2;
- if (argIsNum && _ClassUtil.isNumerical(paramType2)) {
+ if (argIsNum && _ClassUtils.isNumerical(paramType2)) {
final Class<?> nonPrimParamType2 = paramType2.isPrimitive()
- ? _ClassUtil.primitiveClassToBoxingClass(paramType2) : paramType2;
- numConvPrice2 = OverloadedNumberUtil.getArgumentConversionPrice(argType, nonPrimParamType2);
+ ? _ClassUtils.primitiveClassToBoxingClass(paramType2) : paramType2;
+ numConvPrice2 = OverloadedNumberUtils.getArgumentConversionPrice(argType, nonPrimParamType2);
} else {
numConvPrice2 = Integer.MAX_VALUE;
}
@@ -300,16 +300,16 @@ final class ArgumentTypes {
if (numConvPrice1 != numConvPrice2) {
if (numConvPrice1 < numConvPrice2) {
winerParam = 1;
- if (numConvPrice1 < OverloadedNumberUtil.BIG_MANTISSA_LOSS_PRICE
- && numConvPrice2 > OverloadedNumberUtil.BIG_MANTISSA_LOSS_PRICE) {
+ if (numConvPrice1 < OverloadedNumberUtils.BIG_MANTISSA_LOSS_PRICE
+ && numConvPrice2 > OverloadedNumberUtils.BIG_MANTISSA_LOSS_PRICE) {
paramList1StrongWinCnt++;
} else {
paramList1WinCnt++;
}
} else {
winerParam = -1;
- if (numConvPrice2 < OverloadedNumberUtil.BIG_MANTISSA_LOSS_PRICE
- && numConvPrice1 > OverloadedNumberUtil.BIG_MANTISSA_LOSS_PRICE) {
+ if (numConvPrice2 < OverloadedNumberUtils.BIG_MANTISSA_LOSS_PRICE
+ && numConvPrice1 > OverloadedNumberUtils.BIG_MANTISSA_LOSS_PRICE) {
paramList2StrongWinCnt++;
} else {
paramList2WinCnt++;
@@ -347,8 +347,8 @@ final class ArgumentTypes {
if (argTypesLen == paramTypes1Len - 1) {
Class<?> paramType1 = getParamType(paramTypes1, paramTypes1Len, argTypesLen, true);
Class<?> paramType2 = getParamType(paramTypes2, paramTypes2Len, argTypesLen, true);
- if (_ClassUtil.isNumerical(paramType1) && _ClassUtil.isNumerical(paramType2)) {
- int r = OverloadedNumberUtil.compareNumberTypeSpecificity(paramType1, paramType2);
+ if (_ClassUtils.isNumerical(paramType1) && _ClassUtils.isNumerical(paramType2)) {
+ int r = OverloadedNumberUtils.compareNumberTypeSpecificity(paramType1, paramType2);
if (r != 0) return r;
// falls through
}
@@ -377,9 +377,9 @@ final class ArgumentTypes {
// The more specific (smaller) type wins.
final Class<?> nonPrimParamType1 = paramType1.isPrimitive()
- ? _ClassUtil.primitiveClassToBoxingClass(paramType1) : paramType1;
+ ? _ClassUtils.primitiveClassToBoxingClass(paramType1) : paramType1;
final Class<?> nonPrimParamType2 = paramType2.isPrimitive()
- ? _ClassUtil.primitiveClassToBoxingClass(paramType2) : paramType2;
+ ? _ClassUtils.primitiveClassToBoxingClass(paramType2) : paramType2;
if (nonPrimParamType1 == nonPrimParamType2) {
if (nonPrimParamType1 != paramType1) {
@@ -505,7 +505,7 @@ final class ArgumentTypes {
return CONVERSION_DIFFICULTY_IMPOSSIBLE;
}
- formalNP = _ClassUtil.primitiveClassToBoxingClass(formal);
+ formalNP = _ClassUtils.primitiveClassToBoxingClass(formal);
if (actual == formalNP) {
// Character and char, etc.
return CONVERSION_DIFFICULTY_REFLECTION;
@@ -518,7 +518,7 @@ final class ArgumentTypes {
formalNP = formal;
}
if (Number.class.isAssignableFrom(actual) && Number.class.isAssignableFrom(formalNP)) {
- return OverloadedNumberUtil.getArgumentConversionPrice(actual, formalNP) == Integer.MAX_VALUE
+ return OverloadedNumberUtils.getArgumentConversionPrice(actual, formalNP) == Integer.MAX_VALUE
? CONVERSION_DIFFICULTY_IMPOSSIBLE : CONVERSION_DIFFICULTY_REFLECTION;
} else if (formal.isArray()) {
// DefaultObjectWrapper method/constructor calls convert from List to array automatically
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/BeanModel.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/BeanModel.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/BeanModel.java
index 33d5e86..4320251 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/BeanModel.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/BeanModel.java
@@ -45,7 +45,7 @@ import org.apache.freemarker.core.model.TemplateModelIterator;
import org.apache.freemarker.core.model.TemplateModelWithAPISupport;
import org.apache.freemarker.core.model.TemplateScalarModel;
import org.apache.freemarker.core.model.WrapperTemplateModel;
-import org.apache.freemarker.core.util._StringUtil;
+import org.apache.freemarker.core.util._StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -164,7 +164,7 @@ public class BeanModel
private void logNoSuchKey(String key, Map<?, ?> keyMap) {
if (LOG.isDebugEnabled()) {
- LOG.debug("Key " + _StringUtil.jQuoteNoXSS(key) + " was not found on instance of " +
+ LOG.debug("Key " + _StringUtils.jQuoteNoXSS(key) + " was not found on instance of " +
object.getClass().getName() + ". Introspection information for " +
"the class is: " + keyMap);
}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassBasedModelFactory.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassBasedModelFactory.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassBasedModelFactory.java
index 3fd3a2d..c866d65 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassBasedModelFactory.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassBasedModelFactory.java
@@ -27,7 +27,7 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.freemarker.core.model.TemplateHashModel;
import org.apache.freemarker.core.model.TemplateModel;
import org.apache.freemarker.core.model.TemplateModelException;
-import org.apache.freemarker.core.util._ClassUtil;
+import org.apache.freemarker.core.util._ClassUtils;
/**
* Base class for hash models keyed by Java class names.
@@ -91,7 +91,7 @@ abstract class ClassBasedModelFactory implements TemplateHashModel {
classIntrospectorClearingCounter = classIntrospector.getClearingCounter();
}
try {
- final Class clazz = _ClassUtil.forName(key);
+ final Class clazz = _ClassUtils.forName(key);
// This is called so that we trigger the
// class-reloading detector. If clazz is a reloaded class,
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassIntrospector.java
----------------------------------------------------------------------
diff --git a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassIntrospector.java b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassIntrospector.java
index ead6c7a..a1f5935 100644
--- a/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassIntrospector.java
+++ b/freemarker-core/src/main/java/org/apache/freemarker/core/model/impl/ClassIntrospector.java
@@ -411,7 +411,7 @@ class ClassIntrospector {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length == 0
|| paramTypes.length == 1 && paramTypes[0] == int.class /* indexed property reader */) {
- String propName = _MethodUtil.getBeanPropertyNameFromReaderMethodName(
+ String propName = _MethodUtils.getBeanPropertyNameFromReaderMethodName(
method.getName(), method.getReturnType());
if (propName != null) {
if (mergedPRMPs == null) {
[14/17] incubator-freemarker git commit: Renamed XxxUtil classes to
XxxUtils, as this convention is more widespread nowadays.
Posted by dd...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilsTest.java
new file mode 100644
index 0000000..c44eee3
--- /dev/null
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/DateUtilsTest.java
@@ -0,0 +1,1085 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.freemarker.core.util._DateUtils.CalendarFieldsToDateConverter;
+import org.apache.freemarker.core.util._DateUtils.DateParseException;
+import org.apache.freemarker.core.util._DateUtils.DateToISO8601CalendarFactory;
+import org.apache.freemarker.core.util._DateUtils.TrivialCalendarFieldsToDateConverter;
+
+import junit.framework.TestCase;
+
+public class DateUtilsTest extends TestCase {
+
+ private final TimeZone originalDefaultTZ = TimeZone.getDefault();
+
+ @Override
+ protected void setUp() throws Exception {
+ TimeZone.setDefault(TimeZone.getTimeZone("Europe/Prague"));
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ TimeZone.setDefault(originalDefaultTZ);
+ }
+
+ private final DateFormat df
+ = new SimpleDateFormat("G yyyy-MM-dd HH:mm:ss:S Z", Locale.US);
+ {
+ df.setTimeZone(_DateUtils.UTC);
+ }
+
+ private CalendarFieldsToDateConverter cf2dc = new TrivialCalendarFieldsToDateConverter();
+
+ private DateToISO8601CalendarFactory calendarFactory
+ = new _DateUtils.TrivialDateToISO8601CalendarFactory();
+
+ public DateUtilsTest(String name) {
+ super(name);
+ }
+
+ public void testDateToUTCString() throws ParseException {
+ assertEquals(
+ "1998-10-30T15:30:00.512Z",
+ dateToISO8601UTCDateTimeMSString(
+ df.parse("AD 1998-10-30 19:30:00:512 +0400"), true));
+ assertEquals(
+ "1998-10-30T15:30:00.5Z",
+ dateToISO8601UTCDateTimeMSString(
+ df.parse("AD 1998-10-30 19:30:00:500 +0400"), true));
+ assertEquals(
+ "1998-10-30T15:30:00.51Z",
+ dateToISO8601UTCDateTimeMSString(
+ df.parse("AD 1998-10-30 19:30:00:510 +0400"), true));
+ assertEquals(
+ "1998-10-30T15:30:00.1Z",
+ dateToISO8601UTCDateTimeMSString(
+ df.parse("AD 1998-10-30 19:30:00:100 +0400"), true));
+ assertEquals(
+ "1998-10-30T15:30:00.01Z",
+ dateToISO8601UTCDateTimeMSString(
+ df.parse("AD 1998-10-30 19:30:00:10 +0400"), true));
+ assertEquals(
+ "1998-10-30T15:30:00.001Z",
+ dateToISO8601UTCDateTimeMSString(
+ df.parse("AD 1998-10-30 19:30:00:1 +0400"), true));
+ assertEquals(
+ "2000-02-08T06:05:04Z",
+ dateToISO8601UTCDateTimeMSString(
+ df.parse("AD 2000-02-08 09:05:04:0 +0300"), true));
+ assertEquals(
+ "0099-02-28T06:15:24Z",
+ dateToISO8601UTCDateTimeString(
+ df.parse(
+ "AD 0099-03-02 09:15:24:0 +0300"), true));
+ assertEquals(
+ "0010-02-28T06:15:24Z",
+ dateToISO8601UTCDateTimeString(
+ df.parse("AD 0010-03-02 09:15:24:0 +0300"), true));
+ assertEquals(
+ "0001-02-28T06:15:24Z",
+ dateToISO8601UTCDateTimeString(
+ df.parse("AD 0001-03-02 09:15:24:0 +0300"), true));
+ assertEquals(
+ "0000-02-29T06:15:24Z",
+ dateToISO8601UTCDateTimeString(
+ df.parse("BC 0001-03-02 09:15:24:0 +0300"), true));
+ assertEquals(
+ "-1-02-28T06:15:24Z",
+ dateToISO8601UTCDateTimeString(
+ df.parse("BC 2-03-02 09:15:24:0 +0300"), true));
+ assertEquals(
+ "10000-02-28T06:15:24Z",
+ dateToISO8601UTCDateTimeString(
+ df.parse("AD 10000-02-28 09:15:24:0 +0300"), true));
+
+ Date d = df.parse("AD 1998-10-30 19:30:00:512 +0400");
+ assertEquals(
+ "1998-10-30",
+ dateToISO8601UTCDateString(d));
+ assertEquals(
+ "15:30:00.512Z",
+ dateToISO8601UTCTimeMSString(d, true));
+ assertEquals(
+ "15:30:00.512",
+ dateToISO8601UTCTimeMSString(d, false));
+ assertEquals(
+ "1998-10-30",
+ dateToISO8601UTCDateString(
+ new java.sql.Date(d.getTime())));
+ assertEquals(
+ "15:30:00.512Z",
+ dateToISO8601UTCTimeMSString(
+ new java.sql.Time(d.getTime()), true));
+ }
+
+ public void testLocalTime() throws ParseException {
+ Date dsum = df.parse("AD 2010-05-09 20:00:00:0 UTC");
+ Date dwin = df.parse("AD 2010-01-01 20:00:00:0 UTC");
+
+ TimeZone tzRome = TimeZone.getTimeZone("Europe/Rome");
+ if (tzRome.getOffset(0) == 0) {
+ throw new RuntimeException(
+ "Can't get time zone for Europe/Rome!");
+ }
+ assertEquals(
+ "2010-05-09T22:00:00+02:00",
+ dateToISO8601DateTimeString(dsum, tzRome));
+ assertEquals(
+ "2010-01-01T21:00:00+01:00",
+ dateToISO8601DateTimeString(dwin, tzRome));
+ assertEquals(
+ "2010-05-09",
+ dateToISO8601DateString(dsum, tzRome));
+ assertEquals(
+ "2010-01-01",
+ dateToISO8601DateString(dwin, tzRome));
+ assertEquals(
+ "22:00:00+02:00",
+ dateToISO8601TimeString(dsum, tzRome));
+ assertEquals(
+ "21:00:00+01:00",
+ dateToISO8601TimeString(dwin, tzRome));
+
+ TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
+ if (tzNY.getOffset(0) == 0) {
+ throw new RuntimeException(
+ "Can't get time zone for America/New_York!");
+ }
+ assertEquals(
+ "2010-05-09T16:00:00-04:00",
+ dateToISO8601DateTimeString(dsum, tzNY));
+ assertEquals(
+ "2010-01-01T15:00:00-05:00",
+ dateToISO8601DateTimeString(dwin, tzNY));
+ assertEquals(
+ "2010-05-09",
+ dateToISO8601DateString(dsum, tzNY));
+ assertEquals(
+ "2010-01-01",
+ dateToISO8601DateString(dwin, tzNY));
+ assertEquals(
+ "16:00:00-04:00",
+ dateToISO8601TimeString(dsum, tzNY));
+ assertEquals(
+ "15:00:00-05:00",
+ dateToISO8601TimeString(dwin, tzNY));
+
+ TimeZone tzFixed = TimeZone.getTimeZone("GMT+02:30");
+ assertEquals(
+ "2010-05-09T22:30:00+02:30",
+ dateToISO8601DateTimeString(dsum, tzFixed));
+ assertEquals(
+ "2010-01-01T22:30:00+02:30",
+ dateToISO8601DateTimeString(dwin, tzFixed));
+ }
+
+ public void testGetTimeZone() throws Exception {
+ assertTrue(_DateUtils.getTimeZone("GMT") != _DateUtils.UTC);
+ assertTrue(_DateUtils.getTimeZone("UT1") != _DateUtils.UTC);
+ assertEquals(_DateUtils.getTimeZone("UTC"), _DateUtils.UTC);
+
+ assertEquals(_DateUtils.getTimeZone("Europe/Rome"),
+ TimeZone.getTimeZone("Europe/Rome"));
+
+ assertEquals(_DateUtils.getTimeZone("Iceland"), // GMT and no DST
+ TimeZone.getTimeZone("Iceland"));
+
+ try {
+ _DateUtils.getTimeZone("Europe/NoSuch");
+ fail();
+ } catch (UnrecognizedTimeZoneException e) {
+ // good
+ }
+ }
+
+ public void testTimeOnlyDate() throws UnrecognizedTimeZoneException {
+ Date t = new Date(0L);
+ SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
+
+ tf.setTimeZone(_DateUtils.UTC);
+ assertEquals("00:00:00", tf.format(t));
+ assertEquals("00:00:00",
+ dateToISO8601UTCTimeString(t, false));
+
+ TimeZone gmt1 = _DateUtils.getTimeZone("GMT+01");
+ tf.setTimeZone(gmt1);
+ assertEquals("01:00:00", tf.format(t));
+ assertEquals("01:00:00+01:00",
+ dateToISO8601TimeString(t, gmt1));
+ }
+
+ public void testAccuracy() throws ParseException {
+ Date d = df.parse("AD 2000-02-08 09:05:04:250 UTC");
+ assertEquals("2000-02-08T09:05:04Z",
+ dateToISO8601UTCDateTimeString(d, true));
+ assertEquals("2000-02-08T09:05:04.25Z",
+ dateToISO8601String(d, true, true, true,
+ _DateUtils.ACCURACY_MILLISECONDS, null));
+ assertEquals("2000-02-08T09:05:04Z",
+ dateToISO8601String(d, true, true, true,
+ _DateUtils.ACCURACY_SECONDS, null));
+ assertEquals("2000-02-08T09:05Z",
+ dateToISO8601String(d, true, true, true,
+ _DateUtils.ACCURACY_MINUTES, null));
+ assertEquals("2000-02-08T09Z",
+ dateToISO8601String(d, true, true, true,
+ _DateUtils.ACCURACY_HOURS, null));
+
+ d = df.parse("AD 1998-10-30 19:30:00:000 +0400");
+ assertEquals(
+ "15:30:00Z",
+ dateToISO8601UTCTimeMSString(d, true));
+ assertEquals(
+ "15:30:00.000Z",
+ dateToISO8601UTCTimeMSFString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00Z",
+ dateToISO8601UTCDateTimeMSString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00.000Z",
+ dateToISO8601UTCDateTimeMSFString(d, true));
+
+ d = df.parse("AD 1998-10-30 19:30:00:100 +0400");
+ assertEquals(
+ "15:30:00.1Z",
+ dateToISO8601UTCTimeMSString(d, true));
+ assertEquals(
+ "15:30:00.100Z",
+ dateToISO8601UTCTimeMSFString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00.1Z",
+ dateToISO8601UTCDateTimeMSString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00.100Z",
+ dateToISO8601UTCDateTimeMSFString(d, true));
+
+ d = df.parse("AD 1998-10-30 19:30:00:010 +0400");
+ assertEquals(
+ "15:30:00.01Z",
+ dateToISO8601UTCTimeMSString(d, true));
+ assertEquals(
+ "15:30:00.010Z",
+ dateToISO8601UTCTimeMSFString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00.01Z",
+ dateToISO8601UTCDateTimeMSString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00.010Z",
+ dateToISO8601UTCDateTimeMSFString(d, true));
+
+ d = df.parse("AD 1998-10-30 19:30:00:001 +0400");
+ assertEquals(
+ "15:30:00.001Z",
+ dateToISO8601UTCTimeMSString(d, true));
+ assertEquals(
+ "15:30:00.001Z",
+ dateToISO8601UTCTimeMSFString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00.001Z",
+ dateToISO8601UTCDateTimeMSString(d, true));
+ assertEquals(
+ "1998-10-30T15:30:00.001Z",
+ dateToISO8601UTCDateTimeMSFString(d, true));
+ }
+
+ public void testXSFormatISODeviations() throws ParseException, UnrecognizedTimeZoneException {
+ Date dsum = df.parse("AD 2010-05-09 20:00:00:0 UTC");
+ Date dwin = df.parse("AD 2010-01-01 20:00:00:0 UTC");
+
+ TimeZone tzRome = _DateUtils.getTimeZone("Europe/Rome");
+
+ assertEquals(
+ "2010-01-01T21:00:00+01:00",
+ _DateUtils.dateToXSString(dwin, true, true, true, _DateUtils.ACCURACY_SECONDS, tzRome, calendarFactory));
+ assertEquals(
+ "2010-05-09T22:00:00+02:00",
+ _DateUtils.dateToXSString(dsum, true, true, true, _DateUtils.ACCURACY_SECONDS, tzRome, calendarFactory));
+ assertEquals(
+ "2010-01-01+01:00", // ISO doesn't allow date-only with TZ
+ _DateUtils.dateToXSString(dwin, true, false, true, _DateUtils.ACCURACY_SECONDS, tzRome, calendarFactory));
+ assertEquals(
+ "2010-05-09+02:00", // ISO doesn't allow date-only with TZ
+ _DateUtils.dateToXSString(dsum, true, false, true, _DateUtils.ACCURACY_SECONDS, tzRome, calendarFactory));
+ assertEquals(
+ "21:00:00+01:00",
+ _DateUtils.dateToXSString(dwin, false, true, true, _DateUtils.ACCURACY_SECONDS, tzRome, calendarFactory));
+ assertEquals(
+ "22:00:00+02:00",
+ _DateUtils.dateToXSString(dsum, false, true, true, _DateUtils.ACCURACY_SECONDS, tzRome, calendarFactory));
+
+ assertEquals(
+ "-1-02-29T06:15:24Z", // ISO uses 0 for BC 1
+ _DateUtils.dateToXSString(
+ df.parse("BC 0001-03-02 09:15:24:0 +0300"),
+ true, true, true, _DateUtils.ACCURACY_SECONDS, _DateUtils.UTC, calendarFactory));
+ assertEquals(
+ "-2-02-28T06:15:24Z", // ISO uses -1 for BC 2
+ _DateUtils.dateToXSString(
+ df.parse("BC 2-03-02 09:15:24:0 +0300"),
+ true, true, true, _DateUtils.ACCURACY_SECONDS, _DateUtils.UTC, calendarFactory));
+ }
+
+ private String dateToISO8601DateTimeString(
+ Date date, TimeZone tz) {
+ return dateToISO8601String(date, true, true, true,
+ _DateUtils.ACCURACY_SECONDS, tz);
+ }
+
+ private String dateToISO8601UTCDateTimeString(
+ Date date, boolean offsetPart) {
+ return dateToISO8601String(date, true, true, offsetPart,
+ _DateUtils.ACCURACY_SECONDS, _DateUtils.UTC);
+ }
+
+ private String dateToISO8601UTCDateTimeMSString(
+ Date date, boolean offsetPart) {
+ return dateToISO8601String(date, true, true, offsetPart,
+ _DateUtils.ACCURACY_MILLISECONDS, _DateUtils.UTC);
+ }
+
+ private String dateToISO8601UTCDateTimeMSFString(
+ Date date, boolean offsetPart) {
+ return dateToISO8601String(date, true, true, offsetPart,
+ _DateUtils.ACCURACY_MILLISECONDS_FORCED, _DateUtils.UTC);
+ }
+
+ private String dateToISO8601DateString(Date date, TimeZone tz) {
+ return dateToISO8601String(date, true, false, false,
+ _DateUtils.ACCURACY_SECONDS, tz);
+ }
+
+ private String dateToISO8601UTCDateString(Date date) {
+ return dateToISO8601String(date, true, false, false,
+ _DateUtils.ACCURACY_SECONDS, _DateUtils.UTC);
+ }
+
+ private String dateToISO8601TimeString(
+ Date date, TimeZone tz) {
+ return dateToISO8601String(date, false, true, true,
+ _DateUtils.ACCURACY_SECONDS, tz);
+ }
+
+ private String dateToISO8601UTCTimeString(
+ Date date, boolean offsetPart) {
+ return dateToISO8601String(date, false, true, offsetPart,
+ _DateUtils.ACCURACY_SECONDS, _DateUtils.UTC);
+ }
+
+ private String dateToISO8601UTCTimeMSString(
+ Date date, boolean offsetPart) {
+ return dateToISO8601String(date, false, true, offsetPart,
+ _DateUtils.ACCURACY_MILLISECONDS, _DateUtils.UTC);
+ }
+
+ private String dateToISO8601UTCTimeMSFString(
+ Date date, boolean offsetPart) {
+ return dateToISO8601String(date, false, true, offsetPart,
+ _DateUtils.ACCURACY_MILLISECONDS_FORCED, _DateUtils.UTC);
+ }
+
+ private String dateToISO8601String(
+ Date date,
+ boolean datePart, boolean timePart, boolean offsetPart,
+ int accuracy,
+ TimeZone timeZone) {
+ return _DateUtils.dateToISO8601String(
+ date,
+ datePart, timePart, offsetPart,
+ accuracy,
+ timeZone,
+ calendarFactory);
+ }
+
+ public void testParseDate() throws DateParseException {
+ assertDateParsing(
+ "AD 1998-10-29 20:00:00:0 +0000",
+ null,
+ "1998-10-30+04:00", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 1998-10-30 02:00:00:0 +0000",
+ null,
+ "1998-10-30-02:00", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 1998-10-30 02:00:00:0 +0000",
+ "1998-10-30", _DateUtils.parseXSTimeZone("-02:00"));
+ assertDateParsing(
+ null,
+ "AD 1998-10-30 02:00:00:0 +0000",
+ "19981030", _DateUtils.parseXSTimeZone("-02:00"));
+ assertDateParsing(
+ "AD 1998-10-30 00:00:00:0 +0000",
+ null,
+ "1998-10-30Z", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 1998-10-30 00:00:00:0 +0000",
+ "1998-10-30", _DateUtils.UTC);
+ assertDateParsing(
+ null,
+ "AD 1998-10-30 00:00:00:0 +0000",
+ "19981030", _DateUtils.UTC);
+
+ assertDateParsing(
+ "AD 1998-10-29 20:00:00:0 +0000",
+ null,
+ "1998-10-30+04:00", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 1998-10-30 04:00:00:0 +0000",
+ null,
+ "1998-10-30-04:00", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 1998-10-30 00:00:00:0 +0000",
+ null,
+ "1998-10-30Z", _DateUtils.UTC);
+
+ try {
+ // XS doesn't have year 0
+ assertDateParsing(
+ "BC 0000-02-05 00:00:00:0 +0000",
+ null,
+ "0000-02-03Z", _DateUtils.UTC);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ assertDateParsing(
+ null,
+ "BC 0001-02-05 00:00:00:0 +0000",
+ "0000-02-03", _DateUtils.UTC);
+ assertDateParsing(
+ null,
+ "BC 0001-02-05 00:00:00:0 +0000",
+ "00000203", _DateUtils.UTC);
+
+ assertDateParsing(
+ "BC 0001-02-05 00:00:00:0 +0000", // Julian
+ "BC 0002-02-05 00:00:00:0 +0000", // Julian
+ "-0001-02-03", _DateUtils.UTC); // Proleptic Gregorian
+ assertDateParsing(
+ null,
+ "BC 0002-02-05 00:00:00:0 +0000", // Julian
+ "-00010203", _DateUtils.UTC); // Proleptic Gregorian
+
+ assertDateParsing(
+ "AD 0001-02-05 00:00:00:0 +0000", // Julian
+ null,
+ "0001-02-03Z", _DateUtils.UTC); // Proleptic Gregorian
+ assertDateParsing(
+ "AD 0001-02-05 00:00:00:0 +0000", // Julian
+ "0001-02-03", _DateUtils.UTC); // Proleptic Gregorian
+ assertDateParsing(
+ null,
+ "AD 0001-02-05 00:00:00:0 +0000", // Julian
+ "00010203", _DateUtils.UTC); // Proleptic Gregorian
+ assertDateParsing(
+ "AD 1001-12-07 00:00:00:0 +0000", // Julian
+ null,
+ "1001-12-13Z", _DateUtils.UTC); // Proleptic Gregorian
+ assertDateParsing(
+ "AD 1001-12-07 00:00:00:0 +0000", // Julian
+ "1001-12-13", _DateUtils.UTC); // Proleptic Gregorian
+
+ assertDateParsing(
+ "AD 2006-12-31 00:00:00:0 +0000",
+ null,
+ "2006-12-31Z", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 2006-12-31 00:00:00:0 +0000",
+ "2006-12-31", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 2006-01-01 00:00:00:0 +0000",
+ null,
+ "2006-01-01Z", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 2006-01-01 00:00:00:0 +0000",
+ "2006-01-01", _DateUtils.UTC);
+ assertDateParsing(
+ "AD 12006-01-01 00:00:00:0 +0000",
+ "12006-01-01", _DateUtils.UTC);
+ assertDateParsing(
+ null,
+ "AD 12006-01-01 00:00:00:0 +0000",
+ "120060101", _DateUtils.UTC);
+ }
+
+ public void testParseDateMalformed() {
+ assertDateMalformed("1998-10-30x");
+ assertDateMalformed("+1998-10-30");
+ assertDateMalformed("1998-10-");
+ assertDateMalformed("1998-1-30");
+ assertDateMalformed("1998-10-30+01");
+ assertDateMalformed("1998-00-01");
+ assertDateMalformed("1998-13-01");
+ assertDateMalformed("1998-10-00");
+ assertDateMalformed("1998-10-32");
+ assertDateMalformed("1998-02-31");
+
+ assertISO8601DateMalformed("2100103");
+ assertISO8601DateMalformed("210-01-03");
+ assertISO8601DateMalformed("2012-0301");
+ assertISO8601DateMalformed("201203-01");
+ assertISO8601DateMalformed("2012-01-01+01:00");
+ }
+
+ public void testParseTime() throws DateParseException {
+ assertTimeParsing(
+ "AD 1970-01-01 17:30:05:0 +0000",
+ "17:30:05", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 17:30:05:0 +0000",
+ "173005", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 07:30:00:100 +0000",
+ "07:30:00.1", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 07:30:00:120 +0000",
+ "07:30:00.12", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "07:30:00.123", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "07:30:00.1235", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "07:30:00.12346", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "073000.12346", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "073000,12346", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 07:30:00:120 +0000",
+ "07:30:00.12", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 07:30:00:500 +0000",
+ "07:30:00.5", _DateUtils.UTC);
+
+ assertTimeParsing(
+ "AD 1970-01-01 16:30:05:0 +0000",
+ "17:30:05+01:00", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 16:30:05:0 +0000",
+ "173005+01", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 19:00:05:0 +0000",
+ "17:30:05-01:30", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 19:00:05:0 +0000",
+ "173005-0130", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-01 16:30:05:500 +0000",
+ "17:30:05.5+01:00", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 16:30:05:500 +0000",
+ "173005.5+0100", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 16:30:05:500 +0000",
+ "173005.5+01", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 16:00:00:0 +0000",
+ "170000+01", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 16:00:00:0 +0000",
+ "1700+01", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-01 16:00:00:0 +0000",
+ "17+01", _DateUtils.UTC);
+
+ assertTimeParsing(
+ "AD 1970-01-01 00:00:00:0 +0000",
+ "00:00:00", _DateUtils.UTC);
+ assertTimeParsing(
+ "AD 1970-01-02 00:00:00:0 +0000",
+ "24:00:00", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-02 00:00:00:0 +0000",
+ "240000", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-02 00:00:00:0 +0000",
+ "2400", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-02 00:00:00:0 +0000",
+ "24:00", _DateUtils.UTC);
+ assertTimeParsing(
+ null,
+ "AD 1970-01-02 00:00:00:0 +0000",
+ "24", _DateUtils.UTC);
+
+ assertTimeParsing(
+ "AD 1970-01-01 23:59:59:999 +0000",
+ "23:59:59.999", _DateUtils.UTC);
+ }
+
+ public void testParseTimeMalformed() {
+ assertTimeMalformed("00:0000");
+ assertTimeMalformed("00:00:00-01:60");
+ assertTimeMalformed("24:00:01");
+ assertTimeMalformed("00:00:61");
+ assertTimeMalformed("00:60:00");
+ assertTimeMalformed("25:00:00");
+ assertTimeMalformed("2:00:00");
+ assertTimeMalformed("02:0:00");
+ assertTimeMalformed("02:00:0");
+
+ assertISO8601TimeMalformed("1010101");
+ assertISO8601TimeMalformed("10101");
+ assertISO8601TimeMalformed("101");
+ assertISO8601TimeMalformed("1");
+ assertISO8601TimeMalformed("101010-1");
+ assertISO8601TimeMalformed("101010-100");
+ assertISO8601TimeMalformed("101010-10000");
+ assertISO8601TimeMalformed("101010+1");
+ assertISO8601TimeMalformed("101010+100");
+ assertISO8601TimeMalformed("101010+10000");
+ }
+
+ public void testParseDateTime() throws DateParseException {
+ assertDateTimeParsing(
+ "AD 1998-10-30 11:30:00:0 +0000",
+ "1998-10-30T15:30:00+04:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ null,
+ "AD 1998-10-30 11:30:00:0 +0000",
+ "19981030T153000+0400", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 11:30:00:500 +0000",
+ "1998-10-30T15:30:00.5+04:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 15:30:00:0 +0000",
+ "1998-10-30T15:30:00Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ null,
+ "AD 1998-10-30 15:30:00:0 +0000",
+ "19981030T1530Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 15:30:00:500 +0000",
+ "1998-10-30T15:30:00.5Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 11:30:00:0 +0000",
+ "1998-10-30T15:30:00+04:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 15:30:00:0 +0000",
+ "1998-10-30T15:30:00Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 15:30:00:0 +0000",
+ "1998-10-30T15:30:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ null,
+ "AD 1998-10-30 15:30:00:0 +0000",
+ "1998-10-30T15:30", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "AD 1998-10-29 20:00:00:0 +0000",
+ "1998-10-30T00:00:00+04:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 02:00:00:0 +0000",
+ "1998-10-30T00:00:00-02:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 00:00:00:0 +0000",
+ "1998-10-30T00:00:00Z", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "AD 1998-10-29 20:00:00:0 +0000",
+ "1998-10-30T00:00:00+04:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1998-10-30 00:00:00:0 +0000",
+ "1998-10-30T00:00:00Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ null,
+ "AD 1998-10-30 00:00:00:0 +0000",
+ "1998-10-30T00:00Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ null,
+ "AD 1998-10-30 00:00:00:0 +0000",
+ "1998-10-30T00:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ null,
+ "AD 1998-10-30 00:00:00:0 +0000",
+ "19981030T00Z", _DateUtils.UTC);
+
+ // BC years
+ try {
+ assertDateTimeParsing(
+ "",
+ null,
+ "0000-02-03T00:00:00Z", _DateUtils.UTC);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ assertDateTimeParsing(
+ null,
+ "BC 0001-02-05 00:00:00:0 +0000",
+ "0000-02-03T00:00:00Z", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "BC 0001-02-05 00:00:00:0 +0000", // Julian
+ "BC 0002-02-05 00:00:00:0 +0000", // Julian
+ "-0001-02-03T00:00:00Z", _DateUtils.UTC); // Proleptic Gregorian
+
+ assertDateTimeParsing(
+ "AD 0001-02-05 00:00:00:0 +0000", // Julian
+ "0001-02-03T00:00:00Z", _DateUtils.UTC); // Proleptic Gregorian
+ assertDateTimeParsing(
+ "AD 1001-12-07 00:00:00:0 +0000", // Julian
+ "1001-12-13T00:00:00Z", _DateUtils.UTC); // Proleptic Gregorian
+ assertDateTimeParsing(
+ "AD 11001-12-13 00:00:00:0 +0000",
+ "11001-12-13T00:00:00Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ null,
+ "AD 11001-12-13 00:00:00:0 +0000",
+ "110011213T00Z", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "AD 2006-12-31 00:00:00:0 +0000",
+ "2006-12-31T00:00:00Z", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 2006-01-01 00:00:00:0 +0000",
+ "2006-01-01T00:00:00Z", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "1970-01-01T07:30:00.123", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "1970-01-01T07:30:00.1235", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1970-01-01 07:30:00:123 +0000",
+ "1970-01-01T07:30:00.12346", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1970-01-01 07:30:00:120 +0000",
+ "1970-01-01T07:30:00.12", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1970-01-01 07:30:00:500 +0000",
+ "1970-01-01T07:30:00.5", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "AD 1970-01-01 16:30:05:0 +0000",
+ "1970-01-01T17:30:05+01:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1970-01-01 16:30:05:500 +0000",
+ "1970-01-01T17:30:05.5+01:00", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "AD 1970-01-01 00:00:00:0 +0000",
+ "1970-01-01T00:00:00", _DateUtils.UTC);
+ assertDateTimeParsing(
+ "AD 1970-01-02 00:00:00:0 +0000",
+ "1970-01-01T24:00:00", _DateUtils.UTC);
+
+ assertDateTimeParsing(
+ "AD 1970-01-01 23:59:59:999 +0000",
+ "1970-01-01T23:59:59.999", _DateUtils.UTC);
+ }
+
+ public void testParseDateTimeMalformed() throws DateParseException {
+ assertDateTimeMalformed("1998-00-01T00:00:00");
+ assertDateTimeMalformed("1998-13-01T00:00:00");
+ assertDateTimeMalformed("1998-10-00T00:00:00");
+ assertDateTimeMalformed("1998-10-32T00:00:00");
+ assertDateTimeMalformed("1998-02-31T00:00:00");
+ assertDateTimeMalformed("1970-01-02T24:00:01");
+ assertDateTimeMalformed("1970-01-01T00:00:61");
+ assertDateTimeMalformed("1970-01-01T00:60:00");
+ assertDateTimeMalformed("1970-01-01T25:00:00");
+
+ assertISO8601DateTimeMalformed("197-01-01T20:00:00");
+ }
+
+ public void testParseXSTimeZone() throws DateParseException {
+ assertEquals(0,
+ _DateUtils.parseXSTimeZone("Z").getOffset(0));
+ assertEquals(0,
+ _DateUtils.parseXSTimeZone("-00:00").getOffset(0));
+ assertEquals(0,
+ _DateUtils.parseXSTimeZone("+00:00").getOffset(0));
+ assertEquals(90 * 60 * 1000,
+ _DateUtils.parseXSTimeZone("+01:30").getOffset(0));
+ assertEquals(-4 * 60 * 60 * 1000,
+ _DateUtils.parseXSTimeZone("-04:00").getOffset(0));
+ assertEquals(((-23 * 60) - 59) * 60 * 1000,
+ _DateUtils.parseXSTimeZone("-23:59").getOffset(0));
+ assertEquals(((23 * 60) + 59) * 60 * 1000,
+ _DateUtils.parseXSTimeZone("+23:59").getOffset(0));
+ }
+
+ public void testParseXSTimeZoneWrong() {
+ try {
+ _DateUtils.parseXSTimeZone("04:00").getOffset(0);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ try {
+ _DateUtils.parseXSTimeZone("-04:00x").getOffset(0);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ try {
+ _DateUtils.parseXSTimeZone("-04").getOffset(0);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ try {
+ _DateUtils.parseXSTimeZone("+24:00").getOffset(0);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ try {
+ _DateUtils.parseXSTimeZone("-24:00").getOffset(0);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ try {
+ _DateUtils.parseXSTimeZone("-01:60").getOffset(0);
+ fail();
+ } catch (DateParseException e) {
+ echo(e);
+ }
+ }
+
+ public void testParseXSDateTimeFTLAndJavax() throws DateParseException {
+ // Explicit time zone:
+ assertJavaxAndFTLXSDateTimesSame("2014-01-01T13:35:08Z");
+ assertJavaxAndFTLXSDateTimesSame("2014-01-01T13:35:08+02:00");
+
+ // Default time zone:
+ assertJavaxAndFTLXSDateTimesSame("2014-01-01T13:35:08"); // winter
+ assertJavaxAndFTLXSDateTimesSame("2014-07-01T13:35:08"); // summer
+
+ // Proleptic Gregorian
+ assertJavaxAndFTLXSDateTimesSame("1500-01-01T13:35:08Z");
+ assertJavaxAndFTLXSDateTimesSame("0200-01-01T13:35:08Z");
+ assertJavaxAndFTLXSDateTimesSame("0001-01-01T00:00:00+05:00");
+
+ // BC
+ assertJavaxAndFTLXSDateTimesSame("0001-01-01T13:35:08Z");
+ assertJavaxAndFTLXSDateTimesSame("-0001-01-01T13:35:08Z");
+
+ // Hour 24
+ assertJavaxAndFTLXSDateTimesSame("2014-01-01T23:59:59");
+ if (isAtLeastJava6()) { // Java 5 has broken parser that doesn't allow 24.
+ assertJavaxAndFTLXSDateTimesSame("2014-01-31T24:00:00");
+ assertJavaxAndFTLXSDateTimesSame("2014-01-01T24:00:00");
+ }
+ assertJavaxAndFTLXSDateTimesSame("2014-01-02T00:00:00"); // same as the previous
+ assertJavaxAndFTLXSDateTimesSame("2014-02-01T00:00:00"); // same as the previous
+
+ // Under ms
+ assertJavaxAndFTLXSDateTimesSame("2014-01-01T23:59:59.123456789");
+ assertJavaxAndFTLXSDateTimesSame("2014-01-01T23:59:59.1235");
+ }
+
+ private boolean isAtLeastJava6() {
+ try {
+ Class.forName("java.lang.management.LockInfo");
+ } catch (ClassNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
+
+ private final DatatypeFactory datetypeFactory;
+ {
+ try {
+ datetypeFactory = DatatypeFactory.newInstance();
+ } catch (DatatypeConfigurationException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void assertJavaxAndFTLXSDateTimesSame(String s) throws DateParseException {
+ XMLGregorianCalendar xgc = datetypeFactory.newXMLGregorianCalendar(s);
+ Date javaxDate = xgc.toGregorianCalendar().getTime();
+ Date ftlDate = _DateUtils.parseXSDateTime(s, TimeZone.getDefault(), cf2dc);
+ assertEquals(javaxDate, ftlDate);
+ }
+
+ private void assertDateParsing(String expected, String parsed, TimeZone tz) throws DateParseException {
+ assertDateParsing(expected, expected, parsed, tz);
+ }
+
+ private void assertDateParsing(String expectedXS, String expectedISO8601, String parsed, TimeZone tz)
+ throws DateParseException {
+ if (expectedXS != null) {
+ assertEquals(
+ expectedXS,
+ df.format(_DateUtils.parseXSDate(parsed, tz, cf2dc)));
+ }
+ if (expectedISO8601 != null) {
+ assertEquals(
+ expectedISO8601,
+ df.format(_DateUtils.parseISO8601Date(parsed, tz, cf2dc)));
+ }
+ }
+
+ private void assertDateTimeParsing(String expected, String parsed, TimeZone tz) throws DateParseException {
+ assertDateTimeParsing(expected, expected, parsed, tz);
+ }
+
+ private void assertDateTimeParsing(String expectedXS, String expectedISO8601, String parsed, TimeZone tz)
+ throws DateParseException {
+ if (expectedXS != null) {
+ assertEquals(
+ expectedXS,
+ df.format(_DateUtils.parseXSDateTime(parsed, tz, cf2dc)));
+ }
+ if (expectedISO8601 != null) {
+ assertEquals(
+ expectedISO8601,
+ df.format(_DateUtils.parseISO8601DateTime(parsed, tz, cf2dc)));
+ }
+ }
+
+ private void assertTimeParsing(String expected, String parsed, TimeZone tz) throws DateParseException {
+ assertTimeParsing(expected, expected, parsed, tz);
+ }
+
+ private void assertTimeParsing(String expectedXS, String expectedISO8601, String parsed, TimeZone tz)
+ throws DateParseException {
+ if (expectedXS != null) {
+ assertEquals(
+ expectedXS,
+ df.format(_DateUtils.parseXSTime(parsed, tz, cf2dc)));
+ }
+ if (expectedISO8601 != null) {
+ assertEquals(
+ expectedISO8601,
+ df.format(_DateUtils.parseISO8601Time(parsed, tz, cf2dc)));
+ }
+ }
+
+ private void assertDateMalformed(String parsed) {
+ try {
+ _DateUtils.parseXSDate(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ try {
+ _DateUtils.parseISO8601Date(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ }
+
+ private void assertTimeMalformed(String parsed) {
+ try {
+ _DateUtils.parseXSTime(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ try {
+ _DateUtils.parseISO8601Time(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ }
+
+ private void assertDateTimeMalformed(String parsed) {
+ try {
+ _DateUtils.parseXSDateTime(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ try {
+ _DateUtils.parseISO8601DateTime(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ }
+
+ private void assertISO8601DateMalformed(String parsed) {
+ try {
+ _DateUtils.parseISO8601Date(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ }
+
+ private void assertISO8601TimeMalformed(String parsed) {
+ try {
+ _DateUtils.parseISO8601Time(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ }
+
+ private void assertISO8601DateTimeMalformed(String parsed) {
+ try {
+ _DateUtils.parseISO8601DateTime(parsed, _DateUtils.UTC, cf2dc);
+ fail();
+ } catch (DateParseException e) {
+ // Expected
+ echo(e);
+ }
+ }
+
+ private void echo(@SuppressWarnings("unused") DateParseException e) {
+ // System.out.println(e);
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilTest.java
deleted file mode 100644
index d5709da..0000000
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilTest.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-
-import org.junit.Test;
-
-import junit.framework.TestCase;
-
-public class NumberUtilTest extends TestCase {
-
- @Test
- public void testGetSignum() {
- assertEquals(1, _NumberUtil.getSignum(Double.valueOf(Double.POSITIVE_INFINITY)));
- assertEquals(1, _NumberUtil.getSignum(Double.valueOf(3)));
- assertEquals(0, _NumberUtil.getSignum(Double.valueOf(0)));
- assertEquals(-1, _NumberUtil.getSignum(Double.valueOf(-3)));
- assertEquals(-1, _NumberUtil.getSignum(Double.valueOf(Double.NEGATIVE_INFINITY)));
- try {
- _NumberUtil.getSignum(Double.valueOf(Double.NaN));
- fail();
- } catch (ArithmeticException e) {
- // expected
- }
-
- assertEquals(1, _NumberUtil.getSignum(Float.valueOf(Float.POSITIVE_INFINITY)));
- assertEquals(1, _NumberUtil.getSignum(Float.valueOf(3)));
- assertEquals(0, _NumberUtil.getSignum(Float.valueOf(0)));
- assertEquals(-1, _NumberUtil.getSignum(Float.valueOf(-3)));
- assertEquals(-1, _NumberUtil.getSignum(Float.valueOf(Float.NEGATIVE_INFINITY)));
- try {
- _NumberUtil.getSignum(Float.valueOf(Float.NaN));
- fail();
- } catch (ArithmeticException e) {
- // expected
- }
-
- assertEquals(1, _NumberUtil.getSignum(Long.valueOf(3)));
- assertEquals(0, _NumberUtil.getSignum(Long.valueOf(0)));
- assertEquals(-1, _NumberUtil.getSignum(Long.valueOf(-3)));
-
- assertEquals(1, _NumberUtil.getSignum(Integer.valueOf(3)));
- assertEquals(0, _NumberUtil.getSignum(Integer.valueOf(0)));
- assertEquals(-1, _NumberUtil.getSignum(Integer.valueOf(-3)));
-
- assertEquals(1, _NumberUtil.getSignum(Short.valueOf((short) 3)));
- assertEquals(0, _NumberUtil.getSignum(Short.valueOf((short) 0)));
- assertEquals(-1, _NumberUtil.getSignum(Short.valueOf((short) -3)));
-
- assertEquals(1, _NumberUtil.getSignum(Byte.valueOf((byte) 3)));
- assertEquals(0, _NumberUtil.getSignum(Byte.valueOf((byte) 0)));
- assertEquals(-1, _NumberUtil.getSignum(Byte.valueOf((byte) -3)));
-
- assertEquals(1, _NumberUtil.getSignum(BigDecimal.valueOf(3)));
- assertEquals(0, _NumberUtil.getSignum(BigDecimal.valueOf(0)));
- assertEquals(-1, _NumberUtil.getSignum(BigDecimal.valueOf(-3)));
-
- assertEquals(1, _NumberUtil.getSignum(BigInteger.valueOf(3)));
- assertEquals(0, _NumberUtil.getSignum(BigInteger.valueOf(0)));
- assertEquals(-1, _NumberUtil.getSignum(BigInteger.valueOf(-3)));
- }
-
- @Test
- public void testIsBigDecimalInteger() {
- BigDecimal n1 = new BigDecimal("1.125");
- if (n1.precision() != 4 || n1.scale() != 3) {
- throw new RuntimeException("Wrong: " + n1);
- }
- BigDecimal n2 = new BigDecimal("1.125").subtract(new BigDecimal("0.005"));
- if (n2.precision() != 4 || n2.scale() != 3) {
- throw new RuntimeException("Wrong: " + n2);
- }
- BigDecimal n3 = new BigDecimal("123");
- BigDecimal n4 = new BigDecimal("6000");
- BigDecimal n5 = new BigDecimal("1.12345").subtract(new BigDecimal("0.12345"));
- if (n5.precision() != 6 || n5.scale() != 5) {
- throw new RuntimeException("Wrong: " + n5);
- }
- BigDecimal n6 = new BigDecimal("0");
- BigDecimal n7 = new BigDecimal("0.001").subtract(new BigDecimal("0.001"));
- BigDecimal n8 = new BigDecimal("60000.5").subtract(new BigDecimal("0.5"));
- BigDecimal n9 = new BigDecimal("6").movePointRight(3).setScale(-3);
-
- BigDecimal[] ns = new BigDecimal[] {
- n1, n2, n3, n4, n5, n6, n7, n8, n9,
- n1.negate(), n2.negate(), n3.negate(), n4.negate(), n5.negate(), n6.negate(), n7.negate(), n8.negate(),
- n9.negate(),
- };
-
- for (BigDecimal n : ns) {
- assertEquals(n.doubleValue() == n.longValue(), _NumberUtil.isIntegerBigDecimal(n));
- }
-
- }
-
- @Test
- public void testToIntExcact() {
- for (int n : new int[] { Integer.MIN_VALUE, Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE, Integer.MAX_VALUE }) {
- if (n != Integer.MIN_VALUE && n != Integer.MAX_VALUE) {
- assertEquals(n, _NumberUtil.toIntExact(Byte.valueOf((byte) n)));
- assertEquals(n, _NumberUtil.toIntExact(Short.valueOf((short) n)));
- assertEquals(n, _NumberUtil.toIntExact(Float.valueOf(n)));
- }
- assertEquals(n, _NumberUtil.toIntExact(Integer.valueOf(n)));
- assertEquals(n, _NumberUtil.toIntExact(Long.valueOf(n)));
- assertEquals(n, _NumberUtil.toIntExact(Double.valueOf(n)));
- assertEquals(n, _NumberUtil.toIntExact(BigDecimal.valueOf(n)));
- assertEquals(n, _NumberUtil.toIntExact(BigDecimal.valueOf(n * 10L).divide(BigDecimal.TEN)));
- assertEquals(n, _NumberUtil.toIntExact(BigInteger.valueOf(n)));
- }
-
- try {
- _NumberUtil.toIntExact(Long.valueOf(Integer.MIN_VALUE - 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(Long.valueOf(Integer.MAX_VALUE + 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
-
- try {
- _NumberUtil.toIntExact(Float.valueOf(1.00001f));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(Float.valueOf(Integer.MIN_VALUE - 129L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(Float.valueOf(Integer.MAX_VALUE));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
-
- try {
- _NumberUtil.toIntExact(Double.valueOf(1.00001));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(Double.valueOf(Integer.MIN_VALUE - 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(Double.valueOf(Integer.MAX_VALUE + 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
-
- try {
- _NumberUtil.toIntExact(new BigDecimal("100.000001"));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(BigDecimal.valueOf(Integer.MIN_VALUE - 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(BigDecimal.valueOf(Integer.MAX_VALUE + 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
-
- try {
- _NumberUtil.toIntExact(BigInteger.valueOf(Integer.MIN_VALUE - 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- try {
- _NumberUtil.toIntExact(BigInteger.valueOf(Integer.MAX_VALUE + 1L));
- fail();
- } catch (ArithmeticException e) {
- // Expected
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilsTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilsTest.java
new file mode 100644
index 0000000..43d7107
--- /dev/null
+++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/NumberUtilsTest.java
@@ -0,0 +1,215 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.freemarker.core.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import org.junit.Test;
+
+import junit.framework.TestCase;
+
+public class NumberUtilsTest extends TestCase {
+
+ @Test
+ public void testGetSignum() {
+ assertEquals(1, _NumberUtils.getSignum(Double.valueOf(Double.POSITIVE_INFINITY)));
+ assertEquals(1, _NumberUtils.getSignum(Double.valueOf(3)));
+ assertEquals(0, _NumberUtils.getSignum(Double.valueOf(0)));
+ assertEquals(-1, _NumberUtils.getSignum(Double.valueOf(-3)));
+ assertEquals(-1, _NumberUtils.getSignum(Double.valueOf(Double.NEGATIVE_INFINITY)));
+ try {
+ _NumberUtils.getSignum(Double.valueOf(Double.NaN));
+ fail();
+ } catch (ArithmeticException e) {
+ // expected
+ }
+
+ assertEquals(1, _NumberUtils.getSignum(Float.valueOf(Float.POSITIVE_INFINITY)));
+ assertEquals(1, _NumberUtils.getSignum(Float.valueOf(3)));
+ assertEquals(0, _NumberUtils.getSignum(Float.valueOf(0)));
+ assertEquals(-1, _NumberUtils.getSignum(Float.valueOf(-3)));
+ assertEquals(-1, _NumberUtils.getSignum(Float.valueOf(Float.NEGATIVE_INFINITY)));
+ try {
+ _NumberUtils.getSignum(Float.valueOf(Float.NaN));
+ fail();
+ } catch (ArithmeticException e) {
+ // expected
+ }
+
+ assertEquals(1, _NumberUtils.getSignum(Long.valueOf(3)));
+ assertEquals(0, _NumberUtils.getSignum(Long.valueOf(0)));
+ assertEquals(-1, _NumberUtils.getSignum(Long.valueOf(-3)));
+
+ assertEquals(1, _NumberUtils.getSignum(Integer.valueOf(3)));
+ assertEquals(0, _NumberUtils.getSignum(Integer.valueOf(0)));
+ assertEquals(-1, _NumberUtils.getSignum(Integer.valueOf(-3)));
+
+ assertEquals(1, _NumberUtils.getSignum(Short.valueOf((short) 3)));
+ assertEquals(0, _NumberUtils.getSignum(Short.valueOf((short) 0)));
+ assertEquals(-1, _NumberUtils.getSignum(Short.valueOf((short) -3)));
+
+ assertEquals(1, _NumberUtils.getSignum(Byte.valueOf((byte) 3)));
+ assertEquals(0, _NumberUtils.getSignum(Byte.valueOf((byte) 0)));
+ assertEquals(-1, _NumberUtils.getSignum(Byte.valueOf((byte) -3)));
+
+ assertEquals(1, _NumberUtils.getSignum(BigDecimal.valueOf(3)));
+ assertEquals(0, _NumberUtils.getSignum(BigDecimal.valueOf(0)));
+ assertEquals(-1, _NumberUtils.getSignum(BigDecimal.valueOf(-3)));
+
+ assertEquals(1, _NumberUtils.getSignum(BigInteger.valueOf(3)));
+ assertEquals(0, _NumberUtils.getSignum(BigInteger.valueOf(0)));
+ assertEquals(-1, _NumberUtils.getSignum(BigInteger.valueOf(-3)));
+ }
+
+ @Test
+ public void testIsBigDecimalInteger() {
+ BigDecimal n1 = new BigDecimal("1.125");
+ if (n1.precision() != 4 || n1.scale() != 3) {
+ throw new RuntimeException("Wrong: " + n1);
+ }
+ BigDecimal n2 = new BigDecimal("1.125").subtract(new BigDecimal("0.005"));
+ if (n2.precision() != 4 || n2.scale() != 3) {
+ throw new RuntimeException("Wrong: " + n2);
+ }
+ BigDecimal n3 = new BigDecimal("123");
+ BigDecimal n4 = new BigDecimal("6000");
+ BigDecimal n5 = new BigDecimal("1.12345").subtract(new BigDecimal("0.12345"));
+ if (n5.precision() != 6 || n5.scale() != 5) {
+ throw new RuntimeException("Wrong: " + n5);
+ }
+ BigDecimal n6 = new BigDecimal("0");
+ BigDecimal n7 = new BigDecimal("0.001").subtract(new BigDecimal("0.001"));
+ BigDecimal n8 = new BigDecimal("60000.5").subtract(new BigDecimal("0.5"));
+ BigDecimal n9 = new BigDecimal("6").movePointRight(3).setScale(-3);
+
+ BigDecimal[] ns = new BigDecimal[] {
+ n1, n2, n3, n4, n5, n6, n7, n8, n9,
+ n1.negate(), n2.negate(), n3.negate(), n4.negate(), n5.negate(), n6.negate(), n7.negate(), n8.negate(),
+ n9.negate(),
+ };
+
+ for (BigDecimal n : ns) {
+ assertEquals(n.doubleValue() == n.longValue(), _NumberUtils.isIntegerBigDecimal(n));
+ }
+
+ }
+
+ @Test
+ public void testToIntExcact() {
+ for (int n : new int[] { Integer.MIN_VALUE, Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE, Integer.MAX_VALUE }) {
+ if (n != Integer.MIN_VALUE && n != Integer.MAX_VALUE) {
+ assertEquals(n, _NumberUtils.toIntExact(Byte.valueOf((byte) n)));
+ assertEquals(n, _NumberUtils.toIntExact(Short.valueOf((short) n)));
+ assertEquals(n, _NumberUtils.toIntExact(Float.valueOf(n)));
+ }
+ assertEquals(n, _NumberUtils.toIntExact(Integer.valueOf(n)));
+ assertEquals(n, _NumberUtils.toIntExact(Long.valueOf(n)));
+ assertEquals(n, _NumberUtils.toIntExact(Double.valueOf(n)));
+ assertEquals(n, _NumberUtils.toIntExact(BigDecimal.valueOf(n)));
+ assertEquals(n, _NumberUtils.toIntExact(BigDecimal.valueOf(n * 10L).divide(BigDecimal.TEN)));
+ assertEquals(n, _NumberUtils.toIntExact(BigInteger.valueOf(n)));
+ }
+
+ try {
+ _NumberUtils.toIntExact(Long.valueOf(Integer.MIN_VALUE - 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(Long.valueOf(Integer.MAX_VALUE + 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+
+ try {
+ _NumberUtils.toIntExact(Float.valueOf(1.00001f));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(Float.valueOf(Integer.MIN_VALUE - 129L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(Float.valueOf(Integer.MAX_VALUE));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+
+ try {
+ _NumberUtils.toIntExact(Double.valueOf(1.00001));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(Double.valueOf(Integer.MIN_VALUE - 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(Double.valueOf(Integer.MAX_VALUE + 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+
+ try {
+ _NumberUtils.toIntExact(new BigDecimal("100.000001"));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(BigDecimal.valueOf(Integer.MIN_VALUE - 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(BigDecimal.valueOf(Integer.MAX_VALUE + 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+
+ try {
+ _NumberUtils.toIntExact(BigInteger.valueOf(Integer.MIN_VALUE - 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ try {
+ _NumberUtils.toIntExact(BigInteger.valueOf(Integer.MAX_VALUE + 1L));
+ fail();
+ } catch (ArithmeticException e) {
+ // Expected
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/ebb39b84/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilTest.java
----------------------------------------------------------------------
diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilTest.java
deleted file mode 100644
index 1d7043c..0000000
--- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/util/StringUtilTest.java
+++ /dev/null
@@ -1,416 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.freemarker.core.util;
-
-import static junit.framework.TestCase.assertNull;
-import static org.junit.Assert.*;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.regex.Pattern;
-
-import org.hamcrest.Matchers;
-import org.junit.Test;
-
-public class StringUtilTest {
-
- @Test
- public void testV2319() {
- assertEquals("\\n\\r\\f\\b\\t\\x00\\x19", _StringUtil.javaScriptStringEnc("\n\r\f\b\t\u0000\u0019"));
- }
-
- @Test
- public void testControlChars() {
- assertEsc(
- "\n\r\f\b\t \u0000\u0019\u001F \u007F\u0080\u009F \u2028\u2029",
- "\\n\\r\\f\\b\\t \\x00\\x19\\x1F \\x7F\\x80\\x9F \\u2028\\u2029",
- "\\n\\r\\f\\b\\t \\u0000\\u0019\\u001F \\u007F\\u0080\\u009F \\u2028\\u2029");
- }
-
- @Test
- public void testHtmlChars() {
- assertEsc(
- "<safe>/>->]> </foo> <!-- --> <![CDATA[ ]]> <?php?>",
- "<safe>/>->]> <\\/foo> \\x3C!-- --\\> \\x3C![CDATA[ ]]\\> \\x3C?php?>",
- "<safe>/>->]> <\\/foo> \\u003C!-- --\\u003E \\u003C![CDATA[ ]]\\u003E \\u003C?php?>");
- assertEsc("<!c", "\\x3C!c", "\\u003C!c");
- assertEsc("c<!", "c\\x3C!", "c\\u003C!");
- assertEsc("c<", "c\\x3C", "c\\u003C");
- assertEsc("c<c", "c<c", "c<c");
- assertEsc("<c", "<c", "<c");
- assertEsc(">", "\\>", "\\u003E");
- assertEsc("->", "-\\>", "-\\u003E");
- assertEsc("-->", "--\\>", "--\\u003E");
- assertEsc("c-->", "c--\\>", "c--\\u003E");
- assertEsc("-->c", "--\\>c", "--\\u003Ec");
- assertEsc("]>", "]\\>", "]\\u003E");
- assertEsc("]]>", "]]\\>", "]]\\u003E");
- assertEsc("c]]>", "c]]\\>", "c]]\\u003E");
- assertEsc("]]>c", "]]\\>c", "]]\\u003Ec");
- assertEsc("c->", "c->", "c->");
- assertEsc("c>", "c>", "c>");
- assertEsc("-->", "--\\>", "--\\u003E");
- assertEsc("/", "\\/", "\\/");
- assertEsc("/c", "\\/c", "\\/c");
- assertEsc("</", "<\\/", "<\\/");
- assertEsc("</c", "<\\/c", "<\\/c");
- assertEsc("c/", "c/", "c/");
- }
-
- @Test
- public void testJSChars() {
- assertEsc("\"", "\\\"", "\\\"");
- assertEsc("'", "\\'", "'");
- assertEsc("\\", "\\\\", "\\\\");
- }
-
- @Test
- public void testSameStringsReturned() {
- String s = "==> I/m <safe>!";
- assertTrue(s == _StringUtil.jsStringEnc(s, false)); // "==" because is must return the same object
- assertTrue(s == _StringUtil.jsStringEnc(s, true));
-
- s = "";
- assertTrue(s == _StringUtil.jsStringEnc(s, false));
- assertTrue(s == _StringUtil.jsStringEnc(s, true));
-
- s = "\u00E1rv\u00EDzt\u0171r\u0151 \u3020";
- assertEquals(s, _StringUtil.jsStringEnc(s, false));
- assertTrue(s == _StringUtil.jsStringEnc(s, false));
- assertTrue(s == _StringUtil.jsStringEnc(s, true));
- }
-
- @Test
- public void testOneOffs() {
- assertEsc("c\"c\"cc\"\"c", "c\\\"c\\\"cc\\\"\\\"c", "c\\\"c\\\"cc\\\"\\\"c");
- assertEsc("\"c\"cc\"", "\\\"c\\\"cc\\\"", "\\\"c\\\"cc\\\"");
- assertEsc("c/c/cc//c", "c/c/cc//c", "c/c/cc//c");
- assertEsc("c<c<cc<<c", "c<c<cc<<c", "c<c<cc<<c");
- assertEsc("/<", "\\/\\x3C", "\\/\\u003C");
- assertEsc(">", "\\>", "\\u003E");
- assertEsc("]>", "]\\>", "]\\u003E");
- assertEsc("->", "-\\>", "-\\u003E");
- }
-
- private void assertEsc(String s, String javaScript, String json) {
- assertEquals(javaScript, _StringUtil.jsStringEnc(s, false));
- assertEquals(json, _StringUtil.jsStringEnc(s, true));
- }
-
- @Test
- public void testTrim() {
- assertSame(_CollectionUtil.EMPTY_CHAR_ARRAY, _StringUtil.trim(_CollectionUtil.EMPTY_CHAR_ARRAY));
- assertSame(_CollectionUtil.EMPTY_CHAR_ARRAY, _StringUtil.trim(" \t\u0001 ".toCharArray()));
- {
- char[] cs = "foo".toCharArray();
- assertSame(cs, cs);
- }
- assertArrayEquals("foo".toCharArray(), _StringUtil.trim("foo ".toCharArray()));
- assertArrayEquals("foo".toCharArray(), _StringUtil.trim(" foo".toCharArray()));
- assertArrayEquals("foo".toCharArray(), _StringUtil.trim(" foo ".toCharArray()));
- assertArrayEquals("foo".toCharArray(), _StringUtil.trim("\t\tfoo \r\n".toCharArray()));
- assertArrayEquals("x".toCharArray(), _StringUtil.trim(" x ".toCharArray()));
- assertArrayEquals("x y z".toCharArray(), _StringUtil.trim(" x y z ".toCharArray()));
- }
-
- @Test
- public void testIsTrimmedToEmpty() {
- assertTrue(_StringUtil.isTrimmableToEmpty("".toCharArray()));
- assertTrue(_StringUtil.isTrimmableToEmpty("\r\r\n\u0001".toCharArray()));
- assertFalse(_StringUtil.isTrimmableToEmpty("x".toCharArray()));
- assertFalse(_StringUtil.isTrimmableToEmpty(" x ".toCharArray()));
- }
-
- @Test
- public void testJQuote() {
- assertEquals("null", _StringUtil.jQuote(null));
- assertEquals("\"foo\"", _StringUtil.jQuote("foo"));
- assertEquals("\"123\"", _StringUtil.jQuote(Integer.valueOf(123)));
- assertEquals("\"foo's \\\"bar\\\"\"",
- _StringUtil.jQuote("foo's \"bar\""));
- assertEquals("\"\\n\\r\\t\\u0001\"",
- _StringUtil.jQuote("\n\r\t\u0001"));
- assertEquals("\"<\\nb\\rc\\td\\u0001>\"",
- _StringUtil.jQuote("<\nb\rc\td\u0001>"));
- }
-
- @Test
- public void testJQuoteNoXSS() {
- assertEquals("null", _StringUtil.jQuoteNoXSS(null));
- assertEquals("\"foo\"", _StringUtil.jQuoteNoXSS("foo"));
- assertEquals("\"123\"", _StringUtil.jQuoteNoXSS(Integer.valueOf(123)));
- assertEquals("\"foo's \\\"bar\\\"\"",
- _StringUtil.jQuoteNoXSS("foo's \"bar\""));
- assertEquals("\"\\n\\r\\t\\u0001\"",
- _StringUtil.jQuoteNoXSS("\n\r\t\u0001"));
- assertEquals("\"\\u003C\\nb\\rc\\td\\u0001>\"",
- _StringUtil.jQuoteNoXSS("<\nb\rc\td\u0001>"));
- assertEquals("\"\\u003C\\nb\\rc\\td\\u0001>\"",
- _StringUtil.jQuoteNoXSS((Object) "<\nb\rc\td\u0001>"));
- }
-
- @Test
- public void testGlobToRegularExpression() {
- assertGlobMatches("a/b/c.ftl", "a/b/c.ftl");
- assertGlobDoesNotMatch("/a/b/cxftl", "/a/b/c.ftl", "a/b/C.ftl");
-
- assertGlobMatches("a/b/*.ftl", "a/b/.ftl", "a/b/x.ftl", "a/b/xx.ftl");
- assertGlobDoesNotMatch("a/b/*.ftl", "a/c/x.ftl", "a/b/c/x.ftl", "/a/b/x.ftl", "a/b/xxftl");
-
- assertGlobMatches("a/b/?.ftl", "a/b/x.ftl");
- assertGlobDoesNotMatch("a/b/?.ftl", "a/c/x.ftl", "a/b/.ftl", "a/b/xx.ftl", "a/b/xxftl");
-
- assertGlobMatches("a/**/c.ftl", "a/b/c.ftl", "a/c.ftl", "a/b/b2/b3/c.ftl", "a//c.ftl");
- assertGlobDoesNotMatch("a/**/c.ftl", "x/b/c.ftl", "a/b/x.ftl");
-
- assertGlobMatches("**/c.ftl", "a/b/c.ftl", "c.ftl", "/c.ftl", "///c.ftl");
- assertGlobDoesNotMatch("**/c.ftl", "a/b/x.ftl");
-
- assertGlobMatches("a/b/**", "a/b/c.ftl", "a/b/c2/c.ftl", "a/b/", "a/b/c/");
- assertGlobDoesNotMatch("a/b.ftl");
-
- assertGlobMatches("**", "a/b/c.ftl", "");
-
- assertGlobMatches("\\[\\{\\*\\?\\}\\]\\\\", "[{*?}]\\");
- assertGlobDoesNotMatch("\\[\\{\\*\\?\\}\\]\\\\", "[{xx}]\\");
-
- assertGlobMatches("a/b/\\?.ftl", "a/b/?.ftl");
- assertGlobDoesNotMatch("a/b/\\?.ftl", "a/b/x.ftl");
-
- assertGlobMatches("\\?\\?.ftl", "??.ftl");
- assertGlobMatches("\\\\\\\\", "\\\\");
- assertGlobMatches("\\\\\\\\?", "\\\\x");
- assertGlobMatches("x\\", "x");
-
- assertGlobMatches("???*", "123", "1234", "12345");
- assertGlobDoesNotMatch("???*", "12", "1", "");
-
- assertGlobMatches("**/a??/b*.ftl", "a11/b1.ftl", "x/a11/b123.ftl", "x/y/a11/b.ftl");
- assertGlobDoesNotMatch("**/a??/b*.ftl", "a1/b1.ftl", "x/a11/c123.ftl");
-
- assertFalse(_StringUtil.globToRegularExpression("ab*").matcher("aBc").matches());
- assertTrue(_StringUtil.globToRegularExpression("ab*", true).matcher("aBc").matches());
- assertTrue(_StringUtil.globToRegularExpression("ab", true).matcher("aB").matches());
- assertTrue(_StringUtil.globToRegularExpression("\u00E1b*", true).matcher("\u00C1bc").matches());
-
- try {
- _StringUtil.globToRegularExpression("x**/y");
- fail();
- } catch (IllegalArgumentException e) {
- assertThat(e.getMessage(), Matchers.containsString("**"));
- }
-
- try {
- _StringUtil.globToRegularExpression("**y");
- fail();
- } catch (IllegalArgumentException e) {
- assertThat(e.getMessage(), Matchers.containsString("**"));
- }
-
- try {
- _StringUtil.globToRegularExpression("[ab]c");
- fail();
- } catch (IllegalArgumentException e) {
- assertThat(e.getMessage(), Matchers.containsString("unsupported"));
- }
-
- try {
- _StringUtil.globToRegularExpression("{aa,bb}c");
- fail();
- } catch (IllegalArgumentException e) {
- assertThat(e.getMessage(), Matchers.containsString("unsupported"));
- }
- }
-
- private void assertGlobMatches(String glob, String... ss) {
- Pattern pattern = _StringUtil.globToRegularExpression(glob);
- for (String s : ss) {
- if (!pattern.matcher(s).matches()) {
- fail("Glob " + glob + " (regexp: " + pattern + ") doesn't match " + s);
- }
- }
- }
-
- private void assertGlobDoesNotMatch(String glob, String... ss) {
- Pattern pattern = _StringUtil.globToRegularExpression(glob);
- for (String s : ss) {
- if (pattern.matcher(s).matches()) {
- fail("Glob " + glob + " (regexp: " + pattern + ") matches " + s);
- }
- }
- }
-
- @Test
- public void testHTMLEnc() {
- String s = "";
- assertSame(s, _StringUtil.XMLEncNA(s));
-
- s = "asd";
- assertSame(s, _StringUtil.XMLEncNA(s));
-
- assertEquals("a&b<c>d"e'f", _StringUtil.XMLEncNA("a&b<c>d\"e'f"));
- assertEquals("<", _StringUtil.XMLEncNA("<"));
- assertEquals("<a", _StringUtil.XMLEncNA("<a"));
- assertEquals("<a>", _StringUtil.XMLEncNA("<a>"));
- assertEquals("a>", _StringUtil.XMLEncNA("a>"));
- assertEquals("<>", _StringUtil.XMLEncNA("<>"));
- assertEquals("a<>b", _StringUtil.XMLEncNA("a<>b"));
- }
-
- @Test
- public void testXHTMLEnc() throws IOException {
- String s = "";
- assertSame(s, _StringUtil.XHTMLEnc(s));
-
- s = "asd";
- assertSame(s, _StringUtil.XHTMLEnc(s));
-
- testXHTMLEnc("a&b<c>d"e'f", "a&b<c>d\"e'f");
- testXHTMLEnc("<", "<");
- testXHTMLEnc("<a", "<a");
- testXHTMLEnc("<a>", "<a>");
- testXHTMLEnc("a>", "a>");
- testXHTMLEnc("<>", "<>");
- testXHTMLEnc("a<>b", "a<>b");
- }
-
- private void testXHTMLEnc(String expected, String in) throws IOException {
- assertEquals(expected, _StringUtil.XHTMLEnc(in));
-
- StringWriter sw = new StringWriter();
- _StringUtil.XHTMLEnc(in, sw);
- assertEquals(expected, sw.toString());
- }
-
- @Test
- public void testXMLEnc() throws IOException {
- String s = "";
- assertSame(s, _StringUtil.XMLEnc(s));
-
- s = "asd";
- assertSame(s, _StringUtil.XMLEnc(s));
-
- testXMLEnc("a&b<c>d"e'f", "a&b<c>d\"e'f");
- testXMLEnc("<", "<");
- testXMLEnc("<a", "<a");
- testXMLEnc("<a>", "<a>");
- testXMLEnc("a>", "a>");
- testXMLEnc("<>", "<>");
- testXMLEnc("a<>b", "a<>b");
- }
-
- private void testXMLEnc(String expected, String in) throws IOException {
- assertEquals(expected, _StringUtil.XMLEnc(in));
-
- StringWriter sw = new StringWriter();
- _StringUtil.XMLEnc(in, sw);
- assertEquals(expected, sw.toString());
- }
-
- @Test
- public void testXMLEncQAttr() throws IOException {
- String s = "";
- assertSame(s, _StringUtil.XMLEncQAttr(s));
-
- s = "asd";
- assertSame(s, _StringUtil.XMLEncQAttr(s));
-
- assertEquals("a&b<c>d"e'f", _StringUtil.XMLEncQAttr("a&b<c>d\"e'f"));
- assertEquals("<", _StringUtil.XMLEncQAttr("<"));
- assertEquals("<a", _StringUtil.XMLEncQAttr("<a"));
- assertEquals("<a>", _StringUtil.XMLEncQAttr("<a>"));
- assertEquals("a>", _StringUtil.XMLEncQAttr("a>"));
- assertEquals("<>", _StringUtil.XMLEncQAttr("<>"));
- assertEquals("a<>b", _StringUtil.XMLEncQAttr("a<>b"));
- }
-
- @Test
- public void testXMLEncNQG() throws IOException {
- String s = "";
- assertSame(s, _StringUtil.XMLEncNQG(s));
-
- s = "asd";
- assertSame(s, _StringUtil.XMLEncNQG(s));
-
- assertEquals("a&b<c>d\"e'f", _StringUtil.XMLEncNQG("a&b<c>d\"e'f"));
- assertEquals("<", _StringUtil.XMLEncNQG("<"));
- assertEquals("<a", _StringUtil.XMLEncNQG("<a"));
- assertEquals("<a>", _StringUtil.XMLEncNQG("<a>"));
- assertEquals("a>", _StringUtil.XMLEncNQG("a>"));
- assertEquals("<>", _StringUtil.XMLEncNQG("<>"));
- assertEquals("a<>b", _StringUtil.XMLEncNQG("a<>b"));
-
- assertEquals(">", _StringUtil.XMLEncNQG(">"));
- assertEquals("]>", _StringUtil.XMLEncNQG("]>"));
- assertEquals("]]>", _StringUtil.XMLEncNQG("]]>"));
- assertEquals("x]]>", _StringUtil.XMLEncNQG("x]]>"));
- assertEquals("x]>", _StringUtil.XMLEncNQG("x]>"));
- assertEquals("]x>", _StringUtil.XMLEncNQG("]x>"));
- }
-
- @Test
- public void testRTFEnc() throws IOException {
- String s = "";
- assertSame(s, _StringUtil.RTFEnc(s));
-
- s = "asd";
- assertSame(s, _StringUtil.RTFEnc(s));
-
- testRTFEnc("a\\{b\\}c\\\\d", "a{b}c\\d");
- testRTFEnc("\\{", "{");
- testRTFEnc("\\{a", "{a");
- testRTFEnc("\\{a\\}", "{a}");
- testRTFEnc("a\\}", "a}");
- testRTFEnc("\\{\\}", "{}");
- testRTFEnc("a\\{\\}b", "a{}b");
- }
-
- private void testRTFEnc(String expected, String in) throws IOException {
- assertEquals(expected, _StringUtil.RTFEnc(in));
-
- StringWriter sw = new StringWriter();
- _StringUtil.RTFEnc(in, sw);
- assertEquals(expected, sw.toString());
- }
-
- @Test
- public void testNormalizeEOLs() {
- assertNull(_StringUtil.normalizeEOLs(null));
- assertEquals("", _StringUtil.normalizeEOLs(""));
- assertEquals("x", _StringUtil.normalizeEOLs("x"));
- assertEquals("x\ny", _StringUtil.normalizeEOLs("x\ny"));
- assertEquals("x\ny", _StringUtil.normalizeEOLs("x\r\ny"));
- assertEquals("x\ny", _StringUtil.normalizeEOLs("x\ry"));
- assertEquals("\n\n\n\n\n\n", _StringUtil.normalizeEOLs("\n\r\r\r\n\r\n\r"));
- }
-
- @Test
- public void snakeCaseToCamelCase() {
- assertNull(_StringUtil.snakeCaseToCamelCase(null));
- assertEquals("", _StringUtil.snakeCaseToCamelCase(""));
- assertEquals("x", _StringUtil.snakeCaseToCamelCase("x"));
- assertEquals("xxx", _StringUtil.snakeCaseToCamelCase("xXx"));
- assertEquals("fooBar", _StringUtil.snakeCaseToCamelCase("foo_bar"));
- assertEquals("fooBar", _StringUtil.snakeCaseToCamelCase("FOO_BAR"));
- assertEquals("fooBar", _StringUtil.snakeCaseToCamelCase("_foo__bar_"));
- assertEquals("aBC", _StringUtil.snakeCaseToCamelCase("a_b_c"));
- }
-
-}