diff --git a/base-third-project/base-third-step1/pom.xml b/base-third-project/base-third-step1/pom.xml index b99e3206c..5d64b801f 100644 --- a/base-third-project/base-third-step1/pom.xml +++ b/base-third-project/base-third-step1/pom.xml @@ -30,7 +30,6 @@ ../../fine-jboss-transaction-api ../../fine-jgit ../../fine-jna - ../../fine-jodd ../../fine-lookandfeel ../../fine-lz4 ../../fine-org-dom4j diff --git a/base-third-project/base-third-step2/pom.xml b/base-third-project/base-third-step2/pom.xml index bca8d2410..172fc060b 100644 --- a/base-third-project/base-third-step2/pom.xml +++ b/base-third-project/base-third-step2/pom.xml @@ -20,7 +20,6 @@ ../../fine-jai ../../fine-kryo ../../fine-poi-old - ../../fine-redisson ../../fine-xmlgraphics diff --git a/base-third-project/base-third-step6/pom.xml b/base-third-project/base-third-step6/pom.xml index 9f1a67cc3..de85857cc 100644 --- a/base-third-project/base-third-step6/pom.xml +++ b/base-third-project/base-third-step6/pom.xml @@ -16,7 +16,6 @@ ../../fine-druid - ../../fine-socketio ${classes-path}/base-third-step6/classes diff --git a/build.third_step1-jdk11.gradle b/build.third_step1-jdk11.gradle index dc5cd856c..add68e604 100644 --- a/build.third_step1-jdk11.gradle +++ b/build.third_step1-jdk11.gradle @@ -45,7 +45,6 @@ sourceSets{ "${srcDir}/fine-jgit/src/main/java", "${srcDir}/fine-jna/jna/src/main/java", "${srcDir}/fine-jna/jna-platform/src/main/java", - "${srcDir}/fine-jodd/src/main/java", //"${srcDir}/fine-lookandfeel/src/main/java", "${srcDir}/fine-lz4/src/main/java", "${srcDir}/fine-org-dom4j/src/main/java", @@ -92,8 +91,6 @@ def resourceDirs = [ "${srcDir}/fine-jna/jna/src/main/resources", "${srcDir}/fine-jna/jna/src/main/java", "${srcDir}/fine-jna/jna-platform/src/main/java", - "${srcDir}/fine-jodd/src/main/java", - "${srcDir}/fine-jodd/src/main/resources", // "${srcDir}/fine-lookandfeel/src/main/java", "${srcDir}/fine-lz4/src/main/java", "${srcDir}/fine-lz4/src/main/resources", diff --git a/build.third_step1.gradle b/build.third_step1.gradle index a710a46dc..741e4eb6f 100644 --- a/build.third_step1.gradle +++ b/build.third_step1.gradle @@ -46,7 +46,6 @@ sourceSets{ "${srcDir}/fine-jgit/src/main/java", "${srcDir}/fine-jna/jna/src/main/java", "${srcDir}/fine-jna/jna-platform/src/main/java", - "${srcDir}/fine-jodd/src/main/java", //"${srcDir}/fine-lookandfeel/src/main/java", "${srcDir}/fine-lz4/src/main/java", "${srcDir}/fine-org-dom4j/src/main/java", @@ -140,8 +139,6 @@ task copyFiles(type:Copy,dependsOn:'compileJava'){ with dataContent.call("${srcDir}/fine-jna/jna/src/main/java") with dataContent.call("${srcDir}/fine-jna/jna-platform/src/main/java") with dataContent.call("${srcDir}/fine-jna/jna-platform/src/main/resources") - with dataContent.call("${srcDir}/fine-jodd/src/main/java") - with dataContent.call("${srcDir}/fine-jodd/src/main/resources") // with dataContent.call("${srcDir}/fine-lookandfeel/src/main/java") with dataContent.call("${srcDir}/fine-lz4/src/main/java") with dataContent.call("${srcDir}/fine-lz4/src/main/resources") diff --git a/build.third_step2-jdk11.gradle b/build.third_step2-jdk11.gradle index a86a6f1eb..52a6e4465 100644 --- a/build.third_step2-jdk11.gradle +++ b/build.third_step2-jdk11.gradle @@ -35,7 +35,6 @@ sourceSets{ "${srcDir}/fine-jai/src/main/java", "${srcDir}/fine-kryo/src/main/java", "${srcDir}/fine-poi-old/src/main/java", - "${srcDir}/fine-redisson/src/main/java", "${srcDir}/fine-xmlgraphics/xmlgraphics-batik/src/main/java", "${srcDir}/fine-xmlgraphics/xmlgraphics-commons/src/main/java" ] @@ -52,8 +51,6 @@ def resourceDirs = [ "${srcDir}/fine-kryo/src/main/resources", "${srcDir}/fine-poi-old/src/main/java", "${srcDir}/fine-poi-old/src/main/resources", - "${srcDir}/fine-redisson/src/main/java", - "${srcDir}/fine-redisson/src/main/resources", "${srcDir}/fine-xmlgraphics/xmlgraphics-batik/src/main/java", "${srcDir}/fine-xmlgraphics/xmlgraphics-batik/src/main/resources", "${srcDir}/fine-xmlgraphics/xmlgraphics-commons/src/main/java", @@ -91,7 +88,6 @@ String essentialVersion = findProperty("essentialVersion") dependencies{ compileOnly "com.fr.essential:fine-essential:${essentialVersion}" compile fileTree(dir:"${srcDir}/fine-poi-old/lib",include: '**/*.jar') - compile fileTree(dir:"${srcDir}/fine-redisson/lib",include: '**/*.jar') compile fileTree(dir:"${srcDir}/fine-xmlgraphics/xmlgraphics-batik/lib",include: '**/*.jar') compile fileTree(dir:"${srcDir}/fine-xmlgraphics/xmlgraphics-commons/lib",include: '**/*.jar') compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar') diff --git a/build.third_step2.gradle b/build.third_step2.gradle index f7808aed2..4c12912dd 100644 --- a/build.third_step2.gradle +++ b/build.third_step2.gradle @@ -28,7 +28,6 @@ sourceSets{ "${srcDir}/fine-jai/src/main/java", "${srcDir}/fine-kryo/src/main/java", "${srcDir}/fine-poi-old/src/main/java", - "${srcDir}/fine-redisson/src/main/java", "${srcDir}/fine-xmlgraphics/xmlgraphics-batik/src/main/java", "${srcDir}/fine-xmlgraphics/xmlgraphics-commons/src/main/java" ] @@ -64,7 +63,6 @@ String essentialVersion = findProperty("essentialVersion") dependencies{ compileOnly "com.fr.essential:fine-essential:${essentialVersion}" compile fileTree(dir:"${srcDir}/fine-poi-old/lib",include: '**/*.jar') - compile fileTree(dir:"${srcDir}/fine-redisson/lib",include: '**/*.jar') compile fileTree(dir:"${srcDir}/fine-xmlgraphics/xmlgraphics-batik/lib",include: '**/*.jar') compile fileTree(dir:"${srcDir}/fine-xmlgraphics/xmlgraphics-commons/lib",include: '**/*.jar') compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar') @@ -96,8 +94,6 @@ task copyFiles(type:Copy,dependsOn:'compileJava'){ with dataContent.call("${srcDir}/fine-kryo/src/main/resources") with dataContent.call("${srcDir}/fine-poi-old/src/main/java") with dataContent.call("${srcDir}/fine-poi-old/src/main/resources") - with dataContent.call("${srcDir}/fine-redisson/src/main/java") - with dataContent.call("${srcDir}/fine-redisson/src/main/resources") with dataContent.call("${srcDir}/fine-xmlgraphics/xmlgraphics-batik/src/main/java") with dataContent.call("${srcDir}/fine-xmlgraphics/xmlgraphics-batik/src/main/resources") with dataContent.call("${srcDir}/fine-xmlgraphics/xmlgraphics-commons/src/main/java") diff --git a/build.third_step6-jdk11.gradle b/build.third_step6-jdk11.gradle index 2153ca4f2..66ec5dd54 100644 --- a/build.third_step6-jdk11.gradle +++ b/build.third_step6-jdk11.gradle @@ -24,8 +24,7 @@ sourceSets{ main{ java{ srcDirs=[ - "${srcDir}/fine-druid/src/main/java", - "${srcDir}/fine-socketio/src/main/java" + "${srcDir}/fine-druid/src/main/java" ] } } @@ -35,8 +34,6 @@ sourceSets{ def resourceDirs = [ "${srcDir}/fine-druid/src/main/java", "${srcDir}/fine-druid/src/main/resources", - "${srcDir}/fine-socketio/src/main/java", - "${srcDir}/fine-socketio/src/main/resources" ] sourceSets.main.java.outputDir = file('build/classes/6') @@ -71,7 +68,6 @@ dependencies{ compileOnly "com.fr.essential:fine-essential:${essentialVersion}" compile fileTree(dir:"${srcDir}/fine-druid/lib",include:'ojdbc7-12.1.0.jar') compile fileTree(dir:"${srcDir}/fine-druid/lib",include:'**/*.jar') - compile fileTree(dir:"${srcDir}/fine-socketio/lib",include:'**/*.jar') compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar') compile fileTree(dir:System.getenv("JAVA_HOME"),include:"lib/tools.jar") compile group: "com.fr.third.server", name: "servlet-api", version: "3.0" diff --git a/build.third_step6.gradle b/build.third_step6.gradle index e7bb4bc44..597629556 100644 --- a/build.third_step6.gradle +++ b/build.third_step6.gradle @@ -24,8 +24,7 @@ sourceSets{ main{ java{ srcDirs=[ - "${srcDir}/fine-druid/src/main/java", - "${srcDir}/fine-socketio/src/main/java" + "${srcDir}/fine-druid/src/main/java" ] } } @@ -60,7 +59,6 @@ dependencies{ compileOnly "com.fr.essential:fine-essential:${essentialVersion}" compile fileTree(dir:"${srcDir}/fine-druid/lib",include:'ojdbc7-12.1.0.jar') compile fileTree(dir:"${srcDir}/fine-druid/lib",include:'**/*.jar') - compile fileTree(dir:"${srcDir}/fine-socketio/lib",include:'**/*.jar') compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar') compile fileTree(dir:System.getenv("JAVA_HOME"),include:"lib/tools.jar") compile group: "javax.servlet", name: "javax.servlet-api", version: "3.0.1" @@ -84,8 +82,6 @@ task copyFiles(type:Copy,dependsOn:'compileJava'){ println "------------------------------------------------copyfiles" with dataContent.call("${srcDir}/fine-druid/src/main/java") with dataContent.call("${srcDir}/fine-druid/src/main/resources") - with dataContent.call("${srcDir}/fine-socketio/src/main/java") - with dataContent.call("${srcDir}/fine-socketio/src/main/resources") into "${classesDir}" } } diff --git a/fine-jodd/.gitignore b/fine-jodd/.gitignore deleted file mode 100644 index 5d453cd8b..000000000 --- a/fine-jodd/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -*.iml -.idea/ -.DS_Store -.project -.classpath -*.gradle \ No newline at end of file diff --git a/fine-jodd/pom.xml b/fine-jodd/pom.xml deleted file mode 100644 index a51efbb47..000000000 --- a/fine-jodd/pom.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - 4.0.0 - - - com.fr.third - step1 - ${revision} - ../base-third-project/base-third-step1 - - - fine-jodd - ${revision} - - - \ No newline at end of file diff --git a/fine-jodd/readme.md b/fine-jodd/readme.md deleted file mode 100644 index e9ebff3c5..000000000 --- a/fine-jodd/readme.md +++ /dev/null @@ -1,5 +0,0 @@ -## jodd - -版本:3.7.1 - -github地址:https://github.com/oblac/jodd/tree/v3.7.1 diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/Jodd.java b/fine-jodd/src/main/java/com/fr/third/jodd/Jodd.java deleted file mode 100644 index 5cdb45be8..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/Jodd.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd; - -/** - * Jodd! - */ -public class Jodd { - - /** - * Ascii art of Jodds name. Every serious framework needs one:) - */ - public static String JODD = "\n" + - " __ __ __\n" + - " / /___ ____/ /___/ /\n" + - " __ / / __ \\/ __ / __ / \n" + - " / /_/ / /_/ / /_/ / /_/ / \n" + - " \\____/\\____/\\__,_/\\__,_/ \n"; - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanCopy.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanCopy.java deleted file mode 100644 index 6aa1f1cfc..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanCopy.java +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import java.util.Map; - -import static com.fr.third.jodd.util.StringPool.LEFT_SQ_BRACKET; -import static com.fr.third.jodd.util.StringPool.RIGHT_SQ_BRACKET; - -/** - * Powerful tool for copying properties from one bean into another. - * BeanCopy works with POJO beans, but also with Map. - * - * @see BeanVisitor - */ -public class BeanCopy extends BeanVisitorImplBase { - - protected Object destination; - protected boolean forced; - protected boolean declaredTarget; - protected boolean isTargetMap; - - // ---------------------------------------------------------------- ctor - - /** - * Creates new BeanCopy process between the source and the destination. - * Both source and destination can be a POJO object or a Map. - */ - public BeanCopy(final Object source, final Object destination) { - this.source = source; - this.destination = destination; - } - - private BeanCopy(final Object source) { - this.source = source; - } - - /** - * Simple static factory for BeanCopy. - * @see #BeanCopy(Object, Object) - */ - public static BeanCopy beans(final Object source, final Object destination) { - return new BeanCopy(source, destination); - } - - /** - * Creates BeanCopy with given POJO bean as a source. - */ - public static BeanCopy fromBean(final Object source) { - return new BeanCopy(source); - } - - /** - * Creates BeanCopy with given Map as a source. - */ - public static BeanCopy fromMap(final Map source) { - BeanCopy beanCopy = new BeanCopy(source); - - beanCopy.isSourceMap = true; - - return beanCopy; - } - - /** - * Defines source, detects a map. - */ - public static BeanCopy from(final Object source) { - BeanCopy beanCopy = new BeanCopy(source); - - beanCopy.isSourceMap = source instanceof Map; - - return beanCopy; - } - - // ---------------------------------------------------------------- destination - - /** - * Defines destination bean. - */ - public BeanCopy toBean(final Object destination) { - this.destination = destination; - return this; - } - - /** - * Defines destination map. - */ - public BeanCopy toMap(final Map destination) { - this.destination = destination; - - isTargetMap = true; - - return this; - } - - /** - * Defines destination, detects a map. - */ - public BeanCopy to(final Object destination) { - this.destination = destination; - - this.isTargetMap = destination instanceof Map; - - return this; - } - - // ---------------------------------------------------------------- properties - - /** - * Defines if all properties should be copied (when set to true) - * or only public (when set to false, default). - */ - @Override - public BeanCopy declared(final boolean declared) { - this.declared = declared; - this.declaredTarget = declared; - return this; - } - - /** - * Fine-tuning of the declared behaviour. - */ - public BeanCopy declared(final boolean declaredSource, final boolean declaredTarget) { - this.declared = declaredSource; - this.declaredTarget = declaredTarget; - return this; - } - - public BeanCopy forced(final boolean forced) { - this.forced = forced; - return this; - } - - // ---------------------------------------------------------------- visitor - - protected BeanUtil beanUtil; - - /** - * Performs the copying. - */ - public void copy() { - beanUtil = new BeanUtilBean() - .declared(declared) - .forced(forced) - .silent(true); - visit(); - } - - /** - * Copies single property to the destination. - * Exceptions are ignored, so copying continues if - * destination does not have some of the sources properties. - */ - @Override - protected boolean visitProperty(String name, final Object value) { - if (isTargetMap) { - name = LEFT_SQ_BRACKET + name + RIGHT_SQ_BRACKET; - } - - beanUtil.setProperty(destination, name, value); - - return true; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanException.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanException.java deleted file mode 100644 index b556ad43c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanException.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import com.fr.third.jodd.exception.UncheckedException; - -/** - * Unchecked bean exception. - */ -public class BeanException extends UncheckedException { - - public BeanException(final Throwable t) { - super(t); - } - - public BeanException(final String message) { - super(message); - } - - public BeanException(final String message, final BeanProperty bp) { - super(message + ". Invalid property: " + bp); - } - - public BeanException(final String message, final Throwable t) { - super(message, t); - } - - public BeanException(final String message, final BeanProperty bp, final Throwable t) { - super(message + ". Invalid property: " + bp, t); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanProperty.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanProperty.java deleted file mode 100644 index 0042d3262..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanProperty.java +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import com.fr.third.jodd.introspector.ClassDescriptor; -import com.fr.third.jodd.introspector.ClassIntrospector; -import com.fr.third.jodd.introspector.Getter; -import com.fr.third.jodd.introspector.PropertyDescriptor; -import com.fr.third.jodd.introspector.Setter; - -import java.util.function.Supplier; - -/** - * Represents a bean named property. Contains two information: - *
    - *
  1. Bean instance (and cached class descriptor)
  2. - *
  3. Property name
  4. - *
- * Used only internally by {@link BeanUtil} and similar utils. - */ -class BeanProperty { - - BeanProperty(final BeanUtilBean beanUtilBean, final Object bean, final String propertyName) { - this.introspector = beanUtilBean.introspector; - setName(propertyName); - updateBean(bean); - this.last = true; - this.first = true; - this.fullName = bean.getClass().getSimpleName() + '#' + propertyName; - } - - // ---------------------------------------------------------------- bean and descriptor - - final String fullName; // initial name - final ClassIntrospector introspector; - Object bean; - private ClassDescriptor cd; - String name; // property name - boolean last; // is it a last property (when nested) - boolean first; // is it first property (when nested) - String indexString; // indexString for index property - - /** - * Sets current property name. - */ - public void setName(final String name) { - this.name = name; - this.updateProperty = true; - } - - /** - * Sets new bean instance. - */ - private void setBean(final Object bean) { - this.bean = bean; - this.cd = (bean == null ? null : introspector.lookup(bean.getClass())); - this.first = false; - this.updateProperty = true; - } - - /** - * Updates the bean. Detects special case of suppliers. - */ - public void updateBean(final Object bean) { - this.setBean(bean); - - if (this.cd != null && this.cd.isSupplier()) { - final Object newBean = ((Supplier)this.bean).get(); - setBean(newBean); - } - } - - // ---------------------------------------------------------------- simple properties - - // indicates that property descriptor has to be updated - // since there was some property-related change of BeanProperty state - private boolean updateProperty = true; - - // most recent property descriptor - private PropertyDescriptor propertyDescriptor; - - /** - * Loads property descriptor, if property was updated. - */ - private void loadPropertyDescriptor() { - if (updateProperty) { - if (cd == null) { - propertyDescriptor = null; - } else { - propertyDescriptor = cd.getPropertyDescriptor(name, true); - } - updateProperty = false; - } - } - - /** - * Returns getter. - */ - public Getter getGetter(final boolean declared) { - loadPropertyDescriptor(); - return propertyDescriptor != null ? propertyDescriptor.getGetter(declared) : null; - } - - /** - * Returns setter. - */ - public Setter getSetter(final boolean declared) { - loadPropertyDescriptor(); - return propertyDescriptor != null ? propertyDescriptor.getSetter(declared) : null; - } - - /** - * Returns true if class is a map. - */ - public boolean isMap() { - return cd != null && cd.isMap(); - } - - String index; - - // ---------------------------------------------------------------- toString - - @Override - public String toString() { - return fullName + " (" + (bean != null ? bean.getClass().getSimpleName() : "?") + '#' + name + ')'; - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanTemplateParser.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanTemplateParser.java deleted file mode 100644 index c8e576562..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanTemplateParser.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import com.fr.third.jodd.template.ContextTemplateParser; -import com.fr.third.jodd.template.StringTemplateParser; - -/** - * Bean template is a string template with JSP-alike - * macros for injecting context values. - * This is a parser for such bean templates. - *

- * Once set, BeanTemplateParser instance is reusable - * as it doesn't store any parsing state. - *

- * Based on {@link StringTemplateParser}. - */ -public class BeanTemplateParser extends StringTemplateParser { - - /** - * Creates bean-backed MacroResolver. - */ - public ContextTemplateParser of(final Object context) { - return template -> parseWithBean(template, context); - } - - public String parseWithBean(final String template, final Object context) { - return super.parse(template, macroName -> { - Object value = BeanUtil.declaredSilent.getProperty(context, macroName); - - if (value == null) { - return null; - } - return value.toString(); - }); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtil.java deleted file mode 100644 index 661166713..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtil.java +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -/** - * Supreme utility for reading and writing bean properties. However, this one is the fastest available. - * Although it provides various methods, the whole thing can be easily extended to match most needs. - *

- * BeanUtil supports: - *

- * - *

- * Variants includes combinations of forced, declared and silent writing. - *

- *

- * This utility considers both bean property methods (set and get accessors), and bean fields. - * This is done because of several reasons: often there is no need for both set/get accessors, since - * bean logic requires just one functionality (e.g. just reading). In such case, other bean manipulation - * libraries still requires to have both accessors in order to set or get value. - * Another reason is that most common usage is to work with public accessors, and in that case - * private fields are ignored. - */ -public interface BeanUtil { - - /** - * Default instance of {@link BeanUtilBean}. - */ - BeanUtil pojo = new BeanUtilBean(); - - BeanUtil declared = new BeanUtilBean().declared(true); - - BeanUtil silent = new BeanUtilBean().silent(true); - - BeanUtil forced = new BeanUtilBean().forced(true); - - BeanUtil declaredSilent = new BeanUtilBean().declared(true).silent(true); - - BeanUtil declaredForced = new BeanUtilBean().declared(true).forced(true); - - BeanUtil declaredForcedSilent = new BeanUtilBean().declared(true).forced(true).silent(true); - - BeanUtil forcedSilent = new BeanUtilBean().forced(true).silent(true); - - // ---------------------------------------------------------------- SET - - /** - * Sets Java Bean property. - * @param bean Java POJO bean or a Map - * @param name property name - * @param value property value - */ - void setProperty(Object bean, String name, Object value); - - /** - * Sets indexed property. - */ - void setIndexProperty(Object bean, String property, int index, Object value); - - /** - * Sets simple property. - */ - void setSimpleProperty(Object bean, String property, Object value); - - - // ---------------------------------------------------------------- GET - - /** - * Returns value of bean's property. - *

- * In silent mode, returning of null is ambiguous: it may means that property name - * is valid and property value is null or that property name is invalid. - *

- * Using forced mode does not have any influence on the result. - */ - T getProperty(Object bean, String name); - - /** - * Returns value of indexed property. - */ - T getIndexProperty(Object bean, String property, int index); - - /** - * Reads simple property. - */ - T getSimpleProperty(Object bean, String property); - - - // ---------------------------------------------------------------- HAS - - /** - * Returns true if bean has a property. - */ - boolean hasProperty(Object bean, String name); - - /** - * Returns true if bean has only a root property. - * If yes, this means that property may be injected into the bean. - * If not, bean does not contain the property. - */ - boolean hasRootProperty(Object bean, String name); - - /** - * Returns true if simple property exist. - */ - boolean hasSimpleProperty(Object bean, String property); - - - // ---------------------------------------------------------------- type - - /** - * Returns property type. - */ - Class getPropertyType(Object bean, String name); - - - // ---------------------------------------------------------------- misc - - /** - * Returns the very first name chunk of the property. - */ - public String extractThisReference(String propertyName); - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtilBean.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtilBean.java deleted file mode 100644 index 817800239..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtilBean.java +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import com.fr.third.jodd.introspector.Getter; -import com.fr.third.jodd.introspector.Setter; -import com.fr.third.jodd.util.ClassUtil; -import com.fr.third.jodd.util.StringUtil; - -import java.lang.reflect.Array; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Instantiable version of {@link BeanUtil}. - */ -public class BeanUtilBean extends BeanUtilUtil implements BeanUtil { - - /** - * Sets the declared flag. - */ - public BeanUtilBean declared(final boolean declared) { - this.isDeclared = declared; - return this; - } - - /** - * Sets the forced flag. - */ - public BeanUtilBean forced(final boolean forced) { - this.isForced = forced; - return this; - } - - /** - * Sets the silent flag. - */ - public BeanUtilBean silent(final boolean silent) { - this.isSilent = silent; - return this; - } - - // ---------------------------------------------------------------- internal resolver - - /** - * Resolves nested property name to the very last indexed property. - * If forced, null or non-existing properties will be created. - */ - protected void resolveNestedProperties(final BeanProperty bp) { - String name = bp.name; - int dotNdx; - while ((dotNdx = indexOfDot(name)) != -1) { - bp.last = false; - bp.setName(name.substring(0, dotNdx)); - bp.updateBean(getIndexProperty(bp)); - name = name.substring(dotNdx + 1); - } - bp.last = true; - bp.setName(name); - } - - protected boolean resolveExistingNestedProperties(final BeanProperty bp) { - String name = bp.name; - int dotNdx; - while ((dotNdx = indexOfDot(name)) != -1) { - bp.last = false; - bp.setName(name.substring(0, dotNdx)); - final String temp = bp.name; - if (!hasIndexProperty(bp)) { - return false; - } - bp.setName(temp); - bp.updateBean(getIndexProperty(bp)); - name = name.substring(dotNdx + 1); - } - bp.last = true; - bp.setName(name); - return true; - } - - - // ---------------------------------------------------------------- simple property - - @Override - public boolean hasSimpleProperty(final Object bean, final String property) { - return hasSimpleProperty(new BeanProperty(this, bean, property)); - } - - protected boolean hasSimpleProperty(final BeanProperty bp) { - if (bp.bean == null) { - return false; - } - - // try: getter - final Getter getter = bp.getGetter(isDeclared); - if (getter != null) { - return true; - } - - // try: (Map) get("property") - if (bp.isMap()) { - Map map = (Map) bp.bean; - if (map.containsKey(bp.name)) { - return true; - } - } - - return false; - } - - @Override - public T getSimpleProperty(final Object bean, final String property) { - return (T) getSimpleProperty(new BeanProperty(this, bean, property)); - } - - protected Object getSimpleProperty(final BeanProperty bp) { - - if (bp.name.length() == 0) { - if (bp.indexString != null) { - // index string exist, but property name is missing - return bp.bean; - } - throw new BeanException("Invalid property", bp); - } - - Getter getter = bp.getGetter(isDeclared); - - if (getter != null) { - Object result; - try { - result = getter.invokeGetter(bp.bean); - } catch (Exception ex) { - if (isSilent) { - return null; - } - throw new BeanException("Getter failed: " + getter, ex); - } - - if ((result == null) && (isForced)) { - result = createBeanProperty(bp); - } - return result; - } - - // try: (Map) get("property") - if (bp.isMap()) { - Map map = (Map) bp.bean; - Object key = convertIndexToMapKey(getter, bp.name); - - if (!map.containsKey(key)) { - if (!isForced) { - if (isSilent) { - return null; - } - throw new BeanException("Map key not found: " + bp.name, bp); - } - Map value = new HashMap(); - //noinspection unchecked - map.put(key, value); - return value; - } - return map.get(key); - } - - // failed - if (isSilent) { - return null; - } - throw new BeanException("Simple property not found: " + bp.name, bp); - } - - @Override - public void setSimpleProperty(final Object bean, final String property, final Object value) { - setSimpleProperty(new BeanProperty(this, bean, property), value); - } - - /** - * Sets a value of simple property. - */ - @SuppressWarnings({"unchecked"}) - protected void setSimpleProperty(final BeanProperty bp, final Object value) { - Setter setter = bp.getSetter(isDeclared); - - // try: setter - if (setter != null) { - invokeSetter(setter, bp, value); - return; - } - - // try: put("property", value) - if (bp.isMap()) { - ((Map) bp.bean).put(bp.name, value); - return; - } - if (isSilent) { - return; - } - throw new BeanException("Simple property not found: " + bp.name, bp); - } - - // ---------------------------------------------------------------- indexed property - - protected boolean hasIndexProperty(final BeanProperty bp) { - - if (bp.bean == null) { - return false; - } - String indexString = extractIndex(bp); - - if (indexString == null) { - return hasSimpleProperty(bp); - } - - Object resultBean = getSimpleProperty(bp); - - if (resultBean == null) { - return false; - } - - // try: property[index] - if (resultBean.getClass().isArray()) { - int index = parseInt(indexString, bp); - return (index >= 0) && (index < Array.getLength(resultBean)); - } - - // try: list.get(index) - if (resultBean instanceof List) { - int index = parseInt(indexString, bp); - return (index >= 0) && (index < ((List)resultBean).size()); - } - if (resultBean instanceof Map) { - return ((Map)resultBean).containsKey(indexString); - } - - // failed - return false; - } - - @Override - public T getIndexProperty(final Object bean, final String property, final int index) { - BeanProperty bp = new BeanProperty(this, bean, property); - - bp.indexString = bp.index = String.valueOf(index); - - Object value = _getIndexProperty(bp); - - bp.indexString = null; - - return (T) value; - } - - /** - * Get non-nested property value: either simple or indexed property. - * If forced, missing bean will be created if possible. - */ - protected Object getIndexProperty(final BeanProperty bp) { - bp.indexString = extractIndex(bp); - - Object value = _getIndexProperty(bp); - - bp.indexString = null; - - return value; - } - - private Object _getIndexProperty(final BeanProperty bp) { - Object resultBean = getSimpleProperty(bp); - Getter getter = bp.getGetter(isDeclared); - - if (bp.indexString == null) { - return resultBean; // no index, just simple bean - } - if (resultBean == null) { - if (isSilent) { - return null; - } - throw new BeanException("Index property is null: " + bp.name, bp); - } - - // try: property[index] - if (resultBean.getClass().isArray()) { - int index = parseInt(bp.indexString, bp); - if (isForced) { - return arrayForcedGet(bp, resultBean, index); - } else { - return Array.get(resultBean, index); - } - } - - // try: list.get(index) - if (resultBean instanceof List) { - int index = parseInt(bp.indexString, bp); - List list = (List) resultBean; - if (!isForced) { - return list.get(index); - } - if (!bp.last) { - ensureListSize(list, index); - } - Object value = list.get(index); - if (value == null) { - Class listComponentType = extractGenericComponentType(getter); - if (listComponentType == Object.class) { - // not an error: when component type is unknown, use Map as generic bean - listComponentType = Map.class; - } - try { - value = ClassUtil.newInstance(listComponentType); - } catch (Exception ex) { - if (isSilent) { - return null; - } - throw new BeanException("Invalid list element: " + bp.name + '[' + index + ']', bp, ex); - } - //noinspection unchecked - list.set(index, value); - } - return value; - } - - // try: map.get('index') - if (resultBean instanceof Map) { - Map map = (Map) resultBean; - Object key = convertIndexToMapKey(getter, bp.indexString); - - if (!isForced) { - return map.get(key); - } - Object value = map.get(key); - if (!bp.last) { - if (value == null) { - Class mapComponentType = extractGenericComponentType(getter); - if (mapComponentType == Object.class) { - mapComponentType = Map.class; - } - try { - value = ClassUtil.newInstance(mapComponentType); - } catch (Exception ex) { - if (isSilent) { - return null; - } - throw new BeanException("Invalid map element: " + bp.name + '[' + bp.indexString + ']', bp, ex); - } - - //noinspection unchecked - map.put(key, value); - } - } - return value; - } - - // failed - if (isSilent) { - return null; - } - throw new BeanException("Index property is not an array, list or map: " + bp.name, bp); - } - - @Override - public void setIndexProperty(final Object bean, final String property, final int index, final Object value) { - BeanProperty bp = new BeanProperty(this, bean, property); - - bp.indexString = bp.index = String.valueOf(index); - - _setIndexProperty(bp, value); - - bp.indexString = null; - } - - /** - * Sets indexed or regular properties (no nested!). - */ - protected void setIndexProperty(final BeanProperty bp, final Object value) { - bp.indexString = extractIndex(bp); - - _setIndexProperty(bp, value); - - bp.indexString = null; - } - - @SuppressWarnings({"unchecked"}) - private void _setIndexProperty(final BeanProperty bp, Object value) { - if (bp.indexString == null) { - setSimpleProperty(bp, value); - return; - } - - // try: getInner() - Object nextBean = getSimpleProperty(bp); - Getter getter = bp.getGetter(isDeclared); - - if (nextBean == null) { - if (isSilent) { - return; - } - throw new BeanException("Index property is null:" + bp.name, bp); - } - - // inner bean found - if (nextBean.getClass().isArray()) { - int index = parseInt(bp.indexString, bp); - if (isForced) { - arrayForcedSet(bp, nextBean, index, value); - } else { - Array.set(nextBean, index, value); - } - return; - } - - if (nextBean instanceof List) { - int index = parseInt(bp.indexString, bp); - Class listComponentType = extractGenericComponentType(getter); - if (listComponentType != Object.class) { - value = convertType(value, listComponentType); - } - List list = (List) nextBean; - if (isForced) { - ensureListSize(list, index); - } - list.set(index, value); - return; - } - if (nextBean instanceof Map) { - Map map = (Map) nextBean; - Object key = convertIndexToMapKey(getter, bp.indexString); - - Class mapComponentType = extractGenericComponentType(getter); - if (mapComponentType != Object.class) { - value = convertType(value, mapComponentType); - } - map.put(key, value); - return; - } - - // failed - if (isSilent) { - return; - } - throw new BeanException("Index property is not an array, list or map: " + bp.name, bp); - } - - - // ---------------------------------------------------------------- SET - - @Override - public void setProperty(final Object bean, final String name, final Object value) { - BeanProperty beanProperty = new BeanProperty(this, bean, name); - - if (!isSilent) { - resolveNestedProperties(beanProperty); - setIndexProperty(beanProperty, value); - } - else { - try { - resolveNestedProperties(beanProperty); - setIndexProperty(beanProperty, value); - } - catch (Exception ignore) {} - } - } - - // ---------------------------------------------------------------- GET - - /** - * Returns value of bean's property. - */ - @Override - public T getProperty(final Object bean, final String name) { - BeanProperty beanProperty = new BeanProperty(this, bean, name); - if (!isSilent) { - resolveNestedProperties(beanProperty); - return (T) getIndexProperty(beanProperty); - } - else { - try { - resolveNestedProperties(beanProperty); - return (T) getIndexProperty(beanProperty); - } - catch (Exception ignore) { - return null; - } - } - } - - // ---------------------------------------------------------------- HAS - - @Override - public boolean hasProperty(final Object bean, final String name) { - BeanProperty beanProperty = new BeanProperty(this, bean, name); - if (!resolveExistingNestedProperties(beanProperty)) { - return false; - } - return hasIndexProperty(beanProperty); - } - - @Override - public boolean hasRootProperty(final Object bean, String name) { - int dotNdx = indexOfDot(name); - if (dotNdx != -1) { - name = name.substring(0, dotNdx); - } - BeanProperty beanProperty = new BeanProperty(this, bean, name); - extractIndex(beanProperty); - return hasSimpleProperty(beanProperty); - } - - // ---------------------------------------------------------------- type - - @Override - public Class getPropertyType(final Object bean, final String name) { - BeanProperty beanProperty = new BeanProperty(this, bean, name); - if (!resolveExistingNestedProperties(beanProperty)) { - return null; - } - hasIndexProperty(beanProperty); - return extractType(beanProperty); - } - - // ---------------------------------------------------------------- utilities - - private static final char[] INDEX_CHARS = new char[] {'.', '['}; - - /** - * Extract the first name of this reference. - */ - @Override - public String extractThisReference(final String propertyName) { - int ndx = StringUtil.indexOfChars(propertyName, INDEX_CHARS); - if (ndx == -1) { - return propertyName; - } - return propertyName.substring(0, ndx); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtilUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtilUtil.java deleted file mode 100644 index 41276b111..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanUtilUtil.java +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import com.fr.third.jodd.introspector.ClassIntrospector; -import com.fr.third.jodd.introspector.Getter; -import com.fr.third.jodd.introspector.MapperFunction; -import com.fr.third.jodd.introspector.Setter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.ClassUtil; - -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.List; - -/** - * Various bean property utilities that makes writings of {@link BeanUtil} classes easy. - */ -abstract class BeanUtilUtil implements BeanUtil { - - // ---------------------------------------------------------------- flags - - protected boolean isDeclared = false; - protected boolean isForced = false; - protected boolean isSilent = false; - - // ---------------------------------------------------------------- introspector - - protected ClassIntrospector introspector = ClassIntrospector.get(); - protected TypeConverterManager typeConverterManager = TypeConverterManager.get(); - - /** - * Sets {@link ClassIntrospector introspector} implementation. - */ - public void setIntrospector(final ClassIntrospector introspector) { - this.introspector = introspector; - } - - /** - * Sets {@link TypeConverterManager type converter manager} implementation. - */ - public void setTypeConverterManager(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - /** - * Converts object to destination type. Invoked before the - * value is set into destination. Throws TypeConversionException - * if conversion fails. - */ - @SuppressWarnings("unchecked") - protected Object convertType(final Object value, final Class type) { - return typeConverterManager.convertType(value, type); - } - - /** - * Converter to collection. - */ - @SuppressWarnings("unchecked") - protected Object convertToCollection(final Object value, final Class destinationType, final Class componentType) { - return typeConverterManager.convertToCollection(value, destinationType, componentType); - } - - - // ---------------------------------------------------------------- accessors - - /** - * Invokes setter, but first converts type to match the setter type. - */ - protected Object invokeSetter(final Setter setter, final BeanProperty bp, Object value) { - try { - - final MapperFunction setterMapperFunction = setter.getMapperFunction(); - - if (setterMapperFunction != null) { - value = setterMapperFunction.apply(value); - } - - final Class type = setter.getSetterRawType(); - - if (ClassUtil.isTypeOf(type, Collection.class)) { - Class componentType = setter.getSetterRawComponentType(); - - value = convertToCollection(value, type, componentType); - } else { - // no collections - value = convertType(value, type); - } - - setter.invokeSetter(bp.bean, value); - } catch (Exception ex) { - if (isSilent) { - return null; - } - throw new BeanException("Setter failed: " + setter, ex); - } - return value; - } - - // ---------------------------------------------------------------- forced - - /** - * Returns the element of an array forced. If value is null, it will be instantiated. - * If not the last part of indexed bean property, array will be expanded to the index if necessary. - */ - protected Object arrayForcedGet(final BeanProperty bp, Object array, final int index) { - Class componentType = array.getClass().getComponentType(); - if (!bp.last) { - array = ensureArraySize(bp, array, componentType, index); - } - Object value = Array.get(array, index); - if (value == null) { - try { - //noinspection unchecked - value = ClassUtil.newInstance(componentType); - } catch (Exception ex) { - if (isSilent) { - return null; - } - throw new BeanException("Invalid array element: " + bp.name + '[' + index + ']', bp, ex); - } - Array.set(array, index, value); - } - return value; - } - - /** - * Sets the array element forced. If index is greater then arrays length, array will be expanded to the index. - * If speed is critical, it is better to allocate an array with proper size before using this method. - */ - protected void arrayForcedSet(final BeanProperty bp, Object array, final int index, Object value) { - Class componentType = array.getClass().getComponentType(); - array = ensureArraySize(bp, array, componentType, index); - value = convertType(value, componentType); - Array.set(array, index, value); - } - - - @SuppressWarnings({"SuspiciousSystemArraycopy"}) - protected Object ensureArraySize(final BeanProperty bp, Object array, final Class componentType, final int index) { - int len = Array.getLength(array); - if (index >= len) { - Object newArray = Array.newInstance(componentType, index + 1); - System.arraycopy(array, 0, newArray, 0, len); - - Setter setter = bp.getSetter(true); - if (setter == null) { - // no point to check for bp.silent, throws NPE later - throw new BeanException("Setter or field not found: " + bp.name, bp); - } - - newArray = invokeSetter(setter, bp, newArray); - - array = newArray; - } - return array; - } - - @SuppressWarnings({"unchecked"}) - protected void ensureListSize(final List list, final int size) { - int len = list.size(); - while (size >= len) { - list.add(null); - len++; - } - } - - // ---------------------------------------------------------------- index - - /** - * Finds the very first next dot. Ignores dots between index brackets. - * Returns -1 when dot is not found. - */ - protected int indexOfDot(final String name) { - int ndx = 0; - int len = name.length(); - - boolean insideBracket = false; - - while (ndx < len) { - char c = name.charAt(ndx); - - if (insideBracket) { - if (c == ']') { - insideBracket = false; - } - } else { - if (c == '.') { - return ndx; - } - if (c == '[') { - insideBracket = true; - } - } - ndx++; - } - return -1; - } - - - /** - * Extract index string from non-nested property name. - * If index is found, it is stripped from bean property name. - * If no index is found, it returns null. - */ - protected String extractIndex(final BeanProperty bp) { - bp.index = null; - String name = bp.name; - int lastNdx = name.length() - 1; - if (lastNdx < 0) { - return null; - } - if (name.charAt(lastNdx) == ']') { - int leftBracketNdx = name.lastIndexOf('['); - if (leftBracketNdx != -1) { - bp.setName(name.substring(0, leftBracketNdx)); - bp.index = name.substring(leftBracketNdx + 1, lastNdx); - return bp.index; - } - } - return null; - } - - protected int parseInt(final String indexString, final BeanProperty bp) { - try { - return Integer.parseInt(indexString); - } catch (NumberFormatException nfex) { - // no point to use bp.silent, as will throw exception - throw new BeanException("Invalid index: " + indexString, bp, nfex); - } - } - - // ---------------------------------------------------------------- create property - - /** - * Creates new instance for current property name through its setter. - * It uses default constructor! - */ - protected Object createBeanProperty(final BeanProperty bp) { - Setter setter = bp.getSetter(true); - if (setter == null) { - return null; - } - - Class type = setter.getSetterRawType(); - - Object newInstance; - try { - newInstance = ClassUtil.newInstance(type); - } catch (Exception ex) { - if (isSilent) { - return null; - } - throw new BeanException("Invalid property: " + bp.name, bp, ex); - } - - newInstance = invokeSetter(setter, bp, newInstance); - - return newInstance; - } - - // ---------------------------------------------------------------- generic and type - - /** - * Extracts generic component type of a property. Returns Object.class - * when property does not have component. - */ - protected Class extractGenericComponentType(final Getter getter) { - Class componentType = null; - - if (getter != null) { - componentType = getter.getGetterRawComponentType(); - } - - if (componentType == null) { - componentType = Object.class; - } - return componentType; - } - - /** - * Converts Map index to key type. If conversion fails, original value will be returned. - */ - protected Object convertIndexToMapKey(final Getter getter, final Object index) { - Class indexType = null; - - if (getter != null) { - indexType = getter.getGetterRawKeyComponentType(); - } - - // check if set - if (indexType == null) { - indexType = Object.class; // marker for no generic type - } - - if (indexType == Object.class) { - return index; - } - - try { - return convertType(index, indexType); - } catch (Exception ignore) { - return index; - } - } - - /** - * Extracts type of current property. - */ - protected Class extractType(final BeanProperty bp) { - Getter getter = bp.getGetter(isDeclared); - if (getter != null) { - if (bp.index != null) { - Class type = getter.getGetterRawComponentType(); - return type == null ? Object.class : type; - } - return getter.getGetterRawType(); - } - - return null; // this should not happens - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanVisitor.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanVisitor.java deleted file mode 100644 index 210c90bb2..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanVisitor.java +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import com.fr.third.jodd.inex.InExRuleMatcher; -import com.fr.third.jodd.inex.InExRules; -import com.fr.third.jodd.introspector.ClassDescriptor; -import com.fr.third.jodd.introspector.ClassIntrospector; -import com.fr.third.jodd.introspector.FieldDescriptor; -import com.fr.third.jodd.introspector.MethodDescriptor; -import com.fr.third.jodd.introspector.PropertyDescriptor; -import com.fr.third.jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Map; -import java.util.Set; - -import static com.fr.third.jodd.util.StringPool.LEFT_SQ_BRACKET; -import static com.fr.third.jodd.util.StringPool.RIGHT_SQ_BRACKET; - -/** - * Visitor for bean properties. It extracts properties names - * from the source bean and then visits one by one. - * - * @see BeanVisitorImplBase - */ -public abstract class BeanVisitor implements InExRuleMatcher { - - /** - * Source bean. - */ - protected Object source; - /** - * Include/exclude rules. - */ - protected InExRules rules = new InExRules<>(this); - /** - * Flag for enabling declared properties, or just public ones. - */ - protected boolean declared; - /** - * Defines if null values should be ignored. - */ - protected boolean ignoreNullValues; - /** - * Defines if empty string should be ignored. - */ - protected boolean ignoreEmptyString; - /** - * Defines if fields should be included. - */ - protected boolean includeFields; - /** - * Initial matching mode. - */ - protected boolean blacklist = true; - /** - * Indicates the the source is a Map. - */ - protected boolean isSourceMap = false; - - // ---------------------------------------------------------------- util - - /** - * Returns all bean property names. - */ - protected String[] getAllBeanPropertyNames(final Class type, final boolean declared) { - final ClassDescriptor classDescriptor = ClassIntrospector.get().lookup(type); - - final PropertyDescriptor[] propertyDescriptors = classDescriptor.getAllPropertyDescriptors(); - - final ArrayList names = new ArrayList<>(propertyDescriptors.length); - - for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) { - final MethodDescriptor getter = propertyDescriptor.getReadMethodDescriptor(); - if (getter != null) { - if (getter.matchDeclared(declared)) { - names.add(propertyDescriptor.getName()); - } - } - else if (includeFields) { - final FieldDescriptor field = propertyDescriptor.getFieldDescriptor(); - if (field != null) { - if (field.matchDeclared(declared)) { - names.add(field.getName()); - } - } - } - } - - return names.toArray(new String[0]); - } - - /** - * Returns an array of bean properties. If bean is a Map, - * all its keys will be returned. - */ - protected String[] resolveProperties(final Object bean, final boolean declared) { - final String[] properties; - - if (bean instanceof Map) { - final Set keys = ((Map) bean).keySet(); - - properties = new String[keys.size()]; - int ndx = 0; - for (final Object key : keys) { - properties[ndx] = key.toString(); - ndx++; - } - } else { - properties = getAllBeanPropertyNames(bean.getClass(), declared); - } - - return properties; - } - - /** - * Starts visiting properties. - */ - public void visit() { - final String[] properties = resolveProperties(source, declared); - - for (final String name : properties) { - if (name == null) { - continue; - } - - if (!rules.match(name, blacklist)) { - continue; - } - - final Object value; - - String propertyName = name; - - if (isSourceMap) { - propertyName = LEFT_SQ_BRACKET + name + RIGHT_SQ_BRACKET; - } - - if (declared) { - value = BeanUtil.declared.getProperty(source, propertyName); - } else { - value = BeanUtil.pojo.getProperty(source, propertyName); - } - - if (value == null && ignoreNullValues) { - continue; - } - - if (ignoreEmptyString && value instanceof String && StringUtil.isEmpty((String) value)) { - continue; - } - - visitProperty(name, value); - } - } - - /** - * Invoked for each visited property. Returns true if - * visiting should continue, otherwise false to stop. - */ - protected abstract boolean visitProperty(String name, Object value); - - /** - * Compares property name to the rules. - */ - @Override - public boolean accept(final String propertyName, final String rule, final boolean include) { - return propertyName.equals(rule); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanVisitorImplBase.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanVisitorImplBase.java deleted file mode 100644 index e29762ee1..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanVisitorImplBase.java +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -/** - * Default implementation of {@link BeanVisitor} for just setting - * the properties in fluent way. - */ -public abstract class BeanVisitorImplBase extends BeanVisitor { - - @SuppressWarnings("unchecked") - protected T _this() { - return (T) this; - } - - /** - * Excludes all properties, i.e. enables blacklist mode. - */ - public T excludeAll() { - blacklist = false; - return _this(); - } - - /** - * Defines excluded property names. - */ - public T exclude(final String... excludes) { - for (String ex : excludes) { - rules.exclude(ex); - } - return _this(); - } - - /** - * Exclude a property. - */ - public T exclude(final String exclude) { - rules.exclude(exclude); - return _this(); - } - - /** - * Defines included property names. - */ - public T include(final String... includes) { - for (String in : includes) { - rules.include(in); - } - return _this(); - } - - /** - * Include a property. - */ - public T include(final String include) { - rules.include(include); - return _this(); - } - - /** - * Defines included property names as public properties - * of given template class. Sets to black list mode. - */ - public T includeAs(final Class template) { - blacklist = false; - - String[] properties = getAllBeanPropertyNames(template, false); - - include(properties); - - return _this(); - } - - /** - * Defines if null values should be ignored. - */ - public T ignoreNulls(final boolean ignoreNulls) { - this.ignoreNullValues = ignoreNulls; - - return _this(); - } - - /** - * Defines if empty string should be ignored. - */ - public T ignoreEmptyString(final boolean ignoreEmptyString) { - this.ignoreEmptyString = ignoreEmptyString; - return _this(); - } - - /** - * Defines if all properties should be copied (when set to true) - * or only public (when set to false, default). - */ - public T declared(final boolean declared) { - this.declared = declared; - return _this(); - } - - /** - * Defines if fields without getters should be copied too. - */ - public T includeFields(final boolean includeFields) { - this.includeFields = includeFields; - return _this(); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanWalker.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanWalker.java deleted file mode 100644 index d70e0df8c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/BeanWalker.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.bean; - -import java.util.Map; - -/** - * Walker over bean properties. - */ -public class BeanWalker extends BeanVisitorImplBase { - - private final BeanWalkerCallback callback; - - /** - * Functional callback for walking. - */ - public interface BeanWalkerCallback { - void visitProperty(String name, Object value); - } - - public BeanWalker(final BeanWalkerCallback callback) { - this.callback = callback; - } - - /** - * Static ctor. - */ - public static BeanWalker walk(final BeanWalkerCallback callback) { - return new BeanWalker(callback); - } - - public void source(final Object source) { - this.source = source; - - isSourceMap = (source instanceof Map); - - visit(); - } - - public void bean(final Object bean) { - this.source = bean; - - visit(); - } - - public void map(final Map map) { - this.source = map; - - this.isSourceMap = true; - - visit(); - } - - @Override - protected boolean visitProperty(final String name, final Object value) { - callback.visitProperty(name, value); - return true; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/bean/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/bean/package-info.java deleted file mode 100644 index ffaefe198..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/bean/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Java Bean utilities, provides the fastest bean manipulation. - */ -package com.fr.third.jodd.bean; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastBooleanBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastBooleanBuffer.java deleted file mode 100644 index 4789f6b7a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastBooleanBuffer.java +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import java.util.Arrays; - -/** - * Faster {@code boolean} buffer. - */ -public class FastBooleanBuffer { - - private boolean[] buffer; - private int offset; - - /** - * Creates a new {@code boolean} buffer. The buffer capacity is - * initially 64 booleans, though its size increases if necessary. - */ - public FastBooleanBuffer() { - this.buffer = new boolean[64]; - } - - /** - * Creates a new {@code boolean} buffer, with a buffer capacity of - * the specified size. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastBooleanBuffer(final int size) { - this.buffer = new boolean[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code boolean} to buffer. - */ - public void append(final boolean element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - } - - /** - * Appends {@code boolean} array to buffer. - */ - public FastBooleanBuffer append(final boolean[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code boolean} array to buffer. - */ - public FastBooleanBuffer append(final boolean[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastBooleanBuffer append(final FastBooleanBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code boolean} array from buffered content. - */ - public boolean[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code boolean} subarray from buffered content. - */ - public boolean[] toArray(final int start, final int len) { - final boolean[] array = new boolean[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code boolean} element at given index. - */ - public boolean get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastByteBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastByteBuffer.java deleted file mode 100644 index 52e3e2f2d..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastByteBuffer.java +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import java.util.Arrays; - -/** - * Faster {@code byte} buffer. Works faster for smaller buffer sizes. - * After eg. length of 2048 the performances are practically the same. - */ -public class FastByteBuffer { - - private byte[] buffer; - private int offset; - - /** - * Creates a new {@code byte} buffer. The buffer capacity is - * initially 64 bytes, though its size increases if necessary. - */ - public FastByteBuffer() { - this.buffer = new byte[64]; - } - - /** - * Creates a new {@code byte} buffer, with a buffer capacity of - * the specified size. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastByteBuffer(final int size) { - this.buffer = new byte[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code byte} to buffer. - */ - public void append(final byte element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - } - - /** - * Appends {@code byte} array to buffer. - */ - public FastByteBuffer append(final byte[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code byte} array to buffer. - */ - public FastByteBuffer append(final byte[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastByteBuffer append(final FastByteBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code byte} array from buffered content. - */ - public byte[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code byte} subarray from buffered content. - */ - public byte[] toArray(final int start, final int len) { - final byte[] array = new byte[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code byte} element at given index. - */ - public byte get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastCharBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastCharBuffer.java deleted file mode 100644 index 9de22e46a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastCharBuffer.java +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import com.fr.third.jodd.util.CharArraySequence; - -import java.util.Arrays; - -/** - * Faster {@code char} buffer. - */ -public class FastCharBuffer implements CharSequence, Appendable { - - private char[] buffer; - private int offset; - - /** - * Creates a new {@code char} buffer. The buffer capacity is - * initially 64 chars, though its size increases if necessary. - */ - public FastCharBuffer() { - this.buffer = new char[64]; - } - - /** - * Creates a new {@code char} buffer, with a buffer capacity of - * the specified size, in chars. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastCharBuffer(final int size) { - this.buffer = new char[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code char} to buffer. - */ - @Override - public FastCharBuffer append(final char element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - return this; - } - - /** - * Appends {@code char} array to buffer. - */ - public FastCharBuffer append(final char[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code char} array to buffer. - */ - public FastCharBuffer append(final char[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastCharBuffer append(final FastCharBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - @Override - public int length() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code char} array from buffered content. - */ - public char[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code char} subarray from buffered content. - */ - public char[] toArray(final int start, final int len) { - final char[] array = new char[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code char} element at given index. - */ - public char get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - - /** - * Appends character sequence to buffer. - */ - @Override - public FastCharBuffer append(final CharSequence csq) { - append(csq, 0, csq.length()); - return this; - } - - /** - * Appends character sequence to buffer. - */ - @Override - public FastCharBuffer append(final CharSequence csq, final int start, final int end) { - for (int i = start; i < end; i++) { - append(csq.charAt(i)); - } - return this; - } - @Override - public char charAt(final int index) { - return get(index); - } - - @Override - public CharSequence subSequence(final int start, final int end) { - return new CharArraySequence(buffer, start, end - start); - } - - /** - * Returns a String of the char buffer. - * Please use {@code StringBuilder} instead, it is faster. - */ - @Override - public String toString() { - return new String(toArray()); - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastDoubleBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastDoubleBuffer.java deleted file mode 100644 index 9d7531e27..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastDoubleBuffer.java +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import java.util.Arrays; - -/** - * Faster {@code double} buffer. - */ -public class FastDoubleBuffer { - - private double[] buffer; - private int offset; - - /** - * Creates a new {@code double} buffer. The buffer capacity is - * initially 64 doubles, though its size increases if necessary. - */ - public FastDoubleBuffer() { - this.buffer = new double[64]; - } - - /** - * Creates a new {@code double} buffer, with a buffer capacity of - * the specified size. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastDoubleBuffer(final int size) { - this.buffer = new double[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code double} to buffer. - */ - public void append(final double element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - } - - /** - * Appends {@code double} array to buffer. - */ - public FastDoubleBuffer append(final double[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code double} array to buffer. - */ - public FastDoubleBuffer append(final double[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastDoubleBuffer append(final FastDoubleBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code double} array from buffered content. - */ - public double[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code double} subarray from buffered content. - */ - public double[] toArray(final int start, final int len) { - final double[] array = new double[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code double} element at given index. - */ - public double get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastFloatBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastFloatBuffer.java deleted file mode 100644 index 44f8b3a31..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastFloatBuffer.java +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import java.util.Arrays; - -/** - * Faster {@code float} buffer. - */ -public class FastFloatBuffer { - - private float[] buffer; - private int offset; - - /** - * Creates a new {@code float} buffer. The buffer capacity is - * initially 64 floats, though its size increases if necessary. - */ - public FastFloatBuffer() { - this.buffer = new float[64]; - } - - /** - * Creates a new {@code float} buffer, with a buffer capacity of - * the specified size. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastFloatBuffer(final int size) { - this.buffer = new float[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code float} to buffer. - */ - public void append(final float element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - } - - /** - * Appends {@code float} array to buffer. - */ - public FastFloatBuffer append(final float[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code float} array to buffer. - */ - public FastFloatBuffer append(final float[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastFloatBuffer append(final FastFloatBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code float} array from buffered content. - */ - public float[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code float} subarray from buffered content. - */ - public float[] toArray(final int start, final int len) { - final float[] array = new float[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code float} element at given index. - */ - public float get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastIntBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastIntBuffer.java deleted file mode 100644 index ce82f1739..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastIntBuffer.java +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import java.util.Arrays; - -/** - * Faster {@code int} buffer. - */ -public class FastIntBuffer { - - private int[] buffer; - private int offset; - - /** - * Creates a new {@code int} buffer. The buffer capacity is - * initially 64 ints, though its size increases if necessary. - */ - public FastIntBuffer() { - this.buffer = new int[64]; - } - - /** - * Creates a new {@code int} buffer, with a buffer capacity of - * the specified size. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastIntBuffer(final int size) { - this.buffer = new int[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code int} to buffer. - */ - public void append(final int element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - } - - /** - * Appends {@code int} array to buffer. - */ - public FastIntBuffer append(final int[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code int} array to buffer. - */ - public FastIntBuffer append(final int[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastIntBuffer append(final FastIntBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code int} array from buffered content. - */ - public int[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code int} subarray from buffered content. - */ - public int[] toArray(final int start, final int len) { - final int[] array = new int[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code int} element at given index. - */ - public int get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastLongBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastLongBuffer.java deleted file mode 100644 index d057d0dd3..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastLongBuffer.java +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import java.util.Arrays; - -/** - * Faster {@code long} buffer. - */ -public class FastLongBuffer { - - private long[] buffer; - private int offset; - - /** - * Creates a new {@code long} buffer. The buffer capacity is - * initially 64 longs, though its size increases if necessary. - */ - public FastLongBuffer() { - this.buffer = new long[64]; - } - - /** - * Creates a new {@code long} buffer, with a buffer capacity of - * the specified size. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastLongBuffer(final int size) { - this.buffer = new long[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code long} to buffer. - */ - public void append(final long element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - } - - /** - * Appends {@code long} array to buffer. - */ - public FastLongBuffer append(final long[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code long} array to buffer. - */ - public FastLongBuffer append(final long[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastLongBuffer append(final FastLongBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code long} array from buffered content. - */ - public long[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code long} subarray from buffered content. - */ - public long[] toArray(final int start, final int len) { - final long[] array = new long[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code long} element at given index. - */ - public long get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastShortBuffer.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastShortBuffer.java deleted file mode 100644 index 6d741d52b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/FastShortBuffer.java +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.buffer; - -import java.util.Arrays; - -/** - * Faster {@code short} buffer. - */ -public class FastShortBuffer { - - private short[] buffer; - private int offset; - - /** - * Creates a new {@code short} buffer. The buffer capacity is - * initially 64 shorts, though its size increases if necessary. - */ - public FastShortBuffer() { - this.buffer = new short[64]; - } - - /** - * Creates a new {@code short} buffer, with a buffer capacity of - * the specified size. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastShortBuffer(final int size) { - this.buffer = new short[size]; - } - - /** - * Grows the buffer. - */ - private void grow(final int minCapacity) { - final int oldCapacity = buffer.length; - int newCapacity = oldCapacity << 1; - if (newCapacity - minCapacity < 0) { - // special case, min capacity is larger then a grow - newCapacity = minCapacity + 512; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } - - /** - * Appends single {@code short} to buffer. - */ - public void append(final short element) { - if (offset - buffer.length >= 0) { - grow(offset); - } - - buffer[offset++] = element; - } - - /** - * Appends {@code short} array to buffer. - */ - public FastShortBuffer append(final short[] array, final int off, final int len) { - if (offset + len - buffer.length > 0) { - grow(offset + len); - } - - System.arraycopy(array, off, buffer, offset, len); - offset += len; - return this; - } - - /** - * Appends {@code short} array to buffer. - */ - public FastShortBuffer append(final short[] array) { - return append(array, 0, array.length); - } - - /** - * Appends another fast buffer to this one. - */ - public FastShortBuffer append(final FastShortBuffer buff) { - if (buff.offset == 0) { - return this; - } - append(buff.buffer, 0, buff.offset); - return this; - } - - /** - * Returns buffer size. - */ - public int size() { - return offset; - } - - /** - * Tests if this buffer has no elements. - */ - public boolean isEmpty() { - return offset == 0; - } - - /** - * Resets the buffer content. - */ - public void clear() { - offset = 0; - } - - /** - * Creates {@code short} array from buffered content. - */ - public short[] toArray() { - return Arrays.copyOf(buffer, offset); - } - - /** - * Creates {@code short} subarray from buffered content. - */ - public short[] toArray(final int start, final int len) { - final short[] array = new short[len]; - - if (len == 0) { - return array; - } - - System.arraycopy(buffer, start, array, 0, len); - - return array; - } - - /** - * Returns {@code short} element at given index. - */ - public short get(final int index) { - if (index >= offset) { - throw new IndexOutOfBoundsException(); - } - return buffer[index]; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/buffer/package-info.java deleted file mode 100644 index 034811504..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/buffer/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Faster primitive buffers, a simple wrappers over an array. - */ -package com.fr.third.jodd.buffer; diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/AbstractCacheMap.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/AbstractCacheMap.java deleted file mode 100644 index 65e127365..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/AbstractCacheMap.java +++ /dev/null @@ -1,344 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.locks.StampedLock; - -/** - * Default implementation of timed and size cache map. - * Implementations should: - *

- * Uses ReentrantReadWriteLock to synchronize access. - * Since upgrading from a read lock to the write lock is not possible, - * be careful withing {@link #get(Object)} method. - */ -public abstract class AbstractCacheMap implements Cache { - - static class CacheObject { - CacheObject(final K2 key, final V2 object, final long ttl) { - this.key = key; - this.cachedObject = object; - this.ttl = ttl; - this.lastAccess = System.currentTimeMillis(); - } - - final K2 key; - final V2 cachedObject; - long lastAccess; // time of last access - long accessCount; // number of accesses - long ttl; // objects timeout (time-to-live), 0 = no timeout - - boolean isExpired() { - if (ttl == 0) { - return false; - } - return lastAccess + ttl < System.currentTimeMillis(); - } - V2 getObject() { - lastAccess = System.currentTimeMillis(); - accessCount++; - return cachedObject; - } - V2 peekObject() { - return cachedObject; - } - } - - protected Map> cacheMap; - private final StampedLock lock = new StampedLock(); - - // ---------------------------------------------------------------- properties - - protected int cacheSize; // max cache size, 0 = no limit - - /** - * {@inheritDoc} - */ - @Override - public int limit() { - return cacheSize; - } - - protected long timeout; // default timeout, 0 = no timeout - - /** - * Returns default cache timeout or 0 if it is not set. - * Timeout can be set individually for each object. - */ - @Override - public long timeout() { - return timeout; - } - - /** - * Identifies if objects has custom timeouts. - * Should be used to determine if prune for existing objects is needed. - */ - protected boolean existCustomTimeout; - - /** - * Returns true if prune of expired objects should be invoked. - * For internal use. - */ - protected boolean isPruneExpiredActive() { - return (timeout != 0) || existCustomTimeout; - } - - - // ---------------------------------------------------------------- put - - - /** - * {@inheritDoc} - */ - @Override - public void put(final K key, final V object) { - put(key, object, timeout); - } - - - /** - * {@inheritDoc} - */ - @Override - public void put(final K key, final V object, final long timeout) { - Objects.requireNonNull(object); - - final long stamp = lock.writeLock(); - - try { - final CacheObject co = createCacheObject(key, object, timeout); - if (timeout != 0) { - existCustomTimeout = true; - } - if (isReallyFull(key)) { - pruneCache(); - } - cacheMap.put(key, co); - } - finally { - lock.unlockWrite(stamp); - } - } - - protected CacheObject createCacheObject(K key, V object, long timeout) { - return new CacheObject<>(key, object, timeout); - } - - // ---------------------------------------------------------------- get - - protected int hitCount; - protected int missCount; - - /** - * Returns hit count. - */ - public int getHitCount() { - return hitCount; - } - - /** - * Returns miss count. - */ - public int getMissCount() { - return missCount; - } - - /** - * {@inheritDoc} - */ - @Override - public V get(final K key) { - long stamp = lock.readLock(); - - try { - final CacheObject co = cacheMap.get(key); - if (co == null) { - missCount++; - return null; - } - if (co.isExpired()) { - final long newStamp = lock.tryConvertToWriteLock(stamp); - - if (newStamp != 0L) { - stamp = newStamp; - // lock is upgraded to write lock - } - else { - // manually upgrade lock to write lock - lock.unlockRead(stamp); - stamp = lock.writeLock(); - } - - final CacheObject removedCo = cacheMap.remove(key); - if (removedCo != null) { - onRemove(removedCo.key, removedCo.cachedObject); - } - - missCount++; - return null; - } - - hitCount++; - return co.getObject(); - } - finally { - lock.unlock(stamp); - } - } - - // ---------------------------------------------------------------- prune - - /** - * Prune implementation. - */ - protected abstract int pruneCache(); - - /** - * {@inheritDoc} - */ - @Override - public final int prune() { - final long stamp = lock.writeLock(); - try { - return pruneCache(); - } - finally { - lock.unlockWrite(stamp); - } - } - - // ---------------------------------------------------------------- common - - /** - * {@inheritDoc} - */ - @Override - public boolean isFull() { - if (cacheSize == 0) { - return false; - } - return cacheMap.size() >= cacheSize; - } - - protected boolean isReallyFull(final K key) { - if (cacheSize == 0) { - return false; - } - if (cacheMap.size() >= cacheSize) { - return !cacheMap.containsKey(key); - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public V remove(final K key) { - V removedValue = null; - final long stamp = lock.writeLock(); - try { - final CacheObject co = cacheMap.remove(key); - - if (co != null) { - onRemove(co.key, co.cachedObject); - removedValue = co.cachedObject; - } - } - finally { - lock.unlockWrite(stamp); - } - return removedValue; - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - final long stamp = lock.writeLock(); - try { - cacheMap.clear(); - } - finally { - lock.unlockWrite(stamp); - } - } - - /** - * {@inheritDoc} - */ - @Override - public int size() { - return cacheMap.size(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isEmpty() { - return size() == 0; - } - - /** - * {@inheritDoc} - */ - @Override - public Map snapshot(final boolean peek) { - final long stamp = lock.writeLock(); - try { - final Map map = new HashMap<>(cacheMap.size()); - cacheMap.forEach((key, cacheValue) -> { - if (!cacheValue.isExpired()) { - map.put(key, peek ? cacheValue.peekObject() : cacheValue.getObject()); - } - }); - return map; - } - finally { - lock.unlockWrite(stamp); - } - } - - // ---------------------------------------------------------------- protected - - /** - * Callback called on item removal. The cache is still locked. - */ - protected void onRemove(final K key, final V cachedObject) { - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/Cache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/Cache.java deleted file mode 100644 index dae2bbb3d..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/Cache.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.Map; - -/** - * Cache interface. - */ -public interface Cache { - - /** - * Returns cache size or 0 if there is no size limit. - */ - int limit(); - - /** - * Returns default timeout or 0 if it is not set. - */ - long timeout(); - - /** - * Adds an object to the cache with default timeout. - * @see Cache#put(Object, Object, long) - */ - void put(K key, V object); - - /** - * Adds an object to the cache with specified timeout after which it becomes expired. - * If cache is full, {@link #prune()} is invoked to make room for new object. - * Cached value must be non-null. - */ - void put(K key, V object, long timeout); - - /** - * Retrieves an object from the cache. Returns null if object - * is not longer in cache or if it is expired. - */ - V get(K key); - - /** - * Prunes objects from cache and returns the number of removed objects. - * Used strategy depends on cache implementation. - */ - int prune(); - - /** - * Returns true if max cache capacity has been reached - * only if cache is size limited. - */ - boolean isFull(); - - /** - * Removes an object from the cache and returns removed value of {@code null} - * if object was not in the cache or was expired. - */ - V remove(K key); - - /** - * Clears current cache. - */ - void clear(); - - /** - * Returns current cache size. - */ - int size(); - - /** - * Returns true if cache is empty. - */ - boolean isEmpty(); - - /** - * Creates a snapshot from current cache values. Returned values may not - * longer be valid or they might be already expired! Cache is locked during - * the snapshot creation. - * @param peek if set, snapshot will just peek the object and not get them (and modify last access) - */ - Map snapshot(boolean peek); - - default Map snapshot() { - return this.snapshot(false); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FIFOCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/FIFOCache.java deleted file mode 100644 index 0f6d08185..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FIFOCache.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.Iterator; -import java.util.LinkedHashMap; - -/** - * FIFO (first in first out) cache. - * - *

- * FIFO (first in first out): just adds items to the cache as they are accessed, putting them in a queue or buffer and - * not changing their location in the buffer; when the cache is full, items are ejected in the order they were - * added. Cache access overhead is constant time regardless of the size of the cache. The advantage of this algorithm - * is that it's simple and fast; it can be implemented using a simple array and an index. The disadvantage is that - * it's not very smart; it doesn't make any effort to keep more commonly used items in cache. - *

- * Summary for FIFO: fast, not adaptive, not scan resistant. - */ -public class FIFOCache extends AbstractCacheMap { - - public FIFOCache(final int cacheSize) { - this(cacheSize, 0); - } - - /** - * Creates a new LRU cache. - */ - public FIFOCache(final int cacheSize, final long timeout) { - this.cacheSize = cacheSize; - this.timeout = timeout; - cacheMap = new LinkedHashMap<>(cacheSize + 1, 1.0f, false); - } - - - // ---------------------------------------------------------------- prune - - /** - * Prune expired objects and, if cache is still full, the first one. - */ - @Override - protected int pruneCache() { - int count = 0; - CacheObject first = null; - Iterator> values = cacheMap.values().iterator(); - while (values.hasNext()) { - CacheObject co = values.next(); - if (co.isExpired()) { - values.remove(); - onRemove(co.key, co.cachedObject); - count++; - } - if (first == null) { - first = co; - } - } - if (isFull()) { - if (first != null) { - cacheMap.remove(first.key); - onRemove(first.key, first.cachedObject); - count++; - } - } - return count; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileCache.java deleted file mode 100644 index 6b28c27d5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileCache.java +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package com.fr.third.jodd.cache; - -import com.fr.third.jodd.io.FileUtil; - -import java.io.File; -import java.io.IOException; - -/** - * Base in-memory files cache. - */ -public abstract class FileCache { - - protected final Cache cache; - protected final int maxSize; - protected final int maxFileSize; - protected final long timeout; - - protected int usedSize; - - /** - * Creates new File LFU cache. - * @param maxSize total cache size in bytes - * @param maxFileSize max available file size in bytes, may be 0 - * @param timeout timeout, may be 0 - */ - protected FileCache(final int maxSize, final int maxFileSize, final long timeout) { - this.maxSize = maxSize; - this.maxFileSize = maxFileSize; - this.timeout = timeout; - this.cache = createCache(); - } - - /** - * Creates new cache instance for files content. - */ - protected abstract Cache createCache(); - - /** - * Creates CacheObject that updates last access time based on files last modification. - */ - protected AbstractCacheMap.CacheObject createFileCacheObject(File fileKey, byte[] object, long timeout) { - return new AbstractCacheMap.CacheObject(fileKey, object, timeout) { - @Override - boolean isExpired() { - if (fileKey.lastModified() > this.lastAccess) { - this.lastAccess = fileKey.lastModified(); - } - return super.isExpired(); - } - }; - } - - // ---------------------------------------------------------------- get - - /** - * Returns max cache size in bytes. - */ - public int maxSize() { - return maxSize; - } - - /** - * Returns actually used size in bytes. - */ - public int usedSize() { - return usedSize; - } - - /** - * Returns maximum allowed file size that can be added to the cache. - * Files larger than this value will be not added, even if there is - * enough room. - */ - public int maxFileSize() { - return maxFileSize; - } - - /** - * Returns number of cached files. - */ - public int cachedFilesCount() { - return cache.size(); - } - - /** - * Returns timeout. - */ - public long cacheTimeout() { - return cache.timeout(); - } - - /** - * Clears the cache. - */ - public void clear() { - cache.clear(); - usedSize = 0; - } - - // ---------------------------------------------------------------- get - - /** - * Returns cached file bytes. If file is not cached it will be - * read and put in the cache (if all the rules are satisfied). - */ - public byte[] getFileBytes(final File file) throws IOException { - byte[] bytes = cache.get(file); - if (bytes != null) { - return bytes; - } - - // add file - bytes = FileUtil.readBytes(file); - - if ((maxFileSize != 0) && (file.length() > maxFileSize)) { - // don't cache files that size exceed max allowed file size - return bytes; - } - - usedSize += bytes.length; - - // put file into cache - // if used size > total, purge() will be invoked - cache.put(file, bytes); - - return bytes; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileLFUCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileLFUCache.java deleted file mode 100644 index 5857de330..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileLFUCache.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.io.File; - -/** - * Files LFU cache stores files content in memory to dramatically - * speed up performances for frequently read files. - */ -public class FileLFUCache extends FileCache { - - /** - * Creates file LFU cache with specified size. Sets - * {@link #maxFileSize max available file size} to half of this value. - */ - public FileLFUCache(final int maxSize) { - this(maxSize, maxSize / 2, 0); - } - - public FileLFUCache(final int maxSize, final int maxFileSize) { - this(maxSize, maxFileSize, 0); - } - - /** - * Creates new File LFU cache. - * @param maxSize total cache size in bytes - * @param maxFileSize max available file size in bytes, may be 0 - * @param timeout timeout, may be 0 - */ - public FileLFUCache(final int maxSize, final int maxFileSize, final long timeout) { - super(maxSize, maxFileSize, timeout); - } - - @Override - protected Cache createCache() { - return new LFUCache(0, timeout) { - @Override - public boolean isFull() { - return usedSize > FileLFUCache.this.maxSize; - } - - @Override - protected boolean isReallyFull(final File file) { - return isFull(); - } - - @Override - protected void onRemove(final File key, final byte[] cachedObject) { - usedSize -= cachedObject.length; - } - - @Override - protected CacheObject createCacheObject(File key, byte[] object, long timeout) { - return createFileCacheObject(key, object, timeout); - } - }; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileLRUCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileLRUCache.java deleted file mode 100644 index 464bdb2e4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/FileLRUCache.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package com.fr.third.jodd.cache; - -import java.io.File; - -/** - * Cache of recently used files. - */ -public class FileLRUCache extends FileCache { - - /** - * Creates file LRU cache with specified size. Sets - * {@link #maxFileSize max available file size} to half of this value. - */ - public FileLRUCache(final int maxSize) { - this(maxSize, maxSize / 2, 0); - } - - public FileLRUCache(final int maxSize, final int maxFileSize) { - this(maxSize, maxFileSize, 0); - } - - /** - * Creates new File LRU cache. - * @param maxSize total cache size in bytes - * @param maxFileSize max available file size in bytes, may be 0 - * @param timeout timeout, may be 0 - */ - public FileLRUCache(final int maxSize, final int maxFileSize, final long timeout) { - super(maxSize, maxFileSize, timeout); - } - - @Override - protected Cache createCache() { - return new LRUCache(0, timeout) { - @Override - public boolean isFull() { - return usedSize > FileLRUCache.this.maxSize; - } - - @Override - protected boolean isReallyFull(final File file) { - return isFull(); - } - - @Override - protected void onRemove(final File key, final byte[] cachedObject) { - usedSize -= cachedObject.length; - } - - @Override - protected CacheObject createCacheObject(File key, byte[] object, long timeout) { - return createFileCacheObject(key, object, timeout); - } - - }; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/LFUCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/LFUCache.java deleted file mode 100644 index 39ee90d72..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/LFUCache.java +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.HashMap; -import java.util.Iterator; - -/** - * LFU (least frequently used) cache. Frequency is calculated as access count. This cache - * is resistant on 'new usages scenario': when some object is removed from the cache, - * access count of all items in cache is decreased by access count of removed value. - * This allows new frequent elements to come into the cache. - *

- * Frequency of use data is kept on all items. The most frequently used items are kept in the cache. - * Because of the bookkeeping requirements, cache access overhead increases logarithmically with cache size. - * The advantage is that long term usage patterns are captured well, incidentally making the algorithm scan resistant; - * the disadvantage, besides the larger access overhead, is that the algorithm doesn't adapt quickly to changing - * usage patterns, and in particular doesn't help with temporally clustered accesses. - *

- * Summary for LFU: not fast, captures frequency of use, scan resistant. - */ -public class LFUCache extends AbstractCacheMap { - - public LFUCache(final int maxSize) { - this(maxSize, 0); - } - - public LFUCache(final int maxSize, final long timeout) { - this.cacheSize = maxSize; - this.timeout = timeout; - cacheMap = new HashMap<>(maxSize + 1); - } - - // ---------------------------------------------------------------- prune - - /** - * Prunes expired and, if cache is still full, the LFU element(s) from the cache. - * On LFU removal, access count is normalized to value which had removed object. - * Returns the number of removed objects. - */ - @Override - protected int pruneCache() { - int count = 0; - CacheObject comin = null; - - // remove expired items and find cached object with minimal access count - Iterator> values = cacheMap.values().iterator(); - while (values.hasNext()) { - CacheObject co = values.next(); - if (co.isExpired()) { - values.remove(); - onRemove(co.key, co.cachedObject); - count++; - continue; - } - - if (comin == null) { - comin = co; - } else { - if (co.accessCount < comin.accessCount) { - comin = co; - } - } - } - - if (!isFull()) { - return count; - } - - // decrease access count to all cached objects - if (comin != null) { - long minAccessCount = comin.accessCount; - - values = cacheMap.values().iterator(); - while (values.hasNext()) { - CacheObject co = values.next(); - co.accessCount -= minAccessCount; - if (co.accessCount <= 0) { - values.remove(); - onRemove(co.key, co.cachedObject); - count++; - } - } - } - return count; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/LRUCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/LRUCache.java deleted file mode 100644 index 87232a0e5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/LRUCache.java +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Iterator; - - -/** - * LRU (least recently used) cache. - * - *

- * Items are added to the cache as they are accessed; when the cache is full, the least recently used item is ejected. - * This type of cache is typically implemented as a linked list, so that an item in cache, when it is accessed again, - * can be moved back up to the head of the queue; items are ejected from the tail of the queue. Cache access overhead - * is again constant time. This algorithm is simple and fast, and it has a significant advantage over FIFO in being - * able to adapt somewhat to the data access pattern; frequently used items are less likely to be - * ejected from the cache. The main disadvantage is that it can still get filled up with items that are - * unlikely to be reaccessed soon; in particular, it can become useless in the face of scanning type accesses. - * Nonetheless, this is by far the most frequently used caching algorithm. - *

- * Implementation note: unfortunately, it was not possible to have onRemove callback method, - * since LinkedHashMap has its removal methods private. - *

- * Summary for LRU: fast, adaptive, not scan resistant. - */ -public class LRUCache extends AbstractCacheMap { - - public LRUCache(final int cacheSize) { - this(cacheSize, 0); - } - - /** - * Creates a new LRU cache. - */ - public LRUCache(final int cacheSize, final long timeout) { - this.cacheSize = cacheSize; - this.timeout = timeout; - cacheMap = new LinkedHashMap>(cacheSize + 1, 1.0f, true) { - @Override - protected boolean removeEldestEntry(final Map.Entry eldest) { - return LRUCache.this.removeEldestEntry(size()); - } - }; - } - - /** - * Removes the eldest entry if current cache size exceed cache size. - */ - protected boolean removeEldestEntry(final int currentSize) { - if (cacheSize == 0) { - return false; - } - return currentSize > cacheSize; - } - - // ---------------------------------------------------------------- prune - - /** - * Prune only expired objects, LinkedHashMap will take care of LRU if needed. - */ - @Override - protected int pruneCache() { - if (!isPruneExpiredActive()) { - return 0; - } - int count = 0; - Iterator> values = cacheMap.values().iterator(); - while (values.hasNext()) { - CacheObject co = values.next(); - if (co.isExpired()) { - values.remove(); - onRemove(co.key, co.cachedObject); - count++; - } - } - return count; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/NoCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/NoCache.java deleted file mode 100644 index b618a5366..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/NoCache.java +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.Collections; -import java.util.Map; - -/** - * Simple no-cache implementations of {@link Cache} for situation when cache - * needs to be quickly turned-off. - */ -public class NoCache implements Cache { - - @Override - public int limit() { - return 0; - } - - @Override - public long timeout() { - return 0; - } - - @Override - public void put(final K key, final V object) { - // ignore - } - - @Override - public void put(final K key, final V object, final long timeout) { - // ignore - } - - @Override - public V get(final K key) { - return null; - } - - @Override - public int prune() { - return 0; - } - - @Override - public boolean isFull() { - return true; - } - - @Override - public V remove(final K key) { - return null; - } - - @Override - public void clear() { - // ignore - } - - @Override - public int size() { - return 0; - } - - @Override - public boolean isEmpty() { - return true; - } - - @Override - public Map snapshot(final boolean peek) { - return Collections.emptyMap(); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/TimedCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/TimedCache.java deleted file mode 100644 index b861314b4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/TimedCache.java +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Timer; -import java.util.TimerTask; - -/** - * Timed cache. Not limited by size, objects are removed only when they are expired. - * Prune is not invoked explicitly by standard {@link Cache} methods, however, - * it is possible to schedule prunes on fined-rate delays. - */ -public class TimedCache extends AbstractCacheMap { - - public TimedCache(final long timeout) { - this.cacheSize = 0; - this.timeout = timeout; - cacheMap = new HashMap<>(); - } - - // ---------------------------------------------------------------- prune - - /** - * Prunes expired elements from the cache. Returns the number of removed objects. - */ - @Override - protected int pruneCache() { - int count = 0; - Iterator> values = cacheMap.values().iterator(); - while (values.hasNext()) { - CacheObject co = values.next(); - if (co.isExpired()) { - values.remove(); - count++; - } - } - return count; - } - - - // ---------------------------------------------------------------- auto prune - - protected Timer pruneTimer; - - /** - * Schedules prune. - */ - public void schedulePrune(final long delay) { - if (pruneTimer != null) { - pruneTimer.cancel(); - } - pruneTimer = new Timer(); - pruneTimer.schedule( - new TimerTask() { - @Override - public void run() { - prune(); - } - }, delay, delay - ); - } - - /** - * Cancels prune schedules. - */ - public void cancelPruneSchedule() { - if (pruneTimer != null) { - pruneTimer.cancel(); - pruneTimer = null; - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/TypeCache.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/TypeCache.java deleted file mode 100644 index bbda93a1c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/TypeCache.java +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cache; - -import java.util.AbstractMap; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Consumer; -import java.util.function.Function; - -/** - * Types cache. Provides several implementations depending on what you need to be addressed. - * There are two things you should take care off: - *

    - *
  • synchronization - especially on storing items. If not synchronized, one instance of an item may be put - * more then once into the map. This is usually fine, as it happens only during the initialization and makes not - * harm if something is created twice
  • - *
  • weak - if your key classes are replaced during the runtime, you should use weak map, in order to automatically - * remove obsolete keys.
  • - *
- */ -public class TypeCache { - - // ---------------------------------------------------------------- builder - - /** - * Creates a type cache by using a builder. - */ - public static Builder create() { - return new Builder<>(); - } - - /** - * Creates default implementation of the type cache. - */ - @SuppressWarnings("unchecked") - public static TypeCache createDefault() { - return TypeCache.create().get(); - } - - public static class Builder { - private boolean threadsafe; - private boolean weak; - private boolean none; - - /** - * No cache will be used. - * Setting other properties will not have any affect. - */ - public Builder noCache() { - none = true; - return this; - } - - /** - * Cache keys will be weak. - */ - public Builder weak(final boolean weak) { - this.weak = weak; - return this; - } - /** - * Cache will be thread-safe. - */ - public Builder threadsafe(final boolean threadsafe) { - this.threadsafe = threadsafe; - return this; - } - - /** - * Builds a type cache. - */ - public TypeCache get() { - final Map, A> map; - if (none) { - map = new AbstractMap, A>() { - @Override - public A put(final Class key, final A value) { - return null; - } - - @Override - public A get(final Object key) { - return null; - } - - @Override - public Set, A>> entrySet() { - return Collections.emptySet(); - } - }; - } - else if (weak) { - if (threadsafe) { - map = Collections.synchronizedMap(new WeakHashMap<>()); - } else { - map = new WeakHashMap<>(); - } - } else { - if (threadsafe) { - map = new ConcurrentHashMap<>(); - } else { - map = new IdentityHashMap<>(); - } - } - - return new TypeCache<>(map); - } - } - - // ---------------------------------------------------------------- map - - private final Map, T> map; - - private TypeCache(final Map, T> backedMap) { - this.map = backedMap; - } - - /** - * Add values to the map. - */ - public T put(final Class type, final T value) { - return map.put(type, value); - } - - /** - * Returns value from the map or {@code null} if value does not exist. - */ - public T get(final Class key) { - return map.get(key); - } - - /** - * Returns existing value or add default supplied one. - * Use this method instead of {@code get-nullcheck-put} block when - * thread-safety is of importance. - */ - @SuppressWarnings("unchecked") - public T get(final Class key, final Function, ? extends T> mappingFunction) { - return map.computeIfAbsent(key, aClass -> mappingFunction.apply((Class) aClass)); - } - - /** - * Removes element from the type cache. - */ - public T remove(final Class type) { - return map.remove(type); - } - - /** - * Clears complete cache. - */ - public void clear() { - map.clear(); - } - - /** - * Returns cache size. - */ - public int size() { - return map.size(); - } - - /** - * Returns {@code true} if cache is empty. - */ - public boolean isEmpty() { - return map.isEmpty(); - } - - /** - * Iterates all cached values. - */ - public void forEachValue(final Consumer valueConsumer) { - map.values().forEach(valueConsumer); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cache/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/cache/package-info.java deleted file mode 100644 index e7bc6351a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cache/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Some useful caches: LRU, LFU, FIFO. - */ -package com.fr.third.jodd.cache; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/chalk/Chalk.java b/fine-jodd/src/main/java/com/fr/third/jodd/chalk/Chalk.java deleted file mode 100644 index b6f7fad51..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/chalk/Chalk.java +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.chalk; - -import com.fr.third.jodd.util.StringPool; - -/** - * Chalk allows you to color output going to console. - * @see Chalk256 - */ -public class Chalk> { - - /** - * Global flag that disables all the chalks. - * Useful for windows platforms :) - */ - public static boolean enabled = true; - - protected static final String RESET = "0"; - - protected static final String BOLD = "1"; - protected static final String UNBOLD = "22"; // 21 isn't widely supported and 22 does the same thing - protected static final String DIM = "2"; - protected static final String UNDIM = "22"; - protected static final String ITALIC = "3"; - protected static final String UNITALIC = "23"; - protected static final String UNDERLINE = "4"; - protected static final String UNUNDERLINE = "24"; - protected static final String INVERSE = "7"; - protected static final String UNINVERSE = "27"; - protected static final String HIDDEN = "8"; - protected static final String UNHIDDEN = "28"; - protected static final String STRIKETHROUGH = "9"; - protected static final String UNSTRIKETHROUGH = "29"; - - protected static final String COLOR_RESET = "39"; - protected static final String BLACK = "30"; - protected static final String RED = "31"; - protected static final String GREEN = "32"; - protected static final String YELLOW = "33"; - protected static final String BLUE = "34"; - protected static final String MAGENTA = "35"; - protected static final String CYAN = "36"; - protected static final String WHITE = "37"; - protected static final String GRAY = "90"; - - protected static final String BGCOLOR_RESET = "49"; - protected static final String BGBLACK = "40"; - protected static final String BGRED = "41"; - protected static final String BGGREEN = "42"; - protected static final String BGYELLOW = "43"; - protected static final String BGBLUE = "44"; - protected static final String BGMAGENTA = "45"; - protected static final String BGCYAN = "46"; - protected static final String BGWHITE = "47"; - - protected StringBuilder prefix; - protected StringBuilder suffix; - protected String text; - - /** - * Creates new chalk. - */ - public static Chalk chalk() { - return new Chalk(); - } - - @SuppressWarnings("unchecked") - protected T _this() { - return (T) this; - } - - // ---------------------------------------------------------------- style - - public T bold() { - startSequence(BOLD); - endSequence(UNBOLD); - return _this(); - } - - public T italic() { - startSequence(ITALIC); - endSequence(UNITALIC); - return _this(); - } - - public T dim() { - startSequence(DIM); - endSequence(UNDIM); - return _this(); - } - - public T underline() { - startSequence(UNDERLINE); - endSequence(UNUNDERLINE); - return _this(); - } - - public T inverse() { - startSequence(INVERSE); - endSequence(UNINVERSE); - return _this(); - } - - public T hidden() { - startSequence(HIDDEN); - endSequence(UNHIDDEN); - return _this(); - } - public T strikeThrough() { - startSequence(STRIKETHROUGH); - endSequence(UNSTRIKETHROUGH); - return _this(); - } - - // ---------------------------------------------------------------- colors - - public T black() { - startSequence(BLACK); - endSequence(COLOR_RESET); - return _this(); - } - public T red() { - startSequence(RED); - endSequence(COLOR_RESET); - return _this(); - } - public T green() { - startSequence(GREEN); - endSequence(COLOR_RESET); - return _this(); - } - public T yellow() { - startSequence(YELLOW); - endSequence(COLOR_RESET); - return _this(); - } - public T blue() { - startSequence(BLUE); - endSequence(COLOR_RESET); - return _this(); - } - public T magenta() { - startSequence(MAGENTA); - endSequence(COLOR_RESET); - return _this(); - } - public T cyan() { - startSequence(CYAN); - endSequence(COLOR_RESET); - return _this(); - } - public T white() { - startSequence(WHITE); - endSequence(COLOR_RESET); - return _this(); - } - public T gray() { - startSequence(GRAY); - endSequence(COLOR_RESET); - return _this(); - } - public T grey() { - return gray(); - } - - // ---------------------------------------------------------------- bg colors - - public T bgBlack() { - startSequence(BGBLACK); - endSequence(BGCOLOR_RESET); - return _this(); - } - public T bgRed() { - startSequence(BGRED); - endSequence(BGCOLOR_RESET); - return _this(); - } - public T bgGreen() { - startSequence(BGGREEN); - endSequence(BGCOLOR_RESET); - return _this(); - } - public T bgYellow() { - startSequence(BGYELLOW); - endSequence(BGCOLOR_RESET); - return _this(); - } - public T bgBlue() { - startSequence(BGBLUE); - endSequence(BGCOLOR_RESET); - return _this(); - } - public T bgMagenta() { - startSequence(BGMAGENTA); - endSequence(BGCOLOR_RESET); - return _this(); - } - public T bgCyan() { - startSequence(BGCYAN); - endSequence(BGCOLOR_RESET); - return _this(); - } - public T bgWhite() { - startSequence(BGWHITE); - endSequence(BGCOLOR_RESET); - return _this(); - } - - // ---------------------------------------------------------------- internal - - protected void startSequence(final String value) { - if (prefix == null) { - prefix = new StringBuilder(); - prefix.append("\u001B["); - } - else { - prefix.append(StringPool.SEMICOLON); - } - - prefix.append(value); - } - - protected void endSequence(final String value) { - if (suffix == null) { - suffix = new StringBuilder(); - suffix - .append("\u001B[") - .append(value); - } - else { - suffix.insert(2, value + StringPool.SEMICOLON); - } - } - - // ---------------------------------------------------------------- out - - /** - * Returns chalked string. - */ - public String on(final String string) { - if (!enabled) { - return string; - } - - final StringBuilder sb = new StringBuilder(); - - if (prefix != null) { - sb.append(prefix).append("m"); - } - - sb.append(string); - - if (suffix != null) { - sb.append(suffix).append("m"); - } - - return sb.toString(); - } - - /** - * Prints chalked string to system output. - */ - public void print(final String string) { - System.out.print(on(string)); - } - - /** - * Prints chalked string to system output. - */ - public void println(final String string) { - System.out.println(on(string)); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/chalk/Chalk256.java b/fine-jodd/src/main/java/com/fr/third/jodd/chalk/Chalk256.java deleted file mode 100644 index 7dfe67dc6..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/chalk/Chalk256.java +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.chalk; - -/** - * Chalk256 allows you to color output going to ansi-256 console. - * @see Chalk - */ -public class Chalk256 extends Chalk { - - private static final String[] FG_CODES = new String[256]; - private static final String[] BG_CODES = new String[256]; - - static { - for (int i = 0; i < FG_CODES.length; i++) { - FG_CODES[i] = "38;5;" + i; - } - for (int i = 0; i < BG_CODES.length; i++) { - BG_CODES[i] = "48;5;" + i; - } - } - - public static Chalk256 chalk() { - return new Chalk256(); - } - - // ---------------------------------------------------------------- fg codes - - public Chalk256 standard(final int index) { - startSequence(FG_CODES[index(index, 0, 8)]); - endSequence(RESET); - return _this(); - } - public Chalk256 bright(final int index) { - startSequence(FG_CODES[index(index, 8, 16)]); - endSequence(RESET); - return _this(); - } - public Chalk256 rgb(final int index) { - startSequence(FG_CODES[index(index, 16, 232)]); - endSequence(RESET); - return _this(); - } - - /** - * Colors with red-green-blue value, in the range 0 to 6. - */ - public Chalk256 rgb(final int r, final int b, final int g) { - startSequence(FG_CODES[index(36*r + 6*g + b,16, 232)]); - endSequence(RESET); - return _this(); - } - public Chalk256 grayscale(final int index) { - startSequence(FG_CODES[index(index, 232, 256)]); - endSequence(RESET); - return _this(); - } - // ---------------------------------------------------------------- bg codes - - public Chalk256 bgStandard(final int index) { - startSequence(BG_CODES[index(index, 0, 8)]); - endSequence(RESET); - return _this(); - } - public Chalk256 bgBright(final int index) { - startSequence(BG_CODES[index(index, 8, 16)]); - endSequence(RESET); - return _this(); - } - public Chalk256 bgRgb(final int index) { - startSequence(BG_CODES[index(index, 16, 232)]); - endSequence(RESET); - return _this(); - } - - /** - * Colors with red-green-blue value, in the range 0 to 6. - */ - public Chalk256 bgRgb(final int r, final int b, final int g) { - startSequence(BG_CODES[index(36*r + 6*g + b,16, 232)]); - endSequence(RESET); - return _this(); - } - public Chalk256 bgGrayscale(final int index) { - startSequence(BG_CODES[index(index, 232, 256)]); - endSequence(RESET); - return _this(); - } - - // ---------------------------------------------------------------- bgcolors - - private int index(int index, final int from, final int to) { - index += from; - if ((index < from) || (index >= to)) { - throw new IllegalArgumentException("Color index not in range: [0, " + (to - from) + "]"); - } - return index; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/chalk/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/chalk/package-info.java deleted file mode 100644 index 4cb8d94b0..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/chalk/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Little tool for coloring the console output. - */ -package com.fr.third.jodd.chalk; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/cli/Cli.java b/fine-jodd/src/main/java/com/fr/third/jodd/cli/Cli.java deleted file mode 100644 index ade542bcb..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/cli/Cli.java +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.cli; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; - -public class Cli implements Consumer { - - private final List

- * More info: Julian Date on Wikipedia - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class JDateTime implements Comparable, Cloneable, Serializable { - - public static final String DEFAULT_FORMAT = "YYYY-MM-DD hh:mm:ss.mss"; - - // day of week names - public static final int MONDAY = 1; - public static final int TUESDAY = 2; - public static final int WEDNESDAY = 3; - public static final int THURSDAY = 4; - public static final int FRIDAY = 5; - public static final int SATURDAY = 6; - public static final int SUNDAY = 7; - - // month names - public static final int JANUARY = 1; - public static final int FEBRUARY = 2; - public static final int MARCH = 3; - public static final int APRIL = 4; - public static final int MAY = 5; - public static final int JUNE = 6; - public static final int JULY = 7; - public static final int AUGUST = 8; - public static final int SEPTEMBER = 9; - public static final int OCTOBER = 10; - public static final int NOVEMBER = 11; - public static final int DECEMBER = 12; - - /** - * {@link DateTimeStamp} for current date. - */ - protected DateTimeStamp time = new DateTimeStamp(); - - /** - * Day of week, range: [1-7] == [Monday - Sunday] - */ - protected int dayofweek; - - /** - * Day of year, range: [1-365] or [1-366] - */ - protected int dayofyear; - - /** - * Leap year flag. - */ - protected boolean leap; - - /** - * Week of year, range: [1-52] or [1-53] - */ - protected int weekofyear; - - /** - * Week of month. - */ - protected int weekofmonth; - - /** - * Current Julian Date. - */ - protected JulianDateStamp jdate; - - - // ---------------------------------------------------------------- some precalculated times - - /** - * Julian Date for 1970-01-01T00:00:00 (Thursday). - */ - public static final JulianDateStamp JD_1970 = new JulianDateStamp(2440587, 0.5); - - /** - * Julian Date for 2001-01-01T00:00:00 (Monday). - */ - public static final JulianDateStamp JD_2001 = new JulianDateStamp(2451910, 0.5); - - // ---------------------------------------------------------------- julian date (CORE) - - /** - * Returns current {@link DateTimeStamp}. - * Returned instance is still used internally (i.e. it is not cloned before returning). - */ - public DateTimeStamp getDateTimeStamp() { - return time; - } - - /** - * Loads current date time information. - */ - public JDateTime setDateTimeStamp(DateTimeStamp dts) { - return set(dts.year, dts.month, dts.day, dts.hour, dts.minute, dts.second, dts.millisecond); - } - - /** - * Sets current Julian Date. This is the core of the JDateTime class and it - * is used by all other classes. This method performs all calculations - * required for whole class. - * - * @param jds current julian date - */ - public JDateTime setJulianDate(JulianDateStamp jds) { - setJdOnly(jds.clone()); - calculateAdditionalData(); - return this; - } - - /** - * Returns {@link JulianDateStamp}. It is the same instance used internally. - */ - public JulianDateStamp getJulianDate() { - return jdate; - } - - /** - * Returns JDN. Note that JDN is not equal to integer part of julian date. It is calculated by - * rounding to the nearest integer. - */ - public int getJulianDayNumber() { - return jdate.getJulianDayNumber(); - } - - /** - * Internal method for calculating various data other then date/time. - */ - private void calculateAdditionalData() { - this.leap = TimeUtil.isLeapYear(time.year); - this.dayofweek = calcDayOfWeek(); - this.dayofyear = calcDayOfYear(); - this.weekofyear = calcWeekOfYear(firstDayOfWeek, mustHaveDayOfFirstWeek); - this.weekofmonth = calcWeekNumber(time.day, this.dayofweek); - } - - /** - * Internal method that just sets the time stamp and not all other additional - * parameters. Used for faster calculations only and only by main core - * set/add methods. - * - * @param jds julian date - */ - private void setJdOnly(JulianDateStamp jds) { - jdate = jds; - time = TimeUtil.fromJulianDate(jds); - } - - /** - * Core method that sets date and time. All others set() methods use this - * one. Milliseconds are truncated after 3rd digit. - * - * @param year year to set - * @param month month to set - * @param day day to set - * @param hour hour to set - * @param minute minute to set - * @param second second to set - */ - public JDateTime set(int year, int month, int day, int hour, int minute, int second, int millisecond) { - - // fix seconds fractions because of float point arithmetic - //second = ((int) second) + ((int) ((second - (int)second) * 1000 + 1e-9) / 1000.0); -/* - double ms = (second - (int)second) * 1000; - if (ms > 999) { - ms = 999; - } else { - ms += 1.0e-9; - } - second = ((int) second) + ((int) ms / 1000.0); -*/ - jdate = TimeUtil.toJulianDate(year, month, day, hour, minute, second, millisecond); - - // if given time is valid it means that there is no need to calculate it - // again from already calculated Julian date. however, it is still - // necessary to fix milliseconds to match the value that would be - // calculated as setJulianDate() is used. This fix only deals with the - // time, not doing the complete and more extensive date calculation. - // this means that method works faster when regular date is specified. -/* - if (TimeUtil.isValidDateTime(year, month, day, hour, minute, second, millisecond)) { - - int ka = (int)(jdate.fraction + 0.5); - double frac = jdate.fraction + 0.5 - ka + 1.0e-10; - - // hour with minute and second included as fraction - double d_hour = frac * 24.0; - - // minute with second included as a fraction - double d_minute = (d_hour - (int)d_hour) * 60.0; - - second = (d_minute - (int)d_minute) * 60.0; - - // fix calculation errors - second = ((int) (second * 10000) + 0.5) / 10000.0; - - time.year = year; time.month = month; time.day = day; - time.hour = hour; time.minute = minute; time.second = second; - setParams(); - } else { - setJulianDate(jdate); - } -*/ - if (TimeUtil.isValidDateTime(year, month, day, hour, minute, second, millisecond)) { - time.year = year; time.month = month; time.day = day; - time.hour = hour; time.minute = minute; time.second = second; - time.millisecond = millisecond; - calculateAdditionalData(); - } else { - setJulianDate(jdate); - } - - return this; - } - - /** - * Sets just Julian Date and no other parameter such as day of week etc. - * Used internally for speed. - * - * @param year year to set - * @param month month to set - * @param day day to set - * @param hour hour to set - * @param minute minute to set - * @param second second to set - */ - private void setJdOnly(int year, int month, int day, int hour, int minute, int second, int millisecond) { - setJdOnly(TimeUtil.toJulianDate(year, month, day, hour, minute, second, millisecond)); - } - - - // ---------------------------------------------------------------- core calculations - - /** - * Calculates day of week. - */ - private int calcDayOfWeek() { - int jd = (int)(jdate.doubleValue() + 0.5); - return (jd % 7) + 1; - //return (jd + 1) % 7; // return 0 (Sunday), 1 (Monday),... - } - - private static final int[] NUM_DAYS = {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; // 1-based - private static final int[] LEAP_NUM_DAYS = {-1, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}; // 1-based - - /** - * Calculates day of year. - */ - private int calcDayOfYear() { - if (leap) { - return LEAP_NUM_DAYS[time.month] + time.day; - } - return NUM_DAYS[time.month] + time.day; - } - - - /** - * Calculates week of year. Based on: - * "Algorithm for Converting Gregorian Dates to ISO 8601 Week Date" - * by Rick McCarty, 1999 - * - * @param start first day of week - * @param must must have day of week - * - * @return week of year number - */ - private int calcWeekOfYear(int start, int must) { - - // is modification required? - // modification is a fix for the days of year because of the different - // starting day of week. when modification is required, one week is added - // or subtracted to the current day, so calculation of the week of year - // would be correct. - int delta = 0; - if (start <= this.dayofweek) { - if (must < start) { - delta = 7; - } - } else { - if (must >= start) { - delta = -7; - } - } - - int jd = (int)(jdate.doubleValue() + 0.5) + delta; - int WeekDay = (jd % 7) + 1; - - int time_year = time.year; - int DayOfYearNumber = this.dayofyear + delta; - if (DayOfYearNumber < 1) { - time_year--; - DayOfYearNumber = TimeUtil.isLeapYear(time_year) ? 366 + DayOfYearNumber: 365 + DayOfYearNumber; - } else if (DayOfYearNumber > (this.leap ? 366 : 365)) { - DayOfYearNumber = this.leap ? DayOfYearNumber - 366: DayOfYearNumber - 365; - time_year++; - } - - // modification, if required, is finished. proceed to the calculation. - - int firstDay = jd - DayOfYearNumber + 1; - int Jan1WeekDay = (firstDay % 7) + 1; - - // find if the date falls in YearNumber Y - 1 set WeekNumber to 52 or 53 - int YearNumber = time_year; - int WeekNumber = 52; - if ((DayOfYearNumber <= (8 - Jan1WeekDay)) && (Jan1WeekDay > must)) { - YearNumber--; - if ((Jan1WeekDay == must + 1) || ( (Jan1WeekDay == must + 2) && (TimeUtil.isLeapYear(YearNumber)) ) ) { - WeekNumber = 53; - } - } - - // set WeekNumber to 1 to 53 if date falls in YearNumber - int m = 365; - if (YearNumber == time_year) { - if (TimeUtil.isLeapYear(time_year)) { - m = 366; - } - if ((m - DayOfYearNumber) < (must - WeekDay)) { - YearNumber = time_year + 1; - WeekNumber = 1; - } - } - - if (YearNumber == time_year) { - int n = DayOfYearNumber + (7 - WeekDay) + (Jan1WeekDay - 1); - WeekNumber = n / 7; - if (Jan1WeekDay > must) { - WeekNumber -= 1; - } - } - return WeekNumber; - } - - /** - * Return the week number of a day, within a period. This may be the week number in - * a year, or the week number in a month. Usually this will be a value >= 1, but if - * some initial days of the period are excluded from week 1, because - * minimalDaysInFirstWeek is > 1, then the week number will be zero for those - * initial days. Requires the day of week for the given date in order to determine - * the day of week of the first day of the period. - * - * @param dayOfPeriod - * Day-of-year or day-of-month. Should be 1 for first day of period. - * @param dayOfWeek day of week - * - * @return Week number, one-based, or zero if the day falls in part of the - * month before the first week, when there are days before the first - * week because the minimum days in the first week is more than one. - */ - private int calcWeekNumber(int dayOfPeriod, int dayOfWeek) { - // Determine the day of the week of the first day of the period - // in question (either a year or a month). Zero represents the - // first day of the week on this calendar. - int periodStartDayOfWeek = (dayOfWeek - firstDayOfWeek - dayOfPeriod + 1) % 7; - if (periodStartDayOfWeek < 0) { - periodStartDayOfWeek += 7; - } - - // Compute the week number. Initially, ignore the first week, which - // may be fractional (or may not be). We add periodStartDayOfWeek in - // order to fill out the first week, if it is fractional. - int weekNo = (dayOfPeriod + periodStartDayOfWeek - 1) / 7; - - // If the first week is long enough, then count it. If - // the minimal days in the first week is one, or if the period start - // is zero, we always increment weekNo. - if ((7 - periodStartDayOfWeek) >= minDaysInFirstWeek) { - ++weekNo; - } - - return weekNo; - } - - // ---------------------------------------------------------------- add/sub time - - /** - * Adds time to current time. The main add method - all other add() methods - * must use this one. - *

- * There are 2 different kinds of addings, when months are added: - *

    - *
  • when months are not specially concern. All remaining days will be - * added to the next month. Example: 2003-01-31 + 0-01-0 = 2003-03-03
  • - *
  • when months addition is fixed, and month is not approximated. - * example: 2003-01-31 + 0-01-0 = 2003-02-28
  • - *
- * - * @param year delta year - * @param month delta month - * @param day delta days - * @param hour delta hours - * @param minute delta minutes - * @param second delta seconds - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime add(int year, int month, int day, int hour, int minute, int second, int millisecond, boolean monthFix) { - int difference = 0; - if (trackDST) { - difference = TimeZoneUtil.getOffset(this, timezone); - } - addNoDST(year, month, day, hour, minute, second, millisecond, monthFix); - if (trackDST) { - difference = TimeZoneUtil.getOffset(this, timezone) - difference; - if (difference != 0) { - addNoDST(0, 0, 0, 0, 0, 0, difference, false); - } - } - - return this; - } - protected void addNoDST(int year, int month, int day, int hour, int minute, int second, int millisecond, boolean monthFix) { - millisecond += time.millisecond; - second += time.second; - minute += time.minute; - hour += time.hour; - day += time.day; - if (!monthFix) { - month += time.month; - year += time.year; - set(year, month, day, hour, minute, second, millisecond); - } else { - // month fix: - // 1. add all except month and year - // 2. store day value - // 3. add just months - // 4. if new date is not equal to stored, return to last day of previous month - setJdOnly(time.year, time.month, day, hour, minute, second, millisecond); - int from = time.day; - month += time.month + (year * 12); // delta years to add are converted to delta months - setJdOnly(time.year, month, time.day, time.hour, time.minute, time.second, time.millisecond); - if (time.day < from) { - set(time.year, time.month, 0, time.hour, time.minute, time.second, time.millisecond); - } else { - calculateAdditionalData(); - } - - /* - // 5. store month value - // 6. add just year - // 7. if new month is not equal to stored, return to last day of previous month - from = time.month; - year += time.year; - setJdOnly(year, time.month, time.day, time.hour, time.minute, time.second); - if (time.month > from) { - set(time.year, time.month, 0, time.hour, time.minute, time.second); - }*/ - } - } - - public JDateTime sub(int year, int month, int day, int hour, int minute, int second, int millisecond, boolean monthFix) { - return add(-year, -month, -day, -hour, -minute, -second, -millisecond, monthFix); - } - - - /** - * Performs time adding with preset value of monthFix attribute. - * - * @param year delta year - * @param month delta month - * @param day delta days - * @param hour delta hours - * @param minute delta minutes - * @param second delta seconds - * - * @see #add(int, int, int, int, int, int, int, boolean) - */ - public JDateTime add(int year, int month, int day, int hour, int minute, int second, int millisecond) { - return add(year, month, day, hour, minute, second, millisecond, monthFix); - } - public JDateTime sub(int year, int month, int day, int hour, int minute, int second, int millisecond) { - return add(-year, -month, -day, -hour, -minute, -second, millisecond, monthFix); - } - - - /** - * Adds date, leaving time unchanged. - * - * @param year years to add - * @param month months to add - * @param day days to add - * @param monthFix true for month fixing, false otherwise - * - * @see #add(int, int, int, int, int, int, int, boolean) - */ - public JDateTime add(int year, int month, int day, boolean monthFix) { - return add(year, month, day, 0, 0, 0, 0, monthFix); - } - public JDateTime sub(int year, int month, int day, boolean monthFix) { - return add(-year, -month, -day, 0, 0, 0, 0, monthFix); - } - - /** - * Adds date, leaving time unchanged, with preset value of monthFix. - * attribute. - * - * @param year years to add - * @param month months to add - * @param day days to add - * - * @see #add(int, int, int, boolean) - */ - public JDateTime add(int year, int month, int day) { - return add(year, month, day, monthFix); - } - public JDateTime sub(int year, int month, int day) { - return add(-year, -month, -day, monthFix); - } - - /** - * Adds time. - * - * @param hour hours to add - * @param minute minutes to add - * @param second seconds to add - * @param monthFix true for month fixing, false otherwise - * - * @see #add(int, int, int, int, int, int, int) - */ - public JDateTime addTime(int hour, int minute, int second, int millisecond, boolean monthFix) { - return add(0, 0, 0, hour, minute, second, millisecond, monthFix); - } - public JDateTime subTime(int hour, int minute, int second, int millisecond, boolean monthFix) { - return add(0, 0, 0, -hour, -minute, -second, -millisecond, monthFix); - } - - public JDateTime addTime(int hour, int minute, int second, boolean monthFix) { - return add(0, 0, 0, hour, minute, second, 0, monthFix); - } - public JDateTime subTime(int hour, int minute, int second, boolean monthFix) { - return add(0, 0, 0, -hour, -minute, -second, 0, monthFix); - } - - - /** - * Adds time, with preset value of monthFix. - * - * @param hour hours to add - * @param minute minutes to add - * @param second seconds to add - * - * @see #addTime(int, int, int, int, boolean) - */ - public JDateTime addTime(int hour, int minute, int second, int millisecond) { - return addTime(hour, minute, second, millisecond, monthFix); - } - public JDateTime subTime(int hour, int minute, int second, int millisecond) { - return addTime(-hour, -minute, -second, -millisecond, monthFix); - } - public JDateTime addTime(int hour, int minute, int second) { - return addTime(hour, minute, second, 0, monthFix); - } - public JDateTime subTime(int hour, int minute, int second) { - return addTime(-hour, -minute, -second, 0, monthFix); - } - - - /** - * Adds year. - * - * @param y year to add - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime addYear(int y, boolean monthFix) { - return add(y, 0, 0, monthFix); - } - public JDateTime subYear(int y, boolean monthFix) { - return add(-y, 0, 0, monthFix); - } - /** - * Adds year, with preset value of monthFix. - * - * @param y year to add - */ - public JDateTime addYear(int y) { - return addYear(y, monthFix); - } - public JDateTime subYear(int y) { - return addYear(-y, monthFix); - } - - - /** - * Adds month. - * - * @param m month to add - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime addMonth(int m, boolean monthFix) { - return add(0, m, 0, monthFix); - } - public JDateTime subMonth(int m, boolean monthFix) { - return add(0, -m, 0, monthFix); - } - /** - * Adds month, with preset value of monthFix. - * - * @param m month to add - */ - public JDateTime addMonth(int m) { - return addMonth(m, monthFix); - } - public JDateTime subMonth(int m) { - return addMonth(-m, monthFix); - } - - /** - * Adds days. - * - * @param d days to add - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime addDay(int d, boolean monthFix) { - return add(0, 0, d, monthFix); - } - public JDateTime subDay(int d, boolean monthFix) { - return add(0, 0, -d, monthFix); - } - /** - * Adds days, with preset value of monthFix. - * - * @param d days to add - */ - public JDateTime addDay(int d) { - return addDay(d, monthFix); - } - public JDateTime subDay(int d) { - return addDay(-d, monthFix); - } - - /** - * Adds hours. - * - * @param h hours to add - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime addHour(int h, boolean monthFix) { - return addTime(h, 0, 0, 0, monthFix); - } - public JDateTime subHour(int h, boolean monthFix) { - return addTime(-h, 0, 0, 0, monthFix); - } - /** - * Adds hours, with preset value of monthFix. - * - * @param h hours to add - */ - public JDateTime addHour(int h) { - return addHour(h, monthFix); - } - public JDateTime subHour(int h) { - return addHour(-h, monthFix); - } - - - /** - * Adds minutes. - * - * @param m minutes to add. - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime addMinute(int m, boolean monthFix) { - return addTime(0, m, 0, 0, monthFix); - } - public JDateTime subMinute(int m, boolean monthFix) { - return addTime(0, -m, 0, 0, monthFix); - } - /** - * Adds minutes, with preset value of monthFix. - * - * @param m minutes to add. - */ - public JDateTime addMinute(int m) { - return addMinute(m, monthFix); - } - public JDateTime subMinute(int m) { - return addMinute(-m, monthFix); - } - - /** - * Adds seconds. - * - * @param s seconds to add - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime addSecond(int s, boolean monthFix) { - return addTime(0, 0, s, 0, monthFix); - } - public JDateTime subSecond(int s, boolean monthFix) { - return addTime(0, 0, -s, 0, monthFix); - } - /** - * Adds seconds, with preset value of monthFix. - * - * @param s seconds to add - */ - public JDateTime addSecond(int s) { - return addSecond(s, monthFix); - } - public JDateTime subSecond(int s) { - return addSecond(-s, monthFix); - } - - - /** - * Adds milliseconds. - * - * @param ms milliseconds to add - * @param monthFix true for month fixing, false otherwise - */ - public JDateTime addMillisecond(int ms, boolean monthFix) { - return addTime(0, 0, 0, ms, monthFix); - } - public JDateTime subMillisecond(int ms, boolean monthFix) { - return addTime(0, 0, 0, -ms, monthFix); - } - /** - * Adds milliseconds, with preset value of monthFix. - * - * @param ms milliseconds to add - */ - public JDateTime addMillisecond(int ms) { - return addMillisecond(ms, monthFix); - } - public JDateTime subMillisecond(int ms) { - return addMillisecond(-ms, monthFix); - } - - // ---------------------------------------------------------------- ctors & sets - - /** - * Constructor that set date and time. - * - * @param year year to set - * @param month month to set - * @param day day to set - * @param hour hours to set - * @param minute minutes to set - * @param second seconds to set - * @param millisecond milliseconds to set - * - * @see #set(int, int, int, int, int, int, int) - */ - public JDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { - this.set(year, month, day, hour, minute, second, millisecond); - } - - /** - * Sets date, time is set to midnight (00:00:00.000). - * - * @param year year to set - * @param month month to set - * @param day day to set - */ - public JDateTime set(int year, int month, int day) { - return set(year, month, day, 0, 0, 0, 0); - } - - /** - * Constructor that sets just date. Time is set to 00:00:00. - * - * @param year year to set - * @param month month to set - * @param day day to set - * - * @see #set(int, int, int) - */ - public JDateTime(int year, int month, int day) { - this.set(year, month, day); - } - - /** - * Sets time, date is unchanged. - * - * @param hour hours to set - * @param minute minutes to set - * @param second seconds to set - */ - public JDateTime setTime(int hour, int minute, int second, int millisecond) { - return set(time.year, time.month, time.day, hour, minute, second, millisecond); - } - - /** - * Sets date, time remains unchanged. - * - * @param year year - * @param month month - * @param day day - */ - public JDateTime setDate(int year, int month, int day) { - return set(year, month, day, time.hour, time.minute, time.second, time.millisecond); - } - - - // ---------------------------------------------------------------- milliseconds - - /** - * Constructor that sets current time specified as time in milliseconds, from - * the midnight, January 1, 1970 UTC. - * - * @param millis time in milliseconds, from the midnight, January 1, 1970 UTC - * - * @see #setTimeInMillis(long ) - */ - public JDateTime(long millis) { - setTimeInMillis(millis); - } - - /** - * Sets the time based on current time in milliseconds. Current time is - * calculated from the midnight, January 1, 1970 UTC. - *

- * Calculation is divided in two steps, due to precision issues. - * - * @param millis time in milliseconds, from the midnight, January 1, 1970 UTC - */ - public JDateTime setTimeInMillis(long millis) { - millis += timezone.getOffset(millis); - int integer = (int) (millis / TimeUtil.MILLIS_IN_DAY); - double fraction = (double)(millis % TimeUtil.MILLIS_IN_DAY) / TimeUtil.MILLIS_IN_DAY; - integer += JD_1970.integer; - fraction += JD_1970.fraction; - return setJulianDate(new JulianDateStamp(integer, fraction)); - } - - /** - * Returns time based on current time in milliseconds. Current time is - * calculated from the midnight, January 1, 1970 UTC. - *

- * Due to possible huge values calculation is divided in two steps: - * first for fractional difference, and then for integer parts. - * - * @return time in milliseconds, from the midnight, January 1, 1970 UTC - */ - public long getTimeInMillis() { - double then = (jdate.fraction - JD_1970.fraction) * TimeUtil.MILLIS_IN_DAY; - then += (jdate.integer - JD_1970.integer) * TimeUtil.MILLIS_IN_DAY; - then -= timezone.getOffset((long) then); - then += then > 0 ? 1.0e-6 : -1.0e-6; - return (long) then; - } - - - // ---------------------------------------------------------------- date/time sets - - /** - * Sets current year. - * - * @param y year to set - */ - public JDateTime setYear(int y) { - return setDate(y, time.month, time.day); - } - - /** - * Sets current month. - * - * @param m month to set - */ - public JDateTime setMonth(int m) { - return setDate(time.year, m, time.day); - } - - /** - * Sets current day of month. - * - * @param d day to set - */ - public JDateTime setDay(int d) { - return setDate(time.year, time.month, d); - } - - /** - * Set current hour. - * - * @param h hour to set - */ - public JDateTime setHour(int h) { - return setTime(h, time.minute, time.second, time.millisecond); - } - - /** - * Set current minute. - * - * @param m minutes to set - */ - public JDateTime setMinute(int m) { - return setTime(time.hour, m, time.second, time.millisecond); - - } - - /** - * Sets current second. - * - * @param s seconds and milliseconds to set - */ - public JDateTime setSecond(int s) { - return setTime(time.hour, time.minute, s, time.millisecond); - } - - public JDateTime setSecond(int s, int m) { - return setTime(time.hour, time.minute, s, m); - } - - - /** - * Sets current millisecond. - * - * @param m milliseconds to set - */ - public JDateTime setMillisecond(int m) { - return setTime(time.hour, time.minute, time.second, m); - } - - - // ---------------------------------------------------------------- date/time gets - - - /** - * Returns current year. - */ - public int getYear() { - return time.year; - } - - /** - * Returns current month. - */ - public int getMonth() { - return time.month; - } - - /** - * Returns current day of month. - * @see #getDayOfMonth - */ - public int getDay() { - return time.day; - } - - /** - * Returns current day of month. - * @see #getDay - */ - public int getDayOfMonth() { - return time.day; - } - - /** - * Returns current hour. - */ - public int getHour() { - return time.hour; - } - - /** - * Returns current minutes. - */ - public int getMinute() { - return time.minute; - } - - /** - * Return current seconds. For an integer value, just cast the returned - * value. - */ - public int getSecond() { - return time.second; - } - - /** - * Returns current milliseconds. - */ - public int getMillisecond() { - return time.millisecond; - } - - // ---------------------------------------------------------------- other gets - - /** - * Returns current day of week. - */ - public int getDayOfWeek() { - return dayofweek; - } - - /** - * Returns current day of year. - */ - public int getDayOfYear() { - return dayofyear; - } - - /** - * Returns true if current year is leap year. - */ - public boolean isLeapYear() { - return leap; - } - - /** - * Returns current week of year. - */ - public int getWeekOfYear() { - return weekofyear; - } - - /** - * Returns current week of month. - */ - public int getWeekOfMonth() { - return weekofmonth; - } - - - /** - * Returns the length of the specified month in days. - */ - public int getMonthLength(int month) { - return TimeUtil.getMonthLength(time.year, month, this.leap); - } - - /** - * Returns the length of the current month in days. - */ - public int getMonthLength() { - return getMonthLength(time.month); - } - - /** - * Returns era: AD(1) or BC(0). - */ - public int getEra() { - return time.year > 0 ? 1 : 0; - } - - /** - * Calculates the number of milliseconds of a day. - */ - public int getMillisOfDay() { - return ((((time.hour * 60) + time.minute) * 60) + time.second) * 1000 + time.millisecond; - } - - // ---------------------------------------------------------------- current date time - - /** - * Sets current local date and time. - */ - public JDateTime setCurrentTime() { - return setTimeInMillis(System.currentTimeMillis()); - } - - /** - * Constructor that sets current local date and time. - */ - public JDateTime() { - this.setCurrentTime(); - } - - // ---------------------------------------------------------------- conversion - - /** - * Creates JDateTime from Calendar. - */ - public JDateTime(Calendar calendar) { - setDateTime(calendar); - } - - /** - * Sets current date and time from Calendar. - */ - public JDateTime setDateTime(Calendar calendar) { - setTimeInMillis(calendar.getTimeInMillis()); - changeTimeZone(calendar.getTimeZone()); - return this; - } - - /** - * Creates JDateTime from Date. - */ - public JDateTime(Date date) { - setDateTime(date); - } - - /** - * Sets current date and time from Date. - */ - public JDateTime setDateTime(Date date) { - return setTimeInMillis(date.getTime()); - } - - /** - * Converts to Date instance. - */ - public Date convertToDate() { - return new Date(getTimeInMillis()); - } - - /** - * Converts to Calendar instance. - */ - public Calendar convertToCalendar() { - Calendar calendar = Calendar.getInstance(getTimeZone()); - calendar.setTimeInMillis(getTimeInMillis()); - return calendar; - } - - /** - * Converts to java.sql.Date instance. - */ - public java.sql.Date convertToSqlDate() { - return new java.sql.Date(getTimeInMillis()); - } - - /** - * Converts to Time instance. - */ - public Time convertToSqlTime() { - return new Time(getTimeInMillis()); - } - - /** - * Converts to Timestamp instance. - */ - public Timestamp convertToSqlTimestamp() { - return new Timestamp(getTimeInMillis()); - } - - // ---------------------------------------------------------------- ctors from conversions - - /** - * Creates JDateTime from DateTimeStamp. - */ - public JDateTime(DateTimeStamp dts) { - setDateTimeStamp(dts); - } - - - /** - * Creates JDateTime from JulianDateStamp. - */ - public JDateTime(JulianDateStamp jds) { - setJulianDate(jds); - } - - /** - * Creates JDateTime from double that represents JD. - */ - public JDateTime(double jd) { - setJulianDate(new JulianDateStamp(jd)); - } - - /** - * Creates JDateTime from a string. - */ - public JDateTime(String src) { - parse(src); - } - - /** - * Creates JDateTime from a string, using specified template. - */ - public JDateTime(String src, String template) { - parse(src, template); - } - - public JDateTime(String src, JdtFormat jdtFormat) { - parse(src, jdtFormat); - } - - - // ---------------------------------------------------------------- dst - - protected boolean trackDST = JDateTimeDefault.trackDST; - - public boolean isTrackDST() { - return trackDST; - } - - public JDateTime setTrackDST(boolean trackDST) { - this.trackDST = trackDST; - return this; - } - - // ---------------------------------------------------------------- monthFix - - protected boolean monthFix = JDateTimeDefault.monthFix; - - /** - * Returns true if month fix is active. - */ - public boolean isMonthFix() { - return monthFix; - } - - /** - * Sets custom month fix value. - */ - public JDateTime setMonthFix(boolean monthFix) { - this.monthFix = monthFix; - return this; - } - - - // ---------------------------------------------------------------- timezone - - protected TimeZone timezone = JDateTimeDefault.timeZone == null ? TimeZone.getDefault() : JDateTimeDefault.timeZone; - - /** - * Changes current timezone. Current time is changed if time zone has been changed. - */ - public JDateTime changeTimeZone(TimeZone timezone) { - long now = getTimeInMillis(); - int difference = TimeZoneUtil.getOffsetDifference(now, this.timezone, timezone); - this.timezone = timezone; - if (difference != 0) { - addMillisecond(difference); - } - return this; - } - - /** - * Changes time zone. Equivalent to: - * setTimeZone(from); changeTimeZone(to); - */ - public JDateTime changeTimeZone(TimeZone from, TimeZone to) { - this.timezone = from; - changeTimeZone(to); - return this; - } - - /** - * Sets time zone without changing the time. - */ - public JDateTime setTimeZone(TimeZone timezone) { - this.timezone = timezone; - return this; - } - - /** - * Return currently active time zone. - */ - public TimeZone getTimeZone() { - return timezone; - } - - /** - * Returns true if current date is in - * daylight savings time in the time zone. - */ - public boolean isInDaylightTime() { - long now = getTimeInMillis(); - int offset = timezone.getOffset(now); - int rawOffset = timezone.getRawOffset(); - return (offset != rawOffset); - } - - // ---------------------------------------------------------------- locale - - protected Locale locale = JDateTimeDefault.locale == null ? Locale.getDefault() : JDateTimeDefault.locale; - - /** - * Sets custom locale. - */ - public JDateTime setLocale(Locale locale) { - this.locale = locale; - return this; - } - - /** - * Return currently active locale. - */ - public Locale getLocale() { - return locale; - } - - // ---------------------------------------------------------------- format - - protected String format = JDateTimeDefault.format; - - /** - * Defines default format. - */ - public JDateTime setFormat(String format) { - this.format = format; - return this; - } - - /** - * Returns format. - */ - public String getFormat() { - return format; - } - - - protected JdtFormatter jdtFormatter = JDateTimeDefault.formatter; - - /** - * Defines custom formatter. - */ - public JDateTime setJdtFormatter(JdtFormatter jdtFormatter) { - this.jdtFormatter = jdtFormatter; - return this; - } - - /** - * Returns actual {@link JdtFormatter}. - */ - public JdtFormatter getJdtFormatter() { - return jdtFormatter; - } - - /** - * Sets both format and formatter from provided {@link JdtFormat}. - */ - public JDateTime setJdtFormat(JdtFormat jdtFormat) { - this.format = jdtFormat.getFormat(); - this.jdtFormatter = jdtFormat.getFormatter(); - return this; - } - - - // ---------------------------------------------------------------- toString and parse - - - /** - * Returns string representation of date/time in specified format. - */ - public String toString(String format) { - return jdtFormatter.convert(this, format); - } - - /** - * Returns spring representation of current date/time in currently active format. - * @see #getFormat() - */ - @Override - public String toString() { - return jdtFormatter.convert(this, format); - } - - public String toString(JdtFormat jdtFormat) { - return jdtFormat.convert(this); - } - - /** - * Sets date/time from a string given in provided template. - * @param src string containing date time information - * @param format format template - */ - public void parse(String src, String format) { - setDateTimeStamp(jdtFormatter.parse(src, format)); - } - - /** - * Sets date/time from a string and currently active template. - * @param src string containing date time information - * @see #getFormat() - */ - public void parse(String src) { - setDateTimeStamp(jdtFormatter.parse(src, format)); - } - - public void parse(String src, JdtFormat jdtFormat) { - setDateTimeStamp(jdtFormat.parse(src)); - } - - /** - * Checks if some string represents a valid date using actual template. - * - * @return true if date is valid, otherwise false - */ - public boolean isValid(String s) { - return isValid(s, format); - } - - /** - * Checks if some string represents a valid date using provided template. - * - * @return true if date is valid, otherwise false - */ - public boolean isValid(String s, String template) { - DateTimeStamp dtsOriginal; - try { - dtsOriginal = jdtFormatter.parse(s, template); - } catch (Exception ignore) { - return false; - } - if (dtsOriginal == null) { - return false; - } - return TimeUtil.isValidDateTime(dtsOriginal); - } - - - // ---------------------------------------------------------------- week definitions - - protected int firstDayOfWeek = JDateTimeDefault.firstDayOfWeek; - protected int mustHaveDayOfFirstWeek = JDateTimeDefault.mustHaveDayOfFirstWeek; - - /** - * Defines week definitions. - * - * @param start first day in week, [1-7], - * @param must must have day of the 1st week, [1-7] - */ - public JDateTime setWeekDefinition(int start, int must) { - if ((start >= 1) && (start <= 7)) { - firstDayOfWeek = start; - } - if ((must >= 1) && (must <= 7)) { - mustHaveDayOfFirstWeek = must; - minDaysInFirstWeek = convertMin2Must(firstDayOfWeek, must); - } - return this; - } - - /** - * Returns actual the first day of the week. - */ - public int getFirstDayOfWeek() { - return firstDayOfWeek; - } - - /** - * Returns actual must have day of the 1st week. - */ - public int getMustHaveDayOfFirstWeek() { - return mustHaveDayOfFirstWeek; - } - - - // ---------------------------------------------------------------- week definitions (alt) - - protected int minDaysInFirstWeek = JDateTimeDefault.minDaysInFirstWeek; - - /** - * Returns actual minimal number of days of the first week. It is - * calculated from must have day of the first week. - * - * @return minimal number of days of the first week - */ - public int getMinDaysInFirstWeek() { - return minDaysInFirstWeek; - } - - /** - * Defines week alternatively. - * - * @param start first day in week - * @param min minimal days of week - */ - - public JDateTime setWeekDefinitionAlt(int start, int min) { - if ((start >= 1) && (start <= 7)) { - firstDayOfWeek = start; - } - if ((min >= 1) && (min <= 7)) { - mustHaveDayOfFirstWeek = convertMin2Must(firstDayOfWeek, min); - minDaysInFirstWeek = min; - } - return this; - } - - /** - * Converts minimal day of week to must have day of week. - * Method is symmetrical. - * - * @param start first day of week - * @param min minimal day of week - * - * @return must have day of week - */ - private static int convertMin2Must(int start, int min) { - int must = 8 - min + (start - 1); - if (must > 7) { - must -= 7; - } - return must; - } - - // ---------------------------------------------------------------- equals & hashCode - - /** - * Compares if two JDateTime instances are equal. - * Comparison precision is 1e-3 seconds. - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (this.getClass() != obj.getClass()) { - return false; - } - JDateTime jdt = (JDateTime) obj; - return (this.monthFix == jdt.monthFix) && - (this.firstDayOfWeek == jdt.firstDayOfWeek) && - (this.mustHaveDayOfFirstWeek == jdt.mustHaveDayOfFirstWeek) && - (this.time.equals(jdt.time)) && - (this.timezone.equals(jdt.timezone)); - } - - @Override - public int hashCode() { - int result = HashCode.SEED; - result = hash(result, time); - result = hash(result, timezone); - result = hash(result, monthFix); - result = hash(result, firstDayOfWeek); - result = hash(result, mustHaveDayOfFirstWeek); - return result; - } - - - // ---------------------------------------------------------------- clone - - @Override - public JDateTime clone() { - JDateTime jdt = new JDateTime(this.jdate); - jdt.monthFix = this.monthFix; - jdt.timezone = this.timezone; - jdt.locale = this.locale; - jdt.format = this.format; - jdt.jdtFormatter = this.jdtFormatter; - jdt.firstDayOfWeek = this.firstDayOfWeek; - jdt.mustHaveDayOfFirstWeek = this.mustHaveDayOfFirstWeek; - jdt.trackDST = this.trackDST; - return jdt; - } - - - // ---------------------------------------------------------------- compare - - /** - * Compares current JDateTime object with another one, up to 1 millisecond. - * - * @param o JDateTime to compare - * - * @return -1 if the current object is less than the argument, 0 if the argument is - * equal, and 1 if the current object is greater than the argument - */ - public int compareTo(Object o) { - return time.compareTo(((JDateTime) o).getDateTimeStamp()); - } - public int compareTo(JDateTime jd) { - return time.compareTo(jd.getDateTimeStamp()); - } - - /** - * Compares current JDateTime date with another date. Time component is ignored. - */ - public int compareDateTo(JDateTime jd) { - return time.compareDateTo(jd.getDateTimeStamp()); - } - - /** - * Returns true if current time is after then provided time. - */ - public boolean isAfter(JDateTime then) { - return time.compareTo((then).getDateTimeStamp()) > 0; - } - /** - * Returns true if current time is before then provided time. - */ - public boolean isBefore(JDateTime then) { - return time.compareTo((then).getDateTimeStamp()) < 0; - } - - /** - * Returns true if current date is after then provided date. - * Time component is ignored. - */ - public boolean isAfterDate(JDateTime then) { - return time.compareDateTo((then).getDateTimeStamp()) > 0; - } - /** - * Returns true if current date is before then provided date. - * Time component is ignored. - */ - public boolean isBeforeDate(JDateTime then) { - return time.compareDateTo((then).getDateTimeStamp()) < 0; - } - - - // ---------------------------------------------------------------- difference - - /** - * Returns number of full days between two dates. - */ - public int daysBetween(JDateTime then) { - return this.jdate.daysBetween(then.jdate); - } - - /** - * Returns number of full days between two dates. - */ - public int daysBetween(JulianDateStamp then) { - return this.jdate.daysBetween(then); - } - - - // ---------------------------------------------------------------- alternative representation - - - /** - * Returns JD as double value. - */ - public double getJulianDateDouble() { - return jdate.doubleValue(); - } - - /** - * Sets JD. - */ - public JDateTime setJulianDate(double jd) { - return setJulianDate(new JulianDateStamp(jd)); - } - - // ---------------------------------------------------------------- custom equals - - /** - * Returns true if provided date is equal to current one. - * May be used for date validation test. - */ - public boolean equalsDate(int year, int month, int day) { - return (time.year == year) && (time.month == month) && (time.day == day); - } - - /** - * Returns true if two dates are equal. - * Time component is ignored. - */ - public boolean equalsDate(JDateTime date) { - return time.isEqualDate(date.time); - } - - /** - * Returns true if two times are equal. - * Date component is ignored. - */ - public boolean equalsTime(JDateTime date) { - return time.isEqualTime(date.time); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JDateTimeDefault.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JDateTimeDefault.java deleted file mode 100644 index e9646f16c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JDateTimeDefault.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime; - -import com.fr.third.jodd.datetime.format.Iso8601JdtFormatter; -import com.fr.third.jodd.datetime.format.JdtFormatter; - -import java.util.TimeZone; -import java.util.Locale; - -/** - * Defaults for {@link JDateTime}. - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -@SuppressWarnings({"RedundantFieldInitialization"}) -public class JDateTimeDefault { - - /** - * Default value for month fix. - */ - public static boolean monthFix = true; - - /** - * Default time zone. Set it to null - * for system default timezone. - */ - public static TimeZone timeZone = null; // system default - - /** - * Default locale for date names. Set it to null - * for system default locale. - */ - public static Locale locale = null; // system default - - /** - * Default format template. - */ - public static String format = JDateTime.DEFAULT_FORMAT; - - /** - * Default formatter. - */ - public static JdtFormatter formatter = new Iso8601JdtFormatter(); - - /** - * Default definition of first day of week. - */ - public static int firstDayOfWeek = JDateTime.MONDAY; - - /** - * Default number of days first week of year must have. - */ - public static int mustHaveDayOfFirstWeek = 4; - - /** - * Default minimal number of days firs week of year must have. - */ - public static int minDaysInFirstWeek = 4; - - /** - * Default value for tracking DST. - */ - public static boolean trackDST = false; -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JStopWatch.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JStopWatch.java deleted file mode 100644 index daf047fb9..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JStopWatch.java +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime; - -import java.util.List; -import java.util.ArrayList; - -/** - * Nice thread-aware stopwatch that supports time spans, cumulative times and laps. - * Useful for all kind of profiling, time measurements etc. - * - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class JStopWatch { - - /** - * Optional stopwatch name. - */ - protected String name; - /** - * Last start time. - */ - protected long startTime; - /** - * Last stop time. - */ - protected long stopTime; - /** - * Last elapsed time. - */ - protected long spanTime; - /** - * Cumulative elapsed time. - */ - protected long totalTime; - /** - * Running flag. - */ - protected boolean running; - - // ---------------------------------------------------------------- ctors - - /** - * Starts the stopwatch. - */ - public JStopWatch() { - this("#jStopWatch"); - } - - /** - * Starts the named stopwatch. - */ - public JStopWatch(String name) { - this.name = name; - start(); - } - - /** - * Returns stopwatch name. - */ - public String getName() { - return name; - } - - /** - * Returns true if stopwatch is running. - */ - public boolean isRunning() { - return running; - } - - // ---------------------------------------------------------------- basic - - /** - * Starts the stopwatch. {@link #stop()} must be called prior to restart. - * Returns starting time in milliseconds. - */ - public long start() { - if (!running) { - startTime = System.currentTimeMillis(); - running = true; - } - return startTime; - } - - /** - * Restarts the stopwatch. - */ - public long restart() { - startTime = System.currentTimeMillis(); - running = true; - return startTime; - } - - /** - * Stops the stopwatch if running. Returns span time. - * If laps are used, marks the last lap. - */ - public long stop() { - if (running) { - stopTime = System.currentTimeMillis(); - if (laps != null) { - lap(stopTime); - } - spanTime = stopTime - startTime; - totalTime += stopTime - startTime; - running = false; - } - return spanTime; - } - - /** - * Returns total elapsed time from the {@link #start()} in ms. - */ - public long elapsed() { - return System.currentTimeMillis() - startTime; - } - - /** - * Stops the stopwatch and returns total cumulative time in ms. - */ - public long total() { - stop(); - return totalTime; - } - - /** - * Stops the stopwatch and returns total time span for last - * start-stop sequence. - */ - public long span() { - stop(); - return spanTime; - } - - - // ---------------------------------------------------------------- laps - - /** - * List of all laps. Contains long arrays in following format: - *

    - *
  • lap time - current lap time,
  • - *
  • lap span time - elapsed time from start,
  • - *
  • lap millis - lap milliseconds. - *
- */ - protected List laps; - - /** - * Marks a lap and returns its length. May be called only while stop watch is running. - */ - public long lap() { - return lap(System.currentTimeMillis()); - } - - protected long lap(long lap) { - if (!running) { - return 0; - } - long lapSpanTime = lap - startTime; - long lapTime; - if (laps == null) { - lapTime = lapSpanTime; - laps = new ArrayList(); - } else { - long[] previous = laps.get(laps.size() - 1); - lapTime = lap - previous[2]; - } - laps.add(new long[] {lapTime, lapSpanTime, lap}); - return lapTime; - } - - /** - * Returns the total number of laps up to this moment. - */ - public int totalLaps() { - if (laps == null) { - return 0; - } - return laps.size(); - } - - /** - * Returns lap times for 1-based lap index. - * Returns null if laps are not used or if index is invalid. - */ - public long[] getLapTimes(int index) { - if (laps == null) { - return null; - } - if ((index <= 0) || (index > laps.size())) { - return null; - } - return laps.get(index - 1); - } - - // ---------------------------------------------------------------- output - - /** - * Returns total elapsed time as formatted string from the last start. - */ - @Override - public String toString() { - long elapsed = elapsed(); - StringBuilder sb = new StringBuilder(); - sb.append("JStopWatch ").append(name).append(running ? " is running." : "").append('\n'); - if (running) { - sb.append("elapsed: ").append(formatTimeSpan(elapsed)); - } else { - if (spanTime != totalTime) { - sb.append("span: ").append(formatTimeSpan(spanTime)).append('\n'); - } - sb.append("\ntotal: ").append(formatTimeSpan(totalTime)); - } - if (laps != null) { - if (!laps.isEmpty()) { - sb.append('\n'); - sb.append("\n\t\t\tlap\t\telapsed\n"); - } - for (int i = 0; i < laps.size(); i++) { - long[] longs = laps.get(i); - sb.append(" lap #").append(i + 1).append(':').append('\t'); - sb.append(formatTimeSpan(longs[0])).append('\t'); - sb.append(formatTimeSpan(longs[1])).append('\n'); - } - } - return sb.toString(); - } - - /** - * Formats time spans. - */ - public static String formatTimeSpan(long millis) { - long seconds = 0; - long minutes = 0; - long hours = 0; - - if (millis > 1000) { - seconds = millis / 1000; - millis %= 1000; - } - if (seconds > 60) { - minutes = seconds / 60; - seconds %= 60; - } - if (minutes > 60) { - hours = minutes / 60; - minutes %= 60; - } - - StringBuilder result = new StringBuilder(20); - boolean out = false; - if (hours > 0) { - result.append(hours).append(':'); - out = true; - } - if (out || (minutes > 0)) { - if (minutes < 10) { - result.append('0'); - } - result.append(minutes).append(':'); - } - - if (seconds < 10) { - result.append('0'); - } - result.append(seconds).append('.'); - - if (millis < 10) { - result.append('0'); - } - if (millis < 100) { - result.append('0'); - } - result.append(millis); - return result.toString(); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JulianDateStamp.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JulianDateStamp.java deleted file mode 100644 index e42977955..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/JulianDateStamp.java +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime; - -import com.fr.third.jodd.util.HashCode; -import static com.fr.third.jodd.util.HashCode.hash; - -import java.math.BigDecimal; -import java.io.Serializable; - -/** - * Julian Date stamp, for high precision calculations. Julian date is a real - * number and it basically consist of two parts: integer and fraction. Integer - * part carries date information, fraction carries time information. - * - *

- * The Julian day or Julian day number (JDN) is the (integer) number of days that - * have elapsed since Monday, January 1, 4713 BC in the proleptic Julian calendar 1. - * That day is counted as Julian day zero. Thus the multiples of 7 are Mondays. - * Negative values can also be used. - * - *

- * The Julian Date (JD) is the number of days (with decimal fraction of the day) that - * have elapsed since 12 noon Greenwich Mean Time (UT or TT) of that day. - * Rounding to the nearest integer gives the Julian day number. - *

- * For calculations that will have time precision of 1e-3 seconds, both - * fraction and integer part must have enough digits in it. The problem is - * that integer part is big and, on the other hand fractional is small, and - * since final julian date is a sum of this two values, some fraction - * numerals may be lost. Therefore, for higher precision both - * fractional and integer part of julian date real number has to be - * preserved. - *

- * This class stores the unmodified fraction part, but not all digits - * are significant! For 1e-3 seconds precision, only 8 digits after - * the decimal point are significant. - * - * @see TimeUtil - * @see JDateTime - * @see DateTimeStamp - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class JulianDateStamp implements Serializable, Cloneable { - - /** - * Integer part of the Julian Date (JD). - */ - protected int integer; - - /** - * Returns integer part of the Julian Date (JD). - */ - public int getInteger() { - return integer; - } - - /** - * Fraction part of the Julian Date (JD). - * Should be always in [0.0, 1.0) range. - */ - protected double fraction; - - /** - * Returns the fraction part of Julian Date (JD). - * Returned value is always in [0.0, 1.0) range. - */ - public double getFraction() { - return fraction; - } - - /** - * Calculates and returns significant fraction only as an int. - */ - public int getSignificantFraction() { - return (int) (fraction * 100000000); - } - - /** - * Returns JDN. Note that JDN is not equal to {@link #integer}. It is calculated by - * rounding to the nearest integer. - */ - public int getJulianDayNumber() { - if (fraction >= 0.5) { - return integer + 1; - } - return integer; - } - - // ---------------------------------------------------------------- ctors - - /** - * Default empty constructor. - */ - public JulianDateStamp() { - } - - /** - * Creates JD from a double. - */ - public JulianDateStamp(double jd) { - set(jd); - } - - /** - * Creates JD from both integer and fractional part using normalization. - * Normalization occurs when fractional part is out of range. - * - * @see #set(int, double) - * - * @param i integer part - * @param f fractional part should be in range [0.0, 1.0) - */ - public JulianDateStamp(int i, double f) { - set(i, f); - } - - /** - * Creates JD from BigDecimal. - */ - public JulianDateStamp(BigDecimal bd) { - double d = bd.doubleValue(); - integer = (int) d; - bd = bd.subtract(new BigDecimal(integer)); - fraction = bd.doubleValue(); - } - - - // ---------------------------------------------------------------- conversion - - - /** - * Returns double value of JD. - * CAUTION: double values may not be suit for precision math due to - * loss of precision. - */ - public double doubleValue() { - return (double)integer + fraction; - } - - /** - * Returns BigDecimal value of JD. - */ - @SuppressWarnings({"UnpredictableBigDecimalConstructorCall"}) - public BigDecimal toBigDecimal() { - BigDecimal bd = new BigDecimal(integer); - return bd.add(new BigDecimal(fraction)); - } - - /** - * Returns string representation of JD. - * - * @return julian integer as string - */ - @Override - public String toString() { - String s = Double.toString(fraction); - int i = s.indexOf('.'); - s = s.substring(i); - return integer + s; - } - - - // ---------------------------------------------------------------- math - - /** - * Adds a JD to current instance. - */ - public JulianDateStamp add(JulianDateStamp jds) { - int i = this.integer + jds.integer; - double f = this.fraction + jds.fraction; - set(i, f); - return this; - } - - /** - * Adds a double to current instance. - */ - public JulianDateStamp add(double delta) { - set(this.integer, this.fraction + delta); - return this; - } - - - /** - * Subtracts a JD from current instance. - */ - public JulianDateStamp sub(JulianDateStamp jds) { - int i = this.integer - jds.integer; - double f = this.fraction -jds.fraction; - set(i, f); - return this; - } - - /** - * Subtracts a double from current instance. - */ - public JulianDateStamp sub(double delta) { - set(this.integer, this.fraction - delta); - return this; - } - - /** - * Sets integer and fractional part with normalization. - * Normalization means that if double is out of range, - * values will be correctly fixed. - */ - public void set(int i, double f) { - integer = i; - int fi = (int) f; - f -= fi; - integer += fi; - if (f < 0) { - f += 1; - integer--; - } - this.fraction = f; - } - - public void set(double jd) { - integer = (int)jd; - fraction = jd - (double)integer; - } - - - // ---------------------------------------------------------------- between - - /** - * Calculates the number of days between two dates. Returned value is always positive. - */ - public int daysBetween(JulianDateStamp otherDate) { - int difference = daysSpan(otherDate); - return difference >= 0 ? difference : -difference; - } - - /** - * Returns span between two days. Returned value may be positive (when this date - * is after the provided one) or negative (when comparing to future date). - */ - public int daysSpan(JulianDateStamp otherDate) { - int now = getJulianDayNumber(); - int then = otherDate.getJulianDayNumber(); - return now - then; - } - - // ---------------------------------------------------------------- equals & hashCode - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (this.getClass() != object.getClass()) { - return false; - } - JulianDateStamp stamp = (JulianDateStamp) object; - return (stamp.integer == this.integer) && - (Double.compare(stamp.fraction, this.fraction) == 0); - } - - @Override - public int hashCode() { - int result = HashCode.SEED; - result = hash(result, integer); - result = hash(result, fraction); - return result; - } - - // ---------------------------------------------------------------- clone - - @Override - protected JulianDateStamp clone() { - return new JulianDateStamp(this.integer, this.fraction); - } - - // ---------------------------------------------------------------- conversion - - /** - * Returns Reduced Julian Date (RJD), used by astronomers. - * RJD = JD − 2400000 - */ - public JulianDateStamp getReducedJulianDate() { - return new JulianDateStamp(integer - 2400000, fraction); - } - - public void setReducedJulianDate(double rjd) { - set(rjd + 2400000); - } - - /** - * Returns Modified Julian Date (MJD), where date starts from midnight rather than noon. - * RJD = JD − 2400000.5 - */ - public JulianDateStamp getModifiedJulianDate() { - return new JulianDateStamp(integer - 2400000, fraction - 0.5); - } - - public void setModifiedJulianDate(double mjd) { - set(mjd + 2400000.5); - } - - /** - * Returns Truncated Julian Day (TJD), introduced by NASA for the space program. - * TJD began at midnight at the beginning of May 24, 1968 (Friday). - */ - public JulianDateStamp getTruncatedJulianDate() { - return new JulianDateStamp(integer - 2440000, fraction - 0.5); - } - - public void setTruncatedJulianDate(double tjd) { - set(tjd + 2440000.5); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/Period.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/Period.java deleted file mode 100644 index 441a3c612..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/Period.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime; - -/** - * Holds a time period. With julian dates and {@link JDateTime} it is quite - * easy to calculate period in days - just by subtracting two julian day numbers. - * However, calculating hours, minutes and seconds would require more calculation - * and this class provides simple and faster period calculation. - * - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class Period { - - protected final long days; - protected final int hours; - protected final int minutes; - protected final int seconds; - protected final int milliseconds; - - public Period(JDateTime jdt1, JDateTime jdt2) { - if (jdt2.isBefore(jdt1)) { - JDateTime temp = jdt1; - jdt1 = jdt2; - jdt2 = temp; - } - long julian2 = jdt2.getJulianDayNumber(); - long julian1 = jdt1.getJulianDayNumber(); - - long days = julian2 - julian1; - int milliseconds = jdt2.getMillisecond() - jdt1.getMillisecond(); - int seconds = jdt2.getSecond() - jdt1.getSecond(); - int minutes = jdt2.getMinute() - jdt1.getMinute(); - int hours = jdt2.getHour() - jdt1.getHour(); - - if (milliseconds < 0) { - seconds--; - milliseconds += 1000; - } - if (seconds < 0) { - minutes--; - seconds += 60; - } - if (minutes < 0) { - hours--; - minutes += 60; - } - if (hours < 0) { - days--; - hours += 24; - } - - this.days = days; - this.hours = hours; - this.minutes = minutes; - this.seconds = seconds; - this.milliseconds = milliseconds; - } - - /** - * Returns number of days in period. - */ - public long getDays() { - return days; - } - - /** - * Returns hours in period. - */ - public int getHours() { - return hours; - } - - /** - * Returns minutes in period. - */ - public int getMinutes() { - return minutes; - } - - /** - * Returns seconds in period. - */ - public int getSeconds() { - return seconds; - } - - /** - * Returns milliseconds in period. - */ - public int getMilliseconds() { - return milliseconds; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/TimeUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/TimeUtil.java deleted file mode 100644 index 8b13291dc..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/TimeUtil.java +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -/** - * Date time calculations and utilities. TimeUtil is used by - * {@link JDateTime} and it contains few utilities that may be used - * elsewhere, although {@link JDateTime} is recommended for all time - * manipulation. - * - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class TimeUtil { - - public static final int SECONDS_IN_DAY = 60 * 60 * 24; - - public static final long MILLIS_IN_DAY = 1000L * SECONDS_IN_DAY; - - // ---------------------------------------------------------------- misc calc - - /** - * Calculates day of year from given time stamp. - * It may not work for some dates in 1582. - * - * @return day of year in range: [1-366] - */ - public static int dayOfYear(int year, int month, int day) { - int day_of_year; - if (isLeapYear(year)) { - day_of_year = ((275 * month) / 9) - ((month + 9) / 12) + day - 30; - } else { - day_of_year = ((275 * month) / 9) - (((month + 9) / 12) << 1) + day - 30; - } - return day_of_year; - } - - - /** - * Check if the given year is leap year. - * - * @return true if the year is a leap year - */ - public static boolean isLeapYear(int y) { - boolean result = false; - - if (((y % 4) == 0) && // must be divisible by 4... - ((y < 1582) || // and either before reform year... - ((y % 100) != 0) || // or not a century... - ((y % 400) == 0))) { // or a multiple of 400... - result = true; // for leap year. - } - return result; - } - - static final int[] MONTH_LENGTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - - /** - * Returns the length of the specified month in days. Month is 1 for January - * and 12 for December. - * - * @return length of the specified month in days - */ - public static int getMonthLength(int year, int month) { - return getMonthLength(year, month, isLeapYear(year)); - } - - static int getMonthLength(int year, int month, boolean leap) { - if ((month < 1) || (month > 12)) { - throw new IllegalArgumentException("Invalid month: " + month); - } - if (month == 2) { - return leap ? 29 : 28; - } - if ((year == 1582) && (month == 10)) { - return 21; - } - return MONTH_LENGTH[month]; - } - - - // ---------------------------------------------------------------- valid - - /** - * Checks if date is valid. - * - * @return true if date is valid, otherwise false - */ - public static boolean isValidDate(int year, int month, int day) { - if ((month < 1) || (month > 12)) { - return false; - } - int ml = getMonthLength(year, month); - //noinspection RedundantIfStatement - if ((day < 1) || (day > ml)) { - return false; - } - return true; - } - - /** - * Checks if time is valid. - * - * @param hour hour to check - * @param minute minute to check - * @param second second to check - * - * @return true if time is valid, otherwise false - */ - public static boolean isValidTime(int hour, int minute, int second, int millisecond) { - if ((hour < 0) || (hour >= 24)) { - return false; - } - if ((minute < 0) || (minute >= 60)) { - return false; - } - if ((second < 0) || (second >= 60)) { - return false; - } - //noinspection RedundantIfStatement - if ((millisecond < 0) || (millisecond >= 1000)) { - return false; - } - return true; - } - - /** - * Checks if date and time are valid. - * - * @param year year to check - * @param month month to check - * @param day day to check - * @param hour hour to check - * @param minute minute to check - * @param second second to check - * - * @return true if date and time are valid, otherwise false - */ - public static boolean isValidDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { - return (isValidDate(year, month, day) && isValidTime(hour, minute, second, millisecond)); - } - - /** - * Checks if date and time are valid. - * - * @param dts date/time stamp - * - * @return true if date and time are valid, otherwise false - */ - public static boolean isValidDateTime(DateTimeStamp dts) { - return (isValidDate(dts.year, dts.month, dts.day) && isValidTime(dts.hour, dts.minute, dts.second, dts.millisecond)); - } - - - // ---------------------------------------------------------------- julian date - - /** - * Calculates Astronomical Julian Date from given time stamp. - * - * @return Julian Date stamp - */ - public static JulianDateStamp toJulianDate(DateTimeStamp time) { - return toJulianDate(time.year, time.month, time.day, time.hour, time.minute, time.second, time.millisecond); - } - - /** - * Calculates Astronomical Julian Date from given time.

- * - * Astronomical Julian Dates are counting from noon of the January 1st, -4712 - * (julian date 0 is -4712/01/01 12:00:00). Zero year exist. Julian Date - * is always GMT, there are no timezones. - *

- * - * Algorithm based on Numerical Recipesin C, 2nd ed., Cambridge University - * Press 1992, modified and enhanced by Igor Spasic. - * - * @param year year - * @param month month - * @param day day - * @param hour hour - * @param minute minute - * @param second second - * - * @return julian time stamp - */ - public static JulianDateStamp toJulianDate(int year, int month, int day, int hour, int minute, int second, int millisecond) { - - // month range fix - if ((month > 12) || (month < -12)) { - month--; - int delta = month / 12; - year += delta; - month -= delta * 12; - month++; - } - if (month < 0) { - year--; - month += 12; - } - - // decimal day fraction - double frac = (hour / 24.0) + (minute / 1440.0) + (second / 86400.0) + (millisecond / 86400000.0); - if (frac < 0) { // negative time fix - int delta = ((int)(-frac)) + 1; - frac += delta; - day -= delta; - } - //double gyr = year + (0.01 * month) + (0.0001 * day) + (0.0001 * frac) + 1.0e-9; - double gyr = year + (0.01 * month) + (0.0001 * (day + frac)) + 1.0e-9; - - // conversion factors - int iy0; - int im0; - if (month <= 2) { - iy0 = year - 1; - im0 = month + 12; - } else { - iy0 = year; - im0 = month; - } - int ia = iy0 / 100; - int ib = 2 - ia + (ia >> 2); - - // calculate julian date - int jd; - if (year <= 0) { - jd = (int)((365.25 * iy0) - 0.75) + (int)(30.6001 * (im0 + 1)) + day + 1720994; - } else { - jd = (int)(365.25 * iy0) + (int)(30.6001 * (im0 + 1)) + day + 1720994; - } - if (gyr >= 1582.1015) { // on or after 15 October 1582 - jd += ib; - } - //return jd + frac + 0.5; - - return new JulianDateStamp(jd, frac + 0.5); - } - - - /** - * Calculates time stamp from Astronomical Julian Date. - * - * @param JD julian date - * - * @return time stamp - */ - public static DateTimeStamp fromJulianDate(double JD) { - return fromJulianDate(new JulianDateStamp(JD)); - } - - - /** - * Calculates time stamp from Astronomical Julian Date. - * Algorithm based on Numerical Recipesin C, 2nd ed., Cambridge University - * Press 1992. - * - * @param jds julian date stamp - * - * @return time stamp - */ - public static DateTimeStamp fromJulianDate(JulianDateStamp jds) { - DateTimeStamp time = new DateTimeStamp(); - int year, month, day; - double frac; - int jd, ka, kb, kc, kd, ke, ialp; - - //double JD = jds.doubleValue();//jdate; - //jd = (int)(JD + 0.5); // integer julian date - //frac = JD + 0.5 - (double)jd + 1.0e-10; // day fraction - - ka = (int)(jds.fraction + 0.5); - jd = jds.integer + ka; - frac = jds.fraction + 0.5 - ka + 1.0e-10; - - ka = jd; - if (jd >= 2299161) { - ialp = (int)(((double)jd - 1867216.25) / (36524.25)); - ka = jd + 1 + ialp - (ialp >> 2); - } - kb = ka + 1524; - kc = (int)(((double)kb - 122.1) / 365.25); - kd = (int)((double)kc * 365.25); - ke = (int)((double)(kb - kd) / 30.6001); - day = kb - kd - ((int)((double)ke * 30.6001)); - if (ke > 13) { - month = ke - 13; - } else { - month = ke - 1; - } - if ((month == 2) && (day > 28)){ - day = 29; - } - if ((month == 2) && (day == 29) && (ke == 3)) { - year = kc - 4716; - } else if (month > 2) { - year = kc - 4716; - } else { - year = kc - 4715; - } - time.year = year; - time.month = month; - time.day = day; - - // hour with minute and second included as fraction - double d_hour = frac * 24.0; - time.hour = (int) d_hour; // integer hour - - // minute with second included as a fraction - double d_minute = (d_hour - (double)time.hour) * 60.0; - time.minute = (int) d_minute; // integer minute - - double d_second = (d_minute - (double)time.minute) * 60.0; - time.second = (int) d_second; // integer seconds - - double d_millis = (d_second - (double)time.second) * 1000.0; - - // fix calculation errors - time.millisecond = (int) (((d_millis * 10) + 0.5) / 10); - - return time; - } - - // ---------------------------------------------------------------- gc - - /** - * Returns Calendar month from provided JDateTime month. - */ - public static int toCalendarMonth(int month) { - return month - 1; - } - - /** - * Returns Calendar day-of-week from provided JDateTime. - */ - public static int toCalendarDayOfWeek(int dayOfWeek) { - return (dayOfWeek % 7) + 1; - } - - - // ---------------------------------------------------------------- format - - public static final SimpleDateFormat HTTP_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); - - /** - * Formats time to HTTP date/time format. Note that number of milliseconds - * is lost. - */ - public static String formatHttpDate(long millis) { - Date date = new Date(millis); - return HTTP_DATE_FORMAT.format(date); - } - - /** - * Parses the HTTP date/time format. Returns -1 if given string - * is invalid. - */ - public static long parseHttpTime(String time) { - if (time == null) { - return -1; - } - - try { - return TimeUtil.HTTP_DATE_FORMAT.parse(time).getTime(); - } - catch (ParseException e) { - return -1; - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/TimeZoneUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/TimeZoneUtil.java deleted file mode 100644 index d8ce150ae..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/TimeZoneUtil.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime; - -import java.util.TimeZone; - -/** - * Misc timezone utilities. - * - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class TimeZoneUtil { - - /** - * Returns raw offset difference in milliseconds. - */ - public static int getRawOffsetDifference(TimeZone from, TimeZone to) { - int offsetBefore = from.getRawOffset(); - int offsetAfter = to.getRawOffset(); - return offsetAfter - offsetBefore; - } - - /** - * Returns offset difference in milliseconds for given time. - */ - public static int getOffsetDifference(long now, TimeZone from, TimeZone to) { - int offsetBefore = from.getOffset(now); - int offsetAfter = to.getOffset(now); - return offsetAfter - offsetBefore; - } - - /** - * Get offset difference in milliseconds for given jdatetime. - */ - public static int getOffset(JDateTime jdt, TimeZone tz) { - return tz.getOffset( - jdt.getEra(), - jdt.getYear(), - jdt.getMonth() - 1, - jdt.getDay(), - TimeUtil.toCalendarDayOfWeek(jdt.getDayOfWeek()), - jdt.getMillisOfDay() - ); - } - - public static int getOffsetDifference(JDateTime jdt, TimeZone from, TimeZone to) { - int offsetBefore = getOffset(jdt, from); - int offsetAfter = getOffset(jdt, to); - return offsetAfter - offsetBefore; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/AbstractFormatter.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/AbstractFormatter.java deleted file mode 100644 index aec8a7f09..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/AbstractFormatter.java +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime.format; - -import com.fr.third.jodd.datetime.DateTimeStamp; -import com.fr.third.jodd.datetime.JDateTime; -import com.fr.third.jodd.util.CharUtil; - -/** - * Abstract formatter for easier {@link JdtFormatter} implementations. - *

- * For setting date and time, default formatter parses input String against - * specified format. It extracts parts of input string upon patterns - * and then each part is converted to a number for a date/time information. - * It doesn't ignore any non-number character. If conversion fails, - * null is returned. - * - *

- * Getting date time is also user friendly. Specified format may not only - * contains patterns but also any text. To remove errors in decoding when - * text may be recognize as one of patterns, format text may be quoted - * with the special escape sign. Double quote in the text will be decoded - * as a single quote, of course. - *

- * - * It is not necessary to have parsers for all patterns. - * - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public abstract class AbstractFormatter implements JdtFormatter { - - /** - * Available patterns list. Used by {@link #findPattern(char[], int)} - * when parsing date time format. Each formatter will have its own set of - * patterns, in strictly defined order. - */ - protected char[][] patterns; - - /** - * Escape character. - */ - protected char escapeChar = '\''; - - - /** - * Converts String array of patterns to char arrays. - */ - protected void preparePatterns(String[] spat) { - patterns = new char[spat.length][]; - for (int i = 0; i < spat.length; i++) { - patterns[i] = spat[i].toCharArray(); - } - } - - /** - * Finds the longest pattern in provided format starting from specified position. - * All available patterns are stored in {@link #patterns}. - * - * @param format date time format to examine - * @param i starting index - * - * @return 0-based index of founded pattern, or -1 if pattern not found - */ - protected int findPattern(char[] format, int i) { - int frmtc_len = format.length; - boolean match; - int n, lastn = -1; - int maxLen = 0; - for (n = 0; n < patterns.length; n++) { - char[] curr = patterns[n]; // current pattern from the pattern list - if (i > frmtc_len - curr.length) { - continue; - } - match = true; - int delta = 0; - while (delta < curr.length) { // match given pattern - if (curr[delta] != format[i + delta]) { - match = false; // no match, go to next - break; - } - delta++; - } - if (match) { // match - if (patterns[n].length > maxLen) { // find longest match - lastn = n; - maxLen = patterns[n].length; - } - } - } - return lastn; - } - - // ---------------------------------------------------------------- convert - - /** - * Creates a date-time string for founded pattern. Founded patterns - * is identified by its {@link #patterns} index. - * - * @param patternIndex index of founded pattern - * @param jdt date time information - */ - protected abstract String convertPattern(int patternIndex, JDateTime jdt); - - /** - * {@inheritDoc} - * @see JdtFormatter#convert(JDateTime, String) - */ - public String convert(JDateTime jdt, String format) { - char[] fmtc = format.toCharArray(); - int fmtc_len = fmtc.length; - StringBuilder result = new StringBuilder(fmtc_len); - - int i = 0; - while (i < fmtc_len) { - if (fmtc[i] == escapeChar) { // quote founded - int end = i + 1; - while (end < fmtc_len) { - if (fmtc[end] == escapeChar) { // second quote founded - if (end + 1 < fmtc_len) { - end++; - if (fmtc[end] == escapeChar) { // skip double quotes - result.append(escapeChar); // and continue - } else { - break; - } - } - } else { - result.append(fmtc[end]); - } - end++; - } - i = end; - continue; // end of quoted string, continue the main loop - } - - int n = findPattern(fmtc, i); - if (n != -1) { // pattern founded - result.append(convertPattern(n, jdt)); - i += patterns[n].length; - } else { - result.append(fmtc[i]); - i++; - } - } - return result.toString(); - } - - // ---------------------------------------------------------------- parse - - /** - * Parses value for matched pattern. Founded patterns - * is identified by its {@link #patterns} index. - * Note that value may represent both integer and decimals. - * May throw {@link NumberFormatException}. - * - * @param patternIndex index of founded pattern - * @param value value to parse, no spaces or tabs - * @param destination destination to modify - */ - protected abstract void parseValue(int patternIndex, String value, DateTimeStamp destination); - - /** - * {@inheritDoc} - * @see JdtFormatter#parse(String, String) - */ - public DateTimeStamp parse(String value, String format) { - char[] valueChars = value.toCharArray(); - char[] formatChars = format.toCharArray(); - - int i = 0, j = 0; - int valueLen = valueChars.length; - int formatLen = formatChars.length; - - // detect if separators are used - boolean useSeparators = true; - - if (valueLen == formatLen) { - useSeparators = false; - - for (char valueChar : valueChars) { - if (!CharUtil.isDigit(valueChar)) { - useSeparators = true; - break; - } - } - } - - DateTimeStamp time = new DateTimeStamp(); - StringBuilder sb = new StringBuilder(); - while (true) { - int n = findPattern(formatChars, i); - if (n != -1) { // pattern founded - int patternLen = patterns[n].length; - i += patternLen; - sb.setLength(0); - if (!useSeparators) { - for (int k = 0; k < patternLen; k++) { - sb.append(valueChars[j++]); - } - } else { - char next = 0xFFFF; - if (i < formatLen) { - next = formatChars[i]; // next = delimiter - } - while ((j < valueLen) && (valueChars[j] != next)) { - char scj = valueChars[j]; - if ((scj != ' ') && (scj != '\t')) { // ignore surrounding whitespaces - sb.append(valueChars[j]); - } - j++; - } - } - - parseValue(n, sb.toString(), time); - } else { - if (!useSeparators) { - throw new IllegalArgumentException("Invalid value: " + value); - } - if (formatChars[i] == valueChars[j]) { - j++; - } - i++; - } - if ((i == formatLen) || (j == valueLen)) { - break; - } - } - return time; - } - - - // ---------------------------------------------------------------- util - - /** - * Prints values 00 - 99. - */ - protected String print2(int value) { - if (value < 0) { - throw new IllegalArgumentException("Value must be positive: " + value); - } - if (value < 10) { - return '0' + Integer.toString(value); - } - if (value < 100) { - return Integer.toString(value); - } - throw new IllegalArgumentException("Value too big: " + value); - } - - /** - * Prints values 00 - 999. - */ - protected String print3(int value) { - if (value < 0) { - throw new IllegalArgumentException("Value must be positive: " + value); - } - if (value < 10) { - return "00" + Integer.toString(value); - } - if (value < 100) { - return '0' + Integer.toString(value); - } - if (value < 1000) { - return Integer.toString(value); - } - throw new IllegalArgumentException("Value too big: " + value); - } - - /** - * Prints 4 digits and optional minus sign. - */ - protected String printPad4(int value) { - char[] result = new char[4]; - int count = 0; - - if (value < 0) { - result[count++] = '-'; - value = -value; - } - - String str = Integer.toString(value); - - if (value < 10) { - result[count++] = '0'; - result[count++] = '0'; - result[count++] = '0'; - result[count++] = str.charAt(0); - } else if (value < 100) { - result[count++] = '0'; - result[count++] = '0'; - result[count++] = str.charAt(0); - result[count++] = str.charAt(1); - } else if (value < 1000) { - result[count++] = '0'; - result[count++] = str.charAt(0); - result[count++] = str.charAt(1); - result[count++] = str.charAt(2); - } else { - if (count > 0) { - return '-' + str; - } - return str; - } - return new String(result, 0, count); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/Iso8601JdtFormatter.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/Iso8601JdtFormatter.java deleted file mode 100644 index 284def1bf..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/Iso8601JdtFormatter.java +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime.format; - -import com.fr.third.jodd.datetime.DateTimeStamp; -import com.fr.third.jodd.datetime.JDateTime; -import com.fr.third.jodd.datetime.DateTimeStamp; -import com.fr.third.jodd.datetime.JDateTime; -import com.fr.third.jodd.util.LocaleUtil; -import com.fr.third.jodd.util.DateFormatSymbolsEx; - -import java.util.TimeZone; - -/** - * Default {@link JdtFormatter} uses ISO 8601 specification, enhanced by some - * custom patterns. For more information see: - * ISO 8601 on Wikipedia - * - *

- * Patterns list: - * - *

    - *
  • YYYY + year
  • - *
  • MM + month
  • - *
  • DD + day of month
  • - *
  • D - day of week
  • - *
  • MML - month name (add-on)
  • - *
  • MMS - month abbreviation (add-on)
  • - *
  • DL - day of week name (add-on)
  • - *
  • DS - day of week abbreviation (add-on)
  • - *
  • hh + hour
  • - *
  • mm + minute
  • - *
  • ss + seconds (no milliseconds)
  • - *
  • mss + milliseconds (add-on)
  • - *
  • DDD - day of year
  • - *
  • WW - week of year
  • - *
  • WWW - week of year with 'W' prefix
  • - *
  • W - week of month (add-on)
  • - *
  • E - era
  • - *
  • TLZ - time zone long
  • - *
  • TLS - time zone short
  • - *
- * - *

- * Patterns noted with + sign are used both for conversion and parsing. - * All patterns are used for conversion. - * - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class Iso8601JdtFormatter extends AbstractFormatter { - - public Iso8601JdtFormatter() { - preparePatterns( - new String[] { - "YYYY", // 0 + year - "MM", // 1 + month - "DD", // 2 + day of month - "D", // 3 - day of week - "MML", // 4 - month long name - "MMS", // 5 - month short name - "DL", // 6 - day of week long name - "DS", // 7 - day of week short name - "hh", // 8 + hour - "mm", // 9 + minute - "ss", // 10 + seconds - "mss", // 11 + milliseconds - "DDD", // 12 - day of year - "WW", // 13 - week of year - "WWW", // 14 - week of year with 'W' prefix - "W", // 15 - week of month - "E", // 16 - era - "TZL", // 17 - timezone long name - "TZS", // 18 - timezone short name - } - ); - } - - @Override - protected String convertPattern(int patternIndex, JDateTime jdt) { - DateFormatSymbolsEx dfs = LocaleUtil.getDateFormatSymbols(jdt.getLocale()); - switch (patternIndex) { - case 0: - return printPad4(jdt.getYear()); - case 1: - return print2(jdt.getMonth()); - case 2: - return print2(jdt.getDay()); - case 3: - return Integer.toString(jdt.getDayOfWeek()); - case 4: - return dfs.getMonth(jdt.getMonth() - 1); - case 5: - return dfs.getShortMonth(jdt.getMonth() - 1); - case 6: - return dfs.getWeekday((jdt.getDayOfWeek() % 7) + 1); - case 7: - return dfs.getShortWeekday((jdt.getDayOfWeek() % 7) + 1); - case 8: - return print2(jdt.getHour()); - case 9: - return print2(jdt.getMinute()); - case 10: - return print2(jdt.getSecond()); - case 11: - return print3(jdt.getMillisecond()); - case 12: - return print3(jdt.getDayOfYear()); - case 13: - return print2(jdt.getWeekOfYear()); - case 14: - return 'W' + print2(jdt.getWeekOfYear()); - case 15: - return Integer.toString(jdt.getWeekOfMonth()); - case 16: - return jdt.getEra() == 1 ? dfs.getAdEra() : dfs.getBcEra(); - case 17: - return jdt.getTimeZone().getDisplayName( - jdt.isInDaylightTime(), - TimeZone.LONG, - jdt.getLocale()); - case 18: - return jdt.getTimeZone().getDisplayName( - jdt.isInDaylightTime(), - TimeZone.SHORT, - jdt.getLocale()); - default: - return new String(patterns[patternIndex]); - } - } - - @Override - protected void parseValue(int patternIndex, String value, DateTimeStamp destination) { - int v = Integer.parseInt(value); - switch (patternIndex) { - case 0: destination.year = v; break; - case 1: destination.month = v; break; - case 2: destination.day = v; break; - case 8: destination.hour = v; break; - case 9: destination.minute = v; break; - case 10: destination.second = v; break; - case 11: destination.millisecond = v; break; - default: - throw new IllegalArgumentException("Invalid template: " + new String(patterns[patternIndex])); - } - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/JdtFormat.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/JdtFormat.java deleted file mode 100644 index a40ee7439..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/JdtFormat.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime.format; - -import com.fr.third.jodd.datetime.DateTimeStamp; -import com.fr.third.jodd.datetime.JDateTime; - -/** - * Immutable format-formatter pair. - * - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public class JdtFormat { - - protected final String format; - protected final JdtFormatter formatter; - - public JdtFormat(JdtFormatter formatter, String format) { - this.format = format; - this.formatter = formatter; - } - - /** - * Returns format. - */ - public String getFormat() { - return format; - } - - /** - * Returns formatter. - */ - public JdtFormatter getFormatter() { - return formatter; - } - - - /** - * Delegates for {@link JdtFormatter#convert(JDateTime, String)}. - */ - public String convert(JDateTime jdt) { - return formatter.convert(jdt, format); - } - - /** - * Delegates for {@link JdtFormatter#parse(String, String)}. - */ - public DateTimeStamp parse(String value) { - return formatter.parse(value, format); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/JdtFormatter.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/JdtFormatter.java deleted file mode 100644 index 5d7cff1bc..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/JdtFormatter.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.datetime.format; - -import com.fr.third.jodd.datetime.DateTimeStamp; -import com.fr.third.jodd.datetime.JDateTime; - -import java.io.Serializable; - -/** - * Date time formatter performs conversion both from and to string representation of time. - * - * @see AbstractFormatter - * @deprecated jodd目前版本为5.1.6, 此版本已移除此类, 兼容问题暂不删除此类 - */ -@Deprecated -public interface JdtFormatter extends Serializable { - - /** - * Converts date time to a string using specified format. - * - * @param jdt JDateTime to read from - * @param format format - * - * @return formatted string with date time information - */ - String convert(JDateTime jdt, String format); - - /** - * Parses string given in specified format and extracts time information. - * It returns a new instance of DateTimeStamp or null if error occurs. - * - * @param value string containing date time values - * @param format format - * - * @return DateTimeStamp instance with populated data - */ - DateTimeStamp parse(String value, String format); -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/package-info.java deleted file mode 100644 index 1db48ffd9..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/format/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * JDateTime formatters for converting date/time informations to/from strings. - */ -package com.fr.third.jodd.datetime.format; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/datetime/package-info.java deleted file mode 100644 index e35555b43..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/datetime/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Finally, easy manipulation of date and time! - */ -package com.fr.third.jodd.datetime; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/exception/ExceptionUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/exception/ExceptionUtil.java deleted file mode 100644 index b04165fa9..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/exception/ExceptionUtil.java +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.exception; - -import com.fr.third.jodd.io.StreamUtil; -import com.fr.third.jodd.util.StringUtil; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.UndeclaredThrowableException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; - -/** - * Few exception utilities. - */ -public class ExceptionUtil { - - /** - * Returns current stack trace in form of array of stack trace elements. - * First stack trace element is removed. - * Since an exception is thrown internally, this method is slow. - */ - @SuppressWarnings({"ThrowCaughtLocally"}) - public static StackTraceElement[] getCurrentStackTrace() { - StackTraceElement[] ste = new Exception().getStackTrace(); - if (ste.length > 1) { - StackTraceElement[] result = new StackTraceElement[ste.length - 1]; - System.arraycopy(ste, 1, result, 0, ste.length - 1); - return result; - } else { - return ste; - } - } - - // ---------------------------------------------------------------- exception stack trace - - /** - * Returns stack trace filtered by class names. - */ - public static StackTraceElement[] getStackTrace(final Throwable t, final String[] allow, final String[] deny) { - StackTraceElement[] st = t.getStackTrace(); - ArrayList result = new ArrayList<>(st.length); - - elementLoop: - for (StackTraceElement element : st) { - String className = element.getClassName(); - if (allow != null) { - boolean validElemenet = false; - for (String filter : allow) { - if (className.contains(filter)) { - validElemenet = true; - break; - } - } - if (!validElemenet) { - continue; - } - } - if (deny != null) { - for (String filter : deny) { - if (className.contains(filter)) { - continue elementLoop; - } - } - } - result.add(element); - } - st = new StackTraceElement[result.size()]; - return result.toArray(st); - } - - /** - * Returns stack trace chain filtered by class names. - */ - public static StackTraceElement[][] getStackTraceChain(Throwable t, final String[] allow, final String[] deny) { - ArrayList result = new ArrayList<>(); - while (t != null) { - StackTraceElement[] stack = getStackTrace(t, allow, deny); - result.add(stack); - t = t.getCause(); - } - StackTraceElement[][] allStacks = new StackTraceElement[result.size()][]; - for (int i = 0; i < allStacks.length; i++) { - allStacks[i] = result.get(i); - } - return allStacks; - } - - - /** - * Returns exception chain starting from top up to root cause. - */ - public static Throwable[] getExceptionChain(Throwable throwable) { - ArrayList list = new ArrayList<>(); - list.add(throwable); - while ((throwable = throwable.getCause()) != null) { - list.add(throwable); - } - Throwable[] result = new Throwable[list.size()]; - return list.toArray(result); - } - - - // ---------------------------------------------------------------- exception to string - - - /** - * Prints stack trace into a String. - */ - public static String exceptionStackTraceToString(final Throwable t) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw, true); - - t.printStackTrace(pw); - - StreamUtil.close(pw); - StreamUtil.close(sw); - - return sw.toString(); - } - - /** - * Prints full exception stack trace, from top to root cause, into a String. - */ - public static String exceptionChainToString(Throwable t) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw, true); - while (t != null) { - t.printStackTrace(pw); - t = t.getCause(); - } - - StreamUtil.close(pw); - StreamUtil.close(sw); - - return sw.toString(); - } - - /** - * Build a message for the given base message and its cause. - */ - public static String buildMessage(final String message, Throwable cause) { - if (cause != null) { - cause = getRootCause(cause); - StringBuilder buf = new StringBuilder(); - if (message != null) { - buf.append(message).append("; "); - } - buf.append("<--- ").append(cause); - return buf.toString(); - } else { - return message; - } - } - - // ---------------------------------------------------------------- root cause - - /** - * Introspects the Throwable to obtain the root cause. - *

- * This method walks through the exception chain to the last element, - * "root" of the tree, and returns that exception. If no root cause found - * returns provided throwable. - */ - public static Throwable getRootCause(final Throwable throwable) { - Throwable cause = throwable.getCause(); - if (cause == null) { - return throwable; - } - - Throwable t = throwable; - - // defend against (malicious?) circularity - for (int i = 0; i < 1000; i++) { - cause = t.getCause(); - if (cause == null) { - return t; - } - t = cause; - } - - return throwable; - } - - /** - * Finds throwing cause in exception stack. Returns throwable object if cause class is matched. - * Otherwise, returns null. - */ - @SuppressWarnings({"unchecked"}) - public static T findCause(Throwable throwable, final Class cause) { - while (throwable != null) { - if (throwable.getClass().equals(cause)) { - return (T) throwable; - } - throwable = throwable.getCause(); - } - return null; - } - - - // ---------------------------------------------------------------- sql - - /** - * Rolls up SQL exceptions by taking each proceeding exception - * and making it a child of the previous using the setNextException - * method of SQLException. - */ - public static SQLException rollupSqlExceptions(final Collection exceptions) { - SQLException parent = null; - for (SQLException exception : exceptions) { - if (parent != null) { - exception.setNextException(parent); - } - parent = exception; - } - return parent; - } - - // ---------------------------------------------------------------- misc - - /** - * Throws checked exceptions in un-checked manner. - */ - public static void throwRuntimeException(final Throwable throwable) { - throw wrapToRuntimeException(throwable); - } - - /** - * Returns non-null message for a throwable. - */ - public static String message(final Throwable throwable) { - String message = throwable.getMessage(); - - if (StringUtil.isBlank(message)) { - message = throwable.toString(); - } - - return message; - } - - /** - * Wraps exception to {@code RuntimeException}. - */ - public static RuntimeException wrapToRuntimeException(final Throwable throwable) { - if (throwable instanceof RuntimeException) { - return (RuntimeException) throwable; - } - return new RuntimeException(throwable); - } - public static Exception wrapToException(final Throwable throwable) { - if (throwable instanceof Exception) { - return (Exception) throwable; - } - return new RuntimeException(throwable); - } - - /** - * Unwraps invocation and undeclared exceptions to real cause. - */ - public static Throwable unwrapThrowable(final Throwable wrappedThrowable) { - Throwable unwrapped = wrappedThrowable; - while (true) { - if (unwrapped instanceof InvocationTargetException) { - unwrapped = ((InvocationTargetException) unwrapped).getTargetException(); - } - else if (unwrapped instanceof UndeclaredThrowableException) { - unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable(); - } - else { - return unwrapped; - } - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/exception/UncheckedException.java b/fine-jodd/src/main/java/com/fr/third/jodd/exception/UncheckedException.java deleted file mode 100644 index 9e64ef90f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/exception/UncheckedException.java +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.exception; - -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.UncheckedIOException; -import java.util.concurrent.Callable; - -/** - * Unchecked exception and also a wrapper for checked exceptions. - */ -@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) -public class UncheckedException extends RuntimeException { - - protected final Throwable cause; - - /** - * Divider between causes printouts. - */ - protected static final String CAUSE_DIV = "---[cause]------------------------------------------------------------------------"; - - /** - * If set to true stack trace will be enhanced with cause's stack traces. - */ - protected final boolean showCauseDetails; - - // ---------------------------------------------------------------- constructors - - public UncheckedException(final Throwable t) { - super(t.getMessage()); - cause = t; - this.showCauseDetails = true; - } - - public UncheckedException(final Throwable t, final boolean showCauseDetails) { - super(t.getMessage()); - cause = t; - this.showCauseDetails = showCauseDetails; - } - - public UncheckedException() { - super(); - cause = null; - this.showCauseDetails = false; - } - - public UncheckedException(final String message) { - super(message); - cause = null; - this.showCauseDetails = false; - } - - public UncheckedException(final String message, final Throwable t) { - super(message, t); - cause = t; - this.showCauseDetails = true; - } - - public UncheckedException(final String message, final Throwable t, final boolean showCauseDetails) { - super(message, t); - cause = t; - this.showCauseDetails = showCauseDetails; - } - - // ---------------------------------------------------------------- stack trace - - @Override - public void printStackTrace() { - printStackTrace(System.err); - } - - @Override - public void printStackTrace(final PrintStream ps) { - synchronized (ps) { - super.printStackTrace(ps); - if ((cause != null) && showCauseDetails) { - Throwable rootCause = ExceptionUtil.getRootCause(cause); - ps.println(CAUSE_DIV); - rootCause.printStackTrace(ps); - } - } - } - - @Override - public void printStackTrace(final PrintWriter pw) { - synchronized (pw) { - super.printStackTrace(pw); - if ((cause != null) && showCauseDetails) { - Throwable rootCause = ExceptionUtil.getRootCause(cause); - pw.println(CAUSE_DIV); - rootCause.printStackTrace(pw); - } - } - } - - // ---------------------------------------------------------------- txt - - /** - * Returns the detail message, including the message from the nested exception if there is one. - */ - @Override - public String getMessage() { - return ExceptionUtil.buildMessage(super.getMessage(), cause); - } - - // ---------------------------------------------------------------- wrap - - /** - * Wraps checked exceptions in a UncheckedException. - * Unchecked exceptions are not wrapped. - */ - public static V callAndWrapException(final Callable callable) { - try { - return callable.call(); - } - catch (IOException ioex) { - throw new UncheckedIOException(ioex); - } - catch (RuntimeException rtex) { - throw rtex; - } - catch (Exception t) { - throw new UncheckedException(t); - } - } - - @FunctionalInterface - public interface CallableVoid { - public void call() throws Exception; - } - - /** - * Wraps checked exceptions in a UncheckedException. - * Unchecked exceptions are not wrapped. - */ - public static void runAndWrapException(final CallableVoid callable) { - try { - callable.call(); - } - catch (IOException ioex) { - throw new UncheckedIOException(ioex); - } - catch (RuntimeException rtex) { - throw rtex; - } - catch (Exception t) { - throw new UncheckedException(t); - } - } - - /** - * Wraps all exceptions in a UncheckedException - */ - public static RuntimeException wrap(final Throwable t) { - return new UncheckedException(t); - } - - /** - * Wraps all exceptions in a UncheckedException - */ - public static RuntimeException wrap(final Throwable t, final String message) { - return new UncheckedException(message, t); - } - - - // ---------------------------------------------------------------- cause - - /** - * Re-throws cause if exists. - */ - public void rethrow() throws Throwable { - if (cause == null) { - return; - } - throw cause; - } - - /** - * Returns exception cause. - */ - @Override - public Throwable getCause() { - return cause; - } - - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/exception/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/exception/package-info.java deleted file mode 100644 index 7724c1695..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/exception/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Jodds exceptions. - */ -package com.fr.third.jodd.exception; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/inex/InExRuleMatcher.java b/fine-jodd/src/main/java/com/fr/third/jodd/inex/InExRuleMatcher.java deleted file mode 100644 index 398d17cb4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/inex/InExRuleMatcher.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.inex; - -import com.fr.third.jodd.util.Wildcard; - -/** - * Rule matcher. - */ -@FunctionalInterface -public interface InExRuleMatcher { - - /** - * {@link com.fr.third.jodd.util.Wildcard#match(CharSequence, CharSequence) Wilcard} rule matcher. - */ - InExRuleMatcher WILDCARD_RULE_MATCHER = - (value, rule, include) -> Wildcard.match(value, rule); - /** - * {@link com.fr.third.jodd.util.Wildcard#matchPath(String, String) Wilcard path} rule matcher. - */ - InExRuleMatcher WILDCARD_PATH_RULE_MATCHER = - (value, rule, include) -> Wildcard.matchPath(value, rule); - - /** - * Matches the value against the rule. - */ - boolean accept(T value, R rule, boolean include); - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/inex/InExRules.java b/fine-jodd/src/main/java/com/fr/third/jodd/inex/InExRules.java deleted file mode 100644 index 579c64e04..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/inex/InExRules.java +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.inex; - -import java.util.ArrayList; -import java.util.List; - -/** - * A single-class rule engine for includes/excludes filtering logic. It can be used when - * set of objects has to filtered using includes and excludes rules. - * For example, when filtering files by file name etc. - *

- * Rule engine works in one of two modes: - *

    - *
  • blacklist - when any input is allowed by default and when you specify - * explicit excludes. - *
  • - *
  • whitelist - when any input is disabled by default and when you specify - * explicit includes. - *
  • - *
- *

- * The logic of this rule engine depends on the current mode. In both cases, - * always the inverse rules are considered first. For example, for blacklist - * mode, engine first examine excludes, and then includes. This way you can - * set any filter combination. - *

- * All Jodd classes that filters something uses this class to unify the - * behavior across the Jodd library. - *

- * About generics: rule engine examine Values (V). Rules are defined as Definitions (D). - * They are stored internally as R, that is used with Values. - */ -public class InExRules implements InExRuleMatcher { - - public InExRules create() { - return new InExRules<>(); - } - - protected List> rules; - protected final InExRuleMatcher inExRuleMatcher; - protected int includesCount; - protected int excludesCount; - protected boolean blacklist = true; - - /** - * Creates default instance. - */ - public InExRules() { - this.inExRuleMatcher = this; - } - - /** - * Creates instance that uses provided matcher. - */ - public InExRules(final InExRuleMatcher inExRuleMatcher) { - this.inExRuleMatcher = inExRuleMatcher; - } - - /** - * Returns total number of all rules. - */ - public int totalRules() { - if (rules == null) { - return 0; - } - return rules.size(); - } - - /** - * Returns total number of include rules. - */ - public int totalIncludeRules() { - return includesCount; - } - - /** - * Returns total number of exclude rules. - */ - public int totalExcludeRules() { - return excludesCount; - } - - /** - * Returns true if rule engine has at least one rule set. - */ - public boolean hasRules() { - if (rules == null) { - return false; - } - return !rules.isEmpty(); - } - - /** - * Rule definition. - */ - public static class Rule { - public final R value; - public final boolean include; - - public Rule(final R value, final boolean include) { - this.value = value; - this.include = include; - } - - @Override - public String toString() { - return (include ? "+" : "-") + value.toString(); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Rule rule = (Rule) o; - - if (include != rule.include) { - return false; - } - if (!value.equals(rule.value)) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = value.hashCode(); - result = 31 * result + (include ? 1 : 0); - return result; - } - } - - /** - * Returns rule's value on given index. - */ - public R getRule(final int index) { - return rules.get(index).value; - } - - /** - * Resets all the rules in this rule engine. - */ - public void reset() { - if (rules != null) { - rules.clear(); - } - includesCount = excludesCount = 0; - blacklist = true; - } - - /** - * Enables blacklist mode - everything is included by default, - * and user sets explicit excludes. - */ - public void blacklist() { - blacklist = true; - } - - /** - * Returns true if blacklist mode is set. - */ - public boolean isBlacklist() { - return blacklist; - } - - /** - * Enables whitelist mode - everything is excluded by default, - * and user set explicit includes. - */ - public void whitelist() { - blacklist = false; - } - - /** - * Returns true if whitelist mode is set. - */ - public boolean isWhitelist() { - return !blacklist; - } - - /** - * Sets blacklist or whitelist mode depending on rules. Smart mode - * determines the following: - *

    - *
  • If there are only include rules, then the {@link #whitelist() whitelist} mode is set.
  • - *
  • If there are only excluded rules, then the {@link #blacklist() blacklist} mode is set.
  • - *
  • In any other case (both type of rules exist or no rules are set), then mode is not changed.
  • - *
- * Should be called after all the rules are set, before matching starts. - */ - public void detectMode() { - if (excludesCount == 0 && includesCount > 0) { - whitelist(); - } - else if (excludesCount > 0 && includesCount == 0) { - blacklist(); - } - } - - /** - * Adds include rule. - */ - public void include(final D rule) { - addRule(rule, true); - } - - /** - * Adds exclude rule. - */ - public void exclude(final D rule) { - addRule(rule, false); - } - - /** - * Adds a rule. Duplicates are not allowed and will be ignored. - */ - protected void addRule(final D ruleDefinition, final boolean include) { - if (rules == null) { - rules = new ArrayList<>(); - } - - if (include) { - includesCount++; - } else { - excludesCount++; - } - - Rule newRule = new Rule<>(makeRule(ruleDefinition), include); - - if (rules.contains(newRule)) { - return; - } - - rules.add(newRule); - } - - protected R makeRule(final D rule) { - return (R) rule; - } - - /** - * Matches value against the set of rules using current white/black list mode. - */ - public boolean match(final V value) { - return match(value, blacklist); - } - /** - * Matches value against the set of rules using provided white/black list mode. - */ - public boolean match(final V value, final boolean blacklist) { - if (rules == null) { - return blacklist; - } - - boolean include = blacklist; - - if (include) { - include = processExcludes(value, true); - include = processIncludes(value, include); - } - else { - include = processIncludes(value, false); - include = processExcludes(value, include); - } - - return include; - } - - /** - * Applies rules on given flag using current black/white list mode. - * @see #apply(Object, boolean, boolean) - */ - public boolean apply(final V value, final boolean flag) { - return apply(value, blacklist, flag); - } - - /** - * Applies rules on given flag. Flag is only changed if at least one rule - * matched. Otherwise, the same value is returned. This way you can - * chain several rules and have the rule engine change the flag - * only when a rule is matched. - */ - public boolean apply(final V value, final boolean blacklist, boolean flag) { - if (rules == null) { - return flag; - } - - if (blacklist) { - flag = processExcludes(value, flag); - flag = processIncludes(value, flag); - } - else { - flag = processIncludes(value, flag); - flag = processExcludes(value, flag); - } - - return flag; - } - - /** - * Process includes rules. - */ - protected boolean processIncludes(final V value, boolean include) { - if (includesCount > 0) { - if (!include) { - for (Rule rule : rules) { - if (!rule.include) { - continue; - } - - if (inExRuleMatcher.accept(value, rule.value, true)) { - include = true; - break; - } - } - } - } - return include; - } - - /** - * Process excludes rules. - */ - protected boolean processExcludes(final V value, boolean include) { - if (excludesCount > 0) { - if (include) { - for (Rule rule : rules) { - if (rule.include) { - continue; - } - - if (inExRuleMatcher.accept(value, rule.value, false)) { - include = false; - break; - } - } - } - } - return include; - } - - /** - * Matches value against single rule. By default performs equals on value - * against the rule. - */ - @Override - public boolean accept(final V value, final R rule, final boolean include) { - return value.equals(rule); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/inex/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/inex/package-info.java deleted file mode 100644 index bcd7e7694..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/inex/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Include-Exclude rules engine. - */ -package com.fr.third.jodd.inex; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/CachingIntrospector.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/CachingIntrospector.java deleted file mode 100644 index a1fb1342e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/CachingIntrospector.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.cache.TypeCache; - -/** - * Default {@link com.fr.third.jodd.introspector.ClassIntrospector introspector} that caches all class descriptors. - * It can examine either accessible or supported fields/methods/constructors. - *

- * It simply caches all class descriptors. - */ -public class CachingIntrospector implements ClassIntrospector { - - protected final TypeCache cache; - protected final boolean scanAccessible; - protected final boolean enhancedProperties; - protected final boolean includeFieldsAsProperties; - protected final String[] propertyFieldPrefix; - - /** - * Default constructor. - */ - public CachingIntrospector() { - this(true, true, true, null); - } - - /** - * Creates new caching {@link ClassIntrospector}. It may scan - * accessible or supported fields, methods or - * constructors. - */ - public CachingIntrospector(final boolean scanAccessible, final boolean enhancedProperties, final boolean includeFieldsAsProperties, final String[] propertyFieldPrefix) { - this.cache = TypeCache.createDefault(); - this.scanAccessible = scanAccessible; - this.enhancedProperties = enhancedProperties; - this.includeFieldsAsProperties = includeFieldsAsProperties; - this.propertyFieldPrefix = propertyFieldPrefix; - } - - /** - * {@inheritDoc} - */ - @Override - public ClassDescriptor lookup(final Class type) { - return cache.get(type, (t) -> - new ClassDescriptor( - t, - scanAccessible, - enhancedProperties, - includeFieldsAsProperties, - propertyFieldPrefix)); - } - - /** - * {@inheritDoc} - */ - @Override - public void reset() { - cache.clear(); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/ClassDescriptor.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/ClassDescriptor.java deleted file mode 100644 index a63608000..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/ClassDescriptor.java +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.util.ClassUtil; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; - -/** - * A descriptor class for all methods/fields/properties/constructors of a class. - * Static methods/fields are ignored. - *

- * Descriptors are 'lazy': various internal caches are created on first request. - *

- * Throughout this class, public members are defined as members - * defined with "public" keyword and declared in a public type. - * Public members declared by a non-public class is considered non-public - * because access to it from outside is prohibited by the java access control - * anyway. - *

- * Public members defined in public classes are always preferred even - * when we allow private/protected members and types to be visible. - * So if a non-public subtype and a public super type both have a field - * with the same name, the field in the public super type is always used. - */ -public class ClassDescriptor { - - protected final Class type; - protected final boolean scanAccessible; - protected final boolean extendedProperties; - protected final boolean includeFieldsAsProperties; - protected final String[] propertyFieldPrefix; - protected final Class[] interfaces; - protected final Class[] superclasses; - - public ClassDescriptor(final Class type, final boolean scanAccessible, final boolean extendedProperties, final boolean includeFieldsAsProperties, final String[] propertyFieldPrefix) { - this.type = type; - this.scanAccessible = scanAccessible; - this.extendedProperties = extendedProperties; - this.includeFieldsAsProperties = includeFieldsAsProperties; - this.propertyFieldPrefix = propertyFieldPrefix; - - isArray = type.isArray(); - isMap = ClassUtil.isTypeOf(type, Map.class); - isList = ClassUtil.isTypeOf(type, List.class); - isSet = ClassUtil.isTypeOf(type, Set.class); - isCollection = ClassUtil.isTypeOf(type, Collection.class); - isSupplier = ClassUtil.isTypeOf(type, Supplier.class); - - interfaces = ClassUtil.resolveAllInterfaces(type); - superclasses = ClassUtil.resolveAllSuperclasses(type); - - isSystemClass = type.getName().startsWith("java.") && - !type.getName().startsWith("java.awt.geom."); - } - - /** - * Get the class object that this descriptor describes. - */ - public Class getType() { - return type; - } - - /** - * Returns true if this class descriptor - * works with accessible fields/methods/constructors or with - * all supported. - */ - public boolean isScanAccessible() { - return scanAccessible; - } - - /** - * Returns true if properties in this class descriptor - * are extended and include field description. - */ - public boolean isExtendedProperties() { - return extendedProperties; - } - - /** - * Include fields as properties. - */ - public boolean isIncludeFieldsAsProperties() { - return includeFieldsAsProperties; - } - - /** - * Returns property field prefixes. May be null - * if prefixes are not set. If you need to access both prefixed - * and non-prefixed fields, use empty string as one of the prefixes. - */ - public String[] getPropertyFieldPrefix() { - return propertyFieldPrefix; - } - - // ---------------------------------------------------------------- special - - private final boolean isArray; - /** - * Returns true if class is an array. - */ - public boolean isArray() { - return isArray; - } - - private final boolean isMap; - /** - * Returns true if class is a Map. - */ - public boolean isMap() { - return isMap; - } - - private final boolean isList; - /** - * Returns true if class is a List. - */ - public boolean isList() { - return isList; - } - - private final boolean isSet; - /** - * Returns true if type is a Set. - */ - public boolean isSet() { - return isSet; - } - - private final boolean isCollection; - /** - * Returns true if type is a collection. - */ - public boolean isCollection() { - return isCollection; - } - - private final boolean isSupplier; - - /** - * Returns true if type is a supplier. - */ - public boolean isSupplier() { - return isSupplier; - } - - private boolean isSystemClass; - - /** - * Returns true is class is a system class and should not - * expose fields or declared methods. - */ - public boolean isSystemClass() { - return isSystemClass; - } - - // ---------------------------------------------------------------- fields - - private Fields fields; - - /** - * Returns {@link Fields fields collection}. - * Creates new fields collection on first usage. - */ - protected Fields getFields() { - if (fields == null) { - fields = new Fields(this); - } - return fields; - } - - /** - * Returns field descriptor. - */ - public FieldDescriptor getFieldDescriptor(final String name, final boolean declared) { - final FieldDescriptor fieldDescriptor = getFields().getFieldDescriptor(name); - - if (fieldDescriptor != null) { - if (!fieldDescriptor.matchDeclared(declared)) { - return null; - } - } - - return fieldDescriptor; - } - - /** - * Returns all field descriptors, including declared ones. - */ - public FieldDescriptor[] getAllFieldDescriptors() { - return getFields().getAllFieldDescriptors(); - } - - // ---------------------------------------------------------------- methods - - private Methods methods; - - /** - * Returns methods collection. - * Creates new collection on first access. - */ - protected Methods getMethods() { - if (methods == null) { - methods = new Methods(this); - } - return methods; - } - - /** - * Returns {@link MethodDescriptor method descriptor} identified by name and parameters. - */ - public MethodDescriptor getMethodDescriptor(final String name, final boolean declared) { - final MethodDescriptor methodDescriptor = getMethods().getMethodDescriptor(name); - - if ((methodDescriptor != null) && methodDescriptor.matchDeclared(declared)) { - return methodDescriptor; - } - - return methodDescriptor; - } - - - /** - * Returns {@link MethodDescriptor method descriptor} identified by name and parameters. - */ - public MethodDescriptor getMethodDescriptor(final String name, final Class[] params, final boolean declared) { - final MethodDescriptor methodDescriptor = getMethods().getMethodDescriptor(name, params); - - if ((methodDescriptor != null) && methodDescriptor.matchDeclared(declared)) { - return methodDescriptor; - } - - return null; - } - - /** - * Returns an array of all methods with the same name. - */ - public MethodDescriptor[] getAllMethodDescriptors(final String name) { - return getMethods().getAllMethodDescriptors(name); - } - - /** - * Returns an array of all methods. - */ - public MethodDescriptor[] getAllMethodDescriptors() { - return getMethods().getAllMethodDescriptors(); - } - - // ---------------------------------------------------------------- properties - - private Properties properties; - - /** - * Returns properties collection. - * Creates new collection on first access. - */ - protected Properties getProperties() { - if (properties == null) { - properties = new Properties(this); - } - return properties; - } - - /** - * Returns property descriptor. Declared flag is matched on both read and write - * methods. - */ - public PropertyDescriptor getPropertyDescriptor(final String name, final boolean declared) { - PropertyDescriptor propertyDescriptor = getProperties().getPropertyDescriptor(name); - - if ((propertyDescriptor != null) && propertyDescriptor.matchDeclared(declared)) { - return propertyDescriptor; - } - - return null; - } - - /** - * Returns all properties descriptors. - */ - public PropertyDescriptor[] getAllPropertyDescriptors() { - return getProperties().getAllPropertyDescriptors(); - } - - // ---------------------------------------------------------------- ctors - - private Ctors ctors; - - /** - * Returns constructors collection. - * Creates new collection of first access. - */ - protected Ctors getCtors() { - if (ctors == null) { - ctors = new Ctors(this); - } - return ctors; - } - - /** - * Returns the default ctor or null if not found. - */ - public CtorDescriptor getDefaultCtorDescriptor(final boolean declared) { - CtorDescriptor defaultCtor = getCtors().getDefaultCtor(); - - if ((defaultCtor != null) && defaultCtor.matchDeclared(declared)) { - return defaultCtor; - } - return null; - } - - /** - * Returns the constructor identified by arguments or null if not found. - */ - public CtorDescriptor getCtorDescriptor(final Class[] args, final boolean declared) { - CtorDescriptor ctorDescriptor = getCtors().getCtorDescriptor(args); - - if ((ctorDescriptor != null) && ctorDescriptor.matchDeclared(declared)) { - return ctorDescriptor; - } - return null; - } - - /** - * Returns an array of all {@link CtorDescriptor constructor descriptors}. - */ - public CtorDescriptor[] getAllCtorDescriptors() { - return getCtors().getAllCtorDescriptors(); - } - - - // ---------------------------------------------------------------- interfaces - - /** - * Returns all interfaces of this class. - */ - public Class[] getAllInterfaces() { - return interfaces; - } - - /** - * Returns all superclasses of this class. - * Object.class is not included in the - * returned list. - */ - public Class[] getAllSuperclasses() { - return superclasses; - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/ClassIntrospector.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/ClassIntrospector.java deleted file mode 100644 index 8885fa872..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/ClassIntrospector.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - - -import java.util.Objects; - -/** - * Default class {@link ClassIntrospector} simply delegates method calls for - * more convenient usage. - */ -public interface ClassIntrospector { - - class Implementation { - private static ClassIntrospector classIntrospector = new CachingIntrospector(); - - /** - * Sets default implementation. - */ - public static void set(final ClassIntrospector classIntrospector) { - Objects.requireNonNull(classIntrospector); - Implementation.classIntrospector = classIntrospector; - } - } - - /** - * Returns default implementation. - */ - static ClassIntrospector get() { - return Implementation.classIntrospector; - } - - /** - * Returns class descriptor for specified type. - */ - ClassDescriptor lookup(Class type); - - /** - * Clears all cached data. - */ - void reset(); - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/CtorDescriptor.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/CtorDescriptor.java deleted file mode 100644 index cea1a4cc7..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/CtorDescriptor.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.util.ClassUtil; - -import java.lang.reflect.Constructor; - -/** - * Constructor descriptor. - */ -public class CtorDescriptor extends Descriptor { - - protected final Constructor constructor; - protected final Class[] parameters; - - public CtorDescriptor(final ClassDescriptor classDescriptor, final Constructor constructor) { - super(classDescriptor, ClassUtil.isPublic(constructor)); - this.constructor = constructor; - this.parameters = constructor.getParameterTypes(); - - ClassUtil.forceAccess(constructor); - } - - /** - * Returns constructor name. - */ - @Override - public String getName() { - return constructor.getName(); - } - - /** - * Returns constructor. - */ - public Constructor getConstructor() { - return constructor; - } - - /** - * Returns constructors parameters. The returned array - * is not cloned. - */ - public Class[] getParameters() { - return parameters; - } - - /** - * Returns true if this is a default constructor - * (with no parameters). - */ - public boolean isDefault() { - return parameters.length == 0; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Ctors.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Ctors.java deleted file mode 100644 index a48a13734..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Ctors.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import java.lang.reflect.Constructor; - -/** - * Constructors collection. - */ -public class Ctors { - - protected final ClassDescriptor classDescriptor; - protected final CtorDescriptor[] allCtors; - protected CtorDescriptor defaultCtor; - - public Ctors(final ClassDescriptor classDescriptor) { - this.classDescriptor = classDescriptor; - this.allCtors = inspectConstructors(); - } - - /** - * Inspects all declared constructors of a target type. - */ - protected CtorDescriptor[] inspectConstructors() { - Class type = classDescriptor.getType(); - Constructor[] ctors = type.getDeclaredConstructors(); - - CtorDescriptor[] allCtors = new CtorDescriptor[ctors.length]; - - for (int i = 0; i < ctors.length; i++) { - Constructor ctor = ctors[i]; - - CtorDescriptor ctorDescriptor = createCtorDescriptor(ctor); - allCtors[i] = ctorDescriptor; - - if (ctorDescriptor.isDefault()) { - defaultCtor = ctorDescriptor; - } - } - - return allCtors; - } - - /** - * Creates new {@link CtorDescriptor}. - */ - protected CtorDescriptor createCtorDescriptor(final Constructor ctor) { - return new CtorDescriptor(classDescriptor, ctor); - } - - // ---------------------------------------------------------------- get - - /** - * Returns default (no-args) constructor descriptor. - */ - public CtorDescriptor getDefaultCtor() { - return defaultCtor; - } - - /** - * Finds constructor description that matches given argument types. - */ - public CtorDescriptor getCtorDescriptor(final Class... args) { - ctors: - for (CtorDescriptor ctorDescriptor : allCtors) { - Class[] arg = ctorDescriptor.getParameters(); - - if (arg.length != args.length) { - continue; - } - - for (int j = 0; j < arg.length; j++) { - if (arg[j] != args[j]) { - continue ctors; - } - } - - return ctorDescriptor; - } - return null; - } - - /** - * Returns all constructor descriptors. - */ - CtorDescriptor[] getAllCtorDescriptors() { - return allCtors; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Descriptor.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Descriptor.java deleted file mode 100644 index f8d79da0d..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Descriptor.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -/** - * Common descriptor stuff. - */ -public abstract class Descriptor { - - protected final ClassDescriptor classDescriptor; - protected final boolean isPublic; - - protected Descriptor(final ClassDescriptor classDescriptor, final boolean isPublic) { - this.classDescriptor = classDescriptor; - this.isPublic = isPublic; - } - - /** - * Returns belonging class descriptor. - */ - public ClassDescriptor getClassDescriptor() { - return classDescriptor; - } - - /** - * Returns true if descriptor content is public. - */ - public boolean isPublic() { - return isPublic; - } - - /** - * Returns true if descriptor content matches required declared flag. - */ - public boolean matchDeclared(final boolean declared) { - if (!declared) { - return isPublic; - } - return true; - } - - /** - * Returns the name of descriptors target. - */ - public abstract String getName(); - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/FieldDescriptor.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/FieldDescriptor.java deleted file mode 100644 index 7388726b7..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/FieldDescriptor.java +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.util.ClassUtil; - -import java.lang.reflect.Field; -import java.lang.reflect.Type; - -/** - * Field descriptor. Holds additional field data, - * that might be specific to implementation class. - */ -public class FieldDescriptor extends Descriptor { - - public static final FieldDescriptor[] EMPTY_ARRAY = new FieldDescriptor[0]; - - protected final Field field; - protected final Type type; - protected final Class rawType; - protected final Class rawComponentType; - protected final Class rawKeyComponentType; - protected final MapperFunction mapperFunction; - - /** - * Creates new field descriptor and resolve all additional field data. - * Also, forces access to a field. - */ - public FieldDescriptor(final ClassDescriptor classDescriptor, final Field field) { - super(classDescriptor, ClassUtil.isPublic(field)); - this.field = field; - this.type = field.getGenericType(); - this.rawType = ClassUtil.getRawType(type, classDescriptor.getType()); - - final Class[] componentTypes = ClassUtil.getComponentTypes(type, classDescriptor.getType()); - if (componentTypes != null) { - this.rawComponentType = componentTypes[componentTypes.length - 1]; - this.rawKeyComponentType = componentTypes[0]; - } else { - this.rawComponentType = null; - this.rawKeyComponentType = null; - } - - // force access - - ClassUtil.forceAccess(field); - - // mapper - - final Mapper mapper = field.getAnnotation(Mapper.class); - - if (mapper != null) { - mapperFunction = MapperFunctionInstances.get().lookup(mapper.value()); - } else { - mapperFunction = null; - } - } - - /** - * Returns field name. - */ - @Override - public String getName() { - return field.getName(); - } - - /** - * Returns field. - */ - public Field getField() { - return field; - } - - /** - * Returns fields raw type. - */ - public Class getRawType() { - return rawType; - } - - /** - * Returns fields raw component type. Returns null - * if field has no component type. - */ - public Class getRawComponentType() { - return rawComponentType; - } - - /** - * Returns fields raw component type. Returns null - * if field has no component type. - */ - public Class getRawKeyComponentType() { - return rawKeyComponentType; - } - - /** - * Resolves raw component type for given index. This value is NOT cached. - */ - public Class[] resolveRawComponentTypes() { - return ClassUtil.getComponentTypes(type, classDescriptor.getType()); - } - - // ---------------------------------------------------------------- toString - - @Override - public String toString() { - return classDescriptor.getType().getSimpleName() + '#' + field.getName(); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Fields.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Fields.java deleted file mode 100644 index 33a1cc876..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Fields.java +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.util.ClassUtil; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -/** - * Collection of {@link FieldDescriptor field descriptors}. - */ -public class Fields { - - protected final ClassDescriptor classDescriptor; - protected final Map fieldsMap; - - // cache - private FieldDescriptor[] allFields; - - /** - * Creates new fields collection. - */ - public Fields(final ClassDescriptor classDescriptor) { - this.classDescriptor = classDescriptor; - this.fieldsMap = inspectFields(); - } - - /** - * Inspects fields and returns map of {@link FieldDescriptor field descriptors}. - */ - private Map inspectFields() { - if (classDescriptor.isSystemClass()) { - return emptyFields(); - } - final boolean scanAccessible = classDescriptor.isScanAccessible(); - final Class type = classDescriptor.getType(); - - final Field[] fields = scanAccessible ? ClassUtil.getAccessibleFields(type) : ClassUtil.getSupportedFields(type); - - final HashMap map = new HashMap<>(fields.length); - - for (final Field field : fields) { - final String fieldName = field.getName(); - - if (fieldName.equals("serialVersionUID")) { - continue; - } - - map.put(fieldName, createFieldDescriptor(field)); - } - - return map; - } - - /** - * Defines empty fields for special cases. - */ - private Map emptyFields() { - allFields = FieldDescriptor.EMPTY_ARRAY; - return Collections.emptyMap(); - } - - /** - * Creates new {@code FieldDescriptor}. - */ - protected FieldDescriptor createFieldDescriptor(final Field field) { - return new FieldDescriptor(classDescriptor, field); - } - - - // ---------------------------------------------------------------- get - - /** - * Returns {@link FieldDescriptor field descriptor} for given field name - * or null if field does not exist. - */ - public FieldDescriptor getFieldDescriptor(final String name) { - return fieldsMap.get(name); - } - - /** - * Returns all fields of this collection. Returns empty array - * if no fields exist. Initialized lazy. - */ - public FieldDescriptor[] getAllFieldDescriptors() { - if (allFields == null) { - FieldDescriptor[] allFields = new FieldDescriptor[fieldsMap.size()]; - - int index = 0; - for (FieldDescriptor fieldDescriptor : fieldsMap.values()) { - allFields[index] = fieldDescriptor; - index++; - } - - Arrays.sort(allFields, Comparator.comparing(fd -> fd.getField().getName())); - - this.allFields = allFields; - } - return allFields; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Getter.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Getter.java deleted file mode 100644 index 2c62afc99..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Getter.java +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import java.lang.reflect.InvocationTargetException; - -/** - * Unified getter property interface for both methods and fields. - */ -public interface Getter { - - static Getter of(final MethodDescriptor methodDescriptor) { - - return new Getter() { - - @Override - public Object invokeGetter(final Object target) throws InvocationTargetException, IllegalAccessException { - return methodDescriptor.method.invoke(target); - } - - @Override - public Class getGetterRawType() { - return methodDescriptor.getRawReturnType(); - } - - @Override - public Class getGetterRawComponentType() { - return methodDescriptor.getRawReturnComponentType(); - } - - @Override - public Class getGetterRawKeyComponentType() { - return methodDescriptor.getRawReturnKeyComponentType(); - } - }; - } - - static Getter of(final FieldDescriptor fieldDescriptor) { - return new Getter() { - - @Override - public Object invokeGetter(final Object target) throws IllegalAccessException { - return fieldDescriptor.field.get(target); - } - - @Override - public Class getGetterRawType() { - return fieldDescriptor.getRawType(); - } - - @Override - public Class getGetterRawComponentType() { - return fieldDescriptor.getRawComponentType(); - } - - @Override - public Class getGetterRawKeyComponentType() { - return fieldDescriptor.getRawKeyComponentType(); - } - }; - } - - Object invokeGetter(Object target) throws InvocationTargetException, IllegalAccessException; - - Class getGetterRawType(); - - Class getGetterRawComponentType(); - - Class getGetterRawKeyComponentType(); - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Mapper.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Mapper.java deleted file mode 100644 index 27c5c477b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Mapper.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Value or type mapper. - * @see MapperFunction - */ -@Documented -@Retention(value = RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) -public @interface Mapper { - Class value(); -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MapperFunction.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MapperFunction.java deleted file mode 100644 index 436473bcf..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MapperFunction.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import java.util.function.Function; - -/** - * Mapper function allows object to be converted before actually used - usually before injected using - * {@link com.fr.third.jodd.bean.BeanUtil}. - */ -@FunctionalInterface -public interface MapperFunction extends Function { - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MapperFunctionInstances.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MapperFunctionInstances.java deleted file mode 100644 index 06ad30946..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MapperFunctionInstances.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.cache.TypeCache; -import com.fr.third.jodd.util.ClassUtil; - -/** - * Simple cache of {@link MapperFunction} instances. - */ -public class MapperFunctionInstances { - - private static final MapperFunctionInstances MAPPER_FUNCTION_INSTANCES = new MapperFunctionInstances(); - - /** - * Returns the instance. - */ - public static MapperFunctionInstances get() { - return MAPPER_FUNCTION_INSTANCES; - } - - protected TypeCache typeCache = TypeCache.createDefault(); - - public MapperFunction lookup(final Class mapperFunctionClass) { - return typeCache.get(mapperFunctionClass, (c) -> { - try { - return ClassUtil.newInstance(mapperFunctionClass); - } catch (final Exception ex) { - throw new IllegalArgumentException("Invalid mapper class " + c, ex); - } - }); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MethodDescriptor.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MethodDescriptor.java deleted file mode 100644 index 4b45abbff..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MethodDescriptor.java +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.util.ClassUtil; - -import java.lang.reflect.Method; -import java.lang.reflect.Type; - -/** - * Method descriptor. Holds additional method data, - * that might be specific to implementation class. - */ -public class MethodDescriptor extends Descriptor { - - private static final MethodParamDescriptor[] NO_PARAMS = new MethodParamDescriptor[0]; - - protected final Method method; - protected final Type returnType; - protected final Class rawReturnType; - protected final Class rawReturnComponentType; - protected final Class rawReturnKeyComponentType; - protected final MethodParamDescriptor[] parameters; - protected final MapperFunction mapperFunction; - -// protected final Function getterFunction; - - public MethodDescriptor(final ClassDescriptor classDescriptor, final Method method) { - super(classDescriptor, ClassUtil.isPublic(method)); - this.method = method; - this.returnType = method.getGenericReturnType(); - this.rawReturnType = ClassUtil.getRawType(returnType, classDescriptor.getType()); - - final Class[] componentTypes = ClassUtil.getComponentTypes(returnType, classDescriptor.getType()); - if (componentTypes != null) { - this.rawReturnComponentType = componentTypes[componentTypes.length - 1]; - this.rawReturnKeyComponentType = componentTypes[0]; - } else { - this.rawReturnComponentType = null; - this.rawReturnKeyComponentType = null; - } - - // force access - - ClassUtil.forceAccess(method); - - // mapper - - final Mapper mapper = method.getAnnotation(Mapper.class); - - if (mapper != null) { - mapperFunction = MapperFunctionInstances.get().lookup(mapper.value()); - } else { - mapperFunction = null; - } - - // parameters - - if (method.getParameterCount() == 0) { - parameters = NO_PARAMS; - } - else { - parameters = new MethodParamDescriptor[method.getParameterCount()]; - - Class[] params = method.getParameterTypes(); - Type[] genericParams = method.getGenericParameterTypes(); - - for (int i = 0; i < params.length; i++) { - final Class parameterType = params[i]; - final Class rawParameterType = genericParams.length == 0 ? - parameterType : - ClassUtil.getRawType(genericParams[i], classDescriptor.getType()); - final Class rawParameterComponentType = genericParams.length == 0 ? - null : - ClassUtil.getComponentType(genericParams[i], classDescriptor.getType(), -1); - - parameters[i] = new MethodParamDescriptor(parameterType, rawParameterType, rawParameterComponentType); - } - } - -// try { -// MethodHandles.Lookup lookup = MethodHandles.lookup(); -// CallSite callSite = LambdaMetafactory.metafactory(lookup, -// "apply", -// MethodType.methodType(Function.class), -// MethodType.methodType(Object.class, Object.class), -// lookup.findVirtual( -// classDescriptor.getType(), -// method.getName(), -// MethodType.methodType(method.getReturnType())), -// MethodType.methodType(method.getReturnType(), classDescriptor.type) -// ); -// -// this.getterFunction = (Function) callSite.getTarget().invokeExact(); -// } -// catch (Throwable ex) { -// throw new IllegalArgumentException(ex); -// } - } - - /** - * Returns method name. - */ - @Override - public String getName() { - return method.getName(); - } - - /** - * Returns method. - */ - public Method getMethod() { - return method; - } - - /** - * Returns raw return type. - */ - public Class getRawReturnType() { - return rawReturnType; - } - - /** - * Returns raw component type of return type. - * May be null if return type does not have - * components. - */ - public Class getRawReturnComponentType() { - return rawReturnComponentType; - } - - /** - * Returns raw component type of return type. - * May be null if return type does not have - * components. - */ - public Class getRawReturnKeyComponentType() { - return rawReturnKeyComponentType; - } - - /** - * Resolves raw return component types - * This value is NOT cached. - */ - public Class[] resolveRawReturnComponentTypes() { - return ClassUtil.getComponentTypes(returnType, classDescriptor.getType()); - } - - /** - * Returns {@link MethodParamDescriptor method parameteres}. - */ - public MethodParamDescriptor[] getParameters() { - return parameters; - } - - /** - * Returns number of parameters. - */ - public int getParameterCount() { - return parameters.length; - } - - // ---------------------------------------------------------------- toString - - @Override - public String toString() { - return classDescriptor.getType().getSimpleName() + '#' + method.getName() + "()"; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MethodParamDescriptor.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MethodParamDescriptor.java deleted file mode 100644 index 7ee278c52..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/MethodParamDescriptor.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -/** - * Method parameter descriptor. - */ -public class MethodParamDescriptor { - protected final Class type; - protected final Class rawType; - protected final Class rawComponentType; - - public MethodParamDescriptor(final Class parameterType, final Class rawParameterType, final Class rawParameterComponentType) { - this.type = parameterType; - this.rawType = rawParameterType; - this.rawComponentType = rawParameterComponentType; - } - - public Class getType() { - return type; - } - - public Class getRawType() { - return rawType; - } - - public Class getRawComponentType() { - return rawComponentType; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Methods.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Methods.java deleted file mode 100644 index 75e8e267d..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Methods.java +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.util.ArraysUtil; -import com.fr.third.jodd.util.ClassUtil; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; - -/** - * Methods collection. - */ -public class Methods { - - protected final ClassDescriptor classDescriptor; - protected final HashMap methodsMap; - - // cache - private MethodDescriptor[] allMethods; - - public Methods(final ClassDescriptor classDescriptor) { - this.classDescriptor = classDescriptor; - this.methodsMap = inspectMethods(); - } - - /** - * Inspects types methods and return map of {@link MethodDescriptor method descriptors}. - */ - protected HashMap inspectMethods() { - boolean scanAccessible = classDescriptor.isScanAccessible(); - - if (classDescriptor.isSystemClass()) { - scanAccessible = false; - } - - final Class type = classDescriptor.getType(); - - final Method[] methods = scanAccessible ? ClassUtil.getAccessibleMethods(type) : ClassUtil.getSupportedMethods(type); - - final HashMap map = new HashMap<>(methods.length); - - for (final Method method : methods) { - final String methodName = method.getName(); - - MethodDescriptor[] mds = map.get(methodName); - - if (mds == null) { - mds = new MethodDescriptor[1]; - } else { - mds = ArraysUtil.resize(mds, mds.length + 1); - } - - map.put(methodName, mds); - - mds[mds.length - 1] = createMethodDescriptor(method); - } - - return map; - } - - /** - * Creates new {@code MethodDescriptor}. - */ - protected MethodDescriptor createMethodDescriptor(final Method method) { - return new MethodDescriptor(classDescriptor, method); - } - - - // ---------------------------------------------------------------- get - - /** - * Returns a method that matches given name and parameter types. - * Returns null if method is not found. - */ - public MethodDescriptor getMethodDescriptor(final String name, final Class[] paramTypes) { - final MethodDescriptor[] methodDescriptors = methodsMap.get(name); - if (methodDescriptors == null) { - return null; - } - for (MethodDescriptor methodDescriptor : methodDescriptors) { - final Method m = methodDescriptor.getMethod(); - if (ClassUtil.compareParameters(m.getParameterTypes(), paramTypes)) { - return methodDescriptor; - } - } - return null; - } - - /** - * Returns method descriptor for given name. If more then one methods with - * the same name exists, one method will be returned (not determined which one). - * Returns null if no method exist in this collection by given name. - * @see #getMethodDescriptor(String, Class[]) - */ - public MethodDescriptor getMethodDescriptor(final String name) { - final MethodDescriptor[] methodDescriptors = methodsMap.get(name); - if (methodDescriptors == null) { - return null; - } - if (methodDescriptors.length != 1) { - throw new IllegalArgumentException("Method name not unique: " + name); - } - return methodDescriptors[0]; - } - - /** - * Returns all methods for given name. Returns null if method not found. - */ - public MethodDescriptor[] getAllMethodDescriptors(final String name) { - return methodsMap.get(name); - } - - /** - * Returns all methods. Cached. Lazy. - */ - public MethodDescriptor[] getAllMethodDescriptors() { - if (allMethods == null) { - final List allMethodsList = new ArrayList<>(); - - for (MethodDescriptor[] methodDescriptors : methodsMap.values()) { - Collections.addAll(allMethodsList, methodDescriptors); - } - - final MethodDescriptor[] allMethods = allMethodsList.toArray(new MethodDescriptor[0]); - - Arrays.sort(allMethods, Comparator.comparing(md -> md.getMethod().getName())); - - this.allMethods = allMethods; - } - return allMethods; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Properties.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Properties.java deleted file mode 100644 index 1fbca304f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Properties.java +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import com.fr.third.jodd.util.ClassUtil; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; - -import static com.fr.third.jodd.util.ClassUtil.METHOD_GET_PREFIX; -import static com.fr.third.jodd.util.ClassUtil.METHOD_IS_PREFIX; - -/** - * Bean properties collection. Property in Java is defined as a pair of - * read and write method. In Jodd, property can be extended with field - * definition. Moreover, properties will include just single fields. - * This behavior can be controlled via {@link ClassDescriptor}. - */ -public class Properties { - - protected final ClassDescriptor classDescriptor; - protected final HashMap propertyDescriptors; - - // cache - private PropertyDescriptor[] allProperties; - - public Properties(final ClassDescriptor classDescriptor) { - this.classDescriptor = classDescriptor; - this.propertyDescriptors = inspectProperties(); - } - - /** - * Inspects all properties of target type. - */ - protected HashMap inspectProperties() { - boolean scanAccessible = classDescriptor.isScanAccessible(); - Class type = classDescriptor.getType(); - - HashMap map = new HashMap<>(); - - Method[] methods = scanAccessible ? ClassUtil.getAccessibleMethods(type) : ClassUtil.getSupportedMethods(type); - - for (int iteration = 0; iteration < 2; iteration++) { - // first find the getters, and then the setters! - for (Method method : methods) { - if (Modifier.isStatic(method.getModifiers())) { - continue; // ignore static methods - } - - boolean add = false; - boolean issetter = false; - - String propertyName; - - if (iteration == 0) { - propertyName = ClassUtil.getBeanPropertyGetterName(method); - if (propertyName != null) { - add = true; - issetter = false; - } - } else { - propertyName = ClassUtil.getBeanPropertySetterName(method); - if (propertyName != null) { - add = true; - issetter = true; - } - } - - if (add) { - MethodDescriptor methodDescriptor = classDescriptor.getMethodDescriptor(method.getName(), method.getParameterTypes(), true); - addProperty(map, propertyName, methodDescriptor, issetter); - } - } - } - - if (classDescriptor.isIncludeFieldsAsProperties()) { - FieldDescriptor[] fieldDescriptors = classDescriptor.getAllFieldDescriptors(); - String[] prefix = classDescriptor.getPropertyFieldPrefix(); - - for (FieldDescriptor fieldDescriptor : fieldDescriptors) { - Field field = fieldDescriptor.getField(); - - if (Modifier.isStatic(field.getModifiers())) { - continue; // ignore static fields - } - - String name = field.getName(); - - if (prefix != null) { - for (String p : prefix) { - if (!name.startsWith(p)) { - continue; - } - name = name.substring(p.length()); - break; - } - } - - if (!map.containsKey(name)) { - // add missing field as a potential property - map.put(name, createPropertyDescriptor(name, fieldDescriptor)); - } - } - - } - - return map; - } - - - /** - * Adds a setter and/or getter method to the property. - * If property is already defined, the new, updated, definition will be created. - */ - protected void addProperty(final HashMap map, final String name, final MethodDescriptor methodDescriptor, final boolean isSetter) { - MethodDescriptor setterMethod = isSetter ? methodDescriptor : null; - MethodDescriptor getterMethod = isSetter ? null : methodDescriptor; - - PropertyDescriptor existing = map.get(name); - - if (existing == null) { - // new property, just add it - PropertyDescriptor propertyDescriptor = createPropertyDescriptor(name, getterMethod, setterMethod); - - map.put(name, propertyDescriptor); - return; - } - - // property exist - - if (!isSetter) { - // use existing setter - setterMethod = existing.getWriteMethodDescriptor(); - - // check existing - MethodDescriptor existingMethodDescriptor = existing.getReadMethodDescriptor(); - if (existingMethodDescriptor != null) { - // check for special case of double get/is - - // getter with the same name already exist - String methodName = methodDescriptor.getMethod().getName(); - String existingMethodName = existingMethodDescriptor.getMethod().getName(); - - if ( - existingMethodName.startsWith(METHOD_IS_PREFIX) && - methodName.startsWith(METHOD_GET_PREFIX)) { - - // ignore getter when ister exist - return; - } - } - } else { - // setter - // use existing getter - getterMethod = existing.getReadMethodDescriptor(); - - if (getterMethod != null) { - Class returnType = getterMethod.getMethod().getReturnType(); - - if (setterMethod != null) { - Class parameterType = setterMethod.getMethod().getParameterTypes()[0]; - - if (returnType != parameterType) { - // getter's type is different then setter's - return; - } - - } - } - } - - PropertyDescriptor propertyDescriptor = createPropertyDescriptor(name, getterMethod, setterMethod); - - map.put(name, propertyDescriptor); - } - - /** - * Creates new {@link PropertyDescriptor}. Note that this method may be called - * up to three times (depends on use case) for the same property. Each time when - * a property is updated, a new definition is created with updated information. - */ - protected PropertyDescriptor createPropertyDescriptor(final String name, final MethodDescriptor getterMethod, final MethodDescriptor setterMethod) { - return new PropertyDescriptor(classDescriptor, name, getterMethod, setterMethod); - } - - /** - * Creates new field-only {@link PropertyDescriptor}. It will be invoked only once. - */ - protected PropertyDescriptor createPropertyDescriptor(final String name, final FieldDescriptor fieldDescriptor) { - return new PropertyDescriptor(classDescriptor, name, fieldDescriptor); - } - - // ---------------------------------------------------------------- get - - /** - * Returns {@link PropertyDescriptor property descriptor}. - */ - public PropertyDescriptor getPropertyDescriptor(final String name) { - return propertyDescriptors.get(name); - } - - /** - * Returns all property descriptors. - * Properties are sorted by name. - */ - public PropertyDescriptor[] getAllPropertyDescriptors() { - if (allProperties == null) { - PropertyDescriptor[] allProperties = new PropertyDescriptor[propertyDescriptors.size()]; - - int index = 0; - for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) { - allProperties[index] = propertyDescriptor; - index++; - } - - Arrays.sort(allProperties, new Comparator() { - @Override - public int compare(final PropertyDescriptor pd1, final PropertyDescriptor pd2) { - return pd1.getName().compareTo(pd2.getName()); - } - }); - - this.allProperties = allProperties; - } - return allProperties; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/PropertyDescriptor.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/PropertyDescriptor.java deleted file mode 100644 index b6fdb3034..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/PropertyDescriptor.java +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -/** - * Property descriptor. It consist of read, write and field descriptor. - * Only one of those three descriptors may exist. - */ -public class PropertyDescriptor extends Descriptor { - - protected final String name; - protected final MethodDescriptor readMethodDescriptor; - protected final MethodDescriptor writeMethodDescriptor; - protected final FieldDescriptor fieldDescriptor; - - /** - * Creates field-only property descriptor. - */ - public PropertyDescriptor(final ClassDescriptor classDescriptor, final String propertyName, final FieldDescriptor fieldDescriptor) { - super(classDescriptor, false); - this.name = propertyName; - this.readMethodDescriptor = null; - this.writeMethodDescriptor = null; - this.fieldDescriptor = fieldDescriptor; - } - - /** - * Creates property descriptor. - */ - public PropertyDescriptor(final ClassDescriptor classDescriptor, final String propertyName, final MethodDescriptor readMethod, final MethodDescriptor writeMethod) { - super(classDescriptor, - ((readMethod == null) || readMethod.isPublic()) & (writeMethod == null || writeMethod.isPublic()) - ); - this.name = propertyName; - this.readMethodDescriptor = readMethod; - this.writeMethodDescriptor = writeMethod; - - if (classDescriptor.isExtendedProperties()) { - String[] prefix = classDescriptor.getPropertyFieldPrefix(); - - FieldDescriptor fd = null; - - if (prefix != null) { - for (String p : prefix) { - fd = findField(p + propertyName); - - if (fd != null) { - break; - } - } - } - else { - fd = findField(propertyName); - } - - this.fieldDescriptor = fd; - } else { - this.fieldDescriptor = null; - } - } - - /** - * Locates property field. Field is being searched also in all - * superclasses of current class. - */ - protected FieldDescriptor findField(final String fieldName) { - FieldDescriptor fieldDescriptor = classDescriptor.getFieldDescriptor(fieldName, true); - - if (fieldDescriptor != null) { - return fieldDescriptor; - } - - // field descriptor not found in this class - // try to locate it in the superclasses - - Class[] superclasses = classDescriptor.getAllSuperclasses(); - - for (Class superclass : superclasses) { - - ClassDescriptor classDescriptor = ClassIntrospector.get().lookup(superclass); - - fieldDescriptor = classDescriptor.getFieldDescriptor(fieldName, true); - - if (fieldDescriptor != null) { - return fieldDescriptor; - } - } - - // nothing found - return null; - } - - /** - * Returns property name. - */ - @Override - public String getName() { - return name; - } - - /** - * Returns read method of this property. - * May be null if read method is not defined. - */ - public MethodDescriptor getReadMethodDescriptor() { - return readMethodDescriptor; - } - - /** - * Returns write method of this property. - * May be null for read-only properties. - */ - public MethodDescriptor getWriteMethodDescriptor() { - return writeMethodDescriptor; - } - - /** - * Returns the associated field of this property. - * May be null if properties are not enhanced by field description. - */ - public FieldDescriptor getFieldDescriptor() { - return fieldDescriptor; - } - - /** - * Returns true if this is an extended property with - * only field definition and without getter and setter. - */ - public boolean isFieldOnly() { - return (readMethodDescriptor == null) && (writeMethodDescriptor == null); - } - - /** - * Returns true if this property has only a getter method. - */ - public boolean isGetterOnly() { - return (fieldDescriptor == null) && (writeMethodDescriptor == null); - } - - /** - * Returns true if this property has only a setter method. - */ - public boolean isSetterOnly() { - return (fieldDescriptor == null) && (readMethodDescriptor == null); - } - - // ---------------------------------------------------------------- type - - protected Class type; - - /** - * Returns property type. Raw types are detected. - */ - public Class getType() { - if (type == null) { - if (fieldDescriptor != null) { - type = fieldDescriptor.getRawType(); - } - else if (readMethodDescriptor != null) { - type = getGetter(true).getGetterRawType(); - //type = readMethodDescriptor.getGetterRawType(); - } - else if (writeMethodDescriptor != null) { - type = getSetter(true).getSetterRawType(); - //type = writeMethodDescriptor.getSetterRawType(); - } - } - - return type; - } - - // ---------------------------------------------------------------- getters & setters - - protected Getter[] getters; - protected Setter[] setters; - - /** - * Returns {@link Getter}. May return null - * if no matched getter is found. - */ - public Getter getGetter(final boolean declared) { - if (getters == null) { - getters = new Getter[] { - createGetter(false), - createGetter(true), - }; - } - - return getters[declared ? 1 : 0]; - } - - /** - * Creates a {@link Getter}. - */ - protected Getter createGetter(final boolean declared) { - if (readMethodDescriptor != null) { - if (readMethodDescriptor.matchDeclared(declared)) { - return Getter.of(readMethodDescriptor); - } - } - if (fieldDescriptor != null) { - if (fieldDescriptor.matchDeclared(declared)) { - return Getter.of(fieldDescriptor); - } - } - return null; - } - - - /** - * Returns {@link Setter}. May return null - * if no matched setter is found. - */ - public Setter getSetter(final boolean declared) { - if (setters == null) { - setters = new Setter[] { - createSetter(false), - createSetter(true), - }; - } - - return setters[declared ? 1 : 0]; - } - - /** - * Creates a {@link Setter}. - */ - protected Setter createSetter(final boolean declared) { - if (writeMethodDescriptor != null) { - if (writeMethodDescriptor.matchDeclared(declared)) { - return Setter.of(writeMethodDescriptor); - } - } - if (fieldDescriptor != null) { - if (fieldDescriptor.matchDeclared(declared)) { - return Setter.of(fieldDescriptor); - } - } - return null; - } - - // ---------------------------------------------------------------- resolvers - - /** - * Resolves key type for given property descriptor. - */ - public Class resolveKeyType(final boolean declared) { - Class keyType = null; - - Getter getter = getGetter(declared); - - if (getter != null) { - keyType = getter.getGetterRawKeyComponentType(); - } - - if (keyType == null) { - FieldDescriptor fieldDescriptor = getFieldDescriptor(); - - if (fieldDescriptor != null) { - keyType = fieldDescriptor.getRawKeyComponentType(); - } - } - - return keyType; - } - - /** - * Resolves component type for given property descriptor. - */ - public Class resolveComponentType(final boolean declared) { - Class componentType = null; - - Getter getter = getGetter(declared); - - if (getter != null) { - componentType = getter.getGetterRawComponentType(); - } - - if (componentType == null) { - FieldDescriptor fieldDescriptor = getFieldDescriptor(); - - if (fieldDescriptor != null) { - componentType = fieldDescriptor.getRawComponentType(); - } - } - - return componentType; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Setter.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Setter.java deleted file mode 100644 index a03e9f6ff..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/Setter.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.introspector; - -import java.lang.reflect.InvocationTargetException; - -/** - * Unified setter property interface for both methods and fields. - */ -public interface Setter { - - static Setter of(final MethodDescriptor methodDescriptor) { - return new Setter() { - @Override - public void invokeSetter(final Object target, final Object argument) throws InvocationTargetException, IllegalAccessException { - methodDescriptor.method.invoke(target, argument); - } - - @Override - public Class getSetterRawType() { - return methodDescriptor.getParameters()[0].getRawType(); - } - - @Override - public Class getSetterRawComponentType() { - return methodDescriptor.getParameters()[0].getRawComponentType(); - } - - @Override - public MapperFunction getMapperFunction() { - return methodDescriptor.mapperFunction; - } - }; - } - - static Setter of(final FieldDescriptor fieldDescriptor) { - return new Setter() { - @Override - public void invokeSetter(final Object target, final Object argument) throws IllegalAccessException { - fieldDescriptor.field.set(target, argument); - } - - @Override - public Class getSetterRawType() { - return fieldDescriptor.getRawType(); - } - - @Override - public Class getSetterRawComponentType() { - return fieldDescriptor.getRawComponentType(); - } - - @Override - public MapperFunction getMapperFunction() { - return fieldDescriptor.mapperFunction; - } - }; - } - - void invokeSetter(Object target, Object argument) throws IllegalAccessException, InvocationTargetException; - - Class getSetterRawType(); - - Class getSetterRawComponentType(); - - MapperFunction getMapperFunction(); -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/introspector/package-info.java deleted file mode 100644 index 4d9220a84..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/introspector/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Very fast reflection introspector. - */ -package com.fr.third.jodd.introspector; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/AppendableWriter.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/AppendableWriter.java deleted file mode 100644 index 18c460b99..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/AppendableWriter.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package com.fr.third.jodd.io; - -import java.io.Closeable; -import java.io.Flushable; -import java.io.IOException; -import java.io.Writer; -import java.nio.CharBuffer; - -/** - * Appendable writer adapter. - */ -public class AppendableWriter extends Writer { - - private final Appendable appendable; - private final boolean flushable; - private boolean closed; - - public AppendableWriter(final Appendable appendable) { - this.appendable = appendable; - this.flushable = appendable instanceof Flushable; - this.closed = false; - } - - @Override - public void write(final char[] cbuf, final int off, final int len) throws IOException { - checkNotClosed(); - appendable.append(CharBuffer.wrap(cbuf), off, off + len); - } - - @Override - public void write(final int c) throws IOException { - checkNotClosed(); - appendable.append((char) c); - } - - @Override - public Writer append(final char c) throws IOException { - checkNotClosed(); - appendable.append(c); - return this; - } - - @Override - public Writer append(final CharSequence csq, final int start, final int end) throws IOException { - checkNotClosed(); - appendable.append(csq, start, end); - return this; - } - - @Override - public Writer append(final CharSequence csq) throws IOException { - checkNotClosed(); - appendable.append(csq); - return this; - } - - @Override - public void write(final String str, final int off, final int len) throws IOException { - checkNotClosed(); - appendable.append(str, off, off + len); - } - - @Override - public void write(final String str) throws IOException { - appendable.append(str); - } - - @Override - public void write(final char[] cbuf) throws IOException { - appendable.append(CharBuffer.wrap(cbuf)); - } - - @Override - public void flush() throws IOException { - checkNotClosed(); - if (flushable) { - ((Flushable) appendable).flush(); - } - } - - private void checkNotClosed() throws IOException { - if (closed) { - throw new IOException("Cannot write to closed writer " + this); - } - } - - @Override - public void close() throws IOException { - if (!closed) { - flush(); - if (appendable instanceof Closeable) { - ((Closeable) appendable).close(); - } - closed = true; - } - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/CharBufferReader.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/CharBufferReader.java deleted file mode 100644 index 9a5b6a38e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/CharBufferReader.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import java.io.Reader; -import java.nio.CharBuffer; - -/** - * Reader that wraps a CharBuffer. - */ -public class CharBufferReader extends Reader { - - private final CharBuffer charBuffer; - - public CharBufferReader(final CharBuffer charBuffer) { - // duplicate so to allow to move independently, - // but share the same underlying data. - this.charBuffer = charBuffer.duplicate(); - } - - @Override - public int read(final char[] chars, final int offset, final int length) { - int read = Math.min(charBuffer.remaining(), length); - charBuffer.get(chars, offset, read); - return read; - } - - @Override - public int read() { - return charBuffer.position() < charBuffer.limit() ? charBuffer.get() : -1; - } - - @Override - public void close() { - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/FastByteArrayOutputStream.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/FastByteArrayOutputStream.java deleted file mode 100644 index 69efb4ee8..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/FastByteArrayOutputStream.java +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.util.StringUtil; -import com.fr.third.jodd.buffer.FastByteBuffer; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * This class implements an {@link OutputStream} in which the data is - * written into a byte array. The buffer automatically grows as data - * is written to it. - *

- * The data can be retrieved using {@link #toByteArray()} and {@link #toString}. - *

- * Closing a {@link FastByteArrayOutputStream} has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an {@link IOException}. - *

- * This is an alternative implementation of the {@code java.io.FastByteArrayOutputStream} - * class. The original implementation only allocates 32 bytes at the beginning. - * As this class is designed for heavy duty it starts at 1024 bytes. In contrast - * to the original it doesn't reallocate the whole memory block but allocates - * additional buffers. This way no buffers need to be garbage collected and - * the contents don't have to be copied to the new buffer. This class is - * designed to behave exactly like the original. The only exception is the - * deprecated {@code java.io.FastByteArrayOutputStream#toString(int)} method that has been ignored. - */ -public class FastByteArrayOutputStream extends OutputStream { - - private final FastByteBuffer buffer; - - /** - * Creates a new byte array {@link OutputStream}. The buffer capacity is - * initially 1024 bytes, though its size increases if necessary. - */ - public FastByteArrayOutputStream() { - this(1024); - } - - /** - * Creates a new byte array output stream, with a buffer capacity of - * the specified size, in bytes. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastByteArrayOutputStream(final int size) { - buffer = new FastByteBuffer(size); - } - - /** - * @see OutputStream#write(byte[], int, int) - */ - @Override - public void write(final byte[] b, final int off, final int len) { - buffer.append(b, off, len); - } - - /** - * Writes single byte. - */ - @Override - public void write(final int b) { - buffer.append((byte) b); - } - - /** - * @see ByteArrayOutputStream#size() - */ - public int size() { - return buffer.size(); - } - - /** - * Closing a {@link FastByteArrayOutputStream} has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an {@link IOException}. - */ - @Override - public void close() { - //nop - } - - /** - * @see ByteArrayOutputStream#reset() - */ - public void reset() { - buffer.clear(); - } - - /** - * @see ByteArrayOutputStream#writeTo(OutputStream) - */ - public void writeTo(final OutputStream out) throws IOException { - out.write(buffer.toArray()); - } - - /** - * @see ByteArrayOutputStream#toByteArray() - */ - public byte[] toByteArray() { - return buffer.toArray(); - } - - /** - * @see ByteArrayOutputStream#toString() - */ - @Override - public String toString() { - return new String(toByteArray()); - } - - /** - * @see ByteArrayOutputStream#toString(String) - */ - public String toString(final String enc) { - return StringUtil.newString(toByteArray(), enc); - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/FastCharArrayWriter.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/FastCharArrayWriter.java deleted file mode 100644 index cc4a690bb..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/FastCharArrayWriter.java +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.buffer.FastCharBuffer; - -import java.io.CharArrayWriter; -import java.io.IOException; -import java.io.Writer; - -/** - * Similar to {@link FastByteArrayOutputStream} but for {@link Writer}. - */ -public class FastCharArrayWriter extends Writer { - - private final FastCharBuffer buffer; - - /** - * Creates a new writer. The buffer capacity is - * initially 1024 bytes, though its size increases if necessary. - */ - public FastCharArrayWriter() { - this(1024); - } - - /** - * Creates a new char array {@link Writer}, with a buffer capacity of - * the specified size, in bytes. - * - * @param size the initial size. - * @throws IllegalArgumentException if size is negative. - */ - public FastCharArrayWriter(final int size) { - buffer = new FastCharBuffer(size); - } - - /** - * @see Writer#write(char[], int, int) - */ - @Override - public void write(final char[] b, final int off, final int len) { - buffer.append(b, off, len); - } - - /** - * Writes single byte. - */ - @Override - public void write(final int b) { - buffer.append((char) b); - } - - @Override - public void write(final String s, final int off, final int len) { - write(s.toCharArray(), off, len); - } - - /** - * @see CharArrayWriter#size() - */ - public int size() { - return buffer.size(); - } - - /** - * Closing a {@link FastCharArrayWriter} has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an {@link IOException}. - */ - @Override - public void close() { - //nop - } - - /** - * Flushing a {@link FastCharArrayWriter} has no effects. - */ - @Override - public void flush() { - //nop - } - - /** - * @see CharArrayWriter#reset() - */ - public void reset() { - buffer.clear(); - } - - /** - * @see CharArrayWriter#writeTo(Writer) - */ - public void writeTo(final Writer out) throws IOException { - out.write(buffer.toArray()); - } - - /** - * @see CharArrayWriter#toCharArray() - */ - public char[] toCharArray() { - return buffer.toArray(); - } - - /** - * @see CharArrayWriter#toString() - */ - @Override - public String toString() { - return new String(toCharArray()); - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/FileNameUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/FileNameUtil.java deleted file mode 100644 index dccab081a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/FileNameUtil.java +++ /dev/null @@ -1,1006 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.system.SystemUtil; -import com.fr.third.jodd.util.StringPool; - -import java.io.File; - -/** - * General filename and filepath manipulation utilities. - *

- * When dealing with filenames you can hit problems when moving from a Windows - * based development machine to a Unix based production machine. - * This class aims to help avoid those problems. - *

- * NOTE: You may be able to avoid using this class entirely simply by - * using JDK {@link java.io.File File} objects and the two argument constructor - * {@link java.io.File#File(java.io.File, java.lang.String) File(File,String)}. - *

- * Most methods on this class are designed to work the same on both Unix and Windows. - * Those that don't include 'System', 'Unix' or 'Windows' in their name. - *

- * Most methods recognise both separators (forward and back), and both - * sets of prefixes. See the javadoc of each method for details. - *

- * This class defines six components within a filename - * (example C:\dev\project\file.txt): - *

    - *
  • the prefix - C:\
  • - *
  • the path - dev\project\
  • - *
  • the full path - C:\dev\project\
  • - *
  • the name - file.txt
  • - *
  • the base name - file
  • - *
  • the extension - txt
  • - *
- * Note that this class works best if directory filenames end with a separator. - * If you omit the last separator, it is impossible to determine if the filename - * corresponds to a file or a directory. As a result, we have chosen to say - * it corresponds to a file. - *

- * This class only supports Unix and Windows style names. - * Prefixes are matched as follows: - *

{@code
- * Windows:
- * a\b\c.txt           --> ""          --> relative
- * \a\b\c.txt          --> "\"         --> current drive absolute
- * C:a\b\c.txt         --> "C:"        --> drive relative
- * C:\a\b\c.txt        --> "C:\"       --> absolute
- * \\server\a\b\c.txt  --> "\\server\" --> UNC
- *
- * Unix:
- * a/b/c.txt           --> ""          --> relative
- * /a/b/c.txt          --> "/"         --> absolute
- * ~/a/b/c.txt         --> "~/"        --> current user
- * ~                   --> "~/"        --> current user (slash added)
- * ~user/a/b/c.txt     --> "~user/"    --> named user
- * ~user               --> "~user/"    --> named user (slash added)
- * }
- * Both prefix styles are matched always, irrespective of the machine that you are - * currently running on. - */ -public class FileNameUtil { - - /** - * The extension separator character. - */ - private static final char EXTENSION_SEPARATOR = '.'; - - /** - * The Unix separator character. - */ - private static final char UNIX_SEPARATOR = '/'; - - /** - * The Windows separator character. - */ - private static final char WINDOWS_SEPARATOR = '\\'; - - /** - * The system separator character. - */ - private static final char SYSTEM_SEPARATOR = File.separatorChar; - - /** - * The separator character that is the opposite of the system separator. - */ - private static final char OTHER_SEPARATOR; - static { - if (SYSTEM_SEPARATOR == WINDOWS_SEPARATOR) { - OTHER_SEPARATOR = UNIX_SEPARATOR; - } else { - OTHER_SEPARATOR = WINDOWS_SEPARATOR; - } - } - - /** - * Checks if the character is a separator. - */ - private static boolean isSeparator(final char ch) { - return (ch == UNIX_SEPARATOR) || (ch == WINDOWS_SEPARATOR); - } - - // ---------------------------------------------------------------- normalization - - public static String normalize(final String filename) { - return doNormalize(filename, SYSTEM_SEPARATOR, true); - } - - /** - * Normalizes a path, removing double and single dot path steps. - *

- * This method normalizes a path to a standard format. - * The input may contain separators in either Unix or Windows format. - * The output will contain separators in the format of the system. - *

- * A trailing slash will be retained. - * A double slash will be merged to a single slash (but UNC names are handled). - * A single dot path segment will be removed. - * A double dot will cause that path segment and the one before to be removed. - * If the double dot has no parent path segment to work with, null - * is returned. - *

- * The output will be the same on both Unix and Windows except - * for the separator character. - *

{@code
-	 * /foo//               -->   /foo/
-	 * /foo/./              -->   /foo/
-	 * /foo/../bar          -->   /bar
-	 * /foo/../bar/         -->   /bar/
-	 * /foo/../bar/../baz   -->   /baz
-	 * //foo//./bar         -->   /foo/bar
-	 * /../                 -->   null
-	 * ../foo               -->   null
-	 * foo/bar/..           -->   foo/
-	 * foo/../../bar        -->   null
-	 * foo/../bar           -->   bar
-	 * //server/foo/../bar  -->   //server/bar
-	 * //server/../bar      -->   null
-	 * C:\foo\..\bar        -->   C:\bar
-	 * C:\..\bar            -->   null
-	 * ~/foo/../bar/        -->   ~/bar/
-	 * ~/../bar             -->   null
-	 * }
- * (Note the file separator returned will be correct for Windows/Unix) - * - * @param filename the filename to normalize, null returns null - * @return the normalized filename, or null if invalid - */ - public static String normalize(final String filename, final boolean unixSeparator) { - char separator = (unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR); - return doNormalize(filename, separator, true); - } - - public static String normalizeNoEndSeparator(final String filename) { - return doNormalize(filename, SYSTEM_SEPARATOR, false); - } - - /** - * Normalizes a path, removing double and single dot path steps, - * and removing any final directory separator. - *

- * This method normalizes a path to a standard format. - * The input may contain separators in either Unix or Windows format. - * The output will contain separators in the format of the system. - *

- * A trailing slash will be removed. - * A double slash will be merged to a single slash (but UNC names are handled). - * A single dot path segment will be removed. - * A double dot will cause that path segment and the one before to be removed. - * If the double dot has no parent path segment to work with, null - * is returned. - *

- * The output will be the same on both Unix and Windows except - * for the separator character. - *

{@code
-	 * /foo//               -->   /foo
-	 * /foo/./              -->   /foo
-	 * /foo/../bar          -->   /bar
-	 * /foo/../bar/         -->   /bar
-	 * /foo/../bar/../baz   -->   /baz
-	 * /foo//./bar          -->   /foo/bar
-	 * /../                 -->   null
-	 * ../foo               -->   null
-	 * foo/bar/..           -->   foo
-	 * foo/../../bar        -->   null
-	 * foo/../bar           -->   bar
-	 * //server/foo/../bar  -->   //server/bar
-	 * //server/../bar      -->   null
-	 * C:\foo\..\bar        -->   C:\bar
-	 * C:\..\bar            -->   null
-	 * ~/foo/../bar/        -->   ~/bar
-	 * ~/../bar             -->   null
-	 * }
- * (Note the file separator returned will be correct for Windows/Unix) - * - * @param filename the filename to normalize, null returns null - * @return the normalized filename, or null if invalid - */ - public static String normalizeNoEndSeparator(final String filename, final boolean unixSeparator) { - char separator = (unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR); - return doNormalize(filename, separator, false); - } - - /** - * Internal method to perform the normalization. - * - * @param filename file name - * @param separator separator character to use - * @param keepSeparator true to keep the final separator - * @return normalized filename - */ - private static String doNormalize(final String filename, final char separator, final boolean keepSeparator) { - if (filename == null) { - return null; - } - int size = filename.length(); - if (size == 0) { - return filename; - } - int prefix = getPrefixLength(filename); - if (prefix < 0) { - return null; - } - - char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy - filename.getChars(0, filename.length(), array, 0); - - // fix separators throughout - char otherSeparator = (separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR); - for (int i = 0; i < array.length; i++) { - if (array[i] == otherSeparator) { - array[i] = separator; - } - } - - // add extra separator on the end to simplify code below - boolean lastIsDirectory = true; - if (array[size - 1] != separator) { - array[size++] = separator; - lastIsDirectory = false; - } - - // adjoining slashes - for (int i = prefix + 1; i < size; i++) { - if (array[i] == separator && array[i - 1] == separator) { - System.arraycopy(array, i, array, i - 1, size - i); - size--; - i--; - } - } - - // dot slash - for (int i = prefix + 1; i < size; i++) { - if (array[i] == separator && array[i - 1] == '.' && - (i == prefix + 1 || array[i - 2] == separator)) { - if (i == size - 1) { - lastIsDirectory = true; - } - System.arraycopy(array, i + 1, array, i - 1, size - i); - size -= 2; - i--; - } - } - - // double dot slash - outer: - for (int i = prefix + 2; i < size; i++) { - if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' && - (i == prefix + 2 || array[i - 3] == separator)) { - if (i == prefix + 2) { - return null; - } - if (i == size - 1) { - lastIsDirectory = true; - } - int j; - for (j = i - 4 ; j >= prefix; j--) { - if (array[j] == separator) { - // remove b/../ from a/b/../c - System.arraycopy(array, i + 1, array, j + 1, size - i); - size -= (i - j); - i = j + 1; - continue outer; - } - } - // remove a/../ from a/../c - System.arraycopy(array, i + 1, array, prefix, size - i); - size -= (i + 1 - prefix); - i = prefix + 1; - } - } - - if (size <= 0) { // should never be less than 0 - return StringPool.EMPTY; - } - if (size <= prefix) { // should never be less than prefix - return new String(array, 0, size); - } - if (lastIsDirectory && keepSeparator) { - return new String(array, 0, size); // keep trailing separator - } - return new String(array, 0, size - 1); // lose trailing separator - } - - //----------------------------------------------------------------------- - /** - * Concatenates a filename to a base path using normal command line style rules. - *

- * The effect is equivalent to resultant directory after changing - * directory to the first argument, followed by changing directory to - * the second argument. - *

- * The first argument is the base path, the second is the path to concatenate. - * The returned path is always normalized via {@link #normalize(String)}, - * thus .. is handled. - *

- * If pathToAdd is absolute (has an absolute prefix), then - * it will be normalized and returned. - * Otherwise, the paths will be joined, normalized and returned. - *

- * The output will be the same on both Unix and Windows except - * for the separator character. - *

{@code
-	 * /foo/ + bar          -->   /foo/bar
-	 * /foo + bar           -->   /foo/bar
-	 * /foo + /bar          -->   /bar
-	 * /foo + C:/bar        -->   C:/bar
-	 * /foo + C:bar         -->   C:bar (*)
-	 * /foo/a/ + ../bar     -->   foo/bar
-	 * /foo/ + ../../bar    -->   null
-	 * /foo/ + /bar         -->   /bar
-	 * /foo/.. + /bar       -->   /bar
-	 * /foo + bar/c.txt     -->   /foo/bar/c.txt
-	 * /foo/c.txt + bar     -->   /foo/c.txt/bar (!)
-	 * }
- * (*) Note that the Windows relative drive prefix is unreliable when - * used with this method. - * (!) Note that the first parameter must be a path. If it ends with a name, then - * the name will be built into the concatenated path. If this might be a problem, - * use {@link #getFullPath(String)} on the base path argument. - * - * @param basePath the base path to attach to, always treated as a path - * @param fullFilenameToAdd the filename (or path) to attach to the base - * @return the concatenated path, or null if invalid - */ - public static String concat(final String basePath, final String fullFilenameToAdd) { - return doConcat(basePath, fullFilenameToAdd, SYSTEM_SEPARATOR); - } - public static String concat(final String basePath, final String fullFilenameToAdd, final boolean unixSeparator) { - char separator = (unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR); - return doConcat(basePath, fullFilenameToAdd, separator); - } - public static String doConcat(final String basePath, final String fullFilenameToAdd, final char separator) { - int prefix = getPrefixLength(fullFilenameToAdd); - if (prefix < 0) { - return null; - } - if (prefix > 0) { - return doNormalize(fullFilenameToAdd, separator, true); - } - if (basePath == null) { - return null; - } - int len = basePath.length(); - if (len == 0) { - return doNormalize(fullFilenameToAdd, separator, true); - } - char ch = basePath.charAt(len - 1); - if (isSeparator(ch)) { - return doNormalize(basePath + fullFilenameToAdd, separator, true); - } else { - return doNormalize(basePath + '/' + fullFilenameToAdd, separator, true); - } - } - - // ---------------------------------------------------------------- separator conversion - - /** - * Converts all separators to the Unix separator of forward slash. - * - * @param path the path to be changed, null ignored - * @return the updated path - */ - public static String separatorsToUnix(final String path) { - if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) { - return path; - } - return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR); - } - - /** - * Converts all separators to the Windows separator of backslash. - * - * @param path the path to be changed, null ignored - * @return the updated path - */ - public static String separatorsToWindows(final String path) { - if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) { - return path; - } - return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR); - } - - /** - * Converts all separators to the system separator. - * - * @param path the path to be changed, null ignored - * @return the updated path - */ - public static String separatorsToSystem(final String path) { - if (path == null) { - return null; - } - if (SYSTEM_SEPARATOR == WINDOWS_SEPARATOR) { - return separatorsToWindows(path); - } else { - return separatorsToUnix(path); - } - } - - // ---------------------------------------------------------------- prefix - /** - * Returns the length of the filename prefix, such as C:/ or ~/. - *

- * This method will handle a file in either Unix or Windows format. - *

- * The prefix length includes the first slash in the full filename - * if applicable. Thus, it is possible that the length returned is greater - * than the length of the input string. - *

{@code
-	 * Windows:
-	 * a\b\c.txt           --> ""          --> relative
-	 * \a\b\c.txt          --> "\"         --> current drive absolute
-	 * C:a\b\c.txt         --> "C:"        --> drive relative
-	 * C:\a\b\c.txt        --> "C:\"       --> absolute
-	 * \\server\a\b\c.txt  --> "\\server\" --> UNC
-	 *
-	 * Unix:
-	 * a/b/c.txt           --> ""          --> relative
-	 * /a/b/c.txt          --> "/"         --> absolute
-	 * ~/a/b/c.txt         --> "~/"        --> current user
-	 * ~                   --> "~/"        --> current user (slash added)
-	 * ~user/a/b/c.txt     --> "~user/"    --> named user
-	 * ~user               --> "~user/"    --> named user (slash added)
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * ie. both Unix and Windows prefixes are matched regardless. - * - * @param filename the filename to find the prefix in, null returns -1 - * @return the length of the prefix, -1 if invalid or null - */ - public static int getPrefixLength(final String filename) { - if (filename == null) { - return -1; - } - int len = filename.length(); - if (len == 0) { - return 0; - } - char ch0 = filename.charAt(0); - if (ch0 == ':') { - return -1; - } - if (len == 1) { - if (ch0 == '~') { - return 2; // return a length greater than the input - } - return (isSeparator(ch0) ? 1 : 0); - } else { - if (ch0 == '~') { - int posUnix = filename.indexOf(UNIX_SEPARATOR, 1); - int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1); - if (posUnix == -1 && posWin == -1) { - return len + 1; // return a length greater than the input - } - posUnix = (posUnix == -1 ? posWin : posUnix); - posWin = (posWin == -1 ? posUnix : posWin); - return Math.min(posUnix, posWin) + 1; - } - char ch1 = filename.charAt(1); - if (ch1 == ':') { - ch0 = Character.toUpperCase(ch0); - if (ch0 >= 'A' && ch0 <= 'Z') { - if (len == 2 || !isSeparator(filename.charAt(2))) { - return 2; - } - return 3; - } - return -1; - - } else if (isSeparator(ch0) && isSeparator(ch1)) { - int posUnix = filename.indexOf(UNIX_SEPARATOR, 2); - int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2); - if ((posUnix == -1 && posWin == -1) || posUnix == 2 || posWin == 2) { - return -1; - } - posUnix = (posUnix == -1 ? posWin : posUnix); - posWin = (posWin == -1 ? posUnix : posWin); - return Math.min(posUnix, posWin) + 1; - } else { - return (isSeparator(ch0) ? 1 : 0); - } - } - } - - /** - * Returns the index of the last directory separator character. - *

- * This method will handle a file in either Unix or Windows format. - * The position of the last forward or backslash is returned. - *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to find the last path separator in, null returns -1 - * @return the index of the last separator character, or -1 if there is no such character - */ - public static int indexOfLastSeparator(final String filename) { - if (filename == null) { - return -1; - } - int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR); - int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR); - return Math.max(lastUnixPos, lastWindowsPos); - } - - /** - * Returns the index of the last extension separator character, which is a dot. - *

- * This method also checks that there is no directory separator after the last dot. - * To do this it uses {@link #indexOfLastSeparator(String)} which will - * handle a file in either Unix or Windows format. - *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to find the last path separator in, null returns -1 - * @return the index of the last separator character, or -1 if there - * is no such character - */ - public static int indexOfExtension(final String filename) { - if (filename == null) { - return -1; - } - int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR); - int lastSeparator = indexOfLastSeparator(filename); - return (lastSeparator > extensionPos ? -1 : extensionPos); - } - - /** - * Returns true if file has extension. - */ - public static boolean hasExtension(final String filename) { - return indexOfExtension(filename) != -1; - } - - // ---------------------------------------------------------------- get - - /** - * Gets the prefix from a full filename, such as C:/ - * or ~/. - *

- * This method will handle a file in either Unix or Windows format. - * The prefix includes the first slash in the full filename where applicable. - *

{@code
-	 * Windows:
-	 * a\b\c.txt           --> ""          --> relative
-	 * \a\b\c.txt          --> "\"         --> current drive absolute
-	 * C:a\b\c.txt         --> "C:"        --> drive relative
-	 * C:\a\b\c.txt        --> "C:\"       --> absolute
-	 * \\server\a\b\c.txt  --> "\\server\" --> UNC
-	 *
-	 * Unix:
-	 * a/b/c.txt           --> ""          --> relative
-	 * /a/b/c.txt          --> "/"         --> absolute
-	 * ~/a/b/c.txt         --> "~/"        --> current user
-	 * ~                   --> "~/"        --> current user (slash added)
-	 * ~user/a/b/c.txt     --> "~user/"    --> named user
-	 * ~user               --> "~user/"    --> named user (slash added)
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * ie. both Unix and Windows prefixes are matched regardless. - * - * @param filename the filename to query, null returns null - * @return the prefix of the file, null if invalid - */ - public static String getPrefix(final String filename) { - if (filename == null) { - return null; - } - int len = getPrefixLength(filename); - if (len < 0) { - return null; - } - if (len > filename.length()) { - return filename + UNIX_SEPARATOR; // we know this only happens for unix - } - return filename.substring(0, len); - } - - /** - * Gets the path from a full filename, which excludes the prefix. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before and - * including the last forward or backslash. - *

{@code
-	 * C:\a\b\c.txt --> a\b\
-	 * ~/a/b/c.txt  --> a/b/
-	 * a.txt        --> ""
-	 * a/b/c        --> a/b/
-	 * a/b/c/       --> a/b/c/
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - *

- * This method drops the prefix from the result. - * See {@link #getFullPath(String)} for the method that retains the prefix. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getPath(final String filename) { - return doGetPath(filename, 1); - } - - /** - * Gets the path from a full filename, which excludes the prefix, and - * also excluding the final directory separator. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before the - * last forward or backslash. - *

{@code
-	 * C:\a\b\c.txt --> a\b
-	 * ~/a/b/c.txt  --> a/b
-	 * a.txt        --> ""
-	 * a/b/c        --> a/b
-	 * a/b/c/       --> a/b/c
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - *

- * This method drops the prefix from the result. - * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getPathNoEndSeparator(final String filename) { - return doGetPath(filename, 0); - } - - /** - * Does the work of getting the path. - * - * @param filename the filename - * @param separatorAdd 0 to omit the end separator, 1 to return it - * @return the path - */ - private static String doGetPath(final String filename, final int separatorAdd) { - if (filename == null) { - return null; - } - int prefix = getPrefixLength(filename); - if (prefix < 0) { - return null; - } - int index = indexOfLastSeparator(filename); - int endIndex = index + separatorAdd; - if (prefix >= filename.length() || index < 0 || prefix >= endIndex) { - return StringPool.EMPTY; - } - return filename.substring(prefix, endIndex); - } - - /** - * Gets the full path from a full filename, which is the prefix + path. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before and - * including the last forward or backslash. - *

{@code
-	 * C:\a\b\c.txt --> C:\a\b\
-	 * ~/a/b/c.txt  --> ~/a/b/
-	 * a.txt        --> ""
-	 * a/b/c        --> a/b/
-	 * a/b/c/       --> a/b/c/
-	 * C:           --> C:
-	 * C:\          --> C:\
-	 * ~            --> ~/
-	 * ~/           --> ~/
-	 * ~user        --> ~user/
-	 * ~user/       --> ~user/
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getFullPath(final String filename) { - return doGetFullPath(filename, true); - } - - /** - * Gets the full path from a full filename, which is the prefix + path, - * and also excluding the final directory separator. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before the - * last forward or backslash. - *

{@code
-	 * C:\a\b\c.txt --> C:\a\b
-	 * ~/a/b/c.txt  --> ~/a/b
-	 * a.txt        --> ""
-	 * a/b/c        --> a/b
-	 * a/b/c/       --> a/b/c
-	 * C:           --> C:
-	 * C:\          --> C:\
-	 * ~            --> ~
-	 * ~/           --> ~
-	 * ~user        --> ~user
-	 * ~user/       --> ~user
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getFullPathNoEndSeparator(final String filename) { - return doGetFullPath(filename, false); - } - - /** - * Does the work of getting the path. - * - * @param filename the filename - * @param includeSeparator true to include the end separator - * @return the path - */ - private static String doGetFullPath(final String filename, final boolean includeSeparator) { - if (filename == null) { - return null; - } - int prefix = getPrefixLength(filename); - if (prefix < 0) { - return null; - } - if (prefix >= filename.length()) { - if (includeSeparator) { - return getPrefix(filename); // add end slash if necessary - } else { - return filename; - } - } - int index = indexOfLastSeparator(filename); - if (index < 0) { - return filename.substring(0, prefix); - } - int end = index + (includeSeparator ? 1 : 0); - if (end == 0) { - end++; - } - return filename.substring(0, end); - } - - /** - * Gets the name minus the path from a full filename. - *

- * This method will handle a file in either Unix or Windows format. - * The text after the last forward or backslash is returned. - *

{@code
-	 * a/b/c.txt --> c.txt
-	 * a.txt     --> a.txt
-	 * a/b/c     --> c
-	 * a/b/c/    --> ""
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the name of the file without the path, or an empty string if none exists - */ - public static String getName(final String filename) { - if (filename == null) { - return null; - } - int index = indexOfLastSeparator(filename); - return filename.substring(index + 1); - } - - /** - * Gets the base name, minus the full path and extension, from a full filename. - *

- * This method will handle a file in either Unix or Windows format. - * The text after the last forward or backslash and before the last dot is returned. - *

{@code
-	 * a/b/c.txt --> c
-	 * a.txt     --> a
-	 * a/b/c     --> c
-	 * a/b/c/    --> ""
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the name of the file without the path, or an empty string if none exists - */ - public static String getBaseName(final String filename) { - return removeExtension(getName(filename)); - } - - /** - * Gets the extension of a filename. - *

- * This method returns the textual part of the filename after the last dot. - * There must be no directory separator after the dot. - *

{@code
-	 * foo.txt      --> "txt"
-	 * a/b/c.jpg    --> "jpg"
-	 * a/b.txt/c    --> ""
-	 * a/b/c        --> ""
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to retrieve the extension of. - * @return the extension of the file or an empty string if none exists. - */ - public static String getExtension(final String filename) { - if (filename == null) { - return null; - } - int index = indexOfExtension(filename); - if (index == -1) { - return StringPool.EMPTY; - } else { - return filename.substring(index + 1); - } - } - - //----------------------------------------------------------------------- remove - - /** - * Removes the extension from a filename. - *

- * This method returns the textual part of the filename before the last dot. - * There must be no directory separator after the dot. - *

{@code
-	 * foo.txt    --> foo
-	 * a\b\c.jpg  --> a\b\c
-	 * a\b\c      --> a\b\c
-	 * a.b\c      --> a.b\c
-	 * }
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the filename minus the extension - */ - public static String removeExtension(final String filename) { - if (filename == null) { - return null; - } - int index = indexOfExtension(filename); - if (index == -1) { - return filename; - } else { - return filename.substring(0, index); - } - } - - // ---------------------------------------------------------------- equals - - /** - * Checks whether two filenames are equal exactly. - */ - public static boolean equals(final String filename1, final String filename2) { - return equals(filename1, filename2, false); - } - - /** - * Checks whether two filenames are equal using the case rules of the system. - */ - public static boolean equalsOnSystem(final String filename1, final String filename2) { - return equals(filename1, filename2, true); - } - - /** - * Checks whether two filenames are equal optionally using the case rules of the system. - *

- * - * @param filename1 the first filename to query, may be null - * @param filename2 the second filename to query, may be null - * @param system whether to use the system (windows or unix) - * @return true if the filenames are equal, null equals null - */ - private static boolean equals(final String filename1, final String filename2, final boolean system) { - //noinspection StringEquality - if (filename1 == filename2) { - return true; - } - if (filename1 == null || filename2 == null) { - return false; - } - if (system && (SYSTEM_SEPARATOR == WINDOWS_SEPARATOR)) { - return filename1.equalsIgnoreCase(filename2); - } else { - return filename1.equals(filename2); - } - } - - // ---------------------------------------------------------------- split - - /** - * Splits filename into a array of four Strings containing prefix, path, basename and extension. - * Path will contain ending separator. - */ - public static String[] split(final String filename) { - String prefix = getPrefix(filename); - if (prefix == null) { - prefix = StringPool.EMPTY; - } - int lastSeparatorIndex = indexOfLastSeparator(filename); - int lastExtensionIndex = indexOfExtension(filename); - - String path; - String baseName; - String extension; - - if (lastSeparatorIndex == -1) { - path = StringPool.EMPTY; - if (lastExtensionIndex == -1) { - baseName = filename.substring(prefix.length()); - extension = StringPool.EMPTY; - } else { - baseName = filename.substring(prefix.length(), lastExtensionIndex); - extension = filename.substring(lastExtensionIndex + 1); - } - } else { - path = filename.substring(prefix.length(), lastSeparatorIndex + 1); - if (lastExtensionIndex == -1) { - baseName = filename.substring(prefix.length() + path.length()); - extension = StringPool.EMPTY; - } else { - baseName = filename.substring(prefix.length() + path.length(), lastExtensionIndex); - extension = filename.substring(lastExtensionIndex + 1); - } - } - return new String[] {prefix, path, baseName, extension}; - } - - // ---------------------------------------------------------------- home - - /** - * Resolve ~ in the path. - */ - public static String resolveHome(final String path) { - if (path.length() == 1) { - if (path.charAt(0) == '~') { - return SystemUtil.info().getHomeDir(); - } - return path; - } - if (path.length() >= 2) { - if ((path.charAt(0) == '~') && (path.charAt(1) == File.separatorChar)) { - return SystemUtil.info().getHomeDir() + path.substring(1); - } - } - return path; - } - - /** - * Calculates relative path of target path on base path. - */ - public static String relativePath(final String targetPath, final String basePath) { - return new File(basePath).toPath().relativize(new File(targetPath).toPath()).toString(); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/FileUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/FileUtil.java deleted file mode 100644 index d29cb00de..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/FileUtil.java +++ /dev/null @@ -1,1685 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.core.JoddCore; -import com.fr.third.jodd.net.URLDecoder; -import com.fr.third.jodd.system.SystemUtil; -import com.fr.third.jodd.util.DigestEngine; -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.StringUtil; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.io.Writer; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; - -/** - * File utilities. - */ -public class FileUtil { - - private static final String MSG_NOT_A_DIRECTORY = "Not a directory: "; - private static final String MSG_CANT_CREATE = "Can't create: "; - private static final String MSG_NOT_FOUND = "Not found: "; - private static final String MSG_NOT_A_FILE = "Not a file: "; - private static final String MSG_UNABLE_TO_DELETE = "Unable to delete: "; - - private static final int ZERO = 0; - private static final int NEGATIVE_ONE = -1; - private static final String FILE_PROTOCOL = "file"; - private static final String USER_HOME = "~"; - - /** - * Simple factory for {@link File} objects but with home resolving. - */ - public static File file(String fileName) { - fileName = StringUtil.replace(fileName, USER_HOME, SystemUtil.info().getHomeDir()); - return new File(fileName); - } - - /** - * Simple factory for {@link File} objects. - */ - private static File file(final File parent, final String fileName) { - return new File(parent, fileName); - } - - // ---------------------------------------------------------------- misc shortcuts - - /** - * @see #equals(File, File) - */ - public static boolean equals(final String one, final String two) { - return equals(file(one), file(two)); - } - - /** - * Checks if two {@link File}s point to the same {@link File}. - * - * @param one {@link File} one. - * @param two {@link File} two. - * @return {@code true} if the {@link File}s match. - */ - public static boolean equals(File one, File two) { - try { - one = one.getCanonicalFile(); - two = two.getCanonicalFile(); - } catch (final IOException ignore) { - return false; - } - return one.equals(two); - } - - /** - * Converts {@link File} {@link URL}s to {@link File}. Ignores other schemes and returns {@code null}. - */ - public static File toFile(final URL url) { - final String fileName = toFileName(url); - if (fileName == null) { - return null; - } - return file(fileName); - } - - /** - * Converts {@link File} to {@link URL} in a correct way. - * - * @return {@link URL} or {@code null} in case of error. - * @throws MalformedURLException if {@link File} cannot be converted. - */ - public static URL toURL(final File file) throws MalformedURLException { - return file.toURI().toURL(); - } - - /** - * Converts {@link File} {@link URL}s to file name. Accepts only {@link URL}s with 'file' protocol. - * Otherwise, for other schemes returns {@code null}. - * - * @param url {@link URL} to convert - * @return file name - */ - public static String toFileName(final URL url) { - if ((url == null) || !(url.getProtocol().equals(FILE_PROTOCOL))) { - return null; - } - final String filename = url.getFile().replace('/', File.separatorChar); - - return URLDecoder.decode(filename, encoding()); - } - - /** - * Returns a file of either a folder or a containing archive. - */ - public static File toContainerFile(final URL url) { - final String protocol = url.getProtocol(); - if (protocol.equals(FILE_PROTOCOL)) { - return toFile(url); - } - - final String path = url.getPath(); - - return new File(URI.create( - path.substring(ZERO, path.lastIndexOf("!/")))); - } - - /** - * Returns {@code true} if {@link File} exists. - */ - public static boolean isExistingFile(final File file) { - return file != null && file.exists() && file.isFile(); - } - - /** - * Returns {@code true} if directory exists. - */ - public static boolean isExistingFolder(final File folder) { - return folder != null && folder.exists() && folder.isDirectory(); - } - - // ---------------------------------------------------------------- mkdirs - - /** - * @see #mkdirs(File) - */ - public static File mkdirs(final String dirs) throws IOException { - return mkdirs(file(dirs)); - } - - /** - * Creates all directories at once. - * - * @param dirs Directories to make. - * @throws IOException if cannot create directory. - */ - public static File mkdirs(final File dirs) throws IOException { - if (dirs.exists()) { - checkIsDirectory(dirs); - return dirs; - } - return checkCreateDirectory(dirs); - } - - /** - * @see #mkdir(File) - */ - public static File mkdir(final String dir) throws IOException { - return mkdir(file(dir)); - } - - /** - * Creates single directory. - * - * @throws IOException if cannot create directory. - */ - public static File mkdir(final File dir) throws IOException { - if (dir.exists()) { - checkIsDirectory(dir); - return dir; - } - return checkCreateDirectory(dir); - } - - // ---------------------------------------------------------------- touch - - /** - * @see #touch(File) - */ - public static void touch(final String file) throws IOException { - touch(file(file)); - } - - /** - * Implements the Unix "touch" utility. It creates a new {@link File} - * with size 0 or, if the {@link File} exists already, it is opened and - * closed without modifying it, but updating the {@link File} date and time. - */ - public static void touch(final File file) throws IOException { - if (!file.exists()) { - StreamUtil.close(new FileOutputStream(file, false)); - } - file.setLastModified(System.currentTimeMillis()); - } - - // ---------------------------------------------------------------- copy file to file - - /** - * @see #copyFile(File, File) - */ - public static void copyFile(final String srcFile, final String destFile) throws IOException { - copyFile(file(srcFile), file(destFile)); - } - - /** - * Copies a {@link File} to another {@link File}. - * - * @param srcFile Source {@link File}. - * @param destFile Destination {@link File}. - * @throws IOException if cannot copy - */ - public static void copyFile(final File srcFile, final File destFile) throws IOException { - checkFileCopy(srcFile, destFile); - _copyFile(srcFile, destFile); - } - - /** - * Internal file copy when most of the pre-checking has passed. - * - * @param srcFile Source {@link File}. - * @param destFile Destination {@link File}. - * @throws IOException if cannot copy - */ - private static void _copyFile(final File srcFile, final File destFile) throws IOException { - if (destFile.exists()) { - if (destFile.isDirectory()) { - throw new IOException("Destination '" + destFile + "' is a directory"); - } - } - - // do copy file - FileInputStream input = null; - FileOutputStream output = null; - try { - input = new FileInputStream(srcFile); - output = new FileOutputStream(destFile, false); - StreamUtil.copy(input, output); - } finally { - StreamUtil.close(output); - StreamUtil.close(input); - } - - // done - - if (srcFile.length() != destFile.length()) { - throw new IOException("Copy file failed of '" + srcFile + "' to '" + destFile + "' due to different sizes"); - } - destFile.setLastModified(srcFile.lastModified()); - } - - // ---------------------------------------------------------------- copy file to directory - - /** - * @see #copyFileToDir(File, File) - */ - public static File copyFileToDir(final String srcFile, final String destDir) throws IOException { - return copyFileToDir(file(srcFile), file(destDir)); - } - - /** - * Copies a {@link File} to directory with specified copy params and returns copied destination. - */ - public static File copyFileToDir(final File srcFile, final File destDir) throws IOException { - checkExistsAndDirectory(destDir); - final File destFile = file(destDir, srcFile.getName()); - copyFile(srcFile, destFile); - return destFile; - } - - // ---------------------------------------------------------------- copy dir - - /** - * @see #copyDir(File, File) - */ - public static void copyDir(final String srcDir, final String destDir) throws IOException { - copyDir(file(srcDir), file(destDir)); - } - - /** - * Copies directory with specified copy params. - * - * @see #_copyDirectory(File, File) - */ - public static void copyDir(final File srcDir, final File destDir) throws IOException { - checkDirCopy(srcDir, destDir); - _copyDirectory(srcDir, destDir); - } - - /** - * @param srcDir - * @param destDir - * @throws IOException - */ - private static void _copyDirectory(final File srcDir, final File destDir) throws IOException { - if (destDir.exists()) { - checkIsDirectory(destDir); - } else { - checkCreateDirectory(destDir); - destDir.setLastModified(srcDir.lastModified()); - } - - final File[] files = srcDir.listFiles(); - if (files == null) { - throw new IOException("Failed to list contents of: " + srcDir); - } - - IOException exception = null; - for (final File file : files) { - final File destFile = file(destDir, file.getName()); - try { - - if (file.isDirectory()) { - _copyDirectory(file, destFile); - } else { - _copyFile(file, destFile); - } - } catch (final IOException ioex) { - exception = ioex; - } - } - - if (exception != null) { - throw exception; - } - } - - // ---------------------------------------------------------------- move file - - /** - * @see #moveFile(File, File) - */ - public static File moveFile(final String srcFile, final String destFile) throws IOException { - return moveFile(file(srcFile), file(destFile)); - } - - /** - * @see #_moveFile(File, File) - */ - public static File moveFile(final File srcFile, final File destFile) throws IOException { - checkFileCopy(srcFile, destFile); - _moveFile(srcFile, destFile); - return destFile; - } - - /** - * Moves a {@link File}. - * - * @param srcFile Source {@link File}. - * @param destFile Destination directory. - * @throws IOException - */ - private static void _moveFile(final File srcFile, final File destFile) throws IOException { - if (destFile.exists()) { - checkIsFile(destFile); - destFile.delete(); - } - - final boolean rename = srcFile.renameTo(destFile); - if (!rename) { - _copyFile(srcFile, destFile); - srcFile.delete(); - } - } - - // ---------------------------------------------------------------- move file to dir - - /** - * @see #moveFileToDir(File, File) - */ - public static File moveFileToDir(final String srcFile, final String destDir) throws IOException { - return moveFileToDir(file(srcFile), file(destDir)); - } - - /** - * Moves a file to a directory. - * - * @param srcFile Source {@link File}. - * @param destDir Destination directory. - * @throws IOException if there is an error during move. - */ - public static File moveFileToDir(final File srcFile, final File destDir) throws IOException { - checkExistsAndDirectory(destDir); - return moveFile(srcFile, file(destDir, srcFile.getName())); - } - - // ---------------------------------------------------------------- move dir - - /** - * @see #moveDir(File, File) - */ - public static File moveDir(final String srcDir, final String destDir) throws IOException { - return moveDir(file(srcDir), file(destDir)); - } - - /** - * @see #_moveDirectory(File, File) - */ - public static File moveDir(final File srcDir, final File destDir) throws IOException { - checkDirCopy(srcDir, destDir); - _moveDirectory(srcDir, destDir); - return destDir; - } - - /** - * Moves a directory. - * - * @param srcDest Source directory - * @param destDir Destination directory. - * @throws IOException if there is an error during move. - */ - private static void _moveDirectory(final File srcDest, File destDir) throws IOException { - if (destDir.exists()) { - checkIsDirectory(destDir); - destDir = file(destDir, destDir.getName()); - destDir.mkdir(); - } - - final boolean rename = srcDest.renameTo(destDir); - if (!rename) { - _copyDirectory(srcDest, destDir); - deleteDir(srcDest); - } - } - - // ---------------------------------------------------------------- delete file - - /** - * @see #deleteFile(File) - */ - public static void deleteFile(final String destFile) throws IOException { - deleteFile(file(destFile)); - } - - /** - * Deletes a {@link File}. - * - * @param destFile Destination to delete. - * @throws IOException if there was an error deleting. - */ - public static void deleteFile(final File destFile) throws IOException { - checkIsFile(destFile); - checkDeleteSuccessful(destFile); - } - - // ---------------------------------------------------------------- delete dir - - /** - * @see #deleteDir(File) - */ - public static void deleteDir(final String destDir) throws IOException { - deleteDir(file(destDir)); - } - - /** - * Deletes a directory. - * - * @param destDir Destination to delete. - * @throws IOException if there was an error deleting. - */ - public static void deleteDir(final File destDir) throws IOException { - cleanDir(destDir); - checkDeleteSuccessful(destDir); - } - - /** - * @see #cleanDir(File) - */ - public static void cleanDir(final String dest) throws IOException { - cleanDir(file(dest)); - } - - /** - * Cleans a directory without deleting it. - * - * @param destDir destination to clean. - * @throws IOException if something went wrong. - */ - public static void cleanDir(final File destDir) throws IOException { - checkExists(destDir); - checkIsDirectory(destDir); - - final File[] files = destDir.listFiles(); - if (files == null) { - throw new IOException("Failed to list contents of: " + destDir); - } - - IOException exception = null; - for (final File file : files) { - try { - if (file.isDirectory()) { - deleteDir(file); - } else { - file.delete(); - } - } catch (final IOException ioex) { - exception = ioex; - continue; - } - } - - if (exception != null) { - throw exception; - } - } - - // ---------------------------------------------------------------- read/write chars - - /** - * @see #readUTFChars(File) - */ - public static char[] readUTFChars(final String fileName) throws IOException { - return readUTFChars(file(fileName)); - } - - /** - * Reads UTF file content as char array. - * - * @param file {@link File} to read. - * @return array of characters. - * @throws IOException if something went wrong. - */ - public static char[] readUTFChars(final File file) throws IOException { - checkExists(file); - checkIsFile(file); - - final UnicodeInputStream in = unicodeInputStreamOf(file); - try { - return StreamUtil.readChars(in, detectEncoding(in)); - } finally { - StreamUtil.close(in); - } - } - - /** - * Reads file content as char array. - * - * @param file {@link File} to read. - * @param encoding Encoding to use. - * @return array of characters. - * @throws IOException if something went wrong. - */ - public static char[] readChars(final File file, final String encoding) throws IOException { - checkExists(file); - checkIsFile(file); - - final InputStream in = streamOf(file, encoding); - try { - return StreamUtil.readChars(in, encoding); - } finally { - StreamUtil.close(in); - } - } - - /** - * @see #readChars(String, String) - */ - public static char[] readChars(final String fileName) throws IOException { - return readChars(fileName, encoding()); - } - - /** - * @see #readChars(File, String) - */ - public static char[] readChars(final File file) throws IOException { - return readChars(file, encoding()); - } - - /** - * @see #readChars(File, String) - */ - public static char[] readChars(final String fileName, final String encoding) throws IOException { - return readChars(file(fileName), encoding); - } - - /** - * @see #writeChars(File, char[], String) - */ - public static void writeChars(final File dest, final char[] data) throws IOException { - writeChars(dest, data, encoding()); - } - - /** - * @see #writeChars(File, char[]) - */ - public static void writeChars(final String dest, final char[] data) throws IOException { - writeChars(file(dest), data); - } - - /** - * @see #writeChars(File, char[], String) - */ - public static void writeChars(final String dest, final char[] data, final String encoding) throws IOException { - writeChars(file(dest), data, encoding); - } - - /** - * Write characters. append = false - * - * @see #outChars(File, char[], String, boolean) - */ - public static void writeChars(final File dest, final char[] data, final String encoding) throws IOException { - outChars(dest, data, encoding, false); - } - - /** - * Writes characters to {@link File} destination. - * - * @param dest destination {@link File} - * @param data Data as a {@link String} - * @param encoding Encoding as a {@link String} - * @param append {@code true} if appending; {@code false} if {@link File} should be overwritten. - * @throws IOException if something went wrong. - */ - protected static void outChars(final File dest, final char[] data, final String encoding, final boolean append) throws IOException { - if (dest.exists()) { - checkIsFile(dest); - } - final Writer out = new BufferedWriter(StreamUtil.outputStreamWriterOf(new FileOutputStream(dest, append), encoding)); - try { - out.write(data); - } finally { - StreamUtil.close(out); - } - } - - // ---------------------------------------------------------------- read/write string - - /** - * @see #readUTFString(File) - */ - public static String readUTFString(final String fileName) throws IOException { - return readUTFString(file(fileName)); - } - - /** - * Detects optional BOM and reads UTF {@link String} from a {@link File}. - * If BOM is missing, UTF-8 is assumed. - * - * @param file {@link File} to read. - * @return String in UTF encoding. - * @throws IOException if copy to {@link InputStream} errors. - * @see #unicodeInputStreamOf(File) - * @see StreamUtil#copy(InputStream, String) - */ - public static String readUTFString(final File file) throws IOException { - final UnicodeInputStream in = unicodeInputStreamOf(file); - try { - return StreamUtil.copy(in, detectEncoding(in)).toString(); - } finally { - StreamUtil.close(in); - } - } - - /** - * Detects optional BOM and reads UTF {@link String} from an {@link InputStream}. - * If BOM is missing, UTF-8 is assumed. - * - * @param inputStream {@link InputStream} to read. - * @return String in UTF encoding. - * @throws IOException if copy to {@link InputStream} errors. - * @see #unicodeInputStreamOf(File) - * @see StreamUtil#copy(InputStream, String) - */ - public static String readUTFString(final InputStream inputStream) throws IOException { - UnicodeInputStream in = null; - try { - in = new UnicodeInputStream(inputStream, null); - return StreamUtil.copy(in, detectEncoding(in)).toString(); - } finally { - StreamUtil.close(in); - } - } - - /** - * Reads {@link File} content as {@link String} encoded in provided encoding. - * For UTF encoded files, detects optional BOM characters. - * - * @param file {@link File} to read. - * @param encoding Encoding to use. - * @return String representing {@link File} content. - * @throws IOException if copy to {@link InputStream} errors. - * @see #streamOf(File, String) - * @see StreamUtil#copy(InputStream, String) - */ - public static String readString(final File file, final String encoding) throws IOException { - checkExists(file); - checkIsFile(file); - final InputStream in = streamOf(file, encoding); - try { - return StreamUtil.copy(in, encoding).toString(); - } finally { - StreamUtil.close(in); - } - } - - /** - * @see #readString(String, String) - */ - public static String readString(final String source) throws IOException { - return readString(source, encoding()); - } - - /** - * @see #readString(File, String) - */ - public static String readString(final String source, final String encoding) throws IOException { - return readString(file(source), encoding); - } - - /** - * @see #readString(File, String) - */ - public static String readString(final File source) throws IOException { - return readString(source, encoding()); - } - - /** - * @see #writeString(File, String, String) - */ - public static void writeString(final String dest, final String data) throws IOException { - writeString(file(dest), data, encoding()); - } - - /** - * @see #writeString(File, String, String) - */ - public static void writeString(final String dest, final String data, final String encoding) throws IOException { - writeString(file(dest), data, encoding); - } - - /** - * @see #writeString(File, String, String) - */ - public static void writeString(final File dest, final String data) throws IOException { - writeString(dest, data, encoding()); - } - - /** - * Writes String. append = false - * - * @see #outString(File, String, String, boolean) - */ - public static void writeString(final File dest, final String data, final String encoding) throws IOException { - outString(dest, data, encoding, false); - } - - /** - * @see #appendString(File, String) - */ - public static void appendString(final String dest, final String data) throws IOException { - appendString(file(dest), data); - } - - /** - * @see #appendString(File, String, String) - */ - public static void appendString(final String dest, final String data, final String encoding) throws IOException { - appendString(file(dest), data, encoding); - } - - /** - * @see #appendString(File, String, String) - */ - public static void appendString(final File dest, final String data) throws IOException { - appendString(dest, data, encoding()); - } - - /** - * Appends String. append = true - * - * @see #outString(File, String, String, boolean) - */ - public static void appendString(final File dest, final String data, final String encoding) throws IOException { - outString(dest, data, encoding, true); - } - - /** - * Writes data using encoding to {@link File}. - * - * @param dest destination {@link File} - * @param data Data as a {@link String} - * @param encoding Encoding as a {@link String} - * @param append {@code true} if appending; {@code false} if {@link File} should be overwritten. - * @throws IOException if something went wrong. - */ - protected static void outString(final File dest, final String data, final String encoding, final boolean append) throws IOException { - if (dest.exists()) { - checkIsFile(dest); - } - FileOutputStream out = null; - try { - out = new FileOutputStream(dest, append); - out.write(data.getBytes(encoding)); - } finally { - StreamUtil.close(out); - } - } - - // ---------------------------------------------------------------- stream - - - /** - * @see #writeStream(File, InputStream) - */ - public static void writeStream(final String dest, final InputStream in) throws IOException { - writeStream(file(dest), in); - } - - /** - * @see #writeStream(FileOutputStream, InputStream) - */ - public static void writeStream(final File dest, final InputStream in) throws IOException { - writeStream(new FileOutputStream(dest, false), in); - } - - /** - * Write {@link InputStream} in to {@link FileOutputStream}. - * - * @param out {@link FileOutputStream} to write to. - * @param in {@link InputStream} to read. - * @throws IOException if there is an issue reading/writing. - */ - public static void writeStream(final FileOutputStream out, final InputStream in) throws IOException { - try { - StreamUtil.copy(in, out); - } finally { - StreamUtil.close(out); - } - } - - // ---------------------------------------------------------------- read/write string lines - - /** - * @see #readLines(String, String) - */ - public static String[] readLines(final String source) throws IOException { - return readLines(source, encoding()); - } - - /** - * @see #readLines(File, String) - */ - public static String[] readLines(final String source, final String encoding) throws IOException { - return readLines(file(source), encoding); - } - - /** - * @see #readLines(File, String) - */ - public static String[] readLines(final File source) throws IOException { - return readLines(source, encoding()); - } - - /** - * Reads lines from source {@link File} with specified encoding and returns lines as {@link String}s in array. - * - * @param file {@link File} to read. - * @param encoding Endoing to use. - * @return array of Strings which represents lines in the {@link File}. - * @throws IOException if {@link File} does not exist or is not a {@link File} or there is an issue reading - * the {@link File}. - */ - public static String[] readLines(final File file, final String encoding) throws IOException { - checkExists(file); - checkIsFile(file); - final List list = new ArrayList<>(); - - final InputStream in = streamOf(file, encoding); - try { - final BufferedReader br = new BufferedReader(StreamUtil.inputStreamReadeOf(in, encoding)); - String strLine; - while ((strLine = br.readLine()) != null) { - list.add(strLine); - } - } finally { - StreamUtil.close(in); - } - return list.toArray(new String[0]); - } - - // ---------------------------------------------------------------- read/write byte array - - /** - * @see #readBytes(File) - */ - public static byte[] readBytes(final String file) throws IOException { - return readBytes(file(file)); - } - - /** - * @see #readBytes(File, int) - */ - public static byte[] readBytes(final File file) throws IOException { - return readBytes(file, NEGATIVE_ONE); - } - - /** - * Read file and returns byte array with contents. - * - * @param file {@link File} to read - * @param count number of bytes to read - * @return byte array from {@link File} contents. - * @throws IOException if not a {@link File} or {@link File} does not exist or file size is - * larger than {@link Integer#MAX_VALUE}. - */ - public static byte[] readBytes(final File file, final int count) throws IOException { - checkExists(file); - checkIsFile(file); - long numToRead = file.length(); - if (numToRead >= Integer.MAX_VALUE) { - throw new IOException("File is larger then max array size"); - } - - if (count > NEGATIVE_ONE && count < numToRead) { - numToRead = count; - } - - final byte[] bytes = new byte[(int) numToRead]; - final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); - randomAccessFile.readFully(bytes); - randomAccessFile.close(); - - return bytes; - } - - /** - * @see #writeBytes(File, byte[]) - */ - public static void writeBytes(final String dest, final byte[] data) throws IOException { - writeBytes(file(dest), data); - } - - /** - * @see #writeBytes(File, byte[], int, int) - */ - public static void writeBytes(final File dest, final byte[] data) throws IOException { - writeBytes(dest, data, ZERO, data.length); - } - - /** - * @see #writeBytes(File, byte[], int, int) - */ - public static void writeBytes(final String dest, final byte[] data, final int off, final int len) throws IOException { - writeBytes(file(dest), data, off, len); - } - - /** - * Write bytes. append = false - * - * @see #outBytes(File, byte[], int, int, boolean) - */ - public static void writeBytes(final File dest, final byte[] data, final int off, final int len) throws IOException { - outBytes(dest, data, off, len, false); - } - - /** - * @see #appendBytes(File, byte[]) - */ - public static void appendBytes(final String dest, final byte[] data) throws IOException { - appendBytes(file(dest), data); - } - - /** - * @see #appendBytes(File, byte[], int, int) - */ - public static void appendBytes(final String dest, final byte[] data, final int off, final int len) throws IOException { - appendBytes(file(dest), data, off, len); - } - - /** - * @see #appendBytes(File, byte[], int, int) - */ - public static void appendBytes(final File dest, final byte[] data) throws IOException { - appendBytes(dest, data, ZERO, data.length); - } - - /** - * Appends bytes. append = true - * - * @see #outBytes(File, byte[], int, int, boolean) - */ - public static void appendBytes(final File dest, final byte[] data, final int off, final int len) throws IOException { - outBytes(dest, data, off, len, true); - } - - /** - * Writes data to {@link File} destination. - * - * @param dest destination {@link File} - * @param data Data as a {@link String} - * @param off the start offset in the data. - * @param len the number of bytes to write. - * @param append {@code true} if appending; {@code false} if {@link File} should be overwritten. - * @throws IOException if something went wrong. - */ - protected static void outBytes(final File dest, final byte[] data, final int off, final int len, final boolean append) throws IOException { - if (dest.exists()) { - checkIsFile(dest); - } - FileOutputStream out = null; - try { - out = new FileOutputStream(dest, append); - out.write(data, off, len); - } finally { - StreamUtil.close(out); - } - } - - // ---------------------------------------------------------------- equals content - - public static boolean compare(final String file1, final String file2) throws IOException { - return compare(file(file1), file(file2)); - } - - /** - * Compare the contents of two {@link File}s to determine if they are equal or - * not. - *

- * This method checks to see if the two {@link File}s are different lengths - * or if they point to the same {@link File}, before resorting to byte-by-byte - * comparison of the contents. - *

- * Code origin: Avalon - */ - public static boolean compare(final File one, final File two) throws IOException { - final boolean file1Exists = one.exists(); - if (file1Exists != two.exists()) { - return false; - } - - if (!file1Exists) { - return true; - } - - if ((!one.isFile()) || (!two.isFile())) { - throw new IOException("Only files can be compared"); - } - - if (one.length() != two.length()) { - return false; - } - - if (equals(one, two)) { - return true; - } - - InputStream input1 = null; - InputStream input2 = null; - try { - input1 = new FileInputStream(one); - input2 = new FileInputStream(two); - return StreamUtil.compare(input1, input2); - } finally { - StreamUtil.close(input1); - StreamUtil.close(input2); - } - } - - // ---------------------------------------------------------------- time - - /** - * @see #isOlder(File, File) - */ - public static boolean isOlder(final String file, final String reference) { - return isOlder(file(file), file(reference)); - } - - /** - * @see #isNewer(File, File) - */ - public static boolean isNewer(final String file, final String reference) { - return isNewer(file(file), file(reference)); - } - - /** - * Uses {@link File#lastModified()} for reference. - * - * @see #isNewer(File, long) - */ - public static boolean isNewer(final File file, final File reference) { - checkReferenceExists(reference); - return isNewer(file, reference.lastModified()); - } - - /** - * Uses {@link File#lastModified()} for reference. - * - * @see #isOlder(File, long) - */ - public static boolean isOlder(final File file, final File reference) { - checkReferenceExists(reference); - return isOlder(file, reference.lastModified()); - } - - /** - * Tests if the specified {@link File} is newer than the specified time reference. - * - * @param file the {@link File} of which the modification date must be compared. - * @param timeMillis the time reference measured in milliseconds since the - * epoch (00:00:00 GMT, January 1, 1970) - * @return {@code true} if the {@link File} exists and has been modified after - * the given time reference. - */ - public static boolean isNewer(final File file, final long timeMillis) { - return file.exists() && file.lastModified() > timeMillis; - } - - /** - * @see #isNewer(File, long) - */ - public static boolean isNewer(final String file, final long timeMillis) { - return isNewer(file(file), timeMillis); - } - - /** - * Tests if the specified {@link File} is older than the specified time reference. - * - * @param file the {@link File} of which the modification date must be compared. - * @param timeMillis the time reference measured in milliseconds since the - * epoch (00:00:00 GMT, January 1, 1970) - * @return {@code true} if the {@link File} exists and has been modified after - * the given time reference. - */ - public static boolean isOlder(final File file, final long timeMillis) { - return file.exists() && file.lastModified() < timeMillis; - } - - /** - * @see #isOlder(File, long) - */ - public static boolean isOlder(final String file, final long timeMillis) { - return isOlder(file(file), timeMillis); - } - - // ---------------------------------------------------------------- smart copy - - /** - * @see #copy(File, File) - */ - public static void copy(final String src, final String dest) throws IOException { - copy(file(src), file(dest)); - } - - /** - * Smart copy. If source is a directory, copy it to destination. - * Otherwise, if destination is directory, copy source file to it. - * Otherwise, try to copy source file to destination file. - * - * @param src source {@link File} - * @param dest destination {@link File} - * @throws IOException if there is an error copying. - * @see #copyDir(File, File) - * @see #copyFileToDir(File, File) - * @see #copyFile(File, File) - */ - public static void copy(final File src, final File dest) throws IOException { - if (src.isDirectory()) { - copyDir(src, dest); - return; - } - if (dest.isDirectory()) { - copyFileToDir(src, dest); - return; - } - copyFile(src, dest); - } - - // ---------------------------------------------------------------- smart move - - /** - * @see #move(File, File) - */ - public static void move(final String src, final String dest) throws IOException { - move(file(src), file(dest)); - } - - /** - * Smart move. If source is a directory, move it to destination. - * Otherwise, if destination is directory, move source {@link File} to it. - * Otherwise, try to move source {@link File} to destination {@link File}. - * - * @param src source {@link File} - * @param dest destination {@link File} - * @throws IOException if there is an error moving. - * @see #moveDir(File, File) - * @see #moveFileToDir(File, File) - * @see #moveFile(File, File) - */ - public static void move(final File src, final File dest) throws IOException { - if (src.isDirectory()) { - moveDir(src, dest); - return; - } - if (dest.isDirectory()) { - moveFileToDir(src, dest); - return; - } - moveFile(src, dest); - } - - - // ---------------------------------------------------------------- smart delete - - /** - * @see #delete(File) - */ - public static void delete(final String dest) throws IOException { - delete(file(dest)); - } - - /** - * Smart delete of destination file or directory. - * - * @throws IOException if there is an issue deleting the file/directory. - * @see #deleteFile(File) - * @see #deleteDir(File) - */ - public static void delete(final File dest) throws IOException { - if (dest.isDirectory()) { - deleteDir(dest); - return; - } - deleteFile(dest); - } - - // ---------------------------------------------------------------- misc - - /** - * Check if one {@link File} is an ancestor of second one. - * - * @param strict if c then this method returns {@code true} if ancestor - * and {@link File} are equal - * @return {@code true} if ancestor is parent of {@link File}; otherwise, {@code false} - */ - public static boolean isAncestor(final File ancestor, final File file, final boolean strict) { - File parent = strict ? getParentFile(file) : file; - while (true) { - if (parent == null) { - return false; - } - if (parent.equals(ancestor)) { - return true; - } - parent = getParentFile(parent); - } - } - - /** - * Returns parent for the file. The method correctly - * processes "." and ".." in {@link File} names. The name - * remains relative if was relative before. - * Returns {@code null} if the {@link File} has no parent. - * - * @param file {@link File} - * @return {@code null} if the {@link File} has no parent. - */ - public static File getParentFile(final File file) { - int skipCount = ZERO; - File parentFile = file; - while (true) { - parentFile = parentFile.getParentFile(); - if (parentFile == null) { - return null; - } - if (StringPool.DOT.equals(parentFile.getName())) { - continue; - } - if (StringPool.DOTDOT.equals(parentFile.getName())) { - skipCount++; - continue; - } - if (skipCount > ZERO) { - skipCount--; - continue; - } - return parentFile; - } - } - - /** - * Checks if file and its ancestors are acceptable by using {@link FileFilter#accept(File)}. - * - * @param file {@link File} to check. - * @param fileFilter {@link FileFilter} to use. - * @return if file and its ancestors are acceptable - */ - public static boolean isFilePathAcceptable(File file, final FileFilter fileFilter) { - do { - if (fileFilter != null && !fileFilter.accept(file)) { - return false; - } - file = file.getParentFile(); - } while (file != null); - return true; - } - - // ---------------------------------------------------------------- temp - - /** - * @see #createTempDirectory(String, String) - */ - public static File createTempDirectory() throws IOException { - return createTempDirectory(tempPrefix(), null); - } - - /** - * @see #createTempDirectory(String, String, File) - */ - public static File createTempDirectory(final String prefix, final String suffix) throws IOException { - return createTempDirectory(prefix, suffix, null); - } - - /** - * Creates temporary directory. - * - * @see #createTempFile(String, String, File) - */ - public static File createTempDirectory(final String prefix, final String suffix, final File tempDir) throws IOException { - final File file = createTempFile(prefix, suffix, tempDir); - file.delete(); - file.mkdir(); - return file; - } - - /** - * @see #createTempFile(String, String, File, boolean) - */ - public static File createTempFile() throws IOException { - return createTempFile(tempPrefix(), null, null, true); - } - - /** - * Creates temporary {@link File}. - * - * @param prefix The prefix string to be used in generating the file's - * name; must be at least three characters long - * @param suffix The suffix string to be used in generating the file's - * name; may be {@code null}, in which case the - * suffix {@code ".tmp"} will be used - * @param tempDir The directory in which the file is to be created, or - * {@code null} if the default temporary-file - * directory is to be used - * @param create If {@code create} is set to {@code true} {@link File} will be - * physically created on the file system. Otherwise, it will be created and then - * deleted - trick that will make temp {@link File} exist only if they are used. - * @return File - */ - public static File createTempFile(final String prefix, final String suffix, final File tempDir, final boolean create) throws IOException { - final File file = createTempFile(prefix, suffix, tempDir); - file.delete(); - if (create) { - file.createNewFile(); - } - return file; - } - - /** - * Creates temporary {@link File}. Wraps Java method and repeats creation several times - * if something fails. - * - * @param prefix The prefix string to be used in generating the file's - * name; must be at least three characters long - * @param suffix The suffix string to be used in generating the file's - * name; may be {@code null}, in which case the - * suffix {@code ".tmp"} will be used - * @param tempDir The directory in which the file is to be created, or - * {@code null} if the default temporary-file - * directory is to be used - */ - public static File createTempFile(final String prefix, final String suffix, final File tempDir) throws IOException { - int exceptionsCount = ZERO; - while (true) { - try { - return File.createTempFile(prefix, suffix, tempDir).getCanonicalFile(); - } catch (final IOException ioex) { // fixes java.io.WinNTFileSystem.createFileExclusively access denied - if (++exceptionsCount >= 50) { - throw ioex; - } - } - } - } - - // ---------------------------------------------------------------- symlink - - /** - * Determines whether the specified file is a symbolic link rather than an actual file. - * - * @deprecated {@link java.nio.file.Files#isSymbolicLink(java.nio.file.Path)} provides this functionality natively as of Java 1.7. - */ - @Deprecated - public static boolean isSymlink(final File file) { - return Files.isSymbolicLink(file.toPath()); - } - - // ---------------------------------------------------------------- digests - - /** - * Creates MD5 digest of a {@link File}. - * - * @param file {@link File} to create digest of. - * @return MD5 digest of the {@link File}. - */ - public static String md5(final File file) throws IOException { - return DigestEngine.md5().digestString(file); - } - - /** - * Creates SHA-256 digest of a file. - * - * @param file {@link File} to create digest of. - * @return SHA-256 digest of the {@link File}. - */ - public static String sha256(final File file) throws IOException { - return DigestEngine.sha256().digestString(file); - } - - /** - * Creates SHA-512 digest of a file. - * - * @param file {@link File} to create digest of. - * @return SHA-512 digest of the {@link File}. - */ - public static String sha512(final File file) throws IOException { - return DigestEngine.sha512().digestString(file); - } - - /** - * Checks the start of the file for ASCII control characters - * - * @param file {@link File} - * @return true if the the start of the {@link File} is ASCII control characters. - */ - public static boolean isBinary(final File file) throws IOException { - final byte[] bytes = readBytes(file, 128); - - for (final byte b : bytes) { - if (b < 32 && b != 9 && b != 10 && b != 13) { - return true; - } - } - - return false; - } - - /** - * @see #unicodeInputStreamOf(InputStream, String) - * @see #checkExists(File) - * @see #checkIsFile(File) - */ - private static UnicodeInputStream unicodeInputStreamOf(final File file) throws IOException { - checkExists(file); - checkIsFile(file); - return unicodeInputStreamOf(new FileInputStream(file), null); - } - - /** - * Returns new {@link UnicodeInputStream} using {@link InputStream} and targetEncoding. - * - * @param input {@link InputStream} - * @param targetEncoding Encoding to use. - * @return new {@link UnicodeInputStream}. - */ - private static UnicodeInputStream unicodeInputStreamOf(final InputStream input, final String targetEncoding) { - return new UnicodeInputStream(input, targetEncoding); - } - - /** - * Returns either new {@link FileInputStream} or new {@link UnicodeInputStream}. - * - * @return either {@link FileInputStream} or {@link UnicodeInputStream}. - * @throws IOException if something went wrong. - * @see #unicodeInputStreamOf(InputStream, String) - */ - private static InputStream streamOf(final File file, final String encoding) throws IOException { - InputStream in = new FileInputStream(file); - if (encoding.startsWith("UTF")) { - in = unicodeInputStreamOf(in, encoding); - } - return in; - } - - /** - * Detect encoding on {@link UnicodeInputStream} by using {@link UnicodeInputStream#getDetectedEncoding()}. - * - * @param in {@link UnicodeInputStream} - * @return UTF encoding as a String. If encoding could not be detected, defaults to {@link StringPool#UTF_8}. - * @see UnicodeInputStream#getDetectedEncoding() - */ - private static String detectEncoding(final UnicodeInputStream in) { - String encoding = in.getDetectedEncoding(); - if (encoding == null) { - encoding = StringPool.UTF_8; - } - return encoding; - } - - /** - * Checks if {@link File} exists. Throws IOException if not. - * - * @param file {@link File} - * @throws FileNotFoundException if file does not exist. - */ - private static void checkExists(final File file) throws FileNotFoundException { - if (!file.exists()) { - throw new FileNotFoundException(MSG_NOT_FOUND + file); - } - } - - /** - * Checks if {@link File} exists. Throws IllegalArgumentException if not. - * - * @param file {@link File} - * @throws IllegalArgumentException if file does not exist. - */ - private static void checkReferenceExists(final File file) throws IllegalArgumentException { - try { - checkExists(file); - } catch (final FileNotFoundException e) { - throw new IllegalArgumentException("Reference file not found: " + file); - } - } - - /** - * Checks if {@link File} is a file. Throws IOException if not. - * - * @param file {@link File} - * @throws IOException if {@link File} is not a file. - */ - private static void checkIsFile(final File file) throws IOException { - if (!file.isFile()) { - throw new IOException(MSG_NOT_A_FILE + file); - } - } - - /** - * Checks if {@link File} is a directory. Throws IOException if not. - * - * @param dir Directory - * @throws IOException if {@link File} is not a directory. - */ - private static void checkIsDirectory(final File dir) throws IOException { - if (!dir.isDirectory()) { - throw new IOException(MSG_NOT_A_DIRECTORY + dir); - } - } - - /** - * Checks if directory exists. Throws IOException if it does not. - * - * @param dir Directory - * @throws IOException if directory does not exist. - * @see #checkIsDirectory(File) - */ - private static void checkExistsAndDirectory(final File dir) throws IOException { - if (dir.exists()) { - checkIsDirectory(dir); - } - } - - /** - * Checks if directory can be created. Throws IOException if it cannot. - *

- * This actually creates directory (and its ancestors) (as per {@link File#mkdirs()} }). - * - * @param dir Directory - * @throws IOException if directory cannot be created. - */ - private static File checkCreateDirectory(final File dir) throws IOException { - if (!dir.mkdirs()) { - throw new IOException(MSG_CANT_CREATE + dir); - } - return dir; - } - - /** - * Checks if directory can be deleted. Throws IOException if it cannot. - * This actually deletes directory (as per {@link File#delete()}). - * - * @param dir Directory - * @throws IOException if directory cannot be created. - */ - private static void checkDeleteSuccessful(final File dir) throws IOException { - if (!dir.delete()) { - throw new IOException(MSG_UNABLE_TO_DELETE + dir); - } - } - - /** - * Checks that srcDir exists, that it is a directory and if srcDir and destDir are not equal. - * - * @param srcDir Source directory - * @param destDir Destination directory - * @throws IOException if any of the above conditions are not true. - */ - private static void checkDirCopy(final File srcDir, final File destDir) throws IOException { - checkExists(srcDir); - checkIsDirectory(srcDir); - if (equals(srcDir, destDir)) { - throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are equal"); - } - } - - /** - * Checks that file copy can occur. - * - * @param srcFile Source {@link File} - * @param destFile Destination {@link File} - * @throws IOException if srcFile does not exist or is not a file or - * srcFile and destFile are equal or cannot create ancestor directories. - */ - private static void checkFileCopy(final File srcFile, final File destFile) throws IOException { - checkExists(srcFile); - checkIsFile(srcFile); - if (equals(srcFile, destFile)) { - throw new IOException("Files '" + srcFile + "' and '" + destFile + "' are equal"); - } - - final File destParent = destFile.getParentFile(); - if (destParent != null && !destParent.exists()) { - checkCreateDirectory(destParent); - } - } - - // ---------------------------------------------------------------- configs - - /** - * Returns default encoding. - * @return default encoding. - */ - private static String encoding() { - return JoddCore.encoding; - } - - /** - * Returns default prefix for temp files. - * @return default prefix for temp files. - */ - private static String tempPrefix() { - return JoddCore.tempFilePrefix; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/NetUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/NetUtil.java deleted file mode 100644 index 200036324..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/NetUtil.java +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.util.StringUtil; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.URL; -import java.net.UnknownHostException; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.channels.ReadableByteChannel; -import java.nio.file.StandardOpenOption; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Network utilities. - */ -public class NetUtil { - - public static final String LOCAL_HOST = "localhost"; - public static final String LOCAL_IP = "127.0.0.1"; - public static final String DEFAULT_MASK = "255.255.255.0"; - public static final int INT_VALUE_127_0_0_1 = 0x7f000001; - - /** - * Resolves IP address from a hostname. - */ - public static String resolveIpAddress(final String hostname) { - try { - InetAddress netAddress; - - if (hostname == null || hostname.equalsIgnoreCase(LOCAL_HOST)) { - netAddress = InetAddress.getLocalHost(); - } else { - netAddress = Inet4Address.getByName(hostname); - } - return netAddress.getHostAddress(); - } catch (UnknownHostException ignore) { - return null; - } - } - - /** - * Returns IP address as integer. - */ - public static int getIpAsInt(final String ipAddress) { - int ipIntValue = 0; - String[] tokens = StringUtil.splitc(ipAddress, '.'); - for (String token : tokens) { - if (ipIntValue > 0) { - ipIntValue <<= 8; - } - ipIntValue += Integer.parseInt(token); - } - return ipIntValue; - } - - public static int getMaskAsInt(String mask) { - if (!validateIPv4(mask)) { - mask = DEFAULT_MASK; - } - return getIpAsInt(mask); - } - - public static boolean isSocketAccessAllowed(final int localIp, final int socketIp, final int mask) { - boolean _retVal = false; - - if (socketIp == INT_VALUE_127_0_0_1 || (localIp & mask) == (socketIp & mask)) { - _retVal = true; - } - return _retVal; - } - - private static final Pattern ip4RegExp = Pattern.compile("^((?:1?[1-9]?\\d|2(?:[0-4]\\d|5[0-5]))\\.){4}$"); - - /** - * Checks given string against IP address v4 format. - * - * @param input an ip address - may be null - * @return true if param has a valid ip v4 format false otherwise - * @see ip address v4 - */ - public static boolean validateIPv4(final String input) { - Matcher m = ip4RegExp.matcher(input + '.'); - return m.matches(); - } - - /** - * Resolves host name from IP address bytes. - */ - public static String resolveHostName(final byte[] ip) { - try { - InetAddress address = InetAddress.getByAddress(ip); - return address.getHostName(); - } catch (UnknownHostException ignore) { - return null; - } - } - - // ---------------------------------------------------------------- download - - /** - * Downloads resource as byte array. - */ - public static byte[] downloadBytes(final String url) throws IOException { - try (InputStream inputStream = new URL(url).openStream()) { - return StreamUtil.readBytes(inputStream); - } - } - - /** - * Downloads resource as String. - */ - public static String downloadString(final String url, final String encoding) throws IOException { - try (InputStream inputStream = new URL(url).openStream()) { - return new String(StreamUtil.readChars(inputStream, encoding)); - } - } - - /** - * Downloads resource as String. - */ - public static String downloadString(final String url) throws IOException { - try (InputStream inputStream = new URL(url).openStream()) { - return new String(StreamUtil.readChars(inputStream)); - } - } - - /** - * Downloads resource to a file, potentially very efficiently. - */ - public static void downloadFile(final String url, final File file) throws IOException { - try ( - InputStream inputStream = new URL(url).openStream(); - ReadableByteChannel rbc = Channels.newChannel(inputStream); - FileChannel fileChannel = FileChannel.open( - file.toPath(), - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.WRITE) - ) { - fileChannel.transferFrom(rbc, 0, Long.MAX_VALUE); - } - } - - /** - * Get remote file size. Returns -1 if the content length is unknown - * - * @param url remote file url - * @return file size - * @throws IOException JDK-IOException - */ - public static long getRemoteFileSize(String url) throws IOException { - HttpURLConnection connection = null; - try { - connection = (HttpURLConnection) new URL(url).openConnection(); - return connection.getContentLengthLong(); - } finally { - if (connection != null) { - connection.disconnect(); - } - } - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/PathUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/PathUtil.java deleted file mode 100644 index c9eed8f3a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/PathUtil.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.util.StringUtil; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; - -public class PathUtil { - - /** - * Resolves subpath in safer way. For some reason, if child starts with - * a separator it gets resolved as a full path, ignoring the base. - * This method acts different. - */ - public static Path resolve(final Path base, String child) { - if (StringUtil.startsWithChar(child, File.separatorChar)) { - child = child.substring(1); - } - return base.resolve(child); - } - - public static Path resolve(Path path, final String... childs) { - for (String child : childs) { - path = resolve(path, child); - } - return path; - } - - /** - * Reads path content. - */ - public static String readString(final Path path) throws IOException { - try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { - StringWriter writer = new StringWriter(); // flush & close not needed for StringWriter-instance - StreamUtil.copy(reader, writer); - return writer.toString(); - } - } - - /** - * Deletes a directory recursively. - */ - public static void deleteFileTree(final Path directory) throws IOException { - Files.walkFileTree(directory, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException { - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - }); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/StreamGobbler.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/StreamGobbler.java deleted file mode 100644 index feca3f53e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/StreamGobbler.java +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.util.StringPool; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintStream; - -/** - * Consumes a stream. - * For any Process, the input and error streams must read even - * if the data written to these streams is not used by the application. - * The generally accepted solution for this problem is a stream gobbler thread - * that does nothing but consume data from an input stream until stopped. - */ -public class StreamGobbler extends Thread { - - protected final InputStream is; - protected final String prefix; - protected final OutputStream out; - protected final Object lock = new Object(); - protected boolean end = false; - - public StreamGobbler(final InputStream is) { - this(is, null, null); - } - - public StreamGobbler(final InputStream is, final OutputStream output) { - this(is, output, null); - } - - public StreamGobbler(final InputStream is, final OutputStream output, final String prefix) { - this.is = is; - this.prefix = prefix; - this.out = output; - } - - @Override - public void run() { - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - - try { - String line; - while ((line = br.readLine()) != null) { - if (out != null) { - if (prefix != null) { - out.write(prefix.getBytes()); - } - out.write(line.getBytes()); - out.write(StringPool.BYTES_NEW_LINE); - } - } - } - catch (IOException ioe) { - if (out != null) { - ioe.printStackTrace(new PrintStream(out)); - } - } - finally { - if (out != null) { - try { - out.flush(); - } - catch (IOException ignore) { - } - } - try { - br.close(); - } - catch (IOException ignore) { - } - } - - synchronized (lock) { - lock.notifyAll(); - end = true; - } - } - - /** - * Waits for gobbler to end. - */ - public void waitFor() { - try { - synchronized (lock) { - if (!end) { - lock.wait(); - } - } - } - catch (InterruptedException ignore) { - Thread.currentThread().interrupt(); - } - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/StreamUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/StreamUtil.java deleted file mode 100644 index 1c6054c3e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/StreamUtil.java +++ /dev/null @@ -1,656 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.core.JoddCore; - -import javax.activation.DataSource; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.Closeable; -import java.io.Flushable; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; - -/** - * Optimized byte and character stream utilities. - */ -public class StreamUtil { - - private static final int ZERO = 0; - private static final int NEGATIVE_ONE = -1; - private static final int ALL = -1; - - // ---------------------------------------------------------------- silent close - - /** - * Closes silently the closable object. If it is {@link Flushable}, it - * will be flushed first. No exception will be thrown if an I/O error occurs. - */ - public static void close(final Closeable closeable) { - if (closeable != null) { - if (closeable instanceof Flushable) { - try { - ((Flushable) closeable).flush(); - } catch (IOException ignored) { - } - } - - try { - closeable.close(); - } catch (IOException ignored) { - } - } - } - - // ---------------------------------------------------------------- copy - - /** - * Copies bytes from {@link Reader} to {@link Writer} using buffer. - * {@link Reader} and {@link Writer} don't have to be wrapped to buffered, since copying is already optimized. - * - * @param input {@link Reader} to read. - * @param output {@link Writer} to write to. - * @return The total number of characters read. - * @throws IOException if there is an error reading or writing. - */ - public static int copy(final Reader input, final Writer output) throws IOException { - int numToRead = bufferSize(); - char[] buffer = new char[numToRead]; - - int totalRead = ZERO; - int read; - - while ((read = input.read(buffer, ZERO, numToRead)) >= ZERO) { - output.write(buffer, ZERO, read); - totalRead = totalRead + read; - } - - output.flush(); - return totalRead; - } - - /** - * Copies bytes from {@link InputStream} to {@link OutputStream} using buffer. - * {@link InputStream} and {@link OutputStream} don't have to be wrapped to buffered, - * since copying is already optimized. - * - * @param input {@link InputStream} to read. - * @param output {@link OutputStream} to write to. - * @return The total number of bytes read. - * @throws IOException if there is an error reading or writing. - */ - public static int copy(final InputStream input, final OutputStream output) throws IOException { - int numToRead = bufferSize(); - byte[] buffer = new byte[numToRead]; - - int totalRead = ZERO; - int read; - - while ((read = input.read(buffer, ZERO, numToRead)) >= ZERO) { - output.write(buffer, ZERO, read); - totalRead = totalRead + read; - } - - output.flush(); - return totalRead; - } - - /** - * Copies specified number of characters from {@link Reader} to {@link Writer} using buffer. - * {@link Reader} and {@link Writer} don't have to be wrapped to buffered, since copying is already optimized. - * - * @param input {@link Reader} to read. - * @param output {@link Writer} to write to. - * @param count The number of characters to read. - * @return The total number of characters read. - * @throws IOException if there is an error reading or writing. - */ - public static int copy(final Reader input, final Writer output, final int count) throws IOException { - if (count == ALL) { - return copy(input, output); - } - - int numToRead = count; - char[] buffer = new char[numToRead]; - - int totalRead = ZERO; - int read; - - while (numToRead > ZERO) { - read = input.read(buffer, ZERO, bufferSize(numToRead)); - if (read == NEGATIVE_ONE) { - break; - } - output.write(buffer, ZERO, read); - - numToRead = numToRead - read; - totalRead = totalRead + read; - } - - output.flush(); - return totalRead; - } - - /** - * Copies specified number of bytes from {@link InputStream} to {@link OutputStream} using buffer. - * {@link InputStream} and {@link OutputStream} don't have to be wrapped to buffered, since copying is already optimized. - * - * @param input {@link InputStream} to read. - * @param output {@link OutputStream} to write to. - * @param count The number of bytes to read. - * @return The total number of bytes read. - * @throws IOException if there is an error reading or writing. - */ - public static int copy(final InputStream input, final OutputStream output, final int count) throws IOException { - if (count == ALL) { - return copy(input, output); - } - - int numToRead = count; - byte[] buffer = new byte[numToRead]; - - int totalRead = ZERO; - int read; - - while (numToRead > ZERO) { - read = input.read(buffer, ZERO, bufferSize(numToRead)); - if (read == NEGATIVE_ONE) { - break; - } - output.write(buffer, ZERO, read); - - numToRead = numToRead - read; - totalRead = totalRead + read; - } - - output.flush(); - return totalRead; - } - - // ---------------------------------------------------------------- read bytes - - /** - * Reads all available bytes from {@link InputStream} as a byte array. - * Uses {@link InputStream#available()} to determine the size of input stream. - * This is the fastest method for reading {@link InputStream} to byte array, but - * depends on {@link InputStream} implementation of {@link InputStream#available()}. - * - * @param input {@link InputStream} to read. - * @return byte[] - * @throws IOException if total read is less than {@link InputStream#available()}; - */ - public static byte[] readAvailableBytes(final InputStream input) throws IOException { - int numToRead = input.available(); - byte[] buffer = new byte[numToRead]; - - int totalRead = ZERO; - int read; - - while ((totalRead < numToRead) && (read = input.read(buffer, totalRead, numToRead - totalRead)) >= ZERO) { - totalRead = totalRead + read; - } - - if (totalRead < numToRead) { - throw new IOException("Failed to completely read InputStream"); - } - - return buffer; - } - - // ---------------------------------------------------------------- copy to OutputStream - - /** - * @see #copy(Reader, OutputStream, String) - */ - public static T copy(final Reader input, final T output) throws IOException { - return copy(input, output, encoding()); - } - - /** - * @see #copy(Reader, OutputStream, String, int) - */ - public static T copy(final Reader input, final T output, final int count) throws IOException { - return copy(input, output, encoding(), count); - } - - /** - * @see #copy(Reader, OutputStream, String, int) - */ - public static T copy(final Reader input, final T output, final String encoding) throws IOException { - return copy(input, output, encoding, ALL); - } - - /** - * Copies {@link Reader} to {@link OutputStream} using buffer and specified encoding. - * - * @see #copy(Reader, Writer, int) - */ - public static T copy(final Reader input, final T output, final String encoding, final int count) throws IOException { - try (Writer out = outputStreamWriterOf(output, encoding)) { - copy(input, out, count); - return output; - } - } - - /** - * Copies data from {@link DataSource} to a new {@link FastByteArrayOutputStream} and returns this. - * - * @param input {@link DataSource} to copy from. - * @return new {@link FastByteArrayOutputStream} with data from input. - * @see #copyToOutputStream(InputStream) - */ - public static FastByteArrayOutputStream copyToOutputStream(final DataSource input) throws IOException { - return copyToOutputStream(input.getInputStream()); - } - - /** - * @see #copyToOutputStream(InputStream, int) - */ - public static FastByteArrayOutputStream copyToOutputStream(final InputStream input) throws IOException { - return copyToOutputStream(input, ALL); - } - - /** - * Copies {@link InputStream} to a new {@link FastByteArrayOutputStream} using buffer and specified encoding. - * - * @see #copy(InputStream, OutputStream, int) - */ - public static FastByteArrayOutputStream copyToOutputStream(final InputStream input, final int count) throws IOException { - try (FastByteArrayOutputStream output = createFastByteArrayOutputStream()) { - copy(input, output, count); - return output; - } - } - - /** - * @see #copyToOutputStream(Reader, String) - */ - public static FastByteArrayOutputStream copyToOutputStream(final Reader input) throws IOException { - return copyToOutputStream(input, encoding()); - } - - /** - * @see #copyToOutputStream(Reader, String, int) - */ - public static FastByteArrayOutputStream copyToOutputStream(final Reader input, final String encoding) throws IOException { - return copyToOutputStream(input, encoding, ALL); - } - - /** - * @see #copyToOutputStream(Reader, String, int) - */ - public static FastByteArrayOutputStream copyToOutputStream(final Reader input, final int count) throws IOException { - return copyToOutputStream(input, encoding(), count); - } - - /** - * Copies {@link Reader} to a new {@link FastByteArrayOutputStream} using buffer and specified encoding. - * - * @see #copy(Reader, OutputStream, String, int) - */ - public static FastByteArrayOutputStream copyToOutputStream(final Reader input, final String encoding, final int count) throws IOException { - try (FastByteArrayOutputStream output = createFastByteArrayOutputStream()) { - copy(input, output, encoding, count); - return output; - } - } - - // ---------------------------------------------------------------- copy to Writer - - /** - * @see #copy(InputStream, Writer, String) - */ - public static T copy(final InputStream input, final T output) throws IOException { - return copy(input, output, encoding()); - } - - /** - * @see #copy(InputStream, Writer, String, int) - */ - public static T copy(final InputStream input, final T output, final int count) throws IOException { - return copy(input, output, encoding(), count); - } - - /** - * @see #copy(InputStream, Writer, String, int) - */ - public static T copy(final InputStream input, final T output, final String encoding) throws IOException { - return copy(input, output, encoding, ALL); - } - - /** - * Copies {@link InputStream} to {@link Writer} using buffer and specified encoding. - * - * @see #copy(Reader, Writer, int) - */ - public static T copy(final InputStream input, final T output, final String encoding, final int count) throws IOException { - copy(inputStreamReadeOf(input, encoding), output, count); - return output; - } - - /** - * @see #copy(InputStream, String) - */ - public static FastCharArrayWriter copy(final InputStream input) throws IOException { - return copy(input, encoding()); - } - - /** - * @see #copy(InputStream, String, int) - */ - public static FastCharArrayWriter copy(final InputStream input, final int count) throws IOException { - return copy(input, encoding(), count); - } - - /** - * @see #copy(InputStream, String, int) - */ - public static FastCharArrayWriter copy(final InputStream input, final String encoding) throws IOException { - return copy(input, encoding, ALL); - } - - /** - * Copies {@link InputStream} to a new {@link FastCharArrayWriter} using buffer and specified encoding. - * - * @see #copy(InputStream, Writer, String, int) - */ - public static FastCharArrayWriter copy(final InputStream input, final String encoding, final int count) throws IOException { - try (FastCharArrayWriter output = createFastCharArrayWriter()) { - copy(input, output, encoding, count); - return output; - } - } - - /** - * @see #copy(Reader, int) - */ - public static FastCharArrayWriter copy(final Reader input) throws IOException { - return copy(input, ALL); - } - - /** - * Copies {@link Reader} to a new {@link FastCharArrayWriter} using buffer and specified encoding. - * - * @see #copy(Reader, Writer, int) - */ - public static FastCharArrayWriter copy(final Reader input, final int count) throws IOException { - try (FastCharArrayWriter output = createFastCharArrayWriter()) { - copy(input, output, count); - return output; - } - } - - /** - * Copies data from {@link DataSource} to a new {@link FastCharArrayWriter} and returns this. - * - * @param input {@link DataSource} to copy from. - * @return new {@link FastCharArrayWriter} with data from input. - * @see #copy(InputStream) - */ - public static FastCharArrayWriter copy(final DataSource input) throws IOException { - return copy(input.getInputStream()); - } - - // ---------------------------------------------------------------- read bytes - - /** - * @see #readBytes(InputStream, int) - */ - public static byte[] readBytes(final InputStream input) throws IOException { - return readBytes(input, ALL); - } - - /** - * @see #copyToOutputStream(InputStream, int) - */ - public static byte[] readBytes(final InputStream input, final int count) throws IOException { - return copyToOutputStream(input, count).toByteArray(); - } - - /** - * @see #readBytes(Reader, String) - */ - public static byte[] readBytes(final Reader input) throws IOException { - return readBytes(input, encoding()); - } - - /** - * @see #readBytes(Reader, String, int) - */ - public static byte[] readBytes(final Reader input, final int count) throws IOException { - return readBytes(input, encoding(), count); - } - - /** - * @see #readBytes(Reader, String, int) - */ - public static byte[] readBytes(final Reader input, final String encoding) throws IOException { - return readBytes(input, encoding, ALL); - } - - /** - * @see #copyToOutputStream(Reader, String, int) - */ - public static byte[] readBytes(final Reader input, final String encoding, final int count) throws IOException { - return copyToOutputStream(input, encoding, count).toByteArray(); - } - - // ---------------------------------------------------------------- read chars - - /** - * @see #readChars(Reader, int) - */ - public static char[] readChars(final Reader input) throws IOException { - return readChars(input, ALL); - } - - /** - * @see #copy(Reader, int) - */ - public static char[] readChars(final Reader input, final int count) throws IOException { - return copy(input, count).toCharArray(); - } - - /** - * @see #readChars(InputStream, int) - */ - public static char[] readChars(final InputStream input) throws IOException { - return readChars(input, ALL); - } - - /** - * @see #readChars(InputStream, String, int) - */ - public static char[] readChars(final InputStream input, final String encoding) throws IOException { - return readChars(input, encoding, ALL); - } - - /** - * @see #readChars(InputStream, String, int) - */ - public static char[] readChars(final InputStream input, final int count) throws IOException { - return readChars(input, encoding(), count); - } - - /** - * @see #copy(InputStream, String, int) - */ - public static char[] readChars(final InputStream input, final String encoding, final int count) throws IOException { - return copy(input, encoding, count).toCharArray(); - } - - // ---------------------------------------------------------------- compare content - - /** - * Compares the content of two byte streams ({@link InputStream}s). - * - * @return {@code true} if the content of the first {@link InputStream} is equal - * to the content of the second {@link InputStream}. - */ - public static boolean compare(InputStream input1, InputStream input2) throws IOException { - if (!(input1 instanceof BufferedInputStream)) { - input1 = new BufferedInputStream(input1); - } - if (!(input2 instanceof BufferedInputStream)) { - input2 = new BufferedInputStream(input2); - } - int ch = input1.read(); - while (ch != NEGATIVE_ONE) { - int ch2 = input2.read(); - if (ch != ch2) { - return false; - } - ch = input1.read(); - } - int ch2 = input2.read(); - return (ch2 == NEGATIVE_ONE); - } - - /** - * Compares the content of two character streams ({@link Reader}s). - * - * @return {@code true} if the content of the first {@link Reader} is equal - * to the content of the second {@link Reader}. - */ - public static boolean compare(Reader input1, Reader input2) throws IOException { - if (!(input1 instanceof BufferedReader)) { - input1 = new BufferedReader(input1); - } - if (!(input2 instanceof BufferedReader)) { - input2 = new BufferedReader(input2); - } - - int ch = input1.read(); - while (ch != NEGATIVE_ONE) { - int ch2 = input2.read(); - if (ch != ch2) { - return false; - } - ch = input1.read(); - } - int ch2 = input2.read(); - return (ch2 == NEGATIVE_ONE); - } - - // ---------------------------------------------------------------- defaults - - /** - * Returns default IO buffer size. - * - * @return default IO buffer size. - */ - private static int bufferSize() { - return JoddCore.ioBufferSize; - } - - /** - * Returns either count or default IO buffer size (whichever is smaller). - * - * @param count Number of characters or bytes to retrieve. - * @return buffer size (either count or default IO buffer size, whichever is smaller). - */ - private static int bufferSize(final int count) { - final int ioBufferSize = JoddCore.ioBufferSize; - if (count < ioBufferSize) { - return count; - } else { - return ioBufferSize; - } - } - - /** - * Returns default encoding. - * @return default encoding. - */ - private static String encoding() { - return JoddCore.encoding; - } - - // ---------------------------------------------------------------- wrappers - - /** - * Returns new {@link FastCharArrayWriter} using default IO buffer size. - * - * @return new {@link FastCharArrayWriter} using default IO buffer size. - */ - private static FastCharArrayWriter createFastCharArrayWriter() { - return new FastCharArrayWriter(bufferSize()); - } - - /** - * Returns new {@link FastByteArrayOutputStream} using default IO buffer size. - * - * @return new {@link FastByteArrayOutputStream} using default IO buffer size. - */ - private static FastByteArrayOutputStream createFastByteArrayOutputStream() { - return new FastByteArrayOutputStream(bufferSize()); - } - - /** - * @see #inputStreamReadeOf(InputStream, String) - */ - public static InputStreamReader inputStreamReadeOf(final InputStream input) throws UnsupportedEncodingException { - return inputStreamReadeOf(input, encoding()); - } - - /** - * Returns new {@link InputStreamReader} using specified {@link InputStream} and encoding. - * - * @param input {@link InputStream} - * @param encoding Encoding as {@link String} to use for {@link InputStreamReader}. - * @return new {@link InputStreamReader} - * @throws UnsupportedEncodingException if encoding is not valid. - */ - public static InputStreamReader inputStreamReadeOf(final InputStream input, final String encoding) throws UnsupportedEncodingException { - return new InputStreamReader(input, encoding); - } - - /** - * @see #outputStreamWriterOf(OutputStream, String) - */ - public static OutputStreamWriter outputStreamWriterOf(final OutputStream output) throws UnsupportedEncodingException { - return outputStreamWriterOf(output, encoding()); - } - - /** - * Returns new {@link OutputStreamWriter} using specified {@link OutputStream} and encoding. - * - * @param output {@link OutputStream} - * @param encoding Encoding as {@link String} to use for {@link OutputStreamWriter}. - * @return new {@link OutputStreamWriter} - * @throws UnsupportedEncodingException if encoding is not valid. - */ - public static OutputStreamWriter outputStreamWriterOf(final OutputStream output, final String encoding) throws UnsupportedEncodingException { - return new OutputStreamWriter(output, encoding); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/UnicodeInputStream.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/UnicodeInputStream.java deleted file mode 100644 index d56c9296c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/UnicodeInputStream.java +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; - -/** - * Unicode input stream for detecting UTF encodings and reading BOM characters. - * Detects following BOMs: - *

    - *
  • UTF-8
  • - *
  • UTF-16BE
  • - *
  • UTF-16LE
  • - *
  • UTF-32BE
  • - *
  • UTF-32LE
  • - *
- */ -public class UnicodeInputStream extends InputStream { - - public static final int MAX_BOM_SIZE = 4; - - private final PushbackInputStream internalInputStream; - private boolean initialized; - private int BOMSize = -1; - private String encoding; - private final String targetEncoding; - - /** - * Creates new unicode stream. It works in two modes: detect mode and read mode. - *

- * Detect mode is active when target encoding is not specified. - * In detect mode, it tries to detect encoding from BOM if exist. - * If BOM doesn't exist, encoding is not detected. - *

- * Read mode is active when target encoding is set. Then this stream reads - * optional BOM for given encoding. If BOM doesn't exist, nothing is skipped. - */ - public UnicodeInputStream(final InputStream in, final String targetEncoding) { - internalInputStream = new PushbackInputStream(in, MAX_BOM_SIZE); - this.targetEncoding = targetEncoding; - } - - /** - * Returns detected UTF encoding or {@code null} if no UTF encoding has been detected (i.e. no BOM). - * If stream is not read yet, it will be {@link #init() initalized} first. - */ - public String getDetectedEncoding() { - if (!initialized) { - try { - init(); - } catch (IOException ioex) { - throw new IllegalStateException(ioex); - } - } - return encoding; - } - - public static final byte[] BOM_UTF32_BE = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF}; - public static final byte[] BOM_UTF32_LE = new byte[]{(byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00}; - public static final byte[] BOM_UTF8 = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; - public static final byte[] BOM_UTF16_BE = new byte[]{(byte) 0xFE, (byte) 0xFF}; - public static final byte[] BOM_UTF16_LE = new byte[]{(byte) 0xFF, (byte) 0xFE}; - - /** - * Detects and decodes encoding from BOM character. - * Reads ahead four bytes and check for BOM marks. - * Extra bytes are unread back to the stream, so only - * BOM bytes are skipped. - */ - protected void init() throws IOException { - if (initialized) { - return; - } - - if (targetEncoding == null) { - - // DETECT MODE - - byte[] bom = new byte[MAX_BOM_SIZE]; - int n = internalInputStream.read(bom, 0, bom.length); - int unread; - - if ((bom[0] == BOM_UTF32_BE[0]) && (bom[1] == BOM_UTF32_BE[1]) && (bom[2] == BOM_UTF32_BE[2]) && (bom[3] == BOM_UTF32_BE[3])) { - encoding = "UTF-32BE"; - unread = n - 4; - } else if ((bom[0] == BOM_UTF32_LE[0]) && (bom[1] == BOM_UTF32_LE[1]) && (bom[2] == BOM_UTF32_LE[2]) && (bom[3] == BOM_UTF32_LE[3])) { - encoding = "UTF-32LE"; - unread = n - 4; - } else if ((bom[0] == BOM_UTF8[0]) && (bom[1] == BOM_UTF8[1]) && (bom[2] == BOM_UTF8[2])) { - encoding = "UTF-8"; - unread = n - 3; - } else if ((bom[0] == BOM_UTF16_BE[0]) && (bom[1] == BOM_UTF16_BE[1])) { - encoding = "UTF-16BE"; - unread = n - 2; - } else if ((bom[0] == BOM_UTF16_LE[0]) && (bom[1] == BOM_UTF16_LE[1])) { - encoding = "UTF-16LE"; - unread = n - 2; - } else { - // BOM not found, unread all bytes - unread = n; - } - - BOMSize = MAX_BOM_SIZE - unread; - - if (unread > 0) { - internalInputStream.unread(bom, (n - unread), unread); - } - } else { - - // READ MODE - - byte[] bom = null; - - if (targetEncoding.equals("UTF-8")) { - bom = BOM_UTF8; - } else if (targetEncoding.equals("UTF-16LE")) { - bom = BOM_UTF16_LE; - } else if (targetEncoding.equals("UTF-16BE") || targetEncoding.equals("UTF-16")) { - bom = BOM_UTF16_BE; - } else if (targetEncoding.equals("UTF-32LE")) { - bom = BOM_UTF32_LE; - } else if (targetEncoding.equals("UTF-32BE") || targetEncoding.equals("UTF-32")) { - bom = BOM_UTF32_BE; - } else { - // no UTF encoding, no BOM - } - - if (bom != null) { - byte[] fileBom = new byte[bom.length]; - int n = internalInputStream.read(fileBom, 0, bom.length); - - boolean bomDetected = true; - for (int i = 0; i < n; i++) { - if (fileBom[i] != bom[i]) { - bomDetected = false; - break; - } - } - - if (!bomDetected) { - internalInputStream.unread(fileBom, 0, fileBom.length); - } - } - } - - initialized = true; - } - - /** - * Closes input stream. If stream was not used, encoding - * will be unavailable. - */ - @Override - public void close() throws IOException { - internalInputStream.close(); - } - - /** - * Reads byte from the stream. - */ - @Override - public int read() throws IOException { - init(); - return internalInputStream.read(); - } - - /** - * Returns BOM size in bytes. - * Returns -1 if BOM not found. - */ - public int getBOMSize() { - return BOMSize; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/ZipBuilder.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/ZipBuilder.java deleted file mode 100644 index 8a5073f7b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/ZipBuilder.java +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.StringUtil; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.zip.ZipOutputStream; - -/** - * ZIP builder class for building both files or in-memory zips. - */ -public class ZipBuilder { - - private final ZipOutputStream zos; - private final File targetZipFile; - private final ByteArrayOutputStream targetBaos; - - public static ZipBuilder createZipFile(final File zipFile) throws IOException { - return new ZipBuilder(zipFile); - } - public static ZipBuilder createZipFile(final String zipFile) throws IOException { - return new ZipBuilder(new File(zipFile)); - } - - public static ZipBuilder createZipInMemory() { - return new ZipBuilder(); - } - - // ---------------------------------------------------------------- ctors - - protected ZipBuilder(final File zipFile) throws IOException { - if (!FileUtil.isExistingFile(zipFile)) { - FileUtil.touch(zipFile); - } - zos = new ZipOutputStream(new FileOutputStream(zipFile)); - targetZipFile = zipFile; - targetBaos = null; - } - - protected ZipBuilder() { - targetZipFile = null; - targetBaos = new ByteArrayOutputStream(); - zos = new ZipOutputStream(targetBaos); - } - - // ---------------------------------------------------------------- get - - public File toZipFile() { - StreamUtil.close(zos); - - return targetZipFile; - } - - public byte[] toBytes() { - StreamUtil.close(zos); - - if (targetZipFile != null) { - try { - return FileUtil.readBytes(targetZipFile); - } - catch (IOException ignore) { - return null; - } - } - - return targetBaos.toByteArray(); - } - - // ---------------------------------------------------------------- add file to zip - - public AddFileToZip add(final File source) { - return new AddFileToZip(source); - } - - public class AddFileToZip { - private final File file; - private String path; - private String comment; - private boolean recursive = true; - - private AddFileToZip(final File file) { - this.file = file; - } - - /** - * Defines optional entry path. - */ - public AddFileToZip path(final String path) { - this.path = path; - return this; - } - - /** - * Defines optional comment. - */ - public AddFileToZip comment(final String comment) { - this.comment = comment; - return this; - } - /** - * Defines if folders content should be added. - * Ignored when used for files. - */ - public AddFileToZip recursive() { - this.recursive = true; - return this; - } - - /** - * Stores the content into the ZIP. - */ - public ZipBuilder save() throws IOException { - ZipUtil.addToZip(zos, file, path, comment, recursive); - return ZipBuilder.this; - } - } - - // ---------------------------------------------------------------- add content - - public AddContentToZip add(final String content) { - return new AddContentToZip(StringUtil.getBytes(content, StringPool.UTF_8)); - } - - public AddContentToZip add(final byte[] content) { - return new AddContentToZip(content); - } - - public class AddContentToZip { - private final byte[] bytes; - private String path; - private String comment; - - private AddContentToZip(final byte[] content) { - this.bytes = content; - } - - /** - * Defines optional entry path. - */ - public AddContentToZip path(final String path) { - this.path = path; - return this; - } - - /** - * Defines optional comment. - */ - public AddContentToZip comment(final String comment) { - this.comment = comment; - return this; - } - - /** - * Stores the content into the ZIP. - */ - public ZipBuilder save() throws IOException { - ZipUtil.addToZip(zos, bytes, path, comment); - return ZipBuilder.this; - } - } - - // ---------------------------------------------------------------- folder - - public ZipBuilder addFolder(final String folderName) throws IOException { - ZipUtil.addFolderToZip(zos, folderName, null); - return this; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/ZipUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/ZipUtil.java deleted file mode 100644 index fcb10f43e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/ZipUtil.java +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io; - -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.StringUtil; -import com.fr.third.jodd.util.Wildcard; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.zip.Deflater; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -/** - * Performs zip/gzip/zlib operations on files and directories. - * These are just tools over existing java.util.zip classes, - * meaning that existing behavior and bugs are persisted. - * Most common issue is not being able to use UTF8 in file names, - * because implementation uses old ZIP format that supports only - * IBM Code Page 437. This bug was resolved in JDK7: - * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499 - */ -public class ZipUtil { - - public static final String ZIP_EXT = ".zip"; - public static final String GZIP_EXT = ".gz"; - public static final String ZLIB_EXT = ".zlib"; - - // ---------------------------------------------------------------- deflate - - /** - * Compresses a file into zlib archive. - */ - public static File zlib(final String file) throws IOException { - return zlib(new File(file)); - } - - /** - * Compresses a file into zlib archive. - */ - public static File zlib(final File file) throws IOException { - if (file.isDirectory()) { - throw new IOException("Can't zlib folder"); - } - FileInputStream fis = new FileInputStream(file); - Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); - - String zlibFileName = file.getAbsolutePath() + ZLIB_EXT; - - DeflaterOutputStream dos = new DeflaterOutputStream(new FileOutputStream(zlibFileName), deflater); - - try { - StreamUtil.copy(fis, dos); - } finally { - StreamUtil.close(dos); - StreamUtil.close(fis); - } - - return new File(zlibFileName); - } - - // ---------------------------------------------------------------- gzip - - /** - * Compresses a file into gzip archive. - */ - public static File gzip(final String fileName) throws IOException { - return gzip(new File(fileName)); - } - - /** - * Compresses a file into gzip archive. - */ - public static File gzip(final File file) throws IOException { - if (file.isDirectory()) { - throw new IOException("Can't gzip folder"); - } - FileInputStream fis = new FileInputStream(file); - - String gzipName = file.getAbsolutePath() + GZIP_EXT; - - GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(gzipName)); - try { - StreamUtil.copy(fis, gzos); - } finally { - StreamUtil.close(gzos); - StreamUtil.close(fis); - } - - return new File(gzipName); - } - - /** - * Decompress gzip archive. - */ - public static File ungzip(final String file) throws IOException { - return ungzip(new File(file)); - } - - /** - * Decompress gzip archive. - */ - public static File ungzip(final File file) throws IOException { - String outFileName = FileNameUtil.removeExtension(file.getAbsolutePath()); - File out = new File(outFileName); - out.createNewFile(); - - FileOutputStream fos = new FileOutputStream(out); - GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(file)); - try { - StreamUtil.copy(gzis, fos); - } finally { - StreamUtil.close(fos); - StreamUtil.close(gzis); - } - - return out; - } - - // ---------------------------------------------------------------- zip - - /** - * Zips a file or a folder. - * @see #zip(java.io.File) - */ - public static File zip(final String file) throws IOException { - return zip(new File(file)); - } - - /** - * Zips a file or a folder. If adding a folder, all its content will be added. - */ - public static File zip(final File file) throws IOException { - String zipFile = file.getAbsolutePath() + ZIP_EXT; - - return ZipBuilder.createZipFile(zipFile) - .add(file).recursive().save() - .toZipFile(); - } - - // ---------------------------------------------------------------- unzip - - /** - * Lists zip content. - */ - public static List listZip(final File zipFile) throws IOException { - List entries = new ArrayList<>(); - - ZipFile zip = new ZipFile(zipFile); - Enumeration zipEntries = zip.entries(); - - while (zipEntries.hasMoreElements()) { - ZipEntry entry = (ZipEntry) zipEntries.nextElement(); - String entryName = entry.getName(); - - entries.add(entryName); - } - - return Collections.unmodifiableList(entries); - } - - /** - * Extracts zip file content to the target directory. - * @see #unzip(java.io.File, java.io.File, String...) - */ - public static void unzip(final String zipFile, final String destDir, final String... patterns) throws IOException { - unzip(new File(zipFile), new File(destDir), patterns); - } - - /** - * Extracts zip file to the target directory. If patterns are provided - * only matched paths are extracted. - * - * @param zipFile zip file - * @param destDir destination directory - * @param patterns optional wildcard patterns of files to extract, may be null - */ - public static void unzip(final File zipFile, final File destDir, final String... patterns) throws IOException { - ZipFile zip = new ZipFile(zipFile); - Enumeration zipEntries = zip.entries(); - - while (zipEntries.hasMoreElements()) { - ZipEntry entry = (ZipEntry) zipEntries.nextElement(); - String entryName = entry.getName(); - - if (patterns != null && patterns.length > 0) { - if (Wildcard.matchPathOne(entryName, patterns) == -1) { - continue; - } - } - - final File file = (destDir != null) ? new File(destDir, entryName) : new File(entryName); - - // check for Zip slip FLAW - final File rootDir = destDir != null ? destDir : new File("."); - if (!FileUtil.isAncestor(rootDir, file, true)) { - throw new IOException("Unzipping"); - } - - if (entry.isDirectory()) { - if (!file.mkdirs()) { - if (!file.isDirectory()) { - throw new IOException("Failed to create directory: " + file); - } - } - } else { - File parent = file.getParentFile(); - if (parent != null && !parent.exists()) { - if (!parent.mkdirs()) { - if (!file.isDirectory()) { - throw new IOException("Failed to create directory: " + parent); - } - } - } - - InputStream in = zip.getInputStream(entry); - OutputStream out = null; - try { - out = new FileOutputStream(file); - StreamUtil.copy(in, out); - } finally { - StreamUtil.close(out); - StreamUtil.close(in); - } - } - } - - close(zip); - } - - // ---------------------------------------------------------------- zip stream - - /** - * Adds single entry to ZIP output stream. - * - * @param zos zip output stream - * @param file file or folder to add - * @param path relative path of file entry; if null files name will be used instead - * @param comment optional comment - * @param recursive when set to true content of added folders will be added, too - */ - public static void addToZip(final ZipOutputStream zos, final File file, String path, final String comment, final boolean recursive) throws IOException { - if (!file.exists()) { - throw new FileNotFoundException(file.toString()); - } - - if (path == null) { - path = file.getName(); - } - - while (path.length() != 0 && path.charAt(0) == '/') { - path = path.substring(1); - } - - boolean isDir = file.isDirectory(); - - if (isDir) { - // add folder record - if (!StringUtil.endsWithChar(path, '/')) { - path += '/'; - } - } - - ZipEntry zipEntry = new ZipEntry(path); - zipEntry.setTime(file.lastModified()); - - if (comment != null) { - zipEntry.setComment(comment); - } - - if (isDir) { - zipEntry.setSize(0); - zipEntry.setCrc(0); - } - - zos.putNextEntry(zipEntry); - - if (!isDir) { - InputStream is = new FileInputStream(file); - try { - StreamUtil.copy(is, zos); - } finally { - StreamUtil.close(is); - } - } - - zos.closeEntry(); - - // continue adding - - if (recursive && file.isDirectory()) { - boolean noRelativePath = StringUtil.isEmpty(path); - - final File[] children = file.listFiles(); - - if (children != null && children.length != 0) { - for (File child : children) { - String childRelativePath = (noRelativePath ? StringPool.EMPTY : path) + child.getName(); - addToZip(zos, child, childRelativePath, comment, recursive); - } - } - } - - } - - /** - * Adds byte content into the zip as a file. - */ - public static void addToZip(final ZipOutputStream zos, final byte[] content, String path, final String comment) throws IOException { - while (path.length() != 0 && path.charAt(0) == '/') { - path = path.substring(1); - } - - if (StringUtil.endsWithChar(path, '/')) { - path = path.substring(0, path.length() - 1); - } - - ZipEntry zipEntry = new ZipEntry(path); - zipEntry.setTime(System.currentTimeMillis()); - - if (comment != null) { - zipEntry.setComment(comment); - } - - zos.putNextEntry(zipEntry); - - InputStream is = new ByteArrayInputStream(content); - try { - StreamUtil.copy(is, zos); - } finally { - StreamUtil.close(is); - } - - zos.closeEntry(); - } - - public static void addFolderToZip(final ZipOutputStream zos, String path, final String comment) throws IOException { - while (path.length() != 0 && path.charAt(0) == '/') { - path = path.substring(1); - } - - // add folder record - if (!StringUtil.endsWithChar(path, '/')) { - path += '/'; - } - - ZipEntry zipEntry = new ZipEntry(path); - zipEntry.setTime(System.currentTimeMillis()); - - if (comment != null) { - zipEntry.setComment(comment); - } - - zipEntry.setSize(0); - zipEntry.setCrc(0); - - zos.putNextEntry(zipEntry); - zos.closeEntry(); - } - - - // ---------------------------------------------------------------- close - - /** - * Closes zip file safely. - */ - public static void close(final ZipFile zipFile) { - if (zipFile != null) { - try { - zipFile.close(); - } catch (IOException ioex) { - // ignore - } - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/ClassScanner.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/ClassScanner.java deleted file mode 100644 index 3c8df19ea..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/ClassScanner.java +++ /dev/null @@ -1,639 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import com.fr.third.jodd.inex.InExRules; -import com.fr.third.jodd.io.FileNameUtil; -import com.fr.third.jodd.io.FileUtil; -import com.fr.third.jodd.io.StreamUtil; -import com.fr.third.jodd.io.ZipUtil; -import com.fr.third.jodd.util.ArraysUtil; -import com.fr.third.jodd.util.ClassLoaderUtil; -import com.fr.third.jodd.util.Consumers; -import com.fr.third.jodd.util.StringUtil; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.Consumer; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import static com.fr.third.jodd.inex.InExRuleMatcher.WILDCARD_PATH_RULE_MATCHER; -import static com.fr.third.jodd.inex.InExRuleMatcher.WILDCARD_RULE_MATCHER; - -/** - * Convenient class path scanner. - */ -public class ClassScanner { - - private static final String CLASS_FILE_EXT = ".class"; - private static final String JAR_FILE_EXT = ".jar"; - - /** - * Create new class scanner. - */ - public static ClassScanner create() { - return new ClassScanner(); - } - - public ClassScanner() { - this.rulesJars = new InExRules<>(WILDCARD_PATH_RULE_MATCHER); - this.rulesEntries = new InExRules<>(WILDCARD_RULE_MATCHER); - - excludeJars(SYSTEM_JARS); - } - - // ---------------------------------------------------------------- excluded jars - - /** - * Array of system jars that are excluded from the search. - * By default, these paths are common for linux, windows and mac. - */ - protected static final String[] SYSTEM_JARS = new String[] { - "**/jre/lib/*.jar", - "**/jre/lib/ext/*.jar", - "**/Java/Extensions/*.jar", - "**/Classes/*.jar" - }; - - protected static final String[] COMMONLY_EXCLUDED_JARS = new String[] { - "**/tomcat*", - "**/jetty*", - "**/javafx*", - "**/junit*", - "**/javax*", - "**/org.eclipse.*", - "**/ant*", - "**/idea_rt.jar", - }; - - protected final InExRules rulesJars; - - /** - * Specify excluded jars. - */ - public ClassScanner excludeJars(final String... excludedJars) { - for (final String excludedJar : excludedJars) { - rulesJars.exclude(excludedJar); - } - return this; - } - - /** - * Exclude some commonly unused jars. - */ - public ClassScanner excludeCommonJars() { - return excludeJars(COMMONLY_EXCLUDED_JARS); - } - - /** - * Specify included jars. - */ - public ClassScanner includeJars(final String... includedJars) { - for (final String includedJar : includedJars) { - rulesJars.include(includedJar); - } - return this; - } - - /** - * Sets white/black list mode for jars. - */ - public ClassScanner includeAllJars(final boolean blacklist) { - if (blacklist) { - rulesJars.blacklist(); - } else { - rulesJars.whitelist(); - } - return this; - } - - /** - * Sets white/black list mode for jars. - */ - public ClassScanner excludeAllJars(final boolean whitelist) { - if (whitelist) { - rulesJars.whitelist(); - } else { - rulesJars.blacklist(); - } - return this; - } - - // ---------------------------------------------------------------- included entries - - protected static final String[] COMMONLY_EXCLUDED_ENTRIES = new String[] { - "java.*", - "ch.qos.logback.*", - "sun.*", - "com.sun.*", - "org.eclipse.*", - }; - - protected final InExRules rulesEntries; - protected boolean detectEntriesMode = false; - - /** - * Sets included set of names that will be considered during configuration. - * @see InExRules - */ - public ClassScanner includeEntries(final String... includedEntries) { - for (final String includedEntry : includedEntries) { - rulesEntries.include(includedEntry); - } - return this; - } - - /** - * Sets white/black list mode for entries. - */ - public ClassScanner includeAllEntries(final boolean blacklist) { - if (blacklist) { - rulesEntries.blacklist(); - } else { - rulesEntries.whitelist(); - } - return this; - } - /** - * Sets white/black list mode for entries. - */ - public ClassScanner excludeAllEntries(final boolean whitelist) { - if (whitelist) { - rulesEntries.whitelist(); - } else { - rulesEntries.blacklist(); - } - return this; - } - - /** - * Sets excluded names that narrows included set of packages. - * @see InExRules - */ - public ClassScanner excludeEntries(final String... excludedEntries) { - for (final String excludedEntry : excludedEntries) { - rulesEntries.exclude(excludedEntry); - } - return this; - } - - /** - * Excludes some commonly skipped packages. - */ - public ClassScanner excludeCommonEntries() { - return excludeEntries(COMMONLY_EXCLUDED_ENTRIES); - } - - public ClassScanner detectEntriesMode(final boolean detectMode) { - this.detectEntriesMode = detectMode; - return this; - } - - // ---------------------------------------------------------------- implementation - - /** - * If set to true all files will be scanned and not only classes. - */ - protected boolean includeResources; - /** - * If set to true exceptions for entry scans are ignored. - */ - protected boolean ignoreException; - - public ClassScanner includeResources(final boolean includeResources) { - this.includeResources = includeResources; - return this; - } - - /** - * Sets if exceptions during scanning process should be ignored or not. - */ - public ClassScanner ignoreException(final boolean ignoreException) { - this.ignoreException = ignoreException; - return this; - } - - // ---------------------------------------------------------------- scan - - - /** - * Returns true if some JAR file has to be accepted. - */ - protected boolean acceptJar(final File jarFile) { - String path = jarFile.getAbsolutePath(); - path = FileNameUtil.separatorsToUnix(path); - - return rulesJars.match(path); - } - - // ---------------------------------------------------------------- internal - - /** - * Scans classes inside single JAR archive. Archive is scanned as a zip file. - * @see #onEntry(ClassPathEntry) - */ - protected void scanJarFile(final File file) { - final ZipFile zipFile; - try { - zipFile = new ZipFile(file); - } catch (final IOException ioex) { - if (!ignoreException) { - throw new FindFileException("Invalid zip: " + file.getName(), ioex); - } - return; - } - final Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - final ZipEntry zipEntry = (ZipEntry) entries.nextElement(); - final String zipEntryName = zipEntry.getName(); - try { - if (StringUtil.endsWithIgnoreCase(zipEntryName, CLASS_FILE_EXT)) { - final String entryName = prepareEntryName(zipEntryName, true); - final ClassPathEntry classPathEntry = new ClassPathEntry(entryName, zipFile, zipEntry); - try { - scanEntry(classPathEntry); - } finally { - classPathEntry.closeInputStream(); - } - } else if (includeResources) { - final String entryName = prepareEntryName(zipEntryName, false); - final ClassPathEntry classPathEntry = new ClassPathEntry(entryName, zipFile, zipEntry); - try { - scanEntry(classPathEntry); - } finally { - classPathEntry.closeInputStream(); - } - } - } catch (final RuntimeException rex) { - if (!ignoreException) { - ZipUtil.close(zipFile); - throw rex; - } - } - } - ZipUtil.close(zipFile); - } - - /** - * Scans single classpath directory. - * @see #onEntry(ClassPathEntry) - */ - protected void scanClassPath(final File root) { - String rootPath = root.getAbsolutePath(); - if (!rootPath.endsWith(File.separator)) { - rootPath += File.separatorChar; - } - - final FindFile ff = FindFile.create().includeDirs(false).recursive(true).searchPath(rootPath); - File file; - while ((file = ff.nextFile()) != null) { - final String filePath = file.getAbsolutePath(); - try { - if (StringUtil.endsWithIgnoreCase(filePath, CLASS_FILE_EXT)) { - scanClassFile(filePath, rootPath, file, true); - } else if (includeResources) { - scanClassFile(filePath, rootPath, file, false); - } - } catch (final RuntimeException rex) { - if (!ignoreException) { - throw rex; - } - } - } - } - - protected void scanClassFile(final String filePath, final String rootPath, final File file, final boolean isClass) { - if (StringUtil.startsWithIgnoreCase(filePath, rootPath)) { - final String entryName = prepareEntryName(filePath.substring(rootPath.length()), isClass); - final ClassPathEntry classPathEntry = new ClassPathEntry(entryName, file); - try { - scanEntry(classPathEntry); - } finally { - classPathEntry.closeInputStream(); - } - } - } - - /** - * Prepares resource and class names. For classes, it strips '.class' from the end and converts - * all (back)slashes to dots. For resources, it replaces all backslashes to slashes. - */ - protected String prepareEntryName(final String name, final boolean isClass) { - String entryName = name; - if (isClass) { - entryName = name.substring(0, name.length() - 6); // 6 == ".class".length() - entryName = StringUtil.replaceChar(entryName, '/', '.'); - entryName = StringUtil.replaceChar(entryName, '\\', '.'); - } else { - entryName = '/' + StringUtil.replaceChar(entryName, '\\', '/'); - } - return entryName; - } - - /** - * Returns true if some entry name has to be accepted. - * @see #prepareEntryName(String, boolean) - * @see #scanEntry(ClassPathEntry) - */ - protected boolean acceptEntry(final String entryName) { - return rulesEntries.match(entryName); - } - - /** - * If entry name is {@link #acceptEntry(String) accepted} invokes {@link #onEntry(ClassPathEntry)} a callback}. - */ - protected void scanEntry(final ClassPathEntry classPathEntry) { - if (!acceptEntry(classPathEntry.name())) { - return; - } - try { - onEntry(classPathEntry); - } catch (final Exception ex) { - throw new FindFileException("Scan entry error: " + classPathEntry, ex); - } - } - - - // ---------------------------------------------------------------- callback - - private final Consumers entryDataConsumers = Consumers.empty(); - - /** - * Registers a {@link ClassPathEntry class path entry} consumer. - * It will be called on each loaded entry. - */ - public ClassScanner registerEntryConsumer(final Consumer entryDataConsumer) { - entryDataConsumers.add(entryDataConsumer); - return this; - } - - /** - * Called during classpath scanning when class or resource is found. - *

    - *
  • Class name is java-alike class name (pk1.pk2.class) that may be immediately used - * for dynamic loading.
  • - *
  • Resource name starts with '\' and represents either jar path (\pk1/pk2/res) or relative file path (\pk1\pk2\res).
  • - *
- * - * InputStream is provided by InputStreamProvider and opened lazy. - * Once opened, input stream doesn't have to be closed - this is done by this class anyway. - */ - protected void onEntry(final ClassPathEntry classPathEntry) { - entryDataConsumers.accept(classPathEntry); - } - - // ---------------------------------------------------------------- utilities - - /** - * Returns type signature bytes used for searching in class file. - */ - public static byte[] bytecodeSignatureOfType(final Class type) { - final String name = 'L' + type.getName().replace('.', '/') + ';'; - return name.getBytes(); - } - - // ---------------------------------------------------------------- provider - - /** - * Provides input stream on demand. Input stream is not open until get(). - */ - public class ClassPathEntry { - - private final File file; - private final ZipFile zipFile; - private final ZipEntry zipEntry; - private final String name; - - ClassPathEntry(final String name, final ZipFile zipFile, final ZipEntry zipEntry) { - this.name = name; - this.zipFile = zipFile; - this.zipEntry = zipEntry; - this.file = null; - this.inputStream = null; - } - ClassPathEntry(final String name, final File file) { - this.name = name; - this.file = file; - this.zipEntry = null; - this.zipFile = null; - this.inputStream = null; - } - - private InputStream inputStream; - private byte[] inputStreamBytes; - - /** - * Returns entry name. - */ - public String name() { - return name; - } - - /** - * Returns true if archive. - */ - public boolean isArchive() { - return zipFile != null; - } - - /** - * Returns archive name or null if entry is not inside archived file. - */ - public String archiveName() { - if (zipFile != null) { - return zipFile.getName(); - } - return null; - } - - /** - * Returns true if class contains {@link #bytecodeSignatureOfType(Class) type signature}. - * It searches the class content for bytecode signature. This is the fastest way of finding if come - * class uses some type. Please note that if signature exists it still doesn't means that class uses - * it in expected way, therefore, class should be loaded to complete the scan. - */ - public boolean isTypeSignatureInUse(final byte[] bytes) { - try { - final byte[] data = readBytes(); - final int index = ArraysUtil.indexOf(data, bytes); - return index != -1; - } catch (final IOException ioex) { - throw new FindFileException("Read error", ioex); - } - } - - /** - * Reads stream bytes. Since stream can be read only once, the byte content - * is cached. - */ - public byte[] readBytes() throws IOException { - openInputStream(); - - if (inputStreamBytes == null) { - inputStreamBytes = StreamUtil.readBytes(inputStream); - } - return inputStreamBytes; - } - - /** - * Opens zip entry or plain file and returns its input stream. - */ - public InputStream openInputStream() { - if (inputStream != null) { - return inputStream; - } - if (zipFile != null && zipEntry != null) { - try { - inputStream = zipFile.getInputStream(zipEntry); - return inputStream; - } catch (final IOException ioex) { - throw new FindFileException("Input stream error: '" + zipFile.getName() - + "', entry: '" + zipEntry.getName() + "'." , ioex); - } - } - if (file != null) { - try { - inputStream = new FileInputStream(file); - return inputStream; - } catch (final FileNotFoundException fnfex) { - throw new FindFileException("Unable to open: " + file.getAbsolutePath(), fnfex); - } - } - throw new FindFileException("Unable to open stream: " + name()); - } - - /** - * Closes input stream if opened. - */ - public void closeInputStream() { - if (inputStream == null) { - return; - } - StreamUtil.close(inputStream); - inputStream = null; - inputStreamBytes = null; - } - - /** - * Loads class by its name. If {@link #ignoreException} is set, - * no exception is thrown, but null is returned. - */ - public Class loadClass() throws ClassNotFoundException { - try { - return ClassLoaderUtil.loadClass(name); - } catch (final ClassNotFoundException | Error cnfex) { - if (ignoreException) { - return null; - } - throw cnfex; - } - } - - @Override - public String toString() { - return "ClassPathEntry{" + name + '\'' +'}'; - } - } - - // ---------------------------------------------------------------- public scanning - - private final Set filesToScan = new LinkedHashSet<>(); - - /** - * Scans URLs. If (#ignoreExceptions} is set, exceptions - * per one URL will be ignored and loops continues. - */ - public ClassScanner scan(final URL... urls) { - for (final URL url : urls) { - final File file = FileUtil.toContainerFile(url); - if (file == null) { - if (!ignoreException) { - throw new FindFileException("URL is not a valid file: " + url); - } - } - else { - filesToScan.add(file); - } - } - return this; - } - - /** - * Scans {@link com.fr.third.jodd.util.ClassLoaderUtil#getDefaultClasspath() default class path}. - */ - public ClassScanner scanDefaultClasspath() { - return scan(ClassLoaderUtil.getDefaultClasspath()); - } - - /** - * Scans provided paths. - */ - public ClassScanner scan(final File... paths) { - filesToScan.addAll(Arrays.asList(paths)); - return this; - } - - /** - * Scans provided paths. - */ - public ClassScanner scan(final String... paths) { - for (final String path : paths) { - filesToScan.add(new File(path)); - } - return this; - } - - /** - * Starts with the scanner. - */ - public void start() { - if (detectEntriesMode) { - rulesEntries.detectMode(); - } - - filesToScan.forEach(file -> { - final String path = file.getAbsolutePath(); - if (StringUtil.endsWithIgnoreCase(path, JAR_FILE_EXT)) { - if (!acceptJar(file)) { - return; - } - scanJarFile(file); - } else if (file.isDirectory()) { - scanClassPath(file); - } - }); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileExtensionComparator.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileExtensionComparator.java deleted file mode 100644 index 195d25ff4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileExtensionComparator.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import com.fr.third.jodd.io.FileNameUtil; - -import java.io.File; -import java.io.Serializable; -import java.util.Comparator; - -public class FileExtensionComparator implements Comparator, Serializable { - protected final int order; - - public FileExtensionComparator(final boolean ascending) { - if (ascending) { - order = 1; - } else { - order = -1; - } - } - - @Override - public int compare(final File file1, final File file2) { - String ext1 = FileNameUtil.getExtension(file1.getName()); - String ext2 = FileNameUtil.getExtension(file2.getName()); - long diff = ext1.compareToIgnoreCase(ext2); - if (diff == 0) { - return 0; - } - if (diff > 0) { - return order; - } - return -order; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileLastModifiedTimeComparator.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileLastModifiedTimeComparator.java deleted file mode 100644 index 4f610f614..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileLastModifiedTimeComparator.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import java.io.File; -import java.io.Serializable; -import java.util.Comparator; - -public class FileLastModifiedTimeComparator implements Comparator, Serializable { - protected final int order; - - public FileLastModifiedTimeComparator(final boolean ascending) { - if (ascending) { - order = 1; - } else { - order = -1; - } - } - - @Override - public int compare(final File file1, final File file2) { - long diff = file1.lastModified() - file2.lastModified(); - if (diff == 0) { - return 0; - } - if (diff > 0) { - return order; - } - return -order; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileNameComparator.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileNameComparator.java deleted file mode 100644 index c980f71d5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FileNameComparator.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import com.fr.third.jodd.util.NaturalOrderComparator; - -import java.io.File; -import java.io.Serializable; -import java.util.Comparator; - -public class FileNameComparator implements Comparator, Serializable { - protected final int order; - protected NaturalOrderComparator naturalOrderComparator = new NaturalOrderComparator<>(true, true, true); - - public FileNameComparator(final boolean ascending) { - if (ascending) { - order = 1; - } else { - order = -1; - } - } - - @Override - public int compare(final File file1, final File file2) { - int result = naturalOrderComparator.compare(file1.getName(), file2.getName()); - if (result == 0) { - return result; - } - if (result > 0) { - return order; - } - return -order; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FindFile.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FindFile.java deleted file mode 100644 index 2a9a1c8e4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FindFile.java +++ /dev/null @@ -1,795 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import com.fr.third.jodd.inex.InExRules; -import com.fr.third.jodd.io.FileNameUtil; -import com.fr.third.jodd.io.FileUtil; -import com.fr.third.jodd.util.Consumers; -import com.fr.third.jodd.util.MultiComparator; -import com.fr.third.jodd.util.StringUtil; - -import java.io.File; -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.function.Consumer; - -/** - * Generic iterative file finder. Searches all files on specified search path. - * By default, it starts in whitelist mode, where everything is excluded. - * To search, you need to explicitly set include patterns. If no pattern is - * set, then the search starts in blacklist mode, where everything is included (search all). - * - * @see WildcardFindFile - * @see RegExpFindFile - * @see InExRules - */ -public class FindFile implements Iterable { - - public static WildcardFindFile createWildcardFF() { - return new WildcardFindFile(); - } - public static RegExpFindFile createRegExpFF() { - return new RegExpFindFile(); - } - public static FindFile create() { - return new FindFile(); - } - - /** - * Match type. - * @see FindFile#getMatchingFilePath(java.io.File) - * @see FindFile#acceptFile(java.io.File) - */ - public enum Match { - /** - * Full, absolute path. - */ - FULL_PATH, - /** - * Relative path from current root. - */ - RELATIVE_PATH, - /** - * Just file name. - */ - NAME - } - - // ---------------------------------------------------------------- flags - - protected boolean recursive; - protected boolean includeDirs = true; - protected boolean includeFiles = true; - protected boolean walking = true; - protected Match matchType = Match.FULL_PATH; - - /** - * Activates recursive search. - */ - public FindFile recursive(final boolean recursive) { - this.recursive = recursive; - return this; - } - - /** - * Include directories in search. - */ - public FindFile includeDirs(final boolean includeDirs) { - this.includeDirs = includeDirs; - return this; - } - - /** - * Include files in search. - */ - public FindFile includeFiles(final boolean includeFiles) { - this.includeFiles = includeFiles; - return this; - } - - /** - * Sets the walking recursive mode. When walking mode is on (by default), - * folders are walked immediately. Although natural, for large - * set of files, this is not memory-optimal approach, since many - * files are held in memory, when going deeper. - *

- * When walking mode is turned off, folders are processed once - * all files are processed, one after the other. The order is - * not natural, but memory consumption is optimal. - * @see #recursive(boolean) - */ - public FindFile walking(final boolean walking) { - this.walking = walking; - return this; - } - - /** - * Set {@link Match matching type}. - */ - public FindFile matchType(final Match match) { - this.matchType = match; - return this; - } - - public FindFile matchOnlyFileName() { - this.matchType = Match.NAME; - return this; - } - public FindFile matchFullPath() { - this.matchType = Match.FULL_PATH; - return this; - } - public FindFile matchRelativePath() { - this.matchType = Match.RELATIVE_PATH; - return this; - } - - // ---------------------------------------------------------------- consumer - - private Consumers consumers; - - /** - * Registers file consumer - */ - public FindFile onFile(final Consumer fileConsumer) { - if (consumers == null) { - consumers = Consumers.of(fileConsumer); - } - else { - consumers.add(fileConsumer); - } - return this; - } - - // ---------------------------------------------------------------- search path - - /** - * Specifies single search path. - */ - public FindFile searchPath(final File searchPath) { - addPath(searchPath); - return this; - } - - /** - * Specifies a set of search paths. - */ - public FindFile searchPath(final File... searchPath) { - for (final File file : searchPath) { - addPath(file); - } - return this; - } - - /** - * Specifies the search path. If provided path contains - * {@link File#pathSeparator} than string will be tokenized - * and each part will be added separately as a search path. - */ - public FindFile searchPath(final String searchPath) { - if (searchPath.indexOf(File.pathSeparatorChar) != -1) { - final String[] paths = StringUtil.split(searchPath, File.pathSeparator); - for (final String path : paths) { - addPath(new File(path)); - } - } else { - addPath(new File(searchPath)); - } - return this; - } - - /** - * Specifies search paths. - * @see #searchPath(String) - */ - public FindFile searchPaths(final String... searchPaths) { - for (final String searchPath : searchPaths) { - searchPath(searchPath); - } - return this; - } - - /** - * Specifies the search path. Throws an exception if URI is invalid. - */ - public FindFile searchPath(final URI searchPath) { - final File file; - try { - file = new File(searchPath); - } catch (final Exception ex) { - throw new FindFileException("URI error: " + searchPath, ex); - } - - addPath(file); - - return this; - } - - /** - * Specifies the search path. - */ - public FindFile searchPaths(final URI... searchPath) { - for (final URI uri : searchPath) { - searchPath(uri); - } - return this; - } - - /** - * Specifies the search path. Throws an exception if URL is invalid. - */ - public FindFile searchPath(final URL searchPath) { - final File file = FileUtil.toContainerFile(searchPath); - if (file == null) { - throw new FindFileException("URL error: " + searchPath); - } - addPath(file); - return this; - } - - /** - * Specifies the search path. - */ - public FindFile searchPaths(final URL... searchPath) { - for (final URL url : searchPath) { - searchPath(url); - } - return this; - } - - // ---------------------------------------------------------------- files iterator - - /** - * Files iterator simply walks over files array. - * Ignores null items. Consumed files are immediately - * removed from the array. - */ - protected class FilesIterator { - protected final File folder; - protected final String[] fileNames; - protected final File[] files; - - public FilesIterator(final File folder) { - this.folder = folder; - if (sortComparators != null) { - this.files = folder.listFiles(); - - if (this.files != null) { - Arrays.sort(this.files, new MultiComparator<>(sortComparators)); - } - - this.fileNames = null; - } else { - this.files = null; - this.fileNames = folder.list(); - } - } - - public FilesIterator(final String[] fileNames) { - this.folder = null; - if (sortComparators != null) { - final int fileNamesLength = fileNames.length; - this.files = new File[fileNamesLength]; - - for (int i = 0; i < fileNamesLength; i++) { - final String fileName = fileNames[i]; - if (fileName != null) { - this.files[i] = new File(fileName); - } - - } - this.fileNames = null; - } else { - this.files = null; - this.fileNames = fileNames; - } - } - - protected int index; - - /** - * Returns next file or null - * when no next file is available. - */ - public File next() { - if (files != null) { - return nextFile(); - } else if (fileNames != null) { - return nextFileName(); - } else { - return null; - } - } - - protected File nextFileName() { - while (index < fileNames.length) { - final String fileName = fileNames[index]; - - if (fileName == null) { - index++; - continue; - } - fileNames[index] = null; - index++; - - final File file; - if (folder == null) { - file = new File(fileName); - } else { - file = new File(folder, fileName); - } - - if (file.isFile()) { - if (!includeFiles) { - continue; - } - if (!acceptFile(file)) { - continue; - } - } - - return file; - } - return null; - } - - protected File nextFile() { - while (index < files.length) { - final File file = files[index]; - - if (file == null) { - index++; - continue; - } - files[index] = null; - index++; - - if (file.isFile()) { - if (!includeFiles) { - continue; - } - if (!acceptFile(file)) { - continue; - } - } - - return file; - } - return null; - } - } - - // ---------------------------------------------------------------- matching - - protected final InExRules rules = createRulesEngine(); - - /** - * Creates rule engine. - */ - protected InExRules createRulesEngine() { - return new InExRules<>(); - } - - /** - * Defines include pattern. - */ - public FindFile include(final String pattern) { - rules.include(pattern); - return this; - } - - /** - * Defines include patterns. - */ - public FindFile include(final String... patterns) { - for (final String pattern : patterns) { - rules.include(pattern); - } - return this; - } - - /** - * Enables whitelist mode. - */ - public FindFile excludeAll() { - rules.whitelist(); - return this; - } - - /** - * Enables blacklist mode. - */ - public FindFile includeAll() { - rules.blacklist(); - return this; - } - - /** - * Defines exclude pattern. - */ - public FindFile exclude(final String pattern) { - rules.exclude(pattern); - return this; - } - - /** - * Defines exclude patterns. - */ - public FindFile exclude(final String... patterns) { - for (final String pattern : patterns) { - rules.exclude(pattern); - } - return this; - } - - /** - * Determine if file is accepted, based on include and exclude - * rules. Called on each file entry (file or directory) and - * returns true if file passes search criteria. - * File is matched using {@link #getMatchingFilePath(java.io.File) matching file path}. - * @see InExRules - */ - protected boolean acceptFile(final File file) { - final String matchingFilePath = getMatchingFilePath(file); - - if (rules.match(matchingFilePath)) { - if (consumers != null) { - consumers.accept(file); - } - return true; - } - return false; - } - - /** - * Resolves file path depending on {@link Match matching type} - * Returned path is formatted in unix style. - */ - protected String getMatchingFilePath(final File file) { - - String path = null; - - switch (matchType) { - case FULL_PATH: - path = file.getAbsolutePath(); - break; - case RELATIVE_PATH: - path = file.getAbsolutePath(); - path = path.substring(rootPath.length()); - break; - case NAME: - path = file.getName(); - } - - path = FileNameUtil.separatorsToUnix(path); - - return path; - } - - // ---------------------------------------------------------------- next file - - protected LinkedList pathList; - protected LinkedList pathListOriginal; - protected LinkedList todoFolders; - protected LinkedList todoFiles; - - protected File lastFile; - protected File rootFile; - protected String rootPath; - - /** - * Returns last founded file. - * Returns null at the very beginning. - */ - public File lastFile() { - return lastFile; - } - - /** - * Adds existing search path to the file list. - * Non existing files are ignored. - * If path is a folder, it will be scanned for all files. - */ - protected void addPath(final File path) { - if (!path.exists()) { - return; - } - if (pathList == null) { - pathList = new LinkedList<>(); - } - - pathList.add(path); - } - - /** - * Reset the search so it can be run again with very - * same parameters (and sorting options). - */ - public void reset() { - pathList = pathListOriginal; - pathListOriginal = null; - todoFiles = null; - lastFile = null; - rules.reset(); - } - - /** - * Finds the next file. Returns founded file that matches search configuration - * or null if no more files can be found. - */ - public File nextFile() { - if (todoFiles == null) { - init(); - } - - while (true) { - - // iterate files - - if (!todoFiles.isEmpty()) { - final FilesIterator filesIterator = todoFiles.getLast(); - final File nextFile = filesIterator.next(); - - if (nextFile == null) { - todoFiles.removeLast(); - continue; - } - - if (nextFile.isDirectory()) { - if (!walking) { - todoFolders.add(nextFile); - continue; - } - // walking - if (recursive) { - todoFiles.add(new FilesIterator(nextFile)); - } - if (includeDirs) { - if (acceptFile(nextFile)) { - lastFile = nextFile; - return nextFile; - } - } - continue; - } - - lastFile = nextFile; - return nextFile; - } - - // process folders - - final File folder; - boolean initialDir = false; - - if (todoFolders.isEmpty()) { - if (pathList.isEmpty()) { - // the end - return null; - } - - folder = pathList.removeFirst(); - - rootFile = folder; - rootPath = rootFile.getAbsolutePath(); - - initialDir = true; - } else { - folder = todoFolders.removeFirst(); - } - - if ((initialDir) || (recursive)) { - todoFiles.add(new FilesIterator(folder)); - } - - if ((!initialDir) && (includeDirs)) { - if (acceptFile(folder)) { - lastFile = folder; - return folder; - } - } - } - } - - /** - * Finds all files and returns list of founded files. - */ - public List findAll() { - final List allFiles = new ArrayList<>(); - File file; - while ((file = nextFile()) != null) { - allFiles.add(file); - } - return allFiles; - } - - /** - * Initializes file walking. - * Separates input files and folders. - */ - protected void init() { - rules.detectMode(); - - todoFiles = new LinkedList<>(); - todoFolders = new LinkedList<>(); - - if (pathList == null) { - pathList = new LinkedList<>(); - return; - } - - if (pathListOriginal == null) { - pathListOriginal = (LinkedList) pathList.clone(); - } - final String[] files = new String[pathList.size()]; - - int index = 0; - final Iterator iterator = pathList.iterator(); - while (iterator.hasNext()) { - final File file = iterator.next(); - - if (file.isFile()) { - files[index++] = file.getAbsolutePath(); - iterator.remove(); - } - } - - if (index != 0) { - final FilesIterator filesIterator = new FilesIterator(files); - todoFiles.add(filesIterator); - } - } - - /** - * Returns file walking iterator. - */ - @Override - public Iterator iterator() { - - return new Iterator() { - private File nextFile; - - @Override - public boolean hasNext() { - nextFile = nextFile(); - return nextFile != null; - } - - @Override - public File next() { - if (nextFile == null) { - throw new NoSuchElementException(); - } - return nextFile; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - // ---------------------------------------------------------------- sort - - protected List> sortComparators; - - protected void addComparator(final Comparator comparator) { - if (sortComparators == null) { - sortComparators = new ArrayList<>(4); - } - sortComparators.add(comparator); - } - - /** - * Removes ALL sorting options. - */ - public FindFile sortNone() { - sortComparators = null; - return this; - } - - /** - * Adds generic sorting. - */ - public FindFile sortWith(final Comparator fileComparator) { - addComparator(fileComparator); - return this; - } - - /** - * Puts folders before files. - */ - public FindFile sortFoldersFirst() { - addComparator(new FolderFirstComparator(true)); - return this; - } - - /** - * Puts files before folders. - */ - public FindFile sortFoldersLast() { - addComparator(new FolderFirstComparator(false)); - return this; - } - - /** - * Sorts files by file name, using natural sort. - */ - public FindFile sortByName() { - addComparator(new FileNameComparator(true)); - return this; - } - - /** - * Sorts files by file names descending, using natural sort. - */ - public FindFile sortByNameDesc() { - addComparator(new FileNameComparator(false)); - return this; - } - - /** - * Sorts files by file extension. - */ - public FindFile sortByExtension() { - addComparator(new FileExtensionComparator(true)); - return this; - } - - /** - * Sorts files by file extension descending. - */ - public FindFile sortByExtensionDesc() { - addComparator(new FileExtensionComparator(false)); - return this; - } - - /** - * Sorts files by last modified time. - */ - public FindFile sortByTime() { - addComparator(new FileLastModifiedTimeComparator(true)); - return this; - } - - /** - * Sorts files by last modified time descending. - */ - public FindFile sortByTimeDesc() { - addComparator(new FileLastModifiedTimeComparator(false)); - return this; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FindFileException.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FindFileException.java deleted file mode 100644 index b5a142141..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FindFileException.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import com.fr.third.jodd.exception.UncheckedException; - -/** - * Exception during finding files or classes. - */ -public class FindFileException extends UncheckedException { - - public FindFileException(final String message) { - super(message); - } - - public FindFileException(final String message, final Throwable t) { - super(message, t); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FolderFirstComparator.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FolderFirstComparator.java deleted file mode 100644 index 4f1ec062f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/FolderFirstComparator.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import java.io.File; -import java.io.Serializable; -import java.util.Comparator; - -public class FolderFirstComparator implements Comparator, Serializable { - protected final int order; - - public FolderFirstComparator(final boolean foldersFirst) { - if (foldersFirst) { - order = 1; - } else { - order = -1; - } - } - - @Override - public int compare(final File file1, final File file2) { - if (file1.isFile() && file2.isDirectory()) { - return order; - } - if (file1.isDirectory() && file2.isFile()) { - return -order; - } - return 0; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/RegExpFindFile.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/RegExpFindFile.java deleted file mode 100644 index b1ff9f5a9..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/RegExpFindFile.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import com.fr.third.jodd.inex.InExRules; - -import java.util.regex.Pattern; - -/** - * Simple {@link FindFile} that matches file names with regular expression pattern. - * @see com.fr.third.jodd.io.findfile.WildcardFindFile - */ -public class RegExpFindFile extends FindFile { - - public static RegExpFindFile create() { - return new RegExpFindFile(); - } - - @Override - protected InExRules createRulesEngine() { - return new InExRules() { - - @Override - protected Pattern makeRule(final String rule) { - return Pattern.compile(rule); - } - - @Override - public boolean accept(final String path, final Pattern pattern, final boolean include) { - return pattern.matcher(path).matches(); - } - }; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/WildcardFindFile.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/WildcardFindFile.java deleted file mode 100644 index 6c0f83cc4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/WildcardFindFile.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.findfile; - -import com.fr.third.jodd.inex.InExRuleMatcher; -import com.fr.third.jodd.inex.InExRules; - -/** - * {@link FindFile} that matches file names using *, ? - * and ** wildcards. - * - * @see com.fr.third.jodd.io.findfile.RegExpFindFile - */ -public class WildcardFindFile extends FindFile { - - public static WildcardFindFile create() { - return new WildcardFindFile(); - } - - @Override - protected InExRules createRulesEngine() { - return new InExRules<>(InExRuleMatcher.WILDCARD_PATH_RULE_MATCHER); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/package-info.java deleted file mode 100644 index f03ab7175..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/findfile/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Nice utilities for easier files and classes finding. - */ -package com.fr.third.jodd.io.findfile; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/package-info.java deleted file mode 100644 index 492a71fa9..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various IO utilities (files, streams, http...). - */ -package com.fr.third.jodd.io; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUpload.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUpload.java deleted file mode 100644 index 34050cee2..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUpload.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Encapsulates base for uploaded file. Its instance may be - * either valid, when it represent an uploaded file, or invalid - * when uploaded file doesn't exist or there was a problem with it. - */ -public abstract class FileUpload { - - protected final MultipartRequestInputStream input; - protected final int maxFileSize; - protected final FileUploadHeader header; - - protected FileUpload(final MultipartRequestInputStream input, final int maxFileSize) { - this.input = input; - this.header = input.lastHeader; - this.maxFileSize = maxFileSize; - } - - // ---------------------------------------------------------------- header - - /** - * Returns {@link FileUploadHeader} of uploaded file. - */ - public FileUploadHeader getHeader() { - return header; - } - - // ---------------------------------------------------------------- data - - /** - * Returns all bytes of uploaded file. - */ - public abstract byte[] getFileContent() throws IOException; - - /** - * Returns input stream of uploaded file. - */ - public abstract InputStream getFileInputStream() throws IOException; - - // ---------------------------------------------------------------- size and validity - - protected boolean valid; - - protected int size = -1; - - protected boolean fileTooBig; - - /** - * Returns the file upload size or -1 if file was not uploaded. - */ - public int getSize() { - return size; - } - - /** - * Returns true if file was uploaded. - */ - public boolean isUploaded() { - return size != -1; - } - - /** - * Returns true if upload process went correctly. - * This still does not mean that file is uploaded, e.g. when file - * was not specified on the form. - */ - public boolean isValid() { - return valid; - } - - /** - * Returns max file size or -1 if there is no max file size. - */ - public int getMaxFileSize() { - return maxFileSize; - } - - /** - * Returns true if file is too big. File will be marked as invalid. - */ - public boolean isFileTooBig() { - return fileTooBig; - } - - // ---------------------------------------------------------------- status - - /** - * Returns true if uploaded file content is stored in memory. - */ - public abstract boolean isInMemory(); - - // ---------------------------------------------------------------- process - - /** - * Process request input stream. Note that file size is unknown at this point. - * Therefore, the implementation should set the {@link #getSize() size} - * attribute after successful processing. This method also must set the - * {@link #isValid() valid} attribute. - * - * @see MultipartRequestInputStream - */ - protected abstract void processStream() throws IOException; - - // ---------------------------------------------------------------- toString - - /** - * Returns basic information about the uploaded file. - */ - @Override - public String toString() { - return "FileUpload: uploaded=[" + isUploaded() + "] valid=[" + valid + "] field=[" + - header.getFormFieldName() + "] name=[" + header.getFileName() + "] size=[" + size + ']'; - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUploadFactory.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUploadFactory.java deleted file mode 100644 index 4015c80fd..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUploadFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload; - -/** - * {@link FileUpload} factory for handling uploaded files. Implementations may - * handle uploaded files differently: to store them to memory, directly to disk - * or something else. - */ -public interface FileUploadFactory { - - /** - * Creates new instance of {@link FileUpload uploaded file}. - */ - FileUpload create(MultipartRequestInputStream input); -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUploadHeader.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUploadHeader.java deleted file mode 100644 index 74ffb63f3..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/FileUploadHeader.java +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload; - -import com.fr.third.jodd.io.FileNameUtil; -import com.fr.third.jodd.util.StringPool; - -/** - * Parses file upload header. - */ -public class FileUploadHeader { - - String dataHeader; - String formFieldName; - - String formFileName; - String path; - String fileName; - - boolean isFile; - String contentType; - String mimeType; - String mimeSubtype; - String contentDisposition; - - - FileUploadHeader(final String dataHeader) { - this.dataHeader = dataHeader; - isFile = dataHeader.indexOf("filename") > 0; - formFieldName = getDataFieldValue(dataHeader, "name"); - if (isFile) { - formFileName = getDataFieldValue(dataHeader, "filename"); - if (formFileName == null) { - return; - } - if (formFileName.length() == 0) { - path = StringPool.EMPTY; - fileName = StringPool.EMPTY; - } - int ls = FileNameUtil.indexOfLastSeparator(formFileName); - if (ls == -1) { - path = StringPool.EMPTY; - fileName = formFileName; - } else { - path = formFileName.substring(0, ls); - fileName = formFileName.substring(ls + 1); - } - if (fileName.length() > 0) { - this.contentType = getContentType(dataHeader); - mimeType = getMimeType(contentType); - mimeSubtype = getMimeSubtype(contentType); - contentDisposition = getContentDisposition(dataHeader); - } - } - } - - // ---------------------------------------------------------------- utilities - - /** - * Gets value of data field or null if field not found. - */ - private String getDataFieldValue(final String dataHeader, final String fieldName) { - String value = null; - String token = String.valueOf((new StringBuffer(String.valueOf(fieldName))).append('=').append('"')); - int pos = dataHeader.indexOf(token); - if (pos > 0) { - int start = pos + token.length(); - int end = dataHeader.indexOf('"', start); - if ((start > 0) && (end > 0)) { - value = dataHeader.substring(start, end); - } - } - return value; - } - - /** - * Strips content type information from requests data header. - * @param dataHeader data header string - * @return content type or an empty string if no content type defined - */ - private String getContentType(final String dataHeader) { - String token = "Content-Type:"; - int start = dataHeader.indexOf(token); - if (start == -1) { - return StringPool.EMPTY; - } - start += token.length(); - return dataHeader.substring(start).trim(); - } - - private String getContentDisposition(final String dataHeader) { - int start = dataHeader.indexOf(':') + 1; - int end = dataHeader.indexOf(';'); - return dataHeader.substring(start, end); - } - - private String getMimeType(final String ContentType) { - int pos = ContentType.indexOf('/'); - if (pos == -1) { - return ContentType; - } - return ContentType.substring(1, pos); - } - - private String getMimeSubtype(final String ContentType) { - int start = ContentType.indexOf('/'); - if (start == -1) { - return ContentType; - } - start++; - return ContentType.substring(start); - } - - - // ---------------------------------------------------------------- public interface - - /** - * Returns true if uploaded data are correctly marked as a file. - * This is true if header contains string 'filename'. - */ - public boolean isFile() { - return isFile; - } - - /** - * Returns form field name. - */ - public String getFormFieldName() { - return formFieldName; - } - - /** - * Returns complete file name as specified at client side. - */ - public String getFormFilename() { - return formFileName; - } - - /** - * Returns file name (base name and extension, without full path data). - */ - public String getFileName() { - return fileName; - } - - /** - * Returns uploaded content type. It is usually in the following form:
- * mime_type/mime_subtype. - * - * @see #getMimeType() - * @see #getMimeSubtype() - */ - public String getContentType() { - return contentType; - } - - /** - * Returns file types MIME. - */ - public String getMimeType() { - return mimeType; - } - - /** - * Returns file sub type MIME. - */ - public String getMimeSubtype() { - return mimeSubtype; - } - - /** - * Returns content disposition. Usually it is 'form-data'. - */ - public String getContentDisposition() { - return contentDisposition; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/MultipartRequestInputStream.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/MultipartRequestInputStream.java deleted file mode 100644 index 5e88b6631..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/MultipartRequestInputStream.java +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload; - -import com.fr.third.jodd.io.FastByteArrayOutputStream; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Extended input stream based on buffered requests input stream. - * It provides some more functions that might be useful when working - * with uploaded fies. - */ -public class MultipartRequestInputStream extends BufferedInputStream { - - public MultipartRequestInputStream(final InputStream in) { - super(in); - } - - /** - * Reads expected byte. Throws exception on streams end. - */ - public byte readByte() throws IOException { - int i = super.read(); - if (i == -1) { - throw new IOException("End of HTTP request stream reached"); - } - return (byte) i; - } - - /** - * Skips specified number of bytes. - */ - public void skipBytes(final int i) throws IOException { - long len = super.skip(i); - if (len != i) { - throw new IOException("Failed to skip data in HTTP request"); - } - } - - // ---------------------------------------------------------------- boundary - - protected byte[] boundary; - - /** - * Reads boundary from the input stream. - */ - public byte[] readBoundary() throws IOException { - FastByteArrayOutputStream boundaryOutput = new FastByteArrayOutputStream(); - byte b; - // skip optional whitespaces - while ((b = readByte()) <= ' ') { - } - boundaryOutput.write(b); - - // now read boundary chars - while ((b = readByte()) != '\r') { - boundaryOutput.write(b); - } - if (boundaryOutput.size() == 0) { - throw new IOException("Problems with parsing request: invalid boundary"); - } - skipBytes(1); - boundary = new byte[boundaryOutput.size() + 2]; - System.arraycopy(boundaryOutput.toByteArray(), 0, boundary, 2, boundary.length - 2); - boundary[0] = '\r'; - boundary[1] = '\n'; - return boundary; - } - - // ---------------------------------------------------------------- data header - - protected FileUploadHeader lastHeader; - - public FileUploadHeader getLastHeader() { - return lastHeader; - } - - /** - * Reads data header from the input stream. When there is no more - * headers (i.e. end of stream reached), returns null - */ - public FileUploadHeader readDataHeader(final String encoding) throws IOException { - String dataHeader = readDataHeaderString(encoding); - if (dataHeader != null) { - lastHeader = new FileUploadHeader(dataHeader); - } else { - lastHeader = null; - } - return lastHeader; - } - - - protected String readDataHeaderString(final String encoding) throws IOException { - FastByteArrayOutputStream data = new FastByteArrayOutputStream(); - byte b; - while (true) { - // end marker byte on offset +0 and +2 must be 13 - if ((b = readByte()) != '\r') { - data.write(b); - continue; - } - mark(4); - skipBytes(1); - int i = read(); - if (i == -1) { - // reached end of stream - return null; - } - if (i == '\r') { - reset(); - break; - } - reset(); - data.write(b); - } - skipBytes(3); - if (encoding != null) { - return data.toString(encoding); - } else { - return data.toString(); - } - } - - - // ---------------------------------------------------------------- copy - - /** - * Copies bytes from this stream to some output until boundary is - * reached. Returns number of copied bytes. It will throw an exception - * for any irregular behaviour. - */ - public int copyAll(final OutputStream out) throws IOException { - int count = 0; - while (true) { - byte b = readByte(); - if (isBoundary(b)) { - break; - } - out.write(b); - count++; - } - return count; - } - - /** - * Copies max or less number of bytes to output stream. Useful for determining - * if uploaded file is larger then expected. - */ - public int copyMax(final OutputStream out, final int maxBytes) throws IOException { - int count = 0; - while (true) { - byte b = readByte(); - if (isBoundary(b)) { - break; - } - out.write(b); - count++; - if (count == maxBytes) { - return count; - } - } - return count; - } - - /** - * Skips to the boundary and returns total number of bytes skipped. - */ - public int skipToBoundary() throws IOException { - int count = 0; - while (true) { - byte b = readByte(); - count++; - if (isBoundary(b)) { - break; - } - } - return count; - } - - /** - * Checks if the current byte (i.e. one that was read last) represents - * the very first byte of the boundary. - */ - public boolean isBoundary(byte b) throws IOException { - int boundaryLen = boundary.length; - mark(boundaryLen + 1); - int bpos = 0; - while (b == boundary[bpos]) { - b = readByte(); - bpos++; - if (bpos == boundaryLen) { - return true; // boundary found! - } - } - reset(); - return false; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/MultipartStreamParser.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/MultipartStreamParser.java deleted file mode 100644 index faafc010f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/MultipartStreamParser.java +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload; - -import com.fr.third.jodd.io.FastByteArrayOutputStream; -import com.fr.third.jodd.io.upload.impl.MemoryFileUploadFactory; -import com.fr.third.jodd.util.ArraysUtil; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Generic, serlvets-free multipart request input stream parser. - */ -public class MultipartStreamParser { - - protected FileUploadFactory fileUploadFactory; - protected Map requestParameters; - protected Map requestFiles; - - public MultipartStreamParser() { - this(null); - } - - public MultipartStreamParser(final FileUploadFactory fileUploadFactory) { - this.fileUploadFactory = (fileUploadFactory == null ? new MemoryFileUploadFactory() : fileUploadFactory); - } - - private boolean parsed; - - /** - * Sets the loaded flag that indicates that input stream is loaded and parsed. - * Throws an exception if stream already loaded. - */ - protected void setParsed() throws IOException { - if (parsed) { - throw new IOException("Multi-part request already parsed"); - } - parsed = true; - } - - /** - * Returns true if multi-part request is already loaded. - */ - public boolean isParsed() { - return parsed; - } - - // ---------------------------------------------------------------- load and extract - - protected void putFile(final String name, final FileUpload value) { - if (requestFiles == null) { - requestFiles = new HashMap<>(); - } - - FileUpload[] fileUploads = requestFiles.get(name); - - if (fileUploads != null) { - fileUploads = ArraysUtil.append(fileUploads, value); - } else { - fileUploads = new FileUpload[] {value}; - } - - requestFiles.put(name, fileUploads); - } - - protected void putParameters(final String name, final String[] values) { - if (requestParameters == null) { - requestParameters = new HashMap<>(); - } - requestParameters.put(name, values); - } - - protected void putParameter(final String name, final String value) { - if (requestParameters == null) { - requestParameters = new HashMap<>(); - } - - String[] params = requestParameters.get(name); - - if (params != null) { - params = ArraysUtil.append(params, value); - } else { - params = new String[] {value}; - } - - requestParameters.put(name, params); - } - - /** - * Extracts uploaded files and parameters from the request data. - */ - public void parseRequestStream(final InputStream inputStream, final String encoding) throws IOException { - setParsed(); - - MultipartRequestInputStream input = new MultipartRequestInputStream(inputStream); - input.readBoundary(); - while (true) { - FileUploadHeader header = input.readDataHeader(encoding); - if (header == null) { - break; - } - - if (header.isFile) { - String fileName = header.fileName; - if (fileName.length() > 0) { - if (header.contentType.indexOf("application/x-macbinary") > 0) { - input.skipBytes(128); - } - } - FileUpload newFile = fileUploadFactory.create(input); - newFile.processStream(); - if (fileName.length() == 0) { - // file was specified, but no name was provided, therefore it was not uploaded - if (newFile.getSize() == 0) { - newFile.size = -1; - } - } - putFile(header.formFieldName, newFile); - } else { - // no file, therefore it is regular form parameter. - FastByteArrayOutputStream fbos = new FastByteArrayOutputStream(); - input.copyAll(fbos); - String value = encoding != null ? new String(fbos.toByteArray(), encoding) : new String(fbos.toByteArray()); - putParameter(header.formFieldName, value); - } - - input.skipBytes(1); - input.mark(1); - - // read byte, but may be end of stream - int nextByte = input.read(); - if (nextByte == -1 || nextByte == '-') { - input.reset(); - break; - } - input.reset(); - } - } - - // ---------------------------------------------------------------- parameters - - - /** - * Returns single value of a parameter. If parameter name is used for - * more then one parameter, only the first one will be returned. - * - * @return parameter value, or null if not found - */ - public String getParameter(final String paramName) { - if (requestParameters == null) { - return null; - } - String[] values = requestParameters.get(paramName); - if ((values != null) && (values.length > 0)) { - return values[0]; - } - return null; - } - - /** - * Returns the names of the parameters contained in this request. - */ - public Set getParameterNames() { - if (requestParameters == null) { - return Collections.emptySet(); - } - return requestParameters.keySet(); - } - - /** - * Returns all values all of the values the given request parameter has. - */ - public String[] getParameterValues(final String paramName) { - if (requestParameters == null) { - return null; - } - return requestParameters.get(paramName); - } - - - /** - * Returns uploaded file. - * @param paramName parameter name of the uploaded file - * @return uploaded file or null if parameter name not found - */ - public FileUpload getFile(final String paramName) { - if (requestFiles == null) { - return null; - } - FileUpload[] values = requestFiles.get(paramName); - if ((values != null) && (values.length > 0)) { - return values[0]; - } - return null; - } - - - /** - * Returns all uploaded files the given request parameter has. - */ - public FileUpload[] getFiles(final String paramName) { - if (requestFiles == null) { - return null; - } - return requestFiles.get(paramName); - } - - /** - * Returns parameter names of all uploaded files. - */ - public Set getFileParameterNames() { - if (requestFiles == null) { - return Collections.emptySet(); - } - return requestFiles.keySet(); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/AdaptiveFileUpload.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/AdaptiveFileUpload.java deleted file mode 100644 index 48ff6759b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/AdaptiveFileUpload.java +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload.impl; - -import com.fr.third.jodd.core.JoddCore; -import com.fr.third.jodd.io.FastByteArrayOutputStream; -import com.fr.third.jodd.io.FileNameUtil; -import com.fr.third.jodd.io.FileUtil; -import com.fr.third.jodd.io.StreamUtil; -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.io.upload.MultipartRequestInputStream; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * Smart {@link FileUpload} implementation that defer the action of what to do with uploaded file - * for later. Internally, it stores uploaded file either in memory if it is small, or, in all - * other cases, it stores them in TEMP folder. - */ -public class AdaptiveFileUpload extends FileUpload { - - protected static final String TMP_FILE_SUFFIX = ".upload.tmp"; - - protected final int memoryThreshold; - protected final File uploadPath; - protected final boolean breakOnError; - protected final String[] fileExtensions; - protected final boolean allowFileExtensions; - - AdaptiveFileUpload(final MultipartRequestInputStream input, final int memoryThreshold, final File uploadPath, final int maxFileSize, final boolean breakOnError, final String[] extensions, final boolean allowed) { - super(input, maxFileSize); - this.memoryThreshold = memoryThreshold; - this.uploadPath = uploadPath; - this.breakOnError = breakOnError; - this.fileExtensions = extensions; - this.allowFileExtensions = allowed; - } - - // ---------------------------------------------------------------- settings - - public int getMemoryThreshold() { - return memoryThreshold; - } - - public File getUploadPath() { - return uploadPath; - } - - public boolean isBreakOnError() { - return breakOnError; - } - - public String[] getFileExtensions() { - return fileExtensions; - } - - public boolean isAllowFileExtensions() { - return allowFileExtensions; - } - - // ---------------------------------------------------------------- properties - - protected File tempFile; - protected byte[] data; - - /** - * Returns true if file upload resides in memory. - */ - @Override - public boolean isInMemory() { - return data != null; - } - - // ---------------------------------------------------------------- process - - - protected boolean matchFileExtension() throws IOException { - String fileNameExtension = FileNameUtil.getExtension(getHeader().getFileName()); - for (String fileExtension : fileExtensions) { - if (fileNameExtension.equalsIgnoreCase(fileExtension)) { - if (!allowFileExtensions) { // extension matched and it is not allowed - if (breakOnError) { - throw new IOException("Upload filename extension not allowed: " + fileNameExtension); - } - size = input.skipToBoundary(); - return false; - } - return true; // extension matched and it is allowed. - } - } - if (allowFileExtensions) { // extension is not one of the allowed ones. - if (breakOnError) { - throw new IOException("Upload filename extension not allowed: " + fileNameExtension); - } - size = input.skipToBoundary(); - return false; - } - return true; - } - - /** - * Determines if upload is allowed. - */ - protected boolean checkUpload() throws IOException { - if (fileExtensions != null) { - if (!matchFileExtension()) { - return false; - } - } - return true; - } - - @Override - protected void processStream() throws IOException { - if (!checkUpload()) { - return; - } - size = 0; - if (memoryThreshold > 0) { - FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream(memoryThreshold + 1); - int written = input.copyMax(fbaos, memoryThreshold + 1); - data = fbaos.toByteArray(); - if (written <= memoryThreshold) { - size = data.length; - valid = true; - return; - } - } - - tempFile = FileUtil.createTempFile(JoddCore.tempFilePrefix, TMP_FILE_SUFFIX, uploadPath); - BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); - if (data != null) { - size = data.length; - out.write(data); - data = null; // not needed anymore - } - boolean deleteTempFile = false; - try { - if (maxFileSize == -1) { - size += input.copyAll(out); - } else { - size += input.copyMax(out, maxFileSize - size + 1); // one more byte to detect larger files - if (size > maxFileSize) { - deleteTempFile = true; - fileTooBig = true; - valid = false; - if (breakOnError) { - throw new IOException("File upload (" + header.getFileName() + ") too big, > " + maxFileSize); - } - input.skipToBoundary(); - return; - } - } - valid = true; - } finally { - StreamUtil.close(out); - if (deleteTempFile) { - tempFile.delete(); - tempFile = null; - } - } - } - - // ---------------------------------------------------------------- operations - - - /** - * Deletes file uploaded item from disk or memory. - */ - public void delete() { - if (tempFile != null) { - tempFile.delete(); - } - if (data != null) { - data = null; - } - } - - /** - * Writes file uploaded item. - */ - public File write(final String destination) throws IOException { - return write(new File(destination)); - } - - /** - * Writes file upload item to destination folder or to destination file. - * Returns the destination file. - */ - public File write(File destination) throws IOException { - if (destination.isDirectory()) { - destination = new File(destination, this.header.getFileName()); - } - if (data != null) { - FileUtil.writeBytes(destination, data); - } else { - if (tempFile != null) { - FileUtil.move(tempFile, destination); - } - } - return destination; - } - - /** - * Returns the content of file upload item. - */ - @Override - public byte[] getFileContent() throws IOException { - if (data != null) { - return data; - } - if (tempFile != null) { - return FileUtil.readBytes(tempFile); - } - return null; - } - - @Override - public InputStream getFileInputStream() throws IOException { - if (data != null) { - return new BufferedInputStream(new ByteArrayInputStream(data)); - } - if (tempFile != null) { - return new BufferedInputStream(new FileInputStream(tempFile)); - } - return null; - } - - - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/AdaptiveFileUploadFactory.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/AdaptiveFileUploadFactory.java deleted file mode 100644 index d91ac56bd..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/AdaptiveFileUploadFactory.java +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload.impl; - -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.io.upload.FileUploadFactory; -import com.fr.third.jodd.io.upload.MultipartRequestInputStream; - -import java.io.File; - -/** - * - * Factory for {@link AdaptiveFileUpload}. - */ -public class AdaptiveFileUploadFactory implements FileUploadFactory { - - protected int memoryThreshold = 8192; - protected File uploadPath; - protected int maxFileSize = 102400; - protected boolean breakOnError; - protected String[] fileExtensions; - protected boolean allowFileExtensions = true; - - /** - * {@inheritDoc} - */ - @Override - public FileUpload create(final MultipartRequestInputStream input) { - return new AdaptiveFileUpload(input, memoryThreshold, uploadPath, maxFileSize, breakOnError, fileExtensions, allowFileExtensions); - } - - // ---------------------------------------------------------------- properties - - public int getMemoryThreshold() { - return memoryThreshold; - } - /** - * Specifies per file memory limit for keeping uploaded files in the memory. - */ - public AdaptiveFileUploadFactory setMemoryThreshold(final int memoryThreshold) { - if (memoryThreshold >= 0) { - this.memoryThreshold = memoryThreshold; - } - return this; - } - - public File getUploadPath() { - return uploadPath; - } - - /** - * Specifies the upload path. If set to null default - * system TEMP path will be used. - */ - public AdaptiveFileUploadFactory setUploadPath(final File uploadPath) { - this.uploadPath = uploadPath; - return this; - } - - public int getMaxFileSize() { - return maxFileSize; - } - - /** - * Sets maximum file upload size. Setting to -1 - * disables this constraint. - */ - public AdaptiveFileUploadFactory setMaxFileSize(final int maxFileSize) { - this.maxFileSize = maxFileSize; - return this; - } - - public boolean isBreakOnError() { - return breakOnError; - } - - public AdaptiveFileUploadFactory setBreakOnError(final boolean breakOnError) { - this.breakOnError = breakOnError; - return this; - } - - /** - * Specifies if upload should break on error. - */ - public AdaptiveFileUploadFactory breakOnError(final boolean breakOnError) { - this.breakOnError = breakOnError; - return this; - } - - /** - * Allow or disallow set of file extensions. Only one rule can be active at time, - * which means user can only specify extensions that are either allowed or disallowed. - * Setting this value to null will turn this feature off. - */ - public AdaptiveFileUploadFactory setFileExtensions(final String[] fileExtensions, final boolean allow) { - this.fileExtensions = fileExtensions; - this.allowFileExtensions = allow; - return this; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/DiskFileUpload.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/DiskFileUpload.java deleted file mode 100644 index 9edf18988..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/DiskFileUpload.java +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload.impl; - -import com.fr.third.jodd.io.FileUtil; -import com.fr.third.jodd.io.StreamUtil; -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.io.upload.MultipartRequestInputStream; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * {@link FileUpload} that saves uploaded files directly to destination folder. - */ -public class DiskFileUpload extends FileUpload { - - protected final File destFolder; - - DiskFileUpload(final MultipartRequestInputStream input, final File destinationFolder, final int maxFileSize) { - super(input, maxFileSize); - this.destFolder = destinationFolder; - } - - /** - * Returns false as uploaded file is stored on disk. - */ - @Override - public boolean isInMemory() { - return false; - } - - /** - * Returns destination folder. - */ - public File getDestinationFolder() { - return destFolder; - } - - /** - * Returns uploaded and saved file. - */ - public File getFile() { - return file; - } - - protected File file; - - /** - * Returns files content from disk file. - * If error occurs, it returns null - */ - @Override - public byte[] getFileContent() throws IOException { - return FileUtil.readBytes(file); - } - - /** - * Returns new buffered file input stream. - */ - @Override - public InputStream getFileInputStream() throws IOException { - return new BufferedInputStream(new FileInputStream(file)); - } - - @Override - protected void processStream() throws IOException { - file = new File(destFolder, header.getFileName()); - final OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); - - size = 0; - try { - if (maxFileSize == -1) { - size = input.copyAll(out); - } else { - size = input.copyMax(out, maxFileSize + 1); // one more byte to detect larger files - if (size > maxFileSize) { - fileTooBig = true; - valid = false; - input.skipToBoundary(); - return; - } - } - valid = true; - } finally { - StreamUtil.close(out); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/DiskFileUploadFactory.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/DiskFileUploadFactory.java deleted file mode 100644 index 7bdabfaa4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/DiskFileUploadFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload.impl; - -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.io.upload.FileUploadFactory; -import com.fr.third.jodd.io.upload.MultipartRequestInputStream; -import com.fr.third.jodd.system.SystemUtil; - -import java.io.File; -import java.io.IOException; - -/** - * Factory for {@link com.fr.third.jodd.io.upload.impl.DiskFileUpload} - */ -public class DiskFileUploadFactory implements FileUploadFactory { - - protected File destFolder; - - protected int maxFileSize = 102400; - - public DiskFileUploadFactory() throws IOException { - this(SystemUtil.info().getTempDir()); - } - - public DiskFileUploadFactory(final String destFolder) throws IOException { - this(destFolder, 102400); - - } - - public DiskFileUploadFactory(final String destFolder, final int maxFileSize) throws IOException { - setUploadDir(destFolder); - this.maxFileSize = maxFileSize; - } - - - public DiskFileUploadFactory setUploadDir(String destFolder) throws IOException { - if (destFolder == null) { - destFolder = SystemUtil.info().getTempDir(); - } - File destination = new File(destFolder); - if (!destination.exists()) { - destination.mkdirs(); - } - if (!destination.isDirectory()) { - throw new IOException("Invalid destination folder: " + destFolder); - } - this.destFolder = destination; - return this; - } - - public int getMaxFileSize() { - return maxFileSize; - } - - /** - * Sets maximum file upload size. Setting to -1 will disable this constraint. - */ - public DiskFileUploadFactory setMaxFileSize(final int maxFileSize) { - this.maxFileSize = maxFileSize; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public FileUpload create(final MultipartRequestInputStream input) { - return new DiskFileUpload(input, destFolder, maxFileSize); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/MemoryFileUpload.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/MemoryFileUpload.java deleted file mode 100644 index 02c687466..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/MemoryFileUpload.java +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload.impl; - -import com.fr.third.jodd.io.FastByteArrayOutputStream; -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.io.upload.MultipartRequestInputStream; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * {@link FileUpload} that stores uploaded files in memory byte array. - */ -public class MemoryFileUpload extends FileUpload { - - MemoryFileUpload(final MultipartRequestInputStream input, final int maxFileSize) { - super(input, maxFileSize); - } - - // ---------------------------------------------------------------- logic - - protected byte[] data; - - /** - * Returns byte array containing uploaded file data. - */ - @Override - public byte[] getFileContent() { - return data; - } - - /** - * Returns true as uploaded file is stored in memory. - */ - @Override - public boolean isInMemory() { - return true; - } - - /** - * Returns byte array input stream. - */ - @Override - public InputStream getFileInputStream() { - return new ByteArrayInputStream(data); - } - - /** - * Reads data from input stream into byte array and stores file size. - */ - @Override - public void processStream() throws IOException { - FastByteArrayOutputStream out = new FastByteArrayOutputStream(); - size = 0; - if (maxFileSize == -1) { - size += input.copyAll(out); - } else { - size += input.copyMax(out, maxFileSize + 1); // one more byte to detect larger files - if (size > maxFileSize) { - fileTooBig = true; - valid = false; - input.skipToBoundary(); - return; - } - } - data = out.toByteArray(); - size = data.length; - valid = true; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/MemoryFileUploadFactory.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/MemoryFileUploadFactory.java deleted file mode 100644 index 6290b7ce5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/MemoryFileUploadFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.upload.impl; - -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.io.upload.FileUploadFactory; -import com.fr.third.jodd.io.upload.MultipartRequestInputStream; - -/** - * Factory for {@link com.fr.third.jodd.io.upload.impl.MemoryFileUpload}. - */ -public class MemoryFileUploadFactory implements FileUploadFactory { - - protected int maxFileSize = 102400; - - public int getMaxFileSize() { - return maxFileSize; - } - - /** - * Sets maximum file upload size. Setting to -1 will disable this constraint. - */ - public MemoryFileUploadFactory setMaxFileSize(final int maxFileSize) { - this.maxFileSize = maxFileSize; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public FileUpload create(final MultipartRequestInputStream input) { - return new MemoryFileUpload(input, maxFileSize); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/package-info.java deleted file mode 100644 index 53d7a6805..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/impl/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various implementations of uploaded files and their factories. - */ -package com.fr.third.jodd.io.upload.impl; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/package-info.java deleted file mode 100644 index 7a6e30147..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/upload/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Multipart streams and file uploads. - */ -package com.fr.third.jodd.io.upload; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcher.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcher.java deleted file mode 100644 index 006c30c38..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcher.java +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.watch; - -import com.fr.third.jodd.io.FileUtil; -import com.fr.third.jodd.mutable.MutableLong; -import com.fr.third.jodd.util.Consumers; -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.Wildcard; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Timer; -import java.util.TimerTask; -import java.util.function.Consumer; - -public class DirWatcher { - - protected final File dir; - protected HashMap map = new HashMap<>(); - protected int filesCount; - protected Consumers listeners = Consumers.empty(); - protected String[] patterns; - - /** - * Creates new watcher on specified directory. - * You can set file patterns {@link #monitor(String...) later}. - */ - public DirWatcher(final String dir) { - this(dir, null); - } - - /** - * Creates new watched on specified directory with given set of - * wildcard patterns for file names. - */ - public DirWatcher(final String dirName, final String... patterns) { - this.dir = new File(dirName); - - if (!dir.exists() || !dir.isDirectory()) { - throw new DirWatcherException("Invalid watch dir: " + dirName); - } - - this.patterns = patterns; - } - - /** - * Initializes dir watcher by reading all files - * from watched folder. - */ - protected void init() { - final File[] filesArray = dir.listFiles(); - - filesCount = 0; - - if (filesArray != null) { - filesCount = filesArray.length; - - for (final File file : filesArray) { - if (!acceptFile(file)) { - continue; - } - - map.put(file, new MutableLong(file.lastModified())); - } - } - } - - // ---------------------------------------------------------------- flags - - protected boolean ignoreDotFiles = true; - protected boolean startBlank = false; - - /** - * Enables or disables if dot files should be watched. - */ - public DirWatcher ignoreDotFiles(final boolean ignoreDotFiles) { - this.ignoreDotFiles = ignoreDotFiles; - return this; - } - - /** - * Defines if watcher should start blank and consider all present - * files as {@link com.fr.third.jodd.io.watch.DirWatcherEvent.Type#CREATED created}. - * By default all existing files will consider as existing ones. - */ - public DirWatcher startBlank(final boolean startBlank) { - this.startBlank = startBlank; - return this; - } - - /** - * Defines patterns to scan. - */ - public DirWatcher monitor(final String... patterns) { - this.patterns = patterns; - return this; - } - - // ---------------------------------------------------------------- accept - - /** - * Accepts if a file is going to be watched. - */ - protected boolean acceptFile(final File file) { - if (!file.isFile()) { - return false; // ignore non-files - } - - final String fileName = file.getName(); - - if (ignoreDotFiles) { - if (fileName.startsWith(StringPool.DOT)) { - return false; // ignore hidden files - } - } - - if (patterns == null) { - return true; - } - - return Wildcard.matchOne(fileName, patterns) != -1; - } - - // ---------------------------------------------------------------- watch file - - protected File watchFile; - protected long watchFileLastAccessTime; - - /** - * Enables usage of default watch file (".watch.ready"). - */ - public DirWatcher useWatchFile() { - return useWatchFile(".watch.ready"); - } - - /** - * Enables usage of provided watch file. - */ - public DirWatcher useWatchFile(final String name) { - watchFile = new File(dir, name); - - if (!watchFile.isFile() || !watchFile.exists()) { - try { - FileUtil.touch(watchFile); - } catch (final IOException ioex) { - throw new DirWatcherException("Invalid watch file: " + name, ioex); - } - } - - watchFileLastAccessTime = watchFile.lastModified(); - - return this; - } - - - // ---------------------------------------------------------------- timer - - protected Timer timer; - - /** - * Starts the watcher. - */ - public void start(final long pollingInterval) { - if (timer == null) { - if (!startBlank) { - init(); - } - timer = new Timer(true); - timer.schedule(new WatchTask(), 0, pollingInterval); - } - } - /** - * Stops the watcher. - */ - public void stop() { - if (timer != null) { - timer.cancel(); - timer = null; - } - } - - // ---------------------------------------------------------------- timer - - public class WatchTask extends TimerTask { - - protected boolean running; - - @Override - public final void run() { - if (running) { - // if one task takes too long, don't fire another one - return; - } - running = true; - - if (watchFile != null) { - // wait for watch file changes - final long last = watchFile.lastModified(); - - if (last <= watchFileLastAccessTime) { - running = false; - return; - } - watchFileLastAccessTime = last; - } - - // scan! - - final File[] filesArray = dir.listFiles(); - - if (filesArray == null) { - running = false; - return; - } - - HashSet deletedFiles = null; - - // check if there might be a delete file - if (filesArray.length < filesCount) { - deletedFiles = new HashSet<>(map.keySet()); - } - - filesCount = filesArray.length; - - // scan the files and check for modification/addition - for (final File file : filesArray) { - if (!acceptFile(file)) { - continue; - } - - final MutableLong currentTime = map.get(file); - - if (deletedFiles != null) { - deletedFiles.remove(file); - } - - final long lastModified = file.lastModified(); - - if (currentTime == null) { - // new file - map.put(file, new MutableLong(lastModified)); - onChange(DirWatcherEvent.Type.CREATED, file); - } - else if (currentTime.longValue() != lastModified) { - // modified file - currentTime.set(lastModified); - onChange(DirWatcherEvent.Type.MODIFIED, file); - } - } - - // check for deleted files - if (deletedFiles != null) { - for (final File deletedFile : deletedFiles) { - map.remove(deletedFile); - onChange(DirWatcherEvent.Type.DELETED, deletedFile); - } - } - - // stop running - running = false; - } - } - - /** - * Triggers listeners on file change. - */ - protected void onChange(final DirWatcherEvent.Type type, final File file) { - listeners.accept(new DirWatcherEvent(type, file)); - } - - // ---------------------------------------------------------------- listeners - - /** - * Registers {@link com.fr.third.jodd.io.watch.DirWatcherEvent consumer}. - */ - public void register(final Consumer dirWatcherListener) { - listeners.add(dirWatcherListener); - } - - /** - * Removes registered {@link com.fr.third.jodd.io.watch.DirWatcherEvent consumer}. - */ - public void remove(final Consumer dirWatcherListener) { - listeners.remove(dirWatcherListener); - } - - /** - * Removes all event consumers.. - */ - public void clear() { - listeners.clear(); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcherEvent.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcherEvent.java deleted file mode 100644 index 380335d7d..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcherEvent.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package com.fr.third.jodd.io.watch; - -import java.io.File; - -public class DirWatcherEvent { - - private final Type type; - private final File target; - private final long timestamp; - - /** - * Event type that describes file change. - */ - public enum Type { - CREATED, - DELETED, - MODIFIED - } - - DirWatcherEvent(final Type type, final File target) { - this.type = type; - this.target = target; - this.timestamp = System.currentTimeMillis(); - } - - /** - * Returns event type. - */ - public Type type() { - return type; - } - - /** - * Returns event target. - */ - public File target() { - return target; - } - - /** - * Returns event creation timestamp. - */ - public long timestamp() { - return timestamp; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcherException.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcherException.java deleted file mode 100644 index cd127fe2b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/DirWatcherException.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.io.watch; - -import com.fr.third.jodd.exception.UncheckedException; - -/** - * Exception for {@link com.fr.third.jodd.io.watch.DirWatcher}. - */ -public class DirWatcherException extends UncheckedException { - - public DirWatcherException(final String message) { - super(message); - } - - public DirWatcherException(final String message, final Throwable t) { - super(message, t); - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/package-info.java deleted file mode 100644 index 728e80887..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/io/watch/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Smart directory change watcher. - */ -package com.fr.third.jodd.io.watch; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/LazyValue.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/LazyValue.java deleted file mode 100644 index 4c2cc4916..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/LazyValue.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -import java.util.function.Supplier; - -/** - * Holder of a value that is computed lazy. - */ -public class LazyValue implements Supplier { - - private Supplier supplier; - private volatile boolean initialized; - private T value; - - /** - * Creates new instance of LazyValue. - */ - public static LazyValue of(final Supplier supplier) { - return new LazyValue<>(supplier); - } - - private LazyValue(final Supplier supplier) { - this.supplier = supplier; - } - - /** - * Returns the value. Value will be computed on first call. - */ - @Override - public T get() { - if (!initialized) { - synchronized (this) { - if (!initialized) { - final T t = supplier.get(); - value = t; - initialized = true; - supplier = null; - return t; - } - } - } - return value; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableBoolean.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableBoolean.java deleted file mode 100644 index 7f7bf5b3e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableBoolean.java +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * A mutable boolean wrapper. - */ -public final class MutableBoolean implements Comparable, Cloneable { - - public static MutableBoolean of(final boolean value) { - return new MutableBoolean(value); - } - - public MutableBoolean() { - } - - public MutableBoolean(final boolean value) { - this.value = value; - } - - public MutableBoolean(final String value) { - this.value = Boolean.valueOf(value).booleanValue(); - } - - public MutableBoolean(final Boolean value) { - this.value = value.booleanValue(); - } - - public MutableBoolean(final Number number) { - this.value = number.intValue() != 0; - } - - - // ---------------------------------------------------------------- value - - /** - * The mutable value. - */ - public boolean value; - - /** - * Returns mutable value. - */ - public boolean get() { - return value; - } - - /** - * Sets mutable value. - */ - public void set(final boolean value) { - this.value = value; - } - - /** - * Sets mutable value. Throws exception if boolean value is - * null. - */ - public void set(final Boolean value) { - this.value = value.booleanValue(); - } - - - // ---------------------------------------------------------------- object - - /** - * Stringify the value. - */ - @Override - public String toString() { - return Boolean.toString(value); - } - - /** - * Returns a hashcode for this value. - */ - @Override - public int hashCode() { - return value ? 1231 : 1237; - } - - /** - * Compares this object to the specified object. - * - * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj != null) { - if ( ((Boolean)this.value).getClass() == obj.getClass() ) { - return value == ((Boolean) obj).booleanValue(); - } - if (this.getClass() == obj.getClass()) { - return value == ((MutableBoolean) obj).value; - } - } - return false; - } - - // ---------------------------------------------------------------- compare - - /** - * Compares value of two same instances. - */ - @Override - public int compareTo(final MutableBoolean o) { - return (value == o.value) ? 0 : (!value ? -1 : 1); - } - - // ---------------------------------------------------------------- clone - - /** - * Clones object. - */ - @Override - public MutableBoolean clone() { - return new MutableBoolean(value); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableByte.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableByte.java deleted file mode 100644 index 073182400..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableByte.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * A mutable byte wrapper. - */ -public final class MutableByte extends Number implements Comparable, Cloneable { - - public static MutableByte of(final byte value) { - return new MutableByte(value); - } - - public MutableByte() { - } - - public MutableByte(final byte value) { - this.value = value; - } - - public MutableByte(final String value) { - this.value = Byte.parseByte(value); - } - - public MutableByte(final Number number) { - this.value = number.byteValue(); - } - - // ---------------------------------------------------------------- value - - /** - * The mutable value. - */ - public byte value; - - /** - * Returns mutable value. - */ - public byte get() { - return value; - } - - /** - * Sets mutable value. - */ - public void set(final byte value) { - this.value = value; - } - - /** - * Sets mutable value from a Number. - */ - public void set(final Number value) { - this.value = value.byteValue(); - } - - // ---------------------------------------------------------------- object - - /** - * Stringify the value. - */ - @Override - public String toString() { - return Integer.toString(value); - } - - /** - * Returns a hashcode for this value. - */ - @Override - public int hashCode() { - return value; - } - - /** - * Compares this object to the specified object. - * - * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj != null) { - if ( ((Byte)this.value).getClass() == obj.getClass() ) { - return value == ((Byte) obj).byteValue(); - } - if (this.getClass() == obj.getClass()) { - return value == ((MutableByte) obj).value; - } - } - return false; - } - - // ---------------------------------------------------------------- number - - /** - * Returns the value as a int. - */ - @Override - public int intValue() { - return value; - } - - /** - * Returns the value as a long. - */ - @Override - public long longValue() { - return value; - } - - /** - * Returns the value as a float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value as a double. - */ - @Override - public double doubleValue() { - return value; - } - - // ---------------------------------------------------------------- compare - - /** - * Compares value of two same instances. - */ - @Override - public int compareTo(final MutableByte other) { - return value < other.value ? -1 : (value == other.value ? 0 : 1); - } - - // ---------------------------------------------------------------- clone - - /** - * Clones object. - */ - @Override - public MutableByte clone() { - return new MutableByte(value); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableDouble.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableDouble.java deleted file mode 100644 index 0a9b6212e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableDouble.java +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * A mutable double wrapper. - */ -public final class MutableDouble extends Number implements Comparable, Cloneable { - - public static MutableDouble of(final double value) { - return new MutableDouble(value); - } - - public MutableDouble() { - } - - public MutableDouble(final double value) { - this.value = value; - } - - public MutableDouble(final String value) { - this.value = Double.parseDouble(value); - } - - public MutableDouble(final Number number) { - this.value = number.doubleValue(); - } - - // ---------------------------------------------------------------- value - - /** - * The mutable value. - */ - public double value; - - /** - * Returns mutable value. - */ - public double get() { - return value; - } - - /** - * Sets mutable value. - */ - public void set(final double value) { - this.value = value; - } - - /** - * Sets mutable value from a Number. - */ - public void set(final Number value) { - this.value = value.doubleValue(); - } - - // ---------------------------------------------------------------- object - - /** - * Stringify the value. - */ - @Override - public String toString() { - return Double.toString(value); - } - - /** - * Returns a hashcode for this value. - */ - @Override - public int hashCode() { - long bits = Double.doubleToLongBits(value); - return (int) (bits ^ (bits >>> 32)); - } - - /** - * Compares this object to the specified object. - * - * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj != null) { - if ( ((Double)this.value).getClass() == obj.getClass() ) { - return Double.doubleToLongBits(value) == Double.doubleToLongBits(((Double) obj).doubleValue()); - } - if (this.getClass() == obj.getClass()) { - return Double.doubleToLongBits(value) == Double.doubleToLongBits(((MutableDouble) obj).value); - } - } - return false; - } - - // ---------------------------------------------------------------- number - - /** - * Returns the value as a int. - */ - @Override - public int intValue() { - return (int) value; - } - - /** - * Returns the value as a long. - */ - @Override - public long longValue() { - return (long) value; - } - - /** - * Returns the value as a float.. - */ - @Override - public float floatValue() { - return (float) value; - } - - /** - * Returns the value as a double. - */ - @Override - public double doubleValue() { - return value; - } - - // ---------------------------------------------------------------- compare - - /** - * Checks whether the value is the special NaN value. - */ - public boolean isNaN() { - return Double.isNaN(value); - } - - /** - * Checks whether the double value is infinite. - */ - public boolean isInfinite() { - return Double.isInfinite(value); - } - - /** - * Compares value of two same instances. - */ - @Override - public int compareTo(final MutableDouble other) { - return Double.compare(value, other.value); - } - - // ---------------------------------------------------------------- clone - - /** - * Clones object. - */ - @Override - public MutableDouble clone() { - return new MutableDouble(value); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableFloat.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableFloat.java deleted file mode 100644 index 76c6f71b8..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableFloat.java +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * A mutable float wrapper. - */ -public final class MutableFloat extends Number implements Comparable, Cloneable { - - public static MutableFloat of(final float value) { - return new MutableFloat(value); - } - - public MutableFloat() { - } - - public MutableFloat(final float value) { - this.value = value; - } - - public MutableFloat(final String value) { - this.value = Float.parseFloat(value); - } - - public MutableFloat(final Number number) { - this.value = number.floatValue(); - } - - // ---------------------------------------------------------------- value - - /** - * The mutable value. - */ - public float value; - - /** - * Returns mutable value. - */ - public float get() { - return value; - } - - /** - * Sets mutable value. - */ - public void set(final float value) { - this.value = value; - } - - /** - * Sets mutable value from a Number. - */ - public void set(final Number value) { - this.value = value.floatValue(); - } - - // ---------------------------------------------------------------- object - - /** - * Stringify the value. - */ - @Override - public String toString() { - return Float.toString(value); - } - - /** - * Returns a hashcode for this value. - */ - @Override - public int hashCode() { - return Float.floatToIntBits(value); - } - - /** - * Compares this object to the specified object. - * - * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj != null) { - if ( ((Float)this.value).getClass() == obj.getClass() ) { - return Float.floatToIntBits(value) == Float.floatToIntBits(((Float) obj).floatValue()); - } - if (this.getClass() == obj.getClass()) { - return Float.floatToIntBits(value) == Float.floatToIntBits(((MutableFloat) obj).value); - } - } - return false; - } - - // ---------------------------------------------------------------- number - - /** - * Returns the value as a int. - */ - @Override - public int intValue() { - return (int) value; - } - - /** - * Returns the value as a long. - */ - @Override - public long longValue() { - return (long) value; - } - - /** - * Returns the value as a float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value as a double. - */ - @Override - public double doubleValue() { - return value; - } - - // ---------------------------------------------------------------- compare - - /** - * Checks whether the value is the special NaN value. - */ - public boolean isNaN() { - return Float.isNaN(value); - } - - /** - * Checks whether the float value is infinite. - */ - public boolean isInfinite() { - return Float.isInfinite(value); - } - - /** - * Compares value of two same instances. - */ - @Override - public int compareTo(final MutableFloat other) { - return Float.compare(value, other.value); - } - - // ---------------------------------------------------------------- clone - - /** - * Clones object. - */ - @Override - public MutableFloat clone() { - return new MutableFloat(value); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableInteger.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableInteger.java deleted file mode 100644 index 25e259fbe..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableInteger.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * A mutable int wrapper. - */ -public final class MutableInteger extends Number implements Comparable, Cloneable { - - public static MutableInteger of(final int value) { - return new MutableInteger(value); - } - - public MutableInteger() { - } - - public MutableInteger(final int value) { - this.value = value; - } - - public MutableInteger(final String value) { - this.value = Integer.parseInt(value); - } - - public MutableInteger(final Number number) { - this.value = number.intValue(); - } - - // ---------------------------------------------------------------- value - - /** - * The mutable value. - */ - public int value; - - /** - * Returns mutable value. - */ - public int get() { - return value; - } - - /** - * Sets mutable value. - */ - public void set(final int value) { - this.value = value; - } - - /** - * Sets mutable value from a Number. - */ - public void set(final Number value) { - this.value = value.intValue(); - } - - // ---------------------------------------------------------------- object - - /** - * Stringify the value. - */ - @Override - public String toString() { - return Integer.toString(value); - } - - /** - * Returns a hashcode for this value. - */ - @Override - public int hashCode() { - return value; - } - - /** - * Compares this object to the specified object. - * - * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj != null) { - if ( ((Integer)this.value).getClass() == obj.getClass() ) { - return value == ((Integer) obj).intValue(); - } - if (this.getClass() == obj.getClass()) { - return value == ((MutableInteger) obj).value; - } - } - return false; - } - - // ---------------------------------------------------------------- number - - /** - * Returns the value as a int. - */ - @Override - public int intValue() { - return value; - } - - /** - * Returns the value as a long. - */ - @Override - public long longValue() { - return value; - } - - /** - * Returns the value as a float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value as a double. - */ - @Override - public double doubleValue() { - return value; - } - - // ---------------------------------------------------------------- compare - - /** - * Compares value of two same instances. - */ - @Override - public int compareTo(final MutableInteger other) { - return value < other.value ? -1 : (value == other.value ? 0 : 1); - } - - // ---------------------------------------------------------------- clone - - /** - * Clones object. - */ - @Override - public MutableInteger clone() { - return new MutableInteger(value); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableLong.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableLong.java deleted file mode 100644 index e5c0804b4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableLong.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * A mutable long wrapper. - */ -public final class MutableLong extends Number implements Comparable, Cloneable { - - public static MutableLong of(final long value) { - return new MutableLong(value); - } - - public MutableLong() { - } - - public MutableLong(final long value) { - this.value = value; - } - - public MutableLong(final String value) { - this.value = Long.parseLong(value); - } - - public MutableLong(final Number number) { - this.value = number.longValue(); - } - - // ---------------------------------------------------------------- value - - /** - * The mutable value. - */ - public long value; - - /** - * Returns mutable value. - */ - public long get() { - return value; - } - - /** - * Sets mutable value. - */ - public void set(final long value) { - this.value = value; - } - - /** - * Sets mutable value from a Number. - */ - public void set(final Number value) { - this.value = value.longValue(); - } - - // ---------------------------------------------------------------- object - - /** - * Stringify the value. - */ - @Override - public String toString() { - return Long.toString(value); - } - - /** - * Returns a hashcode for this value. - */ - @Override - public int hashCode() { - return (int) (value ^ (value >>> 32)); - } - - /** - * Compares this object to the specified object. - * - * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj != null) { - if ( ((Long)this.value).getClass() == obj.getClass() ) { - return value == ((Long) obj).longValue(); - } - if (this.getClass() == obj.getClass()) { - return value == ((MutableLong) obj).value; - } - } - return false; - } - - // ---------------------------------------------------------------- number - - /** - * Returns the value as a int. - */ - @Override - public int intValue() { - return (int) value; - } - - /** - * Returns the value as a long. - */ - @Override - public long longValue() { - return value; - } - - /** - * Returns the value as a float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value as a double. - */ - @Override - public double doubleValue() { - return value; - } - - // ---------------------------------------------------------------- compare - - /** - * Compares value of two same instances. - */ - @Override - public int compareTo(final MutableLong other) { - return value < other.value ? -1 : (value == other.value ? 0 : 1); - } - - // ---------------------------------------------------------------- clone - - /** - * Clones object. - */ - @Override - public MutableLong clone() { - return new MutableLong(value); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableShort.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableShort.java deleted file mode 100644 index f9943315f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/MutableShort.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * A mutable short wrapper. - */ -public final class MutableShort extends Number implements Comparable, Cloneable { - - public static MutableShort of(final short value) { - return new MutableShort(value); - } - - public MutableShort() { - } - - public MutableShort(final short value) { - this.value = value; - } - - public MutableShort(final String value) { - this.value = Short.parseShort(value); - } - - public MutableShort(final Number number) { - this.value = number.shortValue(); - } - - // ---------------------------------------------------------------- value - - /** - * The mutable value. - */ - public short value; - - /** - * Returns mutable value. - */ - public short get() { - return value; - } - - /** - * Sets mutable value. - */ - public void set(final short value) { - this.value = value; - } - - /** - * Sets mutable value from a Number. - */ - public void set(final Number value) { - this.value = value.shortValue(); - } - - // ---------------------------------------------------------------- object - - /** - * Stringify the value. - */ - @Override - public String toString() { - return Integer.toString(value); - } - - /** - * Returns a hashcode for this value. - */ - @Override - public int hashCode() { - return value; - } - - /** - * Compares this object to the specified object. - * - * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj != null) { - if ( ((Short)this.value).getClass() == obj.getClass() ) { - return value == ((Short) obj).shortValue(); - } - if (this.getClass() == obj.getClass()) { - return value == ((MutableShort) obj).value; - } - } - return false; - } - - // ---------------------------------------------------------------- number - - /** - * Returns the value as a int. - */ - @Override - public int intValue() { - return value; - } - - /** - * Returns the value as a long. - */ - @Override - public long longValue() { - return value; - } - - /** - * Returns the value as a float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value as a double. - */ - @Override - public double doubleValue() { - return value; - } - - // ---------------------------------------------------------------- compare - - /** - * Compares value of two same instances. - */ - @Override - public int compareTo(final MutableShort other) { - return value < other.value ? -1 : (value == other.value ? 0 : 1); - } - - // ---------------------------------------------------------------- clone - - /** - * Clones object. - */ - @Override - public MutableShort clone() { - return new MutableShort(value); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/Value.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/Value.java deleted file mode 100644 index d7b4b1c10..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/Value.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -import java.util.function.Supplier; - -/** - * Generic mutable value holder for holding objects. - */ -public interface Value extends Supplier { - - /** - * Creates default value wrapper. - */ - public static Value of(final R value) { - return new ValueImpl<>(value); - } - - /** - * Sets new value. - */ - public void set(T value); - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/ValueImpl.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/ValueImpl.java deleted file mode 100644 index 4b78e1d53..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/ValueImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.mutable; - -/** - * Default implementation of a {@link Value}. - */ -class ValueImpl implements Value { - - private T value; - - ValueImpl(final T v) { - this.value = v; - } - - @Override - public T get() { - return value; - } - - @Override - public void set(final T value) { - this.value = value; - } - - /** - * Simple to-string representation of a value. - */ - @Override - public String toString() { - if (value == null) { - return "value: {null}"; - } - return "value: {" + value.toString() + '}'; - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/mutable/package-info.java deleted file mode 100644 index 7977956b9..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/mutable/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Mutable number bean-alike implementations. - */ -package com.fr.third.jodd.mutable; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/net/HtmlDecoder.java b/fine-jodd/src/main/java/com/fr/third/jodd/net/HtmlDecoder.java deleted file mode 100644 index cab00f18f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/net/HtmlDecoder.java +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.net; - -import com.fr.third.jodd.io.StreamUtil; -import com.fr.third.jodd.util.BinarySearchBase; -import com.fr.third.jodd.util.CharUtil; -import com.fr.third.jodd.util.StringUtil; - -import java.io.InputStream; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * HTML decoder. - */ -public class HtmlDecoder { - - private static final Map ENTITY_MAP; - private static final char[][] ENTITY_NAMES; - - static { - final Properties entityReferences = new Properties(); - - final String propertiesName = HtmlDecoder.class.getSimpleName() + ".properties"; - - final InputStream is = HtmlDecoder.class.getResourceAsStream(propertiesName); - - try { - entityReferences.load(is); - } - catch (final Exception ex) { - throw new IllegalStateException("Can't load properties", ex); - } finally { - StreamUtil.close(is); - } - - ENTITY_MAP = new HashMap<>(entityReferences.size()); - - final Enumeration keys = (Enumeration) entityReferences.propertyNames(); - while (keys.hasMoreElements()) { - final String name = keys.nextElement(); - final String values = entityReferences.getProperty(name); - final String[] array = StringUtil.splitc(values, ','); - - final char[] chars; - - final String hex = array[0]; - final char value = (char) Integer.parseInt(hex, 16); - - if (array.length == 2) { - final String hex2 = array[1]; - final char value2 = (char) Integer.parseInt(hex2, 16); - - chars = new char[]{value, value2}; - } else { - chars = new char[]{value}; - } - - ENTITY_MAP.put(name, chars); - } - - // create sorted list of entry names - - ENTITY_NAMES = new char[ENTITY_MAP.size()][]; - - int i = 0; - for (final String name : ENTITY_MAP.keySet()) { - ENTITY_NAMES[i++] = name.toCharArray(); - } - - Arrays.sort(ENTITY_NAMES, Comparator.comparing(String::new)); - } - - /** - * Decodes HTML text. Assumes that all character references are properly closed with semi-colon. - */ - public static String decode(final String html) { - - int ndx = html.indexOf('&'); - if (ndx == -1) { - return html; - } - - final StringBuilder result = new StringBuilder(html.length()); - - int lastIndex = 0; - final int len = html.length(); -mainloop: - while (ndx != -1) { - result.append(html.substring(lastIndex, ndx)); - - lastIndex = ndx; - while (html.charAt(lastIndex) != ';') { - lastIndex++; - if (lastIndex == len) { - lastIndex = ndx; - break mainloop; - } - } - - if (html.charAt(ndx + 1) == '#') { - // decimal/hex - final char c = html.charAt(ndx + 2); - final int radix; - if ((c == 'x') || (c == 'X')) { - radix = 16; - ndx += 3; - } else { - radix = 10; - ndx += 2; - } - - final String number = html.substring(ndx, lastIndex); - final int i = Integer.parseInt(number, radix); - result.append((char) i); - lastIndex++; - } else { - // token - final String encodeToken = html.substring(ndx + 1, lastIndex); - - final char[] replacement = ENTITY_MAP.get(encodeToken); - if (replacement == null) { - result.append('&'); - lastIndex = ndx + 1; - } else { - result.append(replacement); - lastIndex++; - } - } - ndx = html.indexOf('&', lastIndex); - } - result.append(html.substring(lastIndex)); - return result.toString(); - } - - private static final class Ptr { - public int offset; - public char c; - } - - /** - * Detects the longest character reference name on given position in char array. - * Returns {@code null} if name not found. - */ - public static String detectName(final char[] input, int ndx) { - final Ptr ptr = new Ptr(); - - int firstIndex = 0; - int lastIndex = ENTITY_NAMES.length - 1; - final int len = input.length; - char[] lastName = null; - - final BinarySearchBase binarySearch = new BinarySearchBase() { - @Override - protected int compare(final int index) { - final char[] name = ENTITY_NAMES[index]; - - if (ptr.offset >= name.length) { - return -1; - } - - return name[ptr.offset] - ptr.c; - } - }; - - while (true) { - ptr.c = input[ndx]; - - if (!CharUtil.isAlphaOrDigit(ptr.c)) { - return lastName != null ? new String(lastName) : null; - } - - firstIndex = binarySearch.findFirst(firstIndex, lastIndex); - if (firstIndex < 0) { - return lastName != null ? new String(lastName) : null; - } - - final char[] element = ENTITY_NAMES[firstIndex]; - - if (element.length == ptr.offset + 1) { - // total match, remember position, continue for finding the longer name - lastName = ENTITY_NAMES[firstIndex]; - } - - lastIndex = binarySearch.findLast(firstIndex, lastIndex); - - if (firstIndex == lastIndex) { - // only one element found, check the rest - for (int i = ptr.offset; i < element.length; i++) { - if (ndx == input.length || element[i] != input[ndx]) { - return lastName != null ? new String(lastName) : null; - } - ndx++; - } - return new String(element); - } - - ptr.offset++; - - ndx++; - if (ndx == len) { - return lastName != null ? new String(lastName) : null; - } - } - } - - /** - * Returns replacement chars for given character reference. - */ - public static char[] lookup(final String name) { - return ENTITY_MAP.get(name); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/net/HtmlEncoder.java b/fine-jodd/src/main/java/com/fr/third/jodd/net/HtmlEncoder.java deleted file mode 100644 index bfac3bf20..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/net/HtmlEncoder.java +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.net; - -import com.fr.third.jodd.util.StringPool; - -/** - * Encodes text and URL strings in various ways resulting HTML-safe text. - * All methods are null safe. - * Invalid HTML chars are not checked with these methods, they are just - * passed as they are. - */ -public class HtmlEncoder { - - private static final int LEN = 0xA1; - private static final int LEN_XML = 0x40; - private static final char[][] TEXT = new char[LEN][]; - private static final char[][] ATTR_SQ = new char[LEN][]; - private static final char[][] ATTR_DQ = new char[LEN][]; - private static final char[][] TEXT_XML = new char[LEN_XML][]; - - private static final char[] AMP = "&".toCharArray(); - private static final char[] QUOT = """.toCharArray(); - private static final char[] APOS = "'".toCharArray(); - private static final char[] LT = "<".toCharArray(); - private static final char[] GT = ">".toCharArray(); - private static final char[] NBSP = " ".toCharArray(); - - /* - * Creates HTML lookup tables for faster encoding. - */ - static { - for (int i = 0; i < LEN_XML; i++) { - TEXT_XML[i] = TEXT[i] = ATTR_SQ[i] = ATTR_DQ[i] = new char[] {(char) i}; - } - for (int i = LEN_XML; i < LEN; i++) { - TEXT[i] = ATTR_SQ[i] = ATTR_DQ[i] = new char[] {(char) i}; - } - - // HTML characters - TEXT['&'] = AMP; // ampersand - TEXT['<'] = LT; // less than - TEXT['>'] = GT; // greater than - TEXT[0xA0] = NBSP; - - // SINGLE QUOTE - ATTR_SQ['&'] = AMP; // ampersand - ATTR_SQ['\''] = APOS; // single quote - ATTR_SQ[0xA0] = NBSP; - - // DOUBLE QUOTE - ATTR_DQ['&'] = AMP; // ampersand - ATTR_DQ['\"'] = QUOT; // double quote - ATTR_DQ[0xA0] = NBSP; - - // XML characters - TEXT_XML['&'] = AMP; // ampersand - TEXT_XML['\"'] = QUOT; // double-quote - TEXT_XML['\''] = APOS; // single-quote (' is not working for all browsers) - TEXT_XML['<'] = LT; // less than - TEXT_XML['>'] = GT; // greater than - } - - // ---------------------------------------------------------------- encode text - - /** - * Encodes attribute value that will be double quoted. - * In this case, only these entities are encoded: - *

    - *
  • & with &amp;
  • - *
  • " with &quot;
  • - *
  • - *
- */ - public static String attributeDoubleQuoted(final CharSequence value) { - return encode(value, ATTR_DQ, LEN); - } - - /** - * Encodes attribute value that will be single quoted. - * In this case, only two entities are encoded: - *
    - *
  • & with &amp;
  • - *
  • ' with &#39;
  • - *
  • - *
- */ - public static String attributeSingleQuoted(final CharSequence value) { - return encode(value, ATTR_SQ, LEN); - } - - /** - * Encodes a string to HTML-safe text. The following characters are replaced: - *
    - *
  • & with &amp;
  • - *
  • < with &lt;
  • - *
  • > with &gt;
  • - *
  • \u00A0 with  
  • - *
- */ - public static String text(final CharSequence text) { - return encode(text, TEXT, LEN); - } - - /** - * Encodes XML string. In XML there are only 5 predefined character entities. - */ - public static String xml(final CharSequence text) { - return encode(text, TEXT_XML, LEN_XML); - } - - // ---------------------------------------------------------------- private - - private static String encode(final CharSequence text, final char[][] buff, final int bufflen) { - int len; - if ((text == null) || ((len = text.length()) == 0)) { - return StringPool.EMPTY; - } - - StringBuilder buffer = new StringBuilder(len + (len >> 2)); - - for (int i = 0; i < len; i++) { - char c = text.charAt(i); - - if (c < bufflen) { - buffer.append(buff[c]); - } else { - buffer.append(c); - } - } - return buffer.toString(); - } - - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/net/HttpMethod.java b/fine-jodd/src/main/java/com/fr/third/jodd/net/HttpMethod.java deleted file mode 100644 index d10d00fc4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/net/HttpMethod.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.net; - -/** - * Http request methods. - * See: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods - */ -public enum HttpMethod { - CONNECT, - DELETE, - GET, - HEAD, - OPTIONS, - PATCH, - POST, - PUT, - TRACE; - - /** - * Returns {@code true} if method name is equal to provided one. - */ - public boolean equalsName(final String name) { - return name().equalsIgnoreCase(name); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/net/HttpStatus.java b/fine-jodd/src/main/java/com/fr/third/jodd/net/HttpStatus.java deleted file mode 100644 index 9626d5517..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/net/HttpStatus.java +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.net; - -/** - * Simple developer-friendly set of HttpStatus codes and messages. - */ -public class HttpStatus { - - private final int status; - protected String message; - - public HttpStatus(final int status, final String message) { - this.status = status; - this.message = message; - } - public HttpStatus(final int status) { - this.status = status; - } - - /** - * Returns {@code true} is status is error. - */ - public boolean isError() { - return status >= 400; - } - /** - * Returns {@code true} is status is successful. - */ - public boolean isSuccess() { - return status < 400; - } - - /** - * Returns status code. - */ - public int status() { - return status; - } - - /** - * Returns status message. - */ - public String message() { - return message; - } - - // ---------------------------------------------------------------- - - public static class Redirection { - private Redirection() { } - - static Redirection instance = new Redirection(); - - public HttpStatus multipleChoice300() { - return new HttpStatus(300, "The requested resource points to a destination with multiple representations."); - } - - public HttpStatus movedPermanently301() { - return new HttpStatus(301, "The requested resource has been assigned a new permanent URL."); - } - public HttpStatus movedTemporarily302() { - return new HttpStatus(302, "The requested resource has been temporarily moved to a different URL."); - } - public HttpStatus notModified304() { - return new HttpStatus(304, "The contents of the requested web page have not been modified since the last access."); - } - public HttpStatus temporaryRedirect307() { - return new HttpStatus(307, "The requested URL resides temporarily under a different URL"); - } - public HttpStatus permanentRedirect308() { - return new HttpStatus(308, "All future requests should be sent using a different URI."); - } - } - - // ---------------------------------------------------------------- 400 - - public static class HttpStatus400 extends HttpStatus { - - public HttpStatus400() { - super(400); - } - public HttpStatus400 badContent() { - message = "The content type of the request data or the content type of a" + - " part of a multipart request is not supported."; - return this; - } - public HttpStatus400 badRequest() { - message = "The API request is invalid or improperly formed."; - return this; - } - public HttpStatus400 exists() { - message = "Resource already exists."; - return this; - } - public HttpStatus400 invalidDocumentValue() { - message = "The request failed because it contained an invalid parameter or" + - " parameter value for the document. Review the API" + - " documentation to determine which parameters are valid for" + - " your request."; - return this; - } - public HttpStatus400 invalidQuery() { - message = "The request is invalid. Check the API documentation to determine" + - " what parameters are supported for the request and to see if" + - " the request contains an invalid combination of parameters" + - " or an invalid parameter value."; - return this; - } - public HttpStatus400 keyExpired() { - message = "The API key provided in the request is invalid, which means the" + - " API server is unable to make the request."; - return this; - } - public HttpStatus400 required() { - message = "The API request is missing required information. The required" + - " information could be a parameter or resource property."; - return this; - } - public HttpStatus400 validationError() { - message = "Validation of input failed."; - return this; - } - } - - // ---------------------------------------------------------------- 401 - - public static class HttpStatus401 extends HttpStatus { - public HttpStatus401() { - super(401); - } - - public HttpStatus401 unauthorized(String message) { - message = "Access is denied due to invalid credentials."; - return this; - } - } - - // ---------------------------------------------------------------- 403 - - public static class HttpStatus403 extends HttpStatus { - public HttpStatus403() { - super(403); - } - - public HttpStatus403 corsRequestOrigin() { - message = "The CORS request is from an unknown origin."; - return this; - } - - public HttpStatus403 forbidden() { - message = "The requested operation is forbidden and cannot be completed."; - return this; - } - public HttpStatus403 limitExceeded() { - message = "The request cannot be completed due to access or rate limitations."; - return this; - } - public HttpStatus403 quotaExceeded() { - message = "The requested operation requires more resources than the quota" + - " allows."; - return this; - } - public HttpStatus403 rateLimitExceeded() { - message = "Too many requests have been sent within a given time span."; - return this; - } - public HttpStatus403 responseTooLarge() { - message = "The requested resource is too large to return."; - return this; - } - public HttpStatus403 unknownAuth() { - message = "The API server does not recognize the authorization scheme used" + - " for the request."; - return this; - } - } - - // ---------------------------------------------------------------- 404 - - public static class HttpStatus404 extends HttpStatus { - public HttpStatus404() { - super(404); - } - - public HttpStatus404 notFound() { - message = "The requested operation failed because a resource associated" + - " with the request could not be found."; - return this; - } - public HttpStatus404 unsupportedProtocol() { - message = "The protocol used in the request is not supported."; - return this; - } - } - - // ---------------------------------------------------------------- 405 - - public static class HttpStatus405 extends HttpStatus { - public HttpStatus405() { - super(405); - } - - public HttpStatus405 httpMethodNotAllowed() { - message = "The HTTP method associated with the request is not supported."; - return this; - } - } - - // ---------------------------------------------------------------- 408 - - public static class HttpStatus408 extends HttpStatus { - public HttpStatus408() { - super(408); - } - - public HttpStatus408 requestTimeout() { - message = "The server did not produce a response within the time that the " + - "server was prepared to wait."; - return this; - } - } - - // ---------------------------------------------------------------- 409 - - public static class HttpStatus409 extends HttpStatus { - public HttpStatus409() { - super(409); - } - - public HttpStatus409 conflict() { - message = "Indicates that the request could not be processed because of " + - "conflict in the request, such as an edit conflict between " + - "multiple simultaneous updates."; - return this; - } - } - - // ---------------------------------------------------------------- 500 - - public static class HttpStatus500 extends HttpStatus { - public HttpStatus500() { - super(500); - } - - public HttpStatus500 internalError() { - message = "The request failed due to an internal error."; - return this; - } - } - - // ---------------------------------------------------------------- 503 - - public static class HttpStatus503 extends HttpStatus { - public HttpStatus503() { - super(503); - } - - public HttpStatus503 serviceUnavailable() { - message = "The server is currently unavailable (because it is overloaded or down for maintenance)."; - return this; - } - } - - // ---------------------------------------------------------------- static - - public static HttpStatus of(final int status, final String message) { - return new HttpStatus(status, message); - } - - public static HttpStatus ok() { - return new HttpStatus(200, "OK"); - } - - public static Redirection redirection() { - return Redirection.instance; - } - - public static HttpStatus400 error400() { - return new HttpStatus400(); - } - public static HttpStatus401 error401() { - return new HttpStatus401(); - } - public static HttpStatus403 error403() { - return new HttpStatus403(); - } - public static HttpStatus404 error404() { - return new HttpStatus404(); - } - public static HttpStatus405 error405() { - return new HttpStatus405(); - } - public static HttpStatus408 error408() { - return new HttpStatus408(); - } - public static HttpStatus409 error409() { - return new HttpStatus409(); - } - public static HttpStatus500 error500() { - return new HttpStatus500(); - } - public static HttpStatus503 error503() { - return new HttpStatus503(); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/net/MimeTypes.java b/fine-jodd/src/main/java/com/fr/third/jodd/net/MimeTypes.java deleted file mode 100644 index 44802fd2f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/net/MimeTypes.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.net; - -import com.fr.third.jodd.io.StreamUtil; -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.StringUtil; -import com.fr.third.jodd.util.Wildcard; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Properties; - -/** - * Map file extensions to MIME types. Based on the most recent Apache mime.types file. - * Duplicated extensions (wmz, sub) are manually resolved. - *

- * See also: - * http://www.iana.org/assignments/media-types/ - * http://www.webmaster-toolkit.com/mime-types.shtml - */ -public class MimeTypes { - - public static final String MIME_APPLICATION_ATOM_XML = "application/atom+xml"; - public static final String MIME_APPLICATION_JAVASCRIPT = "application/javascript"; - public static final String MIME_APPLICATION_JSON = "application/json"; - public static final String MIME_APPLICATION_OCTET_STREAM = "application/octet-stream"; - public static final String MIME_APPLICATION_XML = "application/xml"; - public static final String MIME_TEXT_CSS = "text/css"; - public static final String MIME_TEXT_PLAIN = "text/plain"; - public static final String MIME_TEXT_HTML = "text/html"; - - private static final LinkedHashMap MIME_TYPE_MAP; // extension -> mime-type map - - static { - final Properties mimes = new Properties(); - - final InputStream is = MimeTypes.class.getResourceAsStream(MimeTypes.class.getSimpleName() + ".properties"); - if (is == null) { - throw new IllegalStateException("Mime types file missing"); - } - - try { - mimes.load(is); - } - catch (IOException ioex) { - throw new IllegalStateException("Can't load properties", ioex); - } finally { - StreamUtil.close(is); - } - - MIME_TYPE_MAP = new LinkedHashMap<>(mimes.size() * 2); - - final Enumeration keys = mimes.propertyNames(); - while (keys.hasMoreElements()) { - String mimeType = (String) keys.nextElement(); - final String extensions = mimes.getProperty(mimeType); - - if (mimeType.startsWith("/")) { - mimeType = "application" + mimeType; - } else if (mimeType.startsWith("a/")) { - mimeType = "audio" + mimeType.substring(1); - } else if (mimeType.startsWith("i/")) { - mimeType = "image" + mimeType.substring(1); - } else if (mimeType.startsWith("t/")) { - mimeType = "text" + mimeType.substring(1); - } else if (mimeType.startsWith("v/")) { - mimeType = "video" + mimeType.substring(1); - } - - final String[] allExtensions = StringUtil.splitc(extensions, ' '); - - for (final String extension : allExtensions) { - if (MIME_TYPE_MAP.put(extension, mimeType) != null) { - throw new IllegalArgumentException("Duplicated extension: " + extension); - } - } - } - } - - /** - * Registers MIME type for provided extension. Existing extension type will be overridden. - */ - public static void registerMimeType(final String ext, final String mimeType) { - MIME_TYPE_MAP.put(ext, mimeType); - } - - /** - * Returns the corresponding MIME type to the given extension. - * If no MIME type was found it returns application/octet-stream type. - */ - public static String getMimeType(final String ext) { - String mimeType = lookupMimeType(ext); - if (mimeType == null) { - mimeType = MIME_APPLICATION_OCTET_STREAM; - } - return mimeType; - } - - /** - * Simply returns MIME type or null if no type is found. - */ - public static String lookupMimeType(final String ext) { - return MIME_TYPE_MAP.get(ext.toLowerCase()); - } - - /** - * Finds all extensions that belong to given mime type(s). - * If wildcard mode is on, provided mime type is wildcard pattern. - * @param mimeType list of mime types, separated by comma - * @param useWildcard if set, mime types are wildcard patterns - */ - public static String[] findExtensionsByMimeTypes(String mimeType, final boolean useWildcard) { - final ArrayList extensions = new ArrayList<>(); - - mimeType = mimeType.toLowerCase(); - final String[] mimeTypes = StringUtil.splitc(mimeType, ", "); - - for (final Map.Entry entry : MIME_TYPE_MAP.entrySet()) { - final String entryExtension = entry.getKey(); - final String entryMimeType = entry.getValue().toLowerCase(); - - final int matchResult = useWildcard ? - Wildcard.matchOne(entryMimeType, mimeTypes) : - StringUtil.equalsOne(entryMimeType, mimeTypes); - - if (matchResult != -1) { - extensions.add(entryExtension); - } - } - - if (extensions.isEmpty()) { - return StringPool.EMPTY_ARRAY; - } - - return extensions.toArray(new String[0]); - } - - /** - * Returns {@code true} if given value is one of the registered MIME extensions. - */ - public static boolean isRegisteredExtension(final String extension) { - return MIME_TYPE_MAP.containsKey(extension); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/net/URLCoder.java b/fine-jodd/src/main/java/com/fr/third/jodd/net/URLCoder.java deleted file mode 100644 index fae47414c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/net/URLCoder.java +++ /dev/null @@ -1,511 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.net; - -import com.fr.third.jodd.core.JoddCore; -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.StringUtil; - -import java.io.ByteArrayOutputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.fr.third.jodd.util.CharUtil.isAlpha; -import static com.fr.third.jodd.util.CharUtil.isDigit; -import static com.fr.third.jodd.util.CharUtil.isPchar; -import static com.fr.third.jodd.util.CharUtil.isSubDelimiter; -import static com.fr.third.jodd.util.CharUtil.isUnreserved; - -/** - * Encodes URLs correctly, significantly faster and more convenient. - *

- * Here is an example of full URL: - * {@literal https://jodd:ddoj@www.jodd.org:8080/file;p=1?q=2#third}. - * It consist of: - *

    - *
  • scheme (https)
  • - *
  • user (jodd)
  • - *
  • password (ddoj)
  • - *
  • host (www.jodd.org)
  • - *
  • port (8080)
  • - *
  • path (file)
  • - *
  • path parameter (p=1)
  • - *
  • query parameter (q=2)
  • - *
  • fragment (third)
  • - *
- * Each URL part has its own encoding rules. The only correct way of - * encoding URLs is to encode each part separately, and then to concatenate - * results. For easier query building you can use {@link #build(String) builder}. - * It provides fluent interface for defining query parameters. - */ -public class URLCoder { - - private static final String SCHEME_PATTERN = "([^:/?#]+):"; - - private static final String HTTP_PATTERN = "(http|https):"; - - private static final String USERINFO_PATTERN = "([^@/]*)"; - - private static final String HOST_PATTERN = "([^/?#:]*)"; - - private static final String PORT_PATTERN = "(\\d*)"; - - private static final String PATH_PATTERN = "([^?#]*)"; - - private static final String QUERY_PATTERN = "([^#]*)"; - - private static final String LAST_PATTERN = "(.*)"; - - // Regex patterns that matches URIs. See RFC 3986, appendix B - - private static final Pattern URI_PATTERN = Pattern.compile( - "^(" + SCHEME_PATTERN + ")?" + "(//(" + USERINFO_PATTERN + "@)?" + HOST_PATTERN + "(:" + PORT_PATTERN + - ")?" + ")?" + PATH_PATTERN + "(\\?" + QUERY_PATTERN + ")?" + "(#" + LAST_PATTERN + ")?"); - - private static final Pattern HTTP_URL_PATTERN = Pattern.compile( - '^' + HTTP_PATTERN + "(//(" + USERINFO_PATTERN + "@)?" + HOST_PATTERN + "(:" + PORT_PATTERN + ")?" + ")?" + - PATH_PATTERN + "(\\?" + LAST_PATTERN + ")?"); - - /** - * Enumeration to identify the parts of a URI. - *

- * Contains methods to indicate whether a given character is valid in a specific URI component. - * - * @see RFC 3986 - */ - enum URIPart { - - UNRESERVED { - @Override - public boolean isValid(final char c) { - return isUnreserved(c); - } - }, - - SCHEME { - @Override - public boolean isValid(final char c) { - return isAlpha(c) || isDigit(c) || c == '+' || c == '-' || c == '.'; - } - }, -// AUTHORITY { -// @Override -// public boolean isValid(char c) { -// return isUnreserved(c) || isSubDelimiter(c) || c == ':' || c == '@'; -// } -// }, - USER_INFO { - @Override - public boolean isValid(final char c) { - return isUnreserved(c) || isSubDelimiter(c) || c == ':'; - } - }, - HOST { - @Override - public boolean isValid(final char c) { - return isUnreserved(c) || isSubDelimiter(c); - } - }, - PORT { - @Override - public boolean isValid(final char c) { - return isDigit(c); - } - }, - PATH { - @Override - public boolean isValid(final char c) { - return isPchar(c) || c == '/'; - } - }, - PATH_SEGMENT { - @Override - public boolean isValid(final char c) { - return isPchar(c); - } - }, - QUERY { - @Override - public boolean isValid(final char c) { - return isPchar(c) || c == '/' || c == '?'; - } - }, - QUERY_PARAM { - @Override - public boolean isValid(final char c) { - if (c == '=' || c == '+' || c == '&' || c == ';') { - return false; - } - return isPchar(c) || c == '/' || c == '?'; - } - }, - FRAGMENT { - @Override - public boolean isValid(final char c) { - return isPchar(c) || c == '/' || c == '?'; - } - }; - - /** - * Indicates whether the given character is allowed in this URI component. - * - * @return true if the character is allowed; {@code false} otherwise - */ - public abstract boolean isValid(char c); - - } - - - // ---------------------------------------------------------------- util methods - - /** - * Encodes single URI component. - */ - private static String encodeUriComponent(final String source, final String encoding, final URIPart uriPart) { - if (source == null) { - return null; - } - - byte[] bytes = encodeBytes(StringUtil.getBytes(source, encoding), uriPart); - - char[] chars = new char[bytes.length]; - for (int i = 0; i < bytes.length; i++) { - chars[i] = (char) bytes[i]; - } - return new String(chars); - } - - /** - * Encodes byte array using allowed characters from {@link URIPart}. - */ - private static byte[] encodeBytes(final byte[] source, final URIPart uriPart) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length); - for (byte b : source) { - if (b < 0) { - b += 256; - } - if (uriPart.isValid((char) b)) { - bos.write(b); - } else { - bos.write('%'); - char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)); - char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16)); - bos.write(hex1); - bos.write(hex2); - } - } - return bos.toByteArray(); - } - - // ---------------------------------------------------------------- main methods - - /** - * Encodes string using default RFCP rules. - */ - public static String encode(final String string, final String encoding) { - return encodeUriComponent(string, encoding, URIPart.UNRESERVED); - } - public static String encode(final String string) { - return encodeUriComponent(string, JoddCore.encoding, URIPart.UNRESERVED); - } - - /** - * Encodes the given URI scheme with the given encoding. - */ - public static String encodeScheme(final String scheme, final String encoding) { - return encodeUriComponent(scheme, encoding, URIPart.SCHEME); - } - public static String encodeScheme(final String scheme) { - return encodeUriComponent(scheme, JoddCore.encoding, URIPart.SCHEME); - } - -/* /** - * Encodes the given URI authority with the given encoding. - * - - public static String encodeAuthority(String authority, String encoding) { - return encodeUriComponent(authority, encoding, URIPart.AUTHORITY); - } - public static String encodeAuthority(String authority) { - return encodeUriComponent(authority, JoddCore.encoding, URIPart.AUTHORITY); - } -*/ - - /** - * Encodes the given URI user info with the given encoding. - */ - public static String encodeUserInfo(final String userInfo, final String encoding) { - return encodeUriComponent(userInfo, encoding, URIPart.USER_INFO); - } - public static String encodeUserInfo(final String userInfo) { - return encodeUriComponent(userInfo, JoddCore.encoding, URIPart.USER_INFO); - } - - /** - * Encodes the given URI host with the given encoding. - */ - public static String encodeHost(final String host, final String encoding) { - return encodeUriComponent(host, encoding, URIPart.HOST); - } - public static String encodeHost(final String host) { - return encodeUriComponent(host, JoddCore.encoding, URIPart.HOST); - } - - /** - * Encodes the given URI port with the given encoding. - */ - public static String encodePort(final String port, final String encoding) { - return encodeUriComponent(port, encoding, URIPart.PORT); - } - public static String encodePort(final String port) { - return encodeUriComponent(port, JoddCore.encoding, URIPart.PORT); - } - - /** - * Encodes the given URI path with the given encoding. - */ - public static String encodePath(final String path, final String encoding) { - return encodeUriComponent(path, encoding, URIPart.PATH); - } - public static String encodePath(final String path) { - return encodeUriComponent(path, JoddCore.encoding, URIPart.PATH); - } - - /** - * Encodes the given URI path segment with the given encoding. - */ - public static String encodePathSegment(final String segment, final String encoding) { - return encodeUriComponent(segment, encoding, URIPart.PATH_SEGMENT); - } - public static String encodePathSegment(final String segment) { - return encodeUriComponent(segment, JoddCore.encoding, URIPart.PATH_SEGMENT); - } - - /** - * Encodes the given URI query with the given encoding. - */ - public static String encodeQuery(final String query, final String encoding) { - return encodeUriComponent(query, encoding, URIPart.QUERY); - } - public static String encodeQuery(final String query) { - return encodeUriComponent(query, JoddCore.encoding, URIPart.QUERY); - } - - /** - * Encodes the given URI query parameter with the given encoding. - */ - public static String encodeQueryParam(final String queryParam, final String encoding) { - return encodeUriComponent(queryParam, encoding, URIPart.QUERY_PARAM); - } - public static String encodeQueryParam(final String queryParam) { - return encodeUriComponent(queryParam, JoddCore.encoding, URIPart.QUERY_PARAM); - } - - /** - * Encodes the given URI fragment with the given encoding. - */ - public static String encodeFragment(final String fragment, final String encoding) { - return encodeUriComponent(fragment, encoding, URIPart.FRAGMENT); - } - public static String encodeFragment(final String fragment) { - return encodeUriComponent(fragment, JoddCore.encoding, URIPart.FRAGMENT); - } - - - // ---------------------------------------------------------------- url - - /** - * @see #encodeUri(String, String) - */ - public static String encodeUri(final String uri) { - return encodeUri(uri, JoddCore.encoding); - } - /** - * Encodes the given source URI into an encoded String. All various URI components are - * encoded according to their respective valid character sets. - *

This method does not attempt to encode "=" and "{@literal &}" - * characters in query parameter names and query parameter values because they cannot - * be parsed in a reliable way. - */ - public static String encodeUri(final String uri, final String encoding) { - Matcher m = URI_PATTERN.matcher(uri); - if (m.matches()) { - String scheme = m.group(2); - String authority = m.group(3); - String userinfo = m.group(5); - String host = m.group(6); - String port = m.group(8); - String path = m.group(9); - String query = m.group(11); - String fragment = m.group(13); - - return encodeUriComponents(scheme, authority, userinfo, host, port, path, query, fragment, encoding); - } - throw new IllegalArgumentException("Invalid URI: " + uri); - } - - /** - * @see #encodeHttpUrl(String, String) - */ - public static String encodeHttpUrl(final String httpUrl) { - return encodeHttpUrl(httpUrl, JoddCore.encoding); - } - /** - * Encodes the given HTTP URI into an encoded String. All various URI components are - * encoded according to their respective valid character sets. - *

This method does not support fragments ({@code #}), - * as these are not supposed to be sent to the server, but retained by the client. - *

This method does not attempt to encode "=" and "{@literal &}" - * characters in query parameter names and query parameter values because they cannot - * be parsed in a reliable way. - */ - public static String encodeHttpUrl(final String httpUrl, final String encoding) { - Matcher m = HTTP_URL_PATTERN.matcher(httpUrl); - if (m.matches()) { - String scheme = m.group(1); - String authority = m.group(2); - String userinfo = m.group(4); - String host = m.group(5); - String portString = m.group(7); - String path = m.group(8); - String query = m.group(10); - - return encodeUriComponents(scheme, authority, userinfo, host, portString, path, query, null, encoding); - } - throw new IllegalArgumentException("Invalid HTTP URL: " + httpUrl); - } - - private static String encodeUriComponents( - final String scheme, final String authority, final String userInfo, - final String host, final String port, final String path, final String query, - final String fragment, final String encoding) { - - StringBuilder sb = new StringBuilder(); - - if (scheme != null) { - sb.append(encodeScheme(scheme, encoding)); - sb.append(':'); - } - - if (authority != null) { - sb.append("//"); - if (userInfo != null) { - sb.append(encodeUserInfo(userInfo, encoding)); - sb.append('@'); - } - if (host != null) { - sb.append(encodeHost(host, encoding)); - } - if (port != null) { - sb.append(':'); - sb.append(encodePort(port, encoding)); - } - } - - sb.append(encodePath(path, encoding)); - - if (query != null) { - sb.append('?'); - sb.append(encodeQuery(query, encoding)); - } - - if (fragment != null) { - sb.append('#'); - sb.append(encodeFragment(fragment, encoding)); - } - - return sb.toString(); - } - - // ---------------------------------------------------------------- builder - - /** - * Creates URL builder for user-friendly way of building URLs. - * Provided path is parsed and {@link #encodeUri(String) encoded}. - * @see #build(String, boolean) - */ - public static Builder build(final String path) { - return build(path, true); - } - - /** - * Creates URL builder with given path that can be optionally encoded. - * Since most of the time path is valid and does not require to be encoded, - * use this method to gain some performance. When encoding flag is turned off, - * provided path is used without processing. - *

- * The purpose of builder is to help with query parameters. All other URI parts - * should be set previously or after the URL is built. - */ - public static Builder build(final String path, final boolean encodePath) { - return new Builder(path, encodePath, JoddCore.encoding); - } - - public static class Builder { - protected final StringBuilder url; - protected final String encoding; - protected boolean hasParams; - - public Builder(final String path, final boolean encodePath, final String encoding) { - this.encoding = encoding; - url = new StringBuilder(); - if (encodePath) { - url.append(encodeUri(path, encoding)); - } else { - url.append(path); - } - this.hasParams = url.indexOf(StringPool.QUESTION_MARK) != -1; - } - - public Builder queryParam(final String name, final Object value) { - return queryParam(name, value.toString()); - } - - /** - * Appends new query parameter to the url. - */ - public Builder queryParam(final String name, final String value) { - url.append(hasParams ? '&' : '?'); - hasParams = true; - - url.append(encodeQueryParam(name, encoding)); - - if ((value != null) && (value.length() > 0)) { - url.append('='); - url.append(encodeQueryParam(value, encoding)); - } - return this; - } - - /** - * Returns full URL. - */ - public String get() { - return url.toString(); - } - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/net/URLDecoder.java b/fine-jodd/src/main/java/com/fr/third/jodd/net/URLDecoder.java deleted file mode 100644 index 41f48f9e5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/net/URLDecoder.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.net; - -import com.fr.third.jodd.core.JoddCore; -import com.fr.third.jodd.util.StringUtil; - -import java.io.ByteArrayOutputStream; - -/** - * URL decoder. - */ -public class URLDecoder { - - /** - * Decodes URL elements. - */ - public static String decode(final String url) { - return decode(url, JoddCore.encoding, false); - } - - /** - * Decodes URL elements. This method may be used for all - * parts of URL, except for the query parts, since it does - * not decode the '+' character. - * @see #decodeQuery(String, String) - */ - public static String decode(final String source, final String encoding) { - return decode(source, encoding, false); - } - - /** - * Decodes query name or value. - */ - public static String decodeQuery(final String source) { - return decode(source, JoddCore.encoding, true); - } - - /** - * Decodes query name or value. - */ - public static String decodeQuery(final String source, final String encoding) { - return decode(source, encoding, true); - } - - private static String decode(final String source, final String encoding, final boolean decodePlus) { - int length = source.length(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(length); - - boolean changed = false; - - for (int i = 0; i < length; i++) { - int ch = source.charAt(i); - switch (ch) { - case '%': - if ((i + 2) < length) { - char hex1 = source.charAt(i + 1); - char hex2 = source.charAt(i + 2); - int u = Character.digit(hex1, 16); - int l = Character.digit(hex2, 16); - if (u == -1 || l == -1) { - throw new IllegalArgumentException("Invalid sequence: " + source.substring(i)); - } - bos.write((char) ((u << 4) + l)); - i += 2; - changed = true; - } else { - throw new IllegalArgumentException("Invalid sequence: " + source.substring(i)); - } - break; - - case '+': - if (decodePlus) { - ch = ' '; - changed = true; - } - - default: - bos.write(ch); - } - } - return changed ? StringUtil.newString(bos.toByteArray(), encoding) : source; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/package-info.java deleted file mode 100644 index 67475e62b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Jodd = tools + ioc + mvc + db + aop + tx + json + html {@literal <} 1.7Mb - */ -package com.fr.third.jodd; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/HostInfo.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/HostInfo.java deleted file mode 100644 index 8250563ed..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/HostInfo.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - -import java.io.File; -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * Host information. - */ -abstract class HostInfo { - - /** - * Delegate host info to be resolved lazy. - * Android detection will initialize this class too and since {@code InetAddress.getLocalHost()} - * is forbidden in Android, we will get an exception. - */ - private static class HostInfoLazy { - private final String HOST_NAME; - private final String HOST_ADDRESS; - - public HostInfoLazy() { - String hostName; - String hostAddress; - - try { - final InetAddress localhost = InetAddress.getLocalHost(); - - hostName = localhost.getHostName(); - hostAddress = localhost.getHostAddress(); - } catch (final UnknownHostException uhex) { - hostName = "localhost"; - hostAddress = "127.0.0.1"; - } - - this.HOST_NAME = hostName; - this.HOST_ADDRESS = hostAddress; - } - } - - private static HostInfoLazy hostInfoLazy; - - /** - * Returns host name. - */ - public final String getHostName() { - if (hostInfoLazy == null) { - hostInfoLazy = new HostInfoLazy(); - } - return hostInfoLazy.HOST_NAME; - } - - /** - * Returns host IP address. - */ - public final String getHostAddress() { - if (hostInfoLazy == null) { - hostInfoLazy = new HostInfoLazy(); - } - return hostInfoLazy.HOST_ADDRESS; - } - - // ---------------------------------------------------------------- util - - protected String nosep(final String in) { - if (in.endsWith(File.separator)) { - return in.substring(0, in.length() - 1); - } - return in; - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/JavaInfo.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/JavaInfo.java deleted file mode 100644 index 3be8edcbb..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/JavaInfo.java +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - - -import java.util.ArrayList; - -abstract class JavaInfo extends HostInfo { - - private final String JAVA_VERSION = SystemUtil.get("java.version"); - private final int JAVA_VERSION_NUMBER = detectJavaVersionNumber(); - private final String JAVA_VENDOR = SystemUtil.get("java.vendor"); - private final String JAVA_VENDOR_URL = SystemUtil.get("java.vendor.url"); - private final String JAVA_SPECIFICATION_VERSION = SystemUtil.get("java.specification.version"); - private final String JAVA_SPECIFICATION_NAME = SystemUtil.get("java.specification.name"); - private final String JAVA_SPECIFICATION_VENDOR = SystemUtil.get("java.specification.vendor"); - private final String[] JRE_PACKAGES = buildJrePackages(JAVA_VERSION_NUMBER); - - /** - * Returns Java version string, as specified in system property. - * Returned string contain major version, minor version and revision. - */ - public String getJavaVersion() { - return JAVA_VERSION; - } - - /** - * Returns unified Java version as an integer. - */ - public int getJavaVersionNumber() { - return JAVA_VERSION_NUMBER; - } - - /** - * Returns Java vendor. - */ - public String getJavaVendor() { - return JAVA_VENDOR; - } - - /** - * Returns Java vendor URL. - */ - public String getJavaVendorURL() { - return JAVA_VENDOR_URL; - } - - /** - * Retrieves the version of the currently running JVM. - */ - public String getJavaSpecificationVersion() { - return JAVA_SPECIFICATION_VERSION; - } - - public final String getJavaSpecificationName() { - return JAVA_SPECIFICATION_NAME; - } - - public final String getJavaSpecificationVendor() { - return JAVA_SPECIFICATION_VENDOR; - } - - // ---------------------------------------------------------------- packages - - /** - * Returns list of packages, build into runtime jars. - */ - public String[] getJrePackages() { - return JRE_PACKAGES; - } - - /** - * Builds a set of java core packages. - */ - private String[] buildJrePackages(final int javaVersionNumber) { - final ArrayList packages = new ArrayList<>(); - - switch (javaVersionNumber) { - case 9: - case 8: - case 7: - case 6: - case 5: - // in Java1.5, the apache stuff moved - packages.add("com.sun.org.apache"); - // fall through... - case 4: - if (javaVersionNumber == 4) { - packages.add("org.apache.crimson"); - packages.add("org.apache.xalan"); - packages.add("org.apache.xml"); - packages.add("org.apache.xpath"); - } - packages.add("org.ietf.jgss"); - packages.add("org.w3c.dom"); - packages.add("org.xml.sax"); - // fall through... - case 3: - packages.add("org.omg"); - packages.add("com.sun.corba"); - packages.add("com.sun.jndi"); - packages.add("com.sun.media"); - packages.add("com.sun.naming"); - packages.add("com.sun.org.omg"); - packages.add("com.sun.rmi"); - packages.add("sunw.io"); - packages.add("sunw.util"); - // fall through... - case 2: - packages.add("com.sun.java"); - packages.add("com.sun.image"); - // fall through... - case 1: - default: - // core stuff - packages.add("sun"); - packages.add("java"); - packages.add("javax"); - break; - } - - return packages.toArray(new String[0]); - } - - - - // ---------------------------------------------------------------- java checks - - private int detectJavaVersionNumber() { - String javaVersion = JAVA_VERSION; - - final int lastDashNdx = javaVersion.lastIndexOf('-'); - if (lastDashNdx != -1) { - javaVersion = javaVersion.substring(0, lastDashNdx); - } - - if (javaVersion.startsWith("1.")) { - // up to java 8 - final int index = javaVersion.indexOf('.', 2); - return Integer.parseInt(javaVersion.substring(2, index)); - } else { - final int index = javaVersion.indexOf('.'); - return Integer.parseInt(index == -1 ? javaVersion : javaVersion.substring(0, index)); - } - } - - /** - * Checks if the currently running JVM is at least compliant - * with provided JDK version. - */ - public boolean isAtLeastJavaVersion(final int version) { - return JAVA_VERSION_NUMBER >= version; - } - - /** - * Checks if the currently running JVM is equal to provided version. - */ - public boolean isJavaVersion(final int version) { - return JAVA_VERSION_NUMBER == version; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/JvmInfo.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/JvmInfo.java deleted file mode 100644 index 71ccf7bb3..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/JvmInfo.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - -abstract class JvmInfo extends JavaInfo { - - private final String JAVA_VM_NAME = SystemUtil.get("java.vm.name"); - private final String JAVA_VM_VERSION = SystemUtil.get("java.vm.version"); - private final String JAVA_VM_VENDOR = SystemUtil.get("java.vm.vendor"); - private final String JAVA_VM_INFO = SystemUtil.get("java.vm.info"); - private final String JAVA_VM_SPECIFICATION_NAME = SystemUtil.get("java.vm.specification.name"); - private final String JAVA_VM_SPECIFICATION_VERSION = SystemUtil.get("java.vm.specification.version"); - private final String JAVA_VM_SPECIFICATION_VENDOR = SystemUtil.get("java.vm.specification.vendor"); - - /** - * Returns JVM name. - */ - public final String getJvmName() { - return JAVA_VM_NAME; - } - - /** - * Returns JVM version. - */ - public final String getJvmVersion() { - return JAVA_VM_VERSION; - } - - /** - * Returns VM vendor. - */ - public final String getJvmVendor() { - return JAVA_VM_VENDOR; - } - - /** - * Returns additional VM information. - */ - public final String getJvmInfo() { - return JAVA_VM_INFO; - } - - public final String getJvmSpecificationName() { - return JAVA_VM_SPECIFICATION_NAME; - } - - public final String getJvmSpecificationVersion() { - return JAVA_VM_SPECIFICATION_VERSION; - } - - public final String getJvmSpecificationVendor() { - return JAVA_VM_SPECIFICATION_VENDOR; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/OsInfo.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/OsInfo.java deleted file mode 100644 index b654b4623..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/OsInfo.java +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - -import com.fr.third.jodd.util.ClassLoaderUtil; - -abstract class OsInfo extends JvmInfo { - - private final String OS_VERSION = SystemUtil.get("os.version"); - private final String OS_ARCH = SystemUtil.get("os.arch"); - private final String OS_NAME = SystemUtil.get("os.name"); - - private final boolean IS_ANDROID = isAndroid0(); - private final boolean IS_OS_AIX = matchOS("AIX"); - private final boolean IS_OS_HP_UX = matchOS("HP-UX"); - private final boolean IS_OS_IRIX = matchOS("Irix"); - private final boolean IS_OS_LINUX = matchOS("Linux") || matchOS("LINUX"); - private final boolean IS_OS_MAC = matchOS("Mac"); - private final boolean IS_OS_MAC_OSX = matchOS("Mac OS X"); - private final boolean IS_OS_OS2 = matchOS("OS/2"); - private final boolean IS_OS_SOLARIS = matchOS("Solaris"); - private final boolean IS_OS_SUN_OS = matchOS("SunOS"); - private final boolean IS_OS_WINDOWS = matchOS("Windows"); - private final boolean IS_OS_WINDOWS_2000 = matchOS("Windows", "5.0"); - private final boolean IS_OS_WINDOWS_95 = matchOS("Windows 9", "4.0"); - private final boolean IS_OS_WINDOWS_98 = matchOS("Windows 9", "4.1"); - private final boolean IS_OS_WINDOWS_ME = matchOS("Windows", "4.9"); - private final boolean IS_OS_WINDOWS_NT = matchOS("Windows NT"); - private final boolean IS_OS_WINDOWS_XP = matchOS("Windows", "5.1"); - - private final String FILE_SEPARATOR = SystemUtil.get("file.separator"); - private final String LINE_SEPARATOR = SystemUtil.get("line.separator"); - private final String PATH_SEPARATOR = SystemUtil.get("path.separator"); - private final String FILE_ENCODING = SystemUtil.get("file.encoding"); - - public final String getOsArchitecture() { - return OS_ARCH; - } - - public final String getOsName() { - return OS_NAME; - } - - public final String getOsVersion() { - return OS_VERSION; - } - - /** - * Returns true if system is android. - */ - public boolean isAndroid() { - return IS_ANDROID; - } - - private static boolean isAndroid0() { - try { - Class.forName("android.app.Application", false, ClassLoaderUtil.getSystemClassLoader()); - return true; - } catch (Exception e) { - return false; - } - } - - - public final boolean isAix() { - return IS_OS_AIX; - } - - public final boolean isHpUx() { - return IS_OS_HP_UX; - } - - public final boolean isIrix() { - return IS_OS_IRIX; - } - - public final boolean isLinux() { - return IS_OS_LINUX; - } - - public final boolean isMac() { - return IS_OS_MAC; - } - - public final boolean isMacOsX() { - return IS_OS_MAC_OSX; - } - - public final boolean isOs2() { - return IS_OS_OS2; - } - - public final boolean isSolaris() { - return IS_OS_SOLARIS; - } - - public final boolean isSunOS() { - return IS_OS_SUN_OS; - } - - public final boolean isWindows() { - return IS_OS_WINDOWS; - } - - public final boolean isWindows2000() { - return IS_OS_WINDOWS_2000; - } - - public final boolean isWindows95() { - return IS_OS_WINDOWS_95; - } - - public final boolean isWindows98() { - return IS_OS_WINDOWS_98; - } - - public final boolean isWindowsME() { - return IS_OS_WINDOWS_ME; - } - - public final boolean isWindowsNT() { - return IS_OS_WINDOWS_NT; - } - - public final boolean isWindowsXP() { - return IS_OS_WINDOWS_XP; - } - - // ---------------------------------------------------------------- file - - public final String getFileSeparator() { - return FILE_SEPARATOR; - } - - public final String getLineSeparator() { - return LINE_SEPARATOR; - } - - public final String getPathSeparator() { - return PATH_SEPARATOR; - } - - public final String getFileEncoding() { - return FILE_ENCODING; - } - - // ---------------------------------------------------------------- util - - private boolean matchOS(final String osNamePrefix) { - if (OS_NAME == null) { - return false; - } - - return OS_NAME.startsWith(osNamePrefix); - } - - private boolean matchOS(final String osNamePrefix, final String osVersionPrefix) { - if ((OS_NAME == null) || (OS_VERSION == null)) { - return false; - } - - return OS_NAME.startsWith(osNamePrefix) && OS_VERSION.startsWith(osVersionPrefix); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/RuntimeInfo.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/RuntimeInfo.java deleted file mode 100644 index 55dafd308..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/RuntimeInfo.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - -import java.lang.management.ManagementFactory; - -abstract class RuntimeInfo extends OsInfo { - - private final Runtime runtime = Runtime.getRuntime(); - - /** - * Returns MAX memory. - */ - public final long getMaxMemory(){ - return runtime.maxMemory(); - } - - /** - * Returns TOTAL memory. - */ - public final long getTotalMemory(){ - return runtime.totalMemory(); - } - - /** - * Returns FREE memory. - */ - public final long getFreeMemory(){ - return runtime.freeMemory(); - } - - /** - * Returns usable memory. - */ - public final long getAvailableMemory(){ - return runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory(); - } - - /** - * Returns used memory. - */ - public final long getUsedMemory(){ - return runtime.totalMemory() - runtime.freeMemory(); - } - - /** - * Returns PID of current Java process. - */ - public final long getCurrentPID() { - return Long.parseLong(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]); - } - - /** - * Returns number of CPUs. - */ - public final long getCPUs() { - return runtime.availableProcessors(); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/SystemInfo.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/SystemInfo.java deleted file mode 100644 index 157f3f487..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/SystemInfo.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - -public final class SystemInfo extends UserInfo { -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/SystemUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/SystemUtil.java deleted file mode 100644 index 2713871f3..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/SystemUtil.java +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Objects; - -public class SystemUtil { - - /** - * Returns system property or {@code null} if not set. - */ - public static String get(final String name) { - return get(name, null); - } - - /** - * Returns system property. If key is not available, returns the default value. - */ - public static String get(final String name, final String defaultValue) { - Objects.requireNonNull(name); - - String value = null; - try { - if (System.getSecurityManager() == null) { - value = System.getProperty(name); - } else { - value = AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(name)); - } - } catch (final Exception ignore) { - } - - if (value == null) { - return defaultValue; - } - - return value; - } - - /** - * Returns system property as boolean. - */ - public static boolean getBoolean(final String name, final boolean defaultValue) { - String value = get(name); - if (value == null) { - return defaultValue; - } - - value = value.trim().toLowerCase(); - - switch (value) { - case "true" : - case "yes" : - case "1" : - case "on" : - return true; - case "false": - case "no" : - case "0" : - case "off" : - return false; - default: - return defaultValue; - } - } - - /** - * Returns system property as an int. - */ - public static long getInt(final String name, final int defaultValue) { - String value = get(name); - if (value == null) { - return defaultValue; - } - - value = value.trim().toLowerCase(); - try { - return Integer.parseInt(value); - } - catch (final NumberFormatException nfex) { - return defaultValue; - } - } - - /** - * Returns system property as a long. - */ - public static long getLong(final String name, final long defaultValue) { - String value = get(name); - if (value == null) { - return defaultValue; - } - - value = value.trim().toLowerCase(); - try { - return Long.parseLong(value); - } - catch (final NumberFormatException nfex) { - return defaultValue; - } - } - - // ---------------------------------------------------------------- infos - - private static final SystemInfo systemInfo = new SystemInfo(); - - /** - * Returns system information. - */ - public static SystemInfo info() { - return systemInfo; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/UserInfo.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/UserInfo.java deleted file mode 100644 index f081d0c9e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/UserInfo.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.system; - -import com.fr.third.jodd.util.StringUtil; - -import java.io.File; - -/** - * User information. - */ -abstract class UserInfo extends RuntimeInfo { - - private final String USER_NAME = SystemUtil.get("user.name"); - private final String USER_HOME = nosep(SystemUtil.get("user.home")); - private final String USER_DIR = nosep(SystemUtil.get("user.dir")); - private final String USER_LANGUAGE = SystemUtil.get("user.language"); - private final String USER_COUNTRY = ((SystemUtil.get("user.country") == null) ? SystemUtil.get("user.region") : SystemUtil.get("user.country")); - private final String JAVA_IO_TMPDIR = SystemUtil.get("java.io.tmpdir"); - private final String JAVA_HOME = nosep(SystemUtil.get("java.home")); - private final String[] SYSTEM_CLASS_PATH = StringUtil.splitc(SystemUtil.get("java.class.path"), File.pathSeparator); - - public final String getUserName() { - return USER_NAME; - } - - public final String getHomeDir() { - return USER_HOME; - } - - public final String getWorkingDir() { - return USER_DIR; - } - - public final String getTempDir() { - return JAVA_IO_TMPDIR; - } - - public final String getUserLanguage() { - return USER_LANGUAGE; - } - - public final String getUserCountry() { - return USER_COUNTRY; - } - - public String getJavaHomeDir() { - return JAVA_HOME; - } - - public String[] getSystemClasspath() { - return SYSTEM_CLASS_PATH; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/system/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/system/package-info.java deleted file mode 100644 index 14a01a5a6..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/system/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various system and runtime information in one or two friendly classes. - */ -package com.fr.third.jodd.system; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/template/ContextTemplateParser.java b/fine-jodd/src/main/java/com/fr/third/jodd/template/ContextTemplateParser.java deleted file mode 100644 index 015f2f92b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/template/ContextTemplateParser.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.template; - -import java.util.function.Function; - -/** - * Context withing string template parser operates. - * Curried version of {@link StringTemplateParser#parse(String, Function)} - */ -@FunctionalInterface -public interface ContextTemplateParser { - String parse(String template); -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/template/MapTemplateParser.java b/fine-jodd/src/main/java/com/fr/third/jodd/template/MapTemplateParser.java deleted file mode 100644 index c335414c5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/template/MapTemplateParser.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.template; - -import java.util.Map; - -public class MapTemplateParser extends StringTemplateParser { - - /** - * Creates new working template context of a map. - */ - public ContextTemplateParser of(final Map map) { - return template -> parseWithMap(template, map); - } - - public String parseWithMap(final String template, final Map map) { - return super.parse(template, macroName -> { - Object value = map.get(macroName); - if (value == null) { - return null; - } - return value.toString(); - }); - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/template/StringTemplateParser.java b/fine-jodd/src/main/java/com/fr/third/jodd/template/StringTemplateParser.java deleted file mode 100644 index e29b22024..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/template/StringTemplateParser.java +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.template; - -import com.fr.third.jodd.util.CharUtil; -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.StringUtil; - -import java.util.function.Function; - -/** - * Parser for string macro templates. On parsing, macro values - * in provided string are resolved and replaced with real values. - * Once set, one string template parser can be reused for parsing, - * even using different macro resolvers. - */ -public class StringTemplateParser { - - public static final String DEFAULT_MACRO_PREFIX = "$"; - public static final String DEFAULT_MACRO_START = "${"; - public static final String DEFAULT_MACRO_END = "}"; - - // ---------------------------------------------------------------- properties - - protected boolean replaceMissingKey = true; - protected String missingKeyReplacement; - protected boolean resolveEscapes = true; - protected String macroPrefix = DEFAULT_MACRO_PREFIX; - protected String macroStart = DEFAULT_MACRO_START; - protected String macroEnd = DEFAULT_MACRO_END; - protected char escapeChar = '\\'; - protected boolean parseValues; - - /** - * Specifies if missing keys should be resolved at all, - * true by default. - * If false missing keys will be left as it were, i.e. - * they will not be replaced. - */ - public StringTemplateParser setReplaceMissingKey(final boolean replaceMissingKey) { - this.replaceMissingKey = replaceMissingKey; - return this; - } - - /** - * Specifies replacement for missing keys. If null - * exception will be thrown. - */ - public StringTemplateParser setMissingKeyReplacement(final String missingKeyReplacement) { - this.missingKeyReplacement = missingKeyReplacement; - return this; - } - - /** - * Specifies if escaped values should be resolved. In special usecases, - * when the same string has to be processed more then once, - * this may be set to false so escaped values - * remains. - */ - public StringTemplateParser setResolveEscapes(final boolean resolveEscapes) { - this.resolveEscapes = resolveEscapes; - return this; - } - - /** - * Defines macro start string. - */ - public StringTemplateParser setMacroStart(final String macroStart) { - this.macroStart = macroStart; - return this; - } - - public StringTemplateParser setMacroPrefix(final String macroPrefix) { - this.macroPrefix = macroPrefix; - return this; - } - - - /** - * Defines macro end string. - */ - public StringTemplateParser setMacroEnd(final String macroEnd) { - this.macroEnd = macroEnd; - return this; - } - - /** - * Sets the strict format by setting the macro prefix to null. - */ - public StringTemplateParser setStrictFormat() { - macroPrefix = null; - return this; - } - - /** - * Defines escape character. - */ - public StringTemplateParser setEscapeChar(final char escapeChar) { - this.escapeChar = escapeChar; - return this; - } - - /** - * Defines if macro values has to be parsed, too. - * By default, macro values are returned as they are. - */ - public StringTemplateParser setParseValues(final boolean parseValues) { - this.parseValues = parseValues; - return this; - } - - - // ---------------------------------------------------------------- parse - - /** - * Parses string template and replaces macros with resolved values. - */ - public String parse(String template, final Function macroResolver) { - StringBuilder result = new StringBuilder(template.length()); - - int i = 0; - int len = template.length(); - - // strict flag means that start and end tag are not necessary - boolean strict; - - if (macroPrefix == null) { - // when prefix is not specified, make it equals to macro start - // so we can use the same code - macroPrefix = macroStart; - - strict = true; - } - else { - strict = false; - } - - final int prefixLen = macroPrefix.length(); - final int startLen = macroStart.length(); - final int endLen = macroEnd.length(); - - while (i < len) { - int ndx = template.indexOf(macroPrefix, i); - if (ndx == -1) { - result.append(i == 0 ? template : template.substring(i)); - break; - } - - // check escaped - int j = ndx - 1; - boolean escape = false; - int count = 0; - - while ((j >= 0) && (template.charAt(j) == escapeChar)) { - escape = !escape; - if (escape) { - count++; - } - j--; - } - if (resolveEscapes) { - result.append(template.substring(i, ndx - count)); - } else { - result.append(template.substring(i, ndx)); - } - if (escape) { - result.append(macroPrefix); - - i = ndx + prefixLen; - - continue; - } - - // macro started, detect strict format - - boolean detectedStrictFormat = strict; - - if (!detectedStrictFormat) { - if (StringUtil.isSubstringAt(template, macroStart, ndx)) { - detectedStrictFormat = true; - } - } - - int ndx1; - int ndx2; - - if (!detectedStrictFormat) { - // not strict format: $foo - - ndx += prefixLen; - ndx1 = ndx; - ndx2 = ndx; - - while ((ndx2 < len) && CharUtil.isPropertyNameChar(template.charAt(ndx2))) { - ndx2++; - } - - if (ndx2 == len) { - ndx2--; - } - - while ((ndx2 > ndx) && !CharUtil.isAlphaOrDigit(template.charAt(ndx2))) { - ndx2--; - } - - ndx2++; - - if (ndx2 == ndx1 + 1) { - // no value, hence no macro - result.append(macroPrefix); - - i = ndx1; - continue; - } - } - else { - // strict format: ${foo} - - // find macros end - ndx += startLen; - ndx2 = template.indexOf(macroEnd, ndx); - if (ndx2 == -1) { - throw new IllegalArgumentException("Invalid template, unclosed macro at: " + (ndx - startLen)); - } - - // detect inner macros, there is no escaping - ndx1 = ndx; - while (ndx1 < ndx2) { - int n = StringUtil.indexOf(template, macroStart, ndx1, ndx2); - if (n == -1) { - break; - } - ndx1 = n + startLen; - } - } - - final String name = template.substring(ndx1, ndx2); - - // find value and append - - Object value; - if (missingKeyReplacement != null || !replaceMissingKey) { - try { - value = macroResolver.apply(name); - } catch (Exception ignore) { - value = null; - } - - if (value == null) { - if (replaceMissingKey) { - value = missingKeyReplacement; - } else { - if (detectedStrictFormat) { - value = template.substring(ndx1 - startLen, ndx2 + endLen); - } else { - value = template.substring(ndx1 - 1, ndx2); - } - } - } - } else { - value = macroResolver.apply(name); - if (value == null) { - value = StringPool.EMPTY; - } - } - - if (ndx == ndx1) { - String stringValue = value.toString(); - if (parseValues) { - if (stringValue.contains(macroStart)) { - stringValue = parse(stringValue, macroResolver); - } - } - result.append(stringValue); - - i = ndx2; - if (detectedStrictFormat) { - i += endLen; - } - } else { - // inner macro - template = template.substring(0, ndx1 - startLen) + value.toString() + template.substring(ndx2 + endLen); - len = template.length(); - i = ndx - startLen; - } - } - return result.toString(); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/time/JulianDate.java b/fine-jodd/src/main/java/com/fr/third/jodd/time/JulianDate.java deleted file mode 100644 index d1998d69c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/time/JulianDate.java +++ /dev/null @@ -1,474 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.time; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Objects; - -import static com.fr.third.jodd.time.TimeUtil.MILLIS_IN_DAY; - -/** - * Julian Date stamp, for high precision calculations. Julian date is a real - * number and it basically consist of two parts: integer and fraction. Integer - * part carries date information, fraction carries time information. - * - *

- * The Julian day or Julian day number (JDN) is the (integer) number of days that - * have elapsed since Monday, January 1, 4713 BC in the proleptic Julian calendar 1. - * That day is counted as Julian day zero. Thus the multiples of 7 are Mondays. - * Negative values can also be used. - * - *

- * The Julian Date (JD) is the number of days (with decimal fraction of the day) that - * have elapsed since 12 noon Greenwich Mean Time (UT or TT) of that day. - * Rounding to the nearest integer gives the Julian day number. - *

- * For calculations that will have time precision of 1e-3 seconds, both - * fraction and integer part must have enough digits in it. The problem is - * that integer part is big and, on the other hand fractional is small, and - * since final julian date is a sum of this two values, some fraction - * numerals may be lost. Therefore, for higher precision both - * fractional and integer part of julian date real number has to be - * preserved. - *

- * This class stores the unmodified fraction part, but not all digits - * are significant! For 1e-3 seconds precision, only 8 digits after - * the decimal point are significant. - * - * @see TimeUtil - */ -public class JulianDate implements Serializable, Cloneable { - /** - * Julian Date for 1970-01-01T00:00:00 (Thursday). - */ - public static final JulianDate JD_1970 = new JulianDate(2440587, 0.5); - - /** - * Julian Date for 2001-01-01T00:00:00 (Monday). - */ - public static final JulianDate JD_2001 = new JulianDate(2451910, 0.5); - - - public static JulianDate of(final double value) { - return new JulianDate(value); - } - - public static JulianDate of(final LocalDateTime localDateTime) { - return of(localDateTime.getYear(), - localDateTime.getMonth().getValue(), - localDateTime.getDayOfMonth(), - localDateTime.getHour(), - localDateTime.getMinute(), - localDateTime.getSecond(), - localDateTime.getNano() / 1_000_000); - } - - public static JulianDate of(final LocalDate localDate) { - return of(localDate.getYear(), - localDate.getMonth().getValue(), - localDate.getDayOfMonth(), - 0, 0, 0, 0); - } - - public static JulianDate of(final long milliseconds) { - int integer = (int) (milliseconds / MILLIS_IN_DAY); - double fraction = (double)(milliseconds % MILLIS_IN_DAY) / MILLIS_IN_DAY; - integer += JD_1970.integer; - fraction += JD_1970.fraction; - return new JulianDate(integer, fraction); - } - - public static JulianDate of(final int i, final double f) { - return new JulianDate(i, f); - } - - public static JulianDate of(int year, int month, int day, final int hour, final int minute, final int second, final int millisecond) { - // month range fix - if ((month > 12) || (month < -12)) { - month--; - int delta = month / 12; - year += delta; - month -= delta * 12; - month++; - } - if (month < 0) { - year--; - month += 12; - } - - // decimal day fraction - double frac = (hour / 24.0) + (minute / 1440.0) + (second / 86400.0) + (millisecond / 86400000.0); - if (frac < 0) { // negative time fix - int delta = ((int)(-frac)) + 1; - frac += delta; - day -= delta; - } - //double gyr = year + (0.01 * month) + (0.0001 * day) + (0.0001 * frac) + 1.0e-9; - double gyr = year + (0.01 * month) + (0.0001 * (day + frac)) + 1.0e-9; - - // conversion factors - int iy0; - int im0; - if (month <= 2) { - iy0 = year - 1; - im0 = month + 12; - } else { - iy0 = year; - im0 = month; - } - int ia = iy0 / 100; - int ib = 2 - ia + (ia >> 2); - - // calculate julian date - int jd; - if (year <= 0) { - jd = (int)((365.25 * iy0) - 0.75) + (int)(30.6001 * (im0 + 1)) + day + 1720994; - } else { - jd = (int)(365.25 * iy0) + (int)(30.6001 * (im0 + 1)) + day + 1720994; - } - if (gyr >= 1582.1015) { // on or after 15 October 1582 - jd += ib; - } - //return jd + frac + 0.5; - - return new JulianDate(jd, frac + 0.5); - } - - public static JulianDate now() { - return of(LocalDateTime.now()); - } - - /** - * Integer part of the Julian Date (JD). - */ - protected int integer; - - /** - * Returns integer part of the Julian Date (JD). - */ - public int getInteger() { - return integer; - } - - /** - * Fraction part of the Julian Date (JD). - * Should be always in [0.0, 1.0) range. - */ - protected double fraction; - - /** - * Returns the fraction part of Julian Date (JD). - * Returned value is always in [0.0, 1.0) range. - */ - public double getFraction() { - return fraction; - } - - /** - * Calculates and returns significant fraction only as an int. - */ - public int getSignificantFraction() { - return (int) (fraction * 100_000_000); - } - - /** - * Returns JDN. Note that JDN is not equal to {@link #integer}. It is calculated by - * rounding to the nearest integer. - */ - public int getJulianDayNumber() { - if (fraction >= 0.5) { - return integer + 1; - } - return integer; - } - - /** - * Creates JD from a double. - */ - public JulianDate(final double jd) { - integer = (int) jd; - fraction = jd - (double)integer; - } - - /** - * Creates JD from both integer and fractional part using normalization. - * Normalization occurs when fractional part is out of range. - * - * @see #set(int, double) - * - * @param i integer part - * @param f fractional part should be in range [0.0, 1.0) - */ - public JulianDate(final int i, final double f) { - set(i, f); - } - - /** - * Creates JD from BigDecimal. - */ - public JulianDate(final BigDecimal bd) { - double d = bd.doubleValue(); - integer = (int) d; - fraction = bd.subtract(new BigDecimal(integer)).doubleValue(); - } - - - // ---------------------------------------------------------------- conversion - - - /** - * Returns double value of JD. - * CAUTION: double values may not be suit for precision math due to - * loss of precision. - */ - public double doubleValue() { - return (double)integer + fraction; - } - - /** - * Returns BigDecimal value of JD. - */ - public BigDecimal toBigDecimal() { - return new BigDecimal(integer).add(new BigDecimal(fraction)); - } - - /** - * Returns string representation of JD. - * - * @return julian integer as string - */ - @Override - public String toString() { - String s = Double.toString(fraction); - int i = s.indexOf('.'); - s = s.substring(i); - return integer + s; - } - - /** - * Converts to milliseconds. - */ - public long toMilliseconds() { - double then = (fraction - JD_1970.fraction) * MILLIS_IN_DAY; - then += (integer - JD_1970.integer) * MILLIS_IN_DAY; - then += then > 0 ? 1.0e-6 : -1.0e-6; - return (long) then; - } - - - public LocalDateTime toLocalDateTime() { - int year, month, day; - double frac; - int jd, ka, kb, kc, kd, ke, ialp; - - //double JD = jds.doubleValue();//jdate; - //jd = (int)(JD + 0.5); // integer julian date - //frac = JD + 0.5 - (double)jd + 1.0e-10; // day fraction - - ka = (int)(fraction + 0.5); - jd = integer + ka; - frac = fraction + 0.5 - ka + 1.0e-10; - - ka = jd; - if (jd >= 2299161) { - ialp = (int)(((double)jd - 1867216.25) / (36524.25)); - ka = jd + 1 + ialp - (ialp >> 2); - } - kb = ka + 1524; - kc = (int)(((double)kb - 122.1) / 365.25); - kd = (int)((double)kc * 365.25); - ke = (int)((double)(kb - kd) / 30.6001); - day = kb - kd - ((int)((double)ke * 30.6001)); - if (ke > 13) { - month = ke - 13; - } else { - month = ke - 1; - } - if ((month == 2) && (day > 28)){ - day = 29; - } - if ((month == 2) && (day == 29) && (ke == 3)) { - year = kc - 4716; - } else if (month > 2) { - year = kc - 4716; - } else { - year = kc - 4715; - } - - final int time_year = year; - final int time_month = month; - final int time_day = day; - - // hour with minute and second included as fraction - double d_hour = frac * 24.0; - final int time_hour = (int) d_hour; // integer hour - - // minute with second included as a fraction - double d_minute = (d_hour - (double)time_hour) * 60.0; - final int time_minute = (int) d_minute; // integer minute - - double d_second = (d_minute - (double)time_minute) * 60.0; - final int time_second = (int) d_second; // integer seconds - - double d_millis = (d_second - (double)time_second) * 1000.0; - - // fix calculation errors - final int time_millisecond = (int) (((d_millis * 10) + 0.5) / 10); - - return LocalDateTime.of(time_year, time_month, time_day, time_hour, time_minute, time_second, time_millisecond * 1_000_000); - } - - - // ---------------------------------------------------------------- math - - /** - * Adds two JD and returns a new instance. - */ - public JulianDate add(final JulianDate jds) { - int i = this.integer + jds.integer; - double f = this.fraction + jds.fraction; - return new JulianDate(i, f); - } - - /** - * Adds a double delta value and returns a new instance. - */ - public JulianDate add(final double delta) { - return new JulianDate(this.integer, this.fraction + delta); - } - - - /** - * Subtracts a JD from current instance and returns a new instance. - */ - public JulianDate sub(final JulianDate jds) { - int i = this.integer - jds.integer; - double f = this.fraction -jds.fraction; - return new JulianDate(i, f); - } - - /** - * Subtracts a double from current instance and returns a new instance. - */ - public JulianDate sub(final double delta) { - return new JulianDate(this.integer, this.fraction - delta); - } - - /** - * Sets integer and fractional part with normalization. - * Normalization means that if double is out of range, - * values will be correctly fixed. - */ - private void set(final int i, double f) { - integer = i; - int fi = (int) f; - f -= fi; - integer += fi; - if (f < 0) { - f += 1; - integer--; - } - this.fraction = f; - } - - - // ---------------------------------------------------------------- between - - /** - * Calculates the number of days between two dates. Returned value is always positive. - */ - public int daysBetween(final JulianDate otherDate) { - int difference = daysSpan(otherDate); - return difference >= 0 ? difference : -difference; - } - - /** - * Returns span between two days. Returned value may be positive (when this date - * is after the provided one) or negative (when comparing to future date). - */ - public int daysSpan(final JulianDate otherDate) { - int now = getJulianDayNumber(); - int then = otherDate.getJulianDayNumber(); - return now - then; - } - - // ---------------------------------------------------------------- equals & hashCode - - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (this.getClass() != object.getClass()) { - return false; - } - JulianDate stamp = (JulianDate) object; - return (stamp.integer == this.integer) && - (Double.compare(stamp.fraction, this.fraction) == 0); - } - - @Override - public int hashCode() { - return Objects.hash(integer, fraction); - } - - // ---------------------------------------------------------------- clone - - @Override - protected JulianDate clone() { - return new JulianDate(this.integer, this.fraction); - } - - // ---------------------------------------------------------------- conversion - - /** - * Returns Reduced Julian Date (RJD), used by astronomers. - * RJD = JD − 2400000 - */ - public JulianDate getReducedJulianDate() { - return new JulianDate(integer - 2400000, fraction); - } - - /** - * Returns Modified Julian Date (MJD), where date starts from midnight rather than noon. - * RJD = JD − 2400000.5 - */ - public JulianDate getModifiedJulianDate() { - return new JulianDate(integer - 2400000, fraction - 0.5); - } - - /** - * Returns Truncated Julian Day (TJD), introduced by NASA for the space program. - * TJD began at midnight at the beginning of May 24, 1968 (Friday). - */ - public JulianDate getTruncatedJulianDate() { - return new JulianDate(integer - 2440000, fraction - 0.5); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/time/TimeUtil.java b/fine-jodd/src/main/java/com/fr/third/jodd/time/TimeUtil.java deleted file mode 100644 index 77a05dc1a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/time/TimeUtil.java +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.time; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.TimeZone; - -public class TimeUtil { - - public static final int SECONDS_IN_DAY = 60 * 60 * 24; - public static final long MILLIS_IN_DAY = 1000L * SECONDS_IN_DAY; - - public static final SimpleDateFormat HTTP_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); - - /** - * Converts local date to Date. - */ - public static Date toDate(final LocalDate localDate) { - return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); - } - /** - * Converts local date time to Date. - */ - public static Date toDate(final LocalDateTime localDateTime) { - return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); - } - - /** - * Converts local date time to Calendar. - */ - public static Calendar toCalendar(final LocalDateTime localDateTime) { - return GregorianCalendar.from(ZonedDateTime.of(localDateTime, ZoneId.systemDefault())); - } - - /** - * Converts local date time to Calendar and setting time to midnight. - */ - public static Calendar toCalendar(final LocalDate localDate) { - return GregorianCalendar.from(ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, ZoneId.systemDefault())); - } - - /** - * Converts local date time to epoh milliseconds. - */ - public static long toMilliseconds(final LocalDateTime localDateTime) { - return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); - } - - /** - * Converts local date time to epoh milliseconds assuming start of the day as time point. - */ - public static long toMilliseconds(final LocalDate localDate) { - return toMilliseconds(localDate.atStartOfDay()); - } - - - public static LocalDateTime fromCalendar(final Calendar calendar) { - final TimeZone tz = calendar.getTimeZone(); - final ZoneId zid = tz == null ? ZoneId.systemDefault() : tz.toZoneId(); - return LocalDateTime.ofInstant(calendar.toInstant(), zid); - } - - public static LocalDateTime fromDate(final Date date) { - return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); - } - - public static LocalDateTime fromMilliseconds(final long milliseconds) { - return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneId.systemDefault()); - } - - - /** - * Formats time to HTTP date/time format. Note that number of milliseconds - * is lost. - */ - public static String formatHttpDate(final long millis) { - final Date date = new Date(millis); - return HTTP_DATE_FORMAT.format(date); - } - - /** - * Parses the HTTP date/time format. Returns -1 if given string - * is invalid. - */ - public static long parseHttpTime(final String time) { - if (time == null) { - return -1; - } - - try { - return TimeUtil.HTTP_DATE_FORMAT.parse(time).getTime(); - } - catch (ParseException e) { - return -1; - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/time/package-info.java b/fine-jodd/src/main/java/com/fr/third/jodd/time/package-info.java deleted file mode 100644 index 3cb62ffa3..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/time/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Precise and powerful Julian Date. It's not a LocalDate replacement, it's more an add-on. - */ -package com.fr.third.jodd.time; \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/Converter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/Converter.java deleted file mode 100644 index 076f0d7a0..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/Converter.java +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter; - -import java.math.BigDecimal; -import java.math.BigInteger; - -/** - * Just a convenient {@link TypeConverterManager} usage. - */ -public class Converter { - - private static final Converter CONVERTER = new Converter(); - - /** - * Returns default instance. - */ - public static Converter get() { - return CONVERTER; - } - - // ---------------------------------------------------------------- boolean - - /** - * Converts value to Boolean. - */ - public Boolean toBoolean(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Boolean.class); - return tc.convert(value); - } - - /** - * Converts value to Boolean. Returns default value - * when conversion result is null - */ - public Boolean toBoolean(final Object value, final Boolean defaultValue) { - final Boolean result = toBoolean(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to boolean. Returns default value - * when conversion result is null. - */ - public boolean toBooleanValue(final Object value, final boolean defaultValue) { - final Boolean result = toBoolean(value); - if (result == null) { - return defaultValue; - } - return result.booleanValue(); - } - - /** - * Converts value to boolean with common default value. - */ - public boolean toBooleanValue(final Object value) { - return toBooleanValue(value, false); - } - - // ---------------------------------------------------------------- integer - - /** - * Converts value to Integer. - */ - public Integer toInteger(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Integer.class); - return tc.convert(value); - } - - /** - * Converts value to Integer. Returns default value - * when conversion result is null - */ - public Integer toInteger(final Object value, final Integer defaultValue) { - final Integer result = toInteger(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to int. Returns default value - * when conversion result is null. - */ - public int toIntValue(final Object value, final int defaultValue) { - final Integer result = toInteger(value); - if (result == null) { - return defaultValue; - } - return result.intValue(); - } - - /** - * Converts value to int with common default value. - */ - public int toIntValue(final Object value) { - return toIntValue(value, 0); - } - - // ---------------------------------------------------------------- long - - /** - * Converts value to Long. - */ - public Long toLong(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Long.class); - return tc.convert(value); - } - - /** - * Converts value to Long. Returns default value - * when conversion result is null - */ - public Long toLong(final Object value, final Long defaultValue) { - final Long result = toLong(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to long. Returns default value - * when conversion result is null. - */ - public long toLongValue(final Object value, final long defaultValue) { - final Long result = toLong(value); - if (result == null) { - return defaultValue; - } - return result.longValue(); - } - - /** - * Converts value to long with common default value. - */ - public long toLongValue(final Object value) { - return toLongValue(value, 0); - } - - // ---------------------------------------------------------------- float - - /** - * Converts value to Float. - */ - public Float toFloat(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Float.class); - return tc.convert(value); - } - - /** - * Converts value to Float. Returns default value - * when conversion result is null - */ - public Float toFloat(final Object value, final Float defaultValue) { - final Float result = toFloat(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to float. Returns default value - * when conversion result is null. - */ - public float toFloatValue(final Object value, final float defaultValue) { - final Float result = toFloat(value); - if (result == null) { - return defaultValue; - } - return result.floatValue(); - } - - /** - * Converts value to float with common default value. - */ - public float toFloatValue(final Object value) { - return toFloatValue(value, 0); - } - - // ---------------------------------------------------------------- double - - /** - * Converts value to Double. - */ - public Double toDouble(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Double.class); - return tc.convert(value); - } - - /** - * Converts value to Double. Returns default value - * when conversion result is null - */ - public Double toDouble(final Object value, final Double defaultValue) { - final Double result = toDouble(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to double. Returns default value - * when conversion result is null. - */ - public double toDoubleValue(final Object value, final double defaultValue) { - final Double result = toDouble(value); - if (result == null) { - return defaultValue; - } - return result.doubleValue(); - } - - /** - * Converts value to double with common default value. - */ - public double toDoubleValue(final Object value) { - return toDoubleValue(value, 0); - } - - // ---------------------------------------------------------------- short - - /** - * Converts value to Short. - */ - public Short toShort(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Short.class); - return tc.convert(value); - } - - /** - * Converts value to Short. Returns default value - * when conversion result is null - */ - public Short toShort(final Object value, final Short defaultValue) { - final Short result = toShort(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to short. Returns default value - * when conversion result is null. - */ - public short toShortValue(final Object value, final short defaultValue) { - final Short result = toShort(value); - if (result == null) { - return defaultValue; - } - return result.shortValue(); - } - - /** - * Converts value to short with common default value. - */ - public short toShortValue(final Object value) { - return toShortValue(value, (short) 0); - } - - // ---------------------------------------------------------------- character - - /** - * Converts value to Character. - */ - public Character toCharacter(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Character.class); - return tc.convert(value); - } - - /** - * Converts value to Character. Returns default value - * when conversion result is null - */ - public Character toCharacter(final Object value, final Character defaultValue) { - final Character result = toCharacter(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to char. Returns default value - * when conversion result is null. - */ - public char toCharValue(final Object value, final char defaultValue) { - final Character result = toCharacter(value); - if (result == null) { - return defaultValue; - } - return result.charValue(); - } - - /** - * Converts value to char with common default value. - */ - public char toCharValue(final Object value) { - return toCharValue(value, (char) 0); - } - - // ---------------------------------------------------------------- byte - - /** - * Converts value to Byte. - */ - public Byte toByte(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Byte.class); - return tc.convert(value); - } - - /** - * Converts value to Byte. Returns default value - * when conversion result is null - */ - public Byte toByte(final Object value, final Byte defaultValue) { - final Byte result = toByte(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to byte. Returns default value - * when conversion result is null. - */ - public byte toByteValue(final Object value, final byte defaultValue) { - final Byte result = toByte(value); - if (result == null) { - return defaultValue; - } - return result.byteValue(); - } - - /** - * Converts value to byte with common default value. - */ - public byte toByteValue(final Object value) { - return toByteValue(value, (byte) 0); - } - - // ---------------------------------------------------------------- array - - /** - * Converts value to boolean[]. - */ - public boolean[] toBooleanArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(boolean[].class); - return tc.convert(value); - } - - /** - * Converts value to int[]. - */ - public int[] toIntegerArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(int[].class); - return tc.convert(value); - - } - - /** - * Converts value to long[]. - */ - public long[] toLongArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(long[].class); - return tc.convert(value); - - } - - /** - * Converts value to float[]. - */ - public float[] toFloatArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(float[].class); - return tc.convert(value); - } - - /** - * Converts value to double[]. - */ - public double[] toDoubleArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(double[].class); - return tc.convert(value); - } - - /** - * Converts value to short[]. - */ - public short[] toShortArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(short[].class); - return tc.convert(value); - } - - /** - * Converts value to char[]. - */ - public char[] toCharacterArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(char[].class); - return tc.convert(value); - } - - // ---------------------------------------------------------------- string - - /** - * Converts value to String. - */ - public String toString(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(String.class); - return tc.convert(value); - } - - /** - * Converts value to String. Returns default value - * when conversion result is null - */ - public String toString(final Object value, final String defaultValue) { - final String result = toString(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to String[]. - */ - public String[] toStringArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(String[].class); - return tc.convert(value); - } - - // ---------------------------------------------------------------- class - - /** - * Converts value to Class. - */ - public Class toClass(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Class.class); - return tc.convert(value); - } - - /** - * Converts value to Class[]. - */ - public Class[] toClassArray(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(Class[].class); - return tc.convert(value); - } - - // ---------------------------------------------------------------- bigs - - /** - * Converts value to BigInteger. - */ - public BigInteger toBigInteger(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(BigInteger.class); - return tc.convert(value); - } - - /** - * Converts value to BigInteger. Returns default value - * when conversion result is null - */ - public BigInteger toBigInteger(final Object value, final BigInteger defaultValue) { - final BigInteger result = toBigInteger(value); - if (result == null) { - return defaultValue; - } - return result; - } - - /** - * Converts value to BigDecimal. - */ - public BigDecimal toBigDecimal(final Object value) { - final TypeConverter tc = TypeConverterManager.get().lookup(BigDecimal.class); - return tc.convert(value); - } - - /** - * Converts value to BigDecimal. Returns default value - * when conversion result is null - */ - public BigDecimal toBigDecimal(final Object value, final BigDecimal defaultValue) { - final BigDecimal result = toBigDecimal(value); - if (result == null) { - return defaultValue; - } - return result; - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConversionException.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConversionException.java deleted file mode 100644 index 6b025f5a1..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConversionException.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter; - -import com.fr.third.jodd.exception.UncheckedException; - -/** - * Type conversion exception. - */ -public class TypeConversionException extends UncheckedException { - - public TypeConversionException(final Throwable t) { - super(t); - } - - public TypeConversionException(final String message) { - super(message); - } - - public TypeConversionException(final String message, final Throwable t) { - super(message, t); - } - - public TypeConversionException(final Object value) { - this("Conversion failed: " + value); - } - - public TypeConversionException(final Object value, final Throwable t) { - this("Conversion failed: " + value, t); - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConverter.java deleted file mode 100644 index 358bb8a12..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConverter.java +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter; - -/** - * Object converter interface. - * - * @see TypeConverterManager - */ -@FunctionalInterface -public interface TypeConverter { - - /** - * Converts object received as parameter into object of another class. - * For example, an Integer converter tries to convert given objects - * into target Integer object. Converters should try all reasonable - * ways of conversion into target object, depending on target type. - * - * @param value object to convert from - * - * @return resulting object converted to target type - * @throws TypeConversionException if conversion fails - */ - T convert(Object value); - - /** - * Converts object and returns default value if conversion fails. - */ - default T convert(final Object value, final T defaultValue) { - if (value == null) { - return defaultValue; - } - try { - return convert(value); - } - catch (Exception e) { - return defaultValue; - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConverterManager.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConverterManager.java deleted file mode 100644 index cebbc47ee..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/TypeConverterManager.java +++ /dev/null @@ -1,385 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter; - -import com.fr.third.jodd.cache.TypeCache; -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.mutable.MutableByte; -import com.fr.third.jodd.mutable.MutableDouble; -import com.fr.third.jodd.mutable.MutableFloat; -import com.fr.third.jodd.mutable.MutableInteger; -import com.fr.third.jodd.mutable.MutableLong; -import com.fr.third.jodd.mutable.MutableShort; -import com.fr.third.jodd.typeconverter.impl.ArrayConverter; -import com.fr.third.jodd.typeconverter.impl.BigDecimalConverter; -import com.fr.third.jodd.typeconverter.impl.BigIntegerConverter; -import com.fr.third.jodd.typeconverter.impl.BooleanArrayConverter; -import com.fr.third.jodd.typeconverter.impl.BooleanConverter; -import com.fr.third.jodd.typeconverter.impl.ByteArrayConverter; -import com.fr.third.jodd.typeconverter.impl.ByteConverter; -import com.fr.third.jodd.typeconverter.impl.CalendarConverter; -import com.fr.third.jodd.typeconverter.impl.CharacterArrayConverter; -import com.fr.third.jodd.typeconverter.impl.CharacterConverter; -import com.fr.third.jodd.typeconverter.impl.ClassArrayConverter; -import com.fr.third.jodd.typeconverter.impl.ClassConverter; -import com.fr.third.jodd.typeconverter.impl.CollectionConverter; -import com.fr.third.jodd.typeconverter.impl.DateConverter; -import com.fr.third.jodd.typeconverter.impl.DoubleArrayConverter; -import com.fr.third.jodd.typeconverter.impl.DoubleConverter; -import com.fr.third.jodd.typeconverter.impl.FileConverter; -import com.fr.third.jodd.typeconverter.impl.FileUploadConverter; -import com.fr.third.jodd.typeconverter.impl.FloatArrayConverter; -import com.fr.third.jodd.typeconverter.impl.FloatConverter; -import com.fr.third.jodd.typeconverter.impl.IntegerArrayConverter; -import com.fr.third.jodd.typeconverter.impl.IntegerConverter; -import com.fr.third.jodd.typeconverter.impl.LocalDateConverter; -import com.fr.third.jodd.typeconverter.impl.LocalDateTimeConverter; -import com.fr.third.jodd.typeconverter.impl.LocalTimeConverter; -import com.fr.third.jodd.typeconverter.impl.LocaleConverter; -import com.fr.third.jodd.typeconverter.impl.LongArrayConverter; -import com.fr.third.jodd.typeconverter.impl.LongConverter; -import com.fr.third.jodd.typeconverter.impl.MutableByteConverter; -import com.fr.third.jodd.typeconverter.impl.MutableDoubleConverter; -import com.fr.third.jodd.typeconverter.impl.MutableFloatConverter; -import com.fr.third.jodd.typeconverter.impl.MutableIntegerConverter; -import com.fr.third.jodd.typeconverter.impl.MutableLongConverter; -import com.fr.third.jodd.typeconverter.impl.MutableShortConverter; -import com.fr.third.jodd.typeconverter.impl.ShortArrayConverter; -import com.fr.third.jodd.typeconverter.impl.ShortConverter; -import com.fr.third.jodd.typeconverter.impl.SqlDateConverter; -import com.fr.third.jodd.typeconverter.impl.SqlTimeConverter; -import com.fr.third.jodd.typeconverter.impl.SqlTimestampConverter; -import com.fr.third.jodd.typeconverter.impl.StringArrayConverter; -import com.fr.third.jodd.typeconverter.impl.StringConverter; -import com.fr.third.jodd.typeconverter.impl.TimeZoneConverter; -import com.fr.third.jodd.typeconverter.impl.URIConverter; -import com.fr.third.jodd.typeconverter.impl.URLConverter; -import com.fr.third.jodd.typeconverter.impl.UUIDConverter; -import com.fr.third.jodd.util.ClassUtil; - -import java.io.File; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URI; -import java.net.URL; -import java.sql.Time; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.Calendar; -import java.util.Collection; -import java.util.Locale; -import java.util.TimeZone; -import java.util.UUID; - -/** - * Provides dynamic object conversion to a type. - * Contains a map of registered converters. User may add new converters. - */ -public class TypeConverterManager { - - private static final TypeConverterManager TYPE_CONVERTER_MANAGER = new TypeConverterManager(); - - /** - * Returns default implementation. - */ - public static TypeConverterManager get() { - return TYPE_CONVERTER_MANAGER; - } - - private final TypeCache converters = TypeCache.createDefault(); - - // ---------------------------------------------------------------- methods - - public TypeConverterManager() { - registerDefaults(); - } - - /** - * Registers default set of converters. - */ - public void registerDefaults() { - register(String.class, new StringConverter()); - register(String[].class, new StringArrayConverter(this)); - - final IntegerConverter integerConverter = new IntegerConverter(); - register(Integer.class, integerConverter); - register(int.class, integerConverter); - register(MutableInteger.class, new MutableIntegerConverter(this)); - - final ShortConverter shortConverter = new ShortConverter(); - register(Short.class, shortConverter); - register(short.class, shortConverter); - register(MutableShort.class, new MutableShortConverter(this)); - - final LongConverter longConverter = new LongConverter(); - register(Long.class, longConverter); - register(long.class, longConverter); - register(MutableLong.class, new MutableLongConverter(this)); - - final ByteConverter byteConverter = new ByteConverter(); - register(Byte.class, byteConverter); - register(byte.class, byteConverter); - register(MutableByte.class, new MutableByteConverter(this)); - - final FloatConverter floatConverter = new FloatConverter(); - register(Float.class, floatConverter); - register(float.class, floatConverter); - register(MutableFloat.class, new MutableFloatConverter(this)); - - final DoubleConverter doubleConverter = new DoubleConverter(); - register(Double.class, doubleConverter); - register(double.class, doubleConverter); - register(MutableDouble.class, new MutableDoubleConverter(this)); - - final BooleanConverter booleanConverter = new BooleanConverter(); - register(Boolean.class, booleanConverter); - register(boolean.class, booleanConverter); - - final CharacterConverter characterConverter = new CharacterConverter(); - register(Character.class, characterConverter); - register(char.class, characterConverter); - - register(byte[].class, new ByteArrayConverter(this)); - register(short[].class, new ShortArrayConverter(this)); - register(int[].class, new IntegerArrayConverter(this)); - register(long[].class, new LongArrayConverter(this)); - register(float[].class, new FloatArrayConverter(this)); - register(double[].class, new DoubleArrayConverter(this)); - register(boolean[].class, new BooleanArrayConverter(this)); - register(char[].class, new CharacterArrayConverter(this)); - - // we don't really need these, but converters will be cached and not created every time - register(Integer[].class, new ArrayConverter(this, Integer.class) { - @Override - protected Integer[] createArray(final int length) { - return new Integer[length]; - } - }); - register(Long[].class, new ArrayConverter(this, Long.class) { - @Override - protected Long[] createArray(final int length) { - return new Long[length]; - } - }); - register(Byte[].class, new ArrayConverter(this, Byte.class) { - @Override - protected Byte[] createArray(final int length) { - return new Byte[length]; - } - }); - register(Short[].class, new ArrayConverter(this, Short.class) { - @Override - protected Short[] createArray(final int length) { - return new Short[length]; - } - }); - register(Float[].class, new ArrayConverter(this, Float.class) { - @Override - protected Float[] createArray(final int length) { - return new Float[length]; - } - }); - register(Double[].class, new ArrayConverter(this, Double.class) { - @Override - protected Double[] createArray(final int length) { - return new Double[length]; - } - }); - register(Boolean[].class, new ArrayConverter(this, Boolean.class) { - @Override - protected Boolean[] createArray(final int length) { - return new Boolean[length]; - } - }); - register(Character[].class, new ArrayConverter(this, Character.class) { - @Override - protected Character[] createArray(final int length) { - return new Character[length]; - } - }); - - register(MutableInteger[].class, new ArrayConverter<>(this, MutableInteger.class)); - register(MutableLong[].class, new ArrayConverter<>(this, MutableLong.class)); - register(MutableByte[].class, new ArrayConverter<>(this, MutableByte.class)); - register(MutableShort[].class, new ArrayConverter<>(this, MutableShort.class)); - register(MutableFloat[].class, new ArrayConverter<>(this, MutableFloat.class)); - register(MutableDouble[].class, new ArrayConverter<>(this, MutableDouble.class)); - - register(BigDecimal.class, new BigDecimalConverter()); - register(BigInteger.class, new BigIntegerConverter()); - register(BigDecimal[].class, new ArrayConverter<>(this, BigDecimal.class)); - register(BigInteger[].class, new ArrayConverter<>(this, BigInteger.class)); - - register(java.util.Date.class, new DateConverter()); - register(java.sql.Date.class, new SqlDateConverter()); - register(Time.class, new SqlTimeConverter()); - register(Timestamp.class, new SqlTimestampConverter()); - register(Calendar.class, new CalendarConverter()); -// register(GregorianCalendar.class, new CalendarConverter()); - register(LocalDateTime.class, new LocalDateTimeConverter()); - register(LocalDate.class, new LocalDateConverter()); - register(LocalTime.class, new LocalTimeConverter()); - - register(File.class, new FileConverter()); - register(FileUpload.class, new FileUploadConverter()); - - register(Class.class, new ClassConverter()); - register(Class[].class, new ClassArrayConverter(this)); - - register(URI.class, new URIConverter()); - register(URL.class, new URLConverter()); - - register(Locale.class, new LocaleConverter()); - register(TimeZone.class, new TimeZoneConverter()); - - register(UUID.class, new UUIDConverter()); - } - - /** - * Registers a converter for specified type. - * User must register converter for all super-classes as well. - * - * @param type class that converter is for - * @param typeConverter converter for provided class - */ - public void register(final Class type, final TypeConverter typeConverter) { - converters.put(type, typeConverter); - } - - /** - * Un-registers converter for given type. - */ - public void unregister(final Class type) { - converters.remove(type); - } - - // ---------------------------------------------------------------- lookup - - /** - * Retrieves converter for provided type. Only registered types are matched, - * therefore subclasses must be also registered. - * - * @return founded converter or null - */ - public TypeConverter lookup(final Class type) { - return converters.get(type); - } - - // ---------------------------------------------------------------- converter - - /** - * Converts an object to destination type. If type is registered, it's - * {@link TypeConverter} will be used. If not, it scans of destination is - * an array or enum, as those two cases are handled in a special way. - *

- * If destination type is one of common types, consider using {@link Converter} - * instead for somewhat faster approach (no lookup). - */ - @SuppressWarnings({"unchecked"}) - public T convertType(final Object value, final Class destinationType) { - if (destinationType == Object.class) { - // no conversion :) - return (T) value; - } - - final TypeConverter converter = lookup(destinationType); - - if (converter != null) { - return (T) converter.convert(value); - } - - // no converter - - if (value == null) { - return null; - } - - // check same instances - if (ClassUtil.isInstanceOf(value, destinationType)) { - return (T) value; - } - - // handle destination arrays - if (destinationType.isArray()) { - final ArrayConverter arrayConverter = new ArrayConverter(this, destinationType.getComponentType()); - - return (T) arrayConverter.convert(value); - } - - // handle enums - if (destinationType.isEnum()) { - final Object[] enums = destinationType.getEnumConstants(); - final String valStr = value.toString(); - for (final Object e : enums) { - if (e.toString().equals(valStr)) { - return (T) e; - } - } - } - - // collection - if (ClassUtil.isTypeOf(destinationType, Collection.class)) { - // component type is unknown because of Java's type-erasure - final CollectionConverter collectionConverter = - new CollectionConverter(this, destinationType, Object.class); - - return (T) collectionConverter.convert(value); - } - - // fail - throw new TypeConversionException("Conversion failed of input type: " + value.getClass() + " into: " + destinationType.getName()); - } - - /** - * Special case of {@link #convertType(Object, Class)} when target is collection and - * when component type is known. - */ - @SuppressWarnings("unchecked") - public , T> C convertToCollection(final Object value, final Class destinationType, final Class componentType) { - if (value == null) { - return null; - } - - // check same instances - if (ClassUtil.isInstanceOf(value, destinationType)) { - return (C) value; - } - - final CollectionConverter collectionConverter; - - if (componentType == null) { - collectionConverter = new CollectionConverter(destinationType, Object.class); - } - else { - collectionConverter = new CollectionConverter(destinationType, componentType); - } - - return (C) collectionConverter.convert(value); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ArrayConverter.java deleted file mode 100644 index c48ec6794..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ArrayConverter.java +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.CsvUtil; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Converts given object to an array. This converter is specific, as it - * is not directly registered to a type; but created when needed. - * Conversion rules: - *

    - *
  • null value is returned as null
  • - *
  • source non-array value is checked for Collections
  • - *
  • if non-array element can't be resolved, it is converted to single element array
  • - *
  • source array is converted to target array, by converting each element
  • - *
- */ -@SuppressWarnings("unchecked") -public class ArrayConverter implements TypeConverter { - - public static final char[] NUMBER_DELIMITERS = new char[] {',', ';', '\n'}; - - protected final TypeConverterManager typeConverterManager; - protected final Class targetComponentType; - - public ArrayConverter(final TypeConverterManager typeConverterManager, final Class targetComponentType) { - this.typeConverterManager = typeConverterManager; - this.targetComponentType = targetComponentType; - } - - @Override - public T[] convert(final Object value) { - if (value == null) { - return null; - } - - Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected T convertType(final Object value) { - return typeConverterManager.convertType(value, targetComponentType); - } - - /** - * Creates new array of target component type. - * Default implementation uses reflection to create - * an array of target type. Override it for better performances. - */ - protected T[] createArray(final int length) { - return (T[]) Array.newInstance(targetComponentType, length); - } - - /** - * Creates an array with single element. - */ - protected T[] convertToSingleElementArray(final Object value) { - T[] singleElementArray = createArray(1); - - singleElementArray[0] = convertType(value); - - return singleElementArray; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected T[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - Collection collection = (Collection) value; - T[] target = createArray(collection.size()); - - int i = 0; - for (Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - Iterable iterable = (Iterable) value; - List list = new ArrayList<>(); - - for (Object element : iterable) { - list.add(convertType(element)); - } - - T[] target = createArray(list.size()); - return list.toArray(target); - } - - if (value instanceof CharSequence) { - String[] strings = convertStringToArray(value.toString()); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts string to array, for the {@link #convertValueToArray(Object)} method. - * By default, the string is converted into an array using {@link com.fr.third.jodd.util.CsvUtil}. - */ - protected String[] convertStringToArray(final String value) { - return CsvUtil.toStringArray(value); - } - - /** - * Converts array value to array. - */ - protected T[] convertArrayToArray(final Object value) { - Class valueComponentType = value.getClass().getComponentType(); - - if (valueComponentType == targetComponentType) { - // equal types, no conversion needed - return (T[]) value; - } - - T[] result; - - if (valueComponentType.isPrimitive()) { - // convert primitive array to target array - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - Object[] array = (Object[]) value; - result = createArray(array.length); - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - /** - * Converts primitive array to target array. - */ - @SuppressWarnings("AutoBoxing") - protected T[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - T[] result = null; - - if (primitiveComponentType == int.class) { - int[] array = (int[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - else if (primitiveComponentType == long.class) { - long[] array = (long[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - else if (primitiveComponentType == float.class) { - float[] array = (float[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - else if (primitiveComponentType == double.class) { - double[] array = (double[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - else if (primitiveComponentType == short.class) { - short[] array = (short[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - else if (primitiveComponentType == byte.class) { - byte[] array = (byte[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - else if (primitiveComponentType == char.class) { - char[] array = (char[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - else if (primitiveComponentType == boolean.class) { - boolean[] array = (boolean[]) value; - result = createArray(array.length); - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BigDecimalConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BigDecimalConverter.java deleted file mode 100644 index d26c2575c..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BigDecimalConverter.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; - -import java.math.BigDecimal; - -/** - * Converts given object to BigDecimal. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible
  • - *
- */ -public class BigDecimalConverter implements TypeConverter { - - @Override - public BigDecimal convert(final Object value) { - if (value == null) { - return null; - } - - if (value instanceof BigDecimal) { - return (BigDecimal) value; - } - try { - return new BigDecimal(value.toString().trim()); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BigIntegerConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BigIntegerConverter.java deleted file mode 100644 index ce8edaad8..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BigIntegerConverter.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; - -import java.math.BigInteger; - -/** - * Converts given object to BigInteger. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible
  • - *
- */ -public class BigIntegerConverter implements TypeConverter { - - public BigInteger convert(final Object value) { - if (value == null) { - return null; - } - - if (value instanceof BigInteger) { - return (BigInteger) value; - } - if (value instanceof Number) { - return new BigInteger(String.valueOf(((Number)value).longValue())); - } - try { - return new BigInteger(value.toString().trim()); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BooleanArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BooleanArrayConverter.java deleted file mode 100644 index a084110f5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BooleanArrayConverter.java +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Converts given object to boolean[]. - */ -public class BooleanArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public BooleanArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public boolean[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected boolean convertType(final Object value) { - return typeConverterManager.convertType(value, boolean.class).booleanValue(); - } - - /** - * Creates an array with single element. - */ - protected boolean[] convertToSingleElementArray(final Object value) { - return new boolean[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected boolean[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final boolean[] target = new boolean[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final ArrayList booleanArrayList = new ArrayList<>(); - - for (final Object element : iterable) { - final boolean convertedValue = convertType(element); - booleanArrayList.add(Boolean.valueOf(convertedValue)); - } - - final boolean[] array = new boolean[booleanArrayList.size()]; - - for (int i = 0; i < booleanArrayList.size(); i++) { - final Boolean b = booleanArrayList.get(i); - array[i] = b.booleanValue(); - } - - return array; - } - - if (value instanceof CharSequence) { - final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected boolean[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final boolean[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new boolean[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected boolean[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - boolean[] result = null; - - if (primitiveComponentType == boolean.class) { - return (boolean[]) value; - } - - if (primitiveComponentType == int.class) { - final int[] array = (int[]) value; - result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != 0; - } - } - else if (primitiveComponentType == long.class) { - final long[] array = (long[]) value; - result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != 0; - } - } - else if (primitiveComponentType == float.class) { - final float[] array = (float[]) value; - result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != 0; - } - } - else if (primitiveComponentType == double.class) { - final double[] array = (double[]) value; - result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != 0; - } - } - else if (primitiveComponentType == short.class) { - final short[] array = (short[]) value; - result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != 0; - } - } - else if (primitiveComponentType == byte.class) { - final byte[] array = (byte[]) value; - result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != 0; - } - } - else if (primitiveComponentType == char.class) { - final char[] array = (char[]) value; - result = new boolean[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != 0; - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BooleanConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BooleanConverter.java deleted file mode 100644 index 79e400916..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/BooleanConverter.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; - -import static com.fr.third.jodd.util.StringPool.*; - -/** - * Converts given object to Boolean. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed. Then common boolean strings are matched: - * "yes", "y", "true", "on", "1" for true; and opposite values - * for false.
  • - *
- */ -public class BooleanConverter implements TypeConverter { - - public Boolean convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Boolean.class) { - return (Boolean) value; - } - - String stringValue = value.toString(); - if (stringValue.isEmpty()) { - return Boolean.FALSE; - } - - stringValue = stringValue.trim().toLowerCase(); - if (stringValue.equals(YES) || - stringValue.equals(Y) || - stringValue.equals(TRUE) || - stringValue.equals(ON) || - stringValue.equals(ONE)) { - return Boolean.TRUE; - } - if (stringValue.equals(NO) || - stringValue.equals(N) || - stringValue.equals(FALSE) || - stringValue.equals(OFF) || - stringValue.equals(ZERO)) { - return Boolean.FALSE; - } - - throw new TypeConversionException(value); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ByteArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ByteArrayConverter.java deleted file mode 100644 index e2263517f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ByteArrayConverter.java +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.io.FileUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.StringUtil; - -import java.io.File; -import java.io.IOException; -import java.sql.Blob; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; - -/** - * Converts given object to byte[]. - */ -public class ByteArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public ByteArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public byte[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected byte convertType(final Object value) { - return typeConverterManager.convertType(value, byte.class).byteValue(); - } - - /** - * Creates an array with single element. - */ - protected byte[] convertToSingleElementArray(final Object value) { - return new byte[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * types and collections, iterates them to make conversion - * and to create target array. - */ - protected byte[] convertValueToArray(final Object value) { - if (value instanceof Blob) { - final Blob blob = (Blob) value; - try { - final long length = blob.length(); - if (length > Integer.MAX_VALUE) { - throw new TypeConversionException("Blob is too big."); - } - return blob.getBytes(1, (int) length); - } catch (SQLException sex) { - throw new TypeConversionException(value, sex); - } - } - - if (value instanceof File) { - try { - return FileUtil.readBytes((File) value); - } catch (IOException ioex) { - throw new TypeConversionException(value, ioex); - } - } - - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final byte[] target = new byte[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final ArrayList byteArrayList = new ArrayList<>(); - - for (final Object element : iterable) { - final byte convertedValue = convertType(element); - byteArrayList.add(Byte.valueOf(convertedValue)); - } - - final byte[] array = new byte[byteArrayList.size()]; - - for (int i = 0; i < byteArrayList.size(); i++) { - final Byte b = byteArrayList.get(i); - array[i] = b.byteValue(); - } - - return array; - } - - if (value instanceof CharSequence) { - final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected byte[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final byte[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new byte[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected byte[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - byte[] result = null; - - if (primitiveComponentType == byte.class) { - return (byte[]) value; - } - - if (primitiveComponentType == int.class) { - final int[] array = (int[]) value; - result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (byte) array[i]; - } - } - else if (primitiveComponentType == long.class) { - final long[] array = (long[]) value; - result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (byte) array[i]; - } - } - else if (primitiveComponentType == float.class) { - final float[] array = (float[]) value; - result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (byte) array[i]; - } - } - else if (primitiveComponentType == double.class) { - final double[] array = (double[]) value; - result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (byte) array[i]; - } - } - else if (primitiveComponentType == short.class) { - final short[] array = (short[]) value; - result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (byte) array[i]; - } - } - else if (primitiveComponentType == char.class) { - final char[] array = (char[]) value; - result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (byte) array[i]; - } - } - else if (primitiveComponentType == boolean.class) { - final boolean[] array = (boolean[]) value; - result = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (byte) (array[i] ? 1 : 0); - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ByteConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ByteConverter.java deleted file mode 100644 index e58d40bff..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ByteConverter.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to Byte. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible.
  • - *
- * Number string may start with plus and minus sign. - */ -public class ByteConverter implements TypeConverter { - - @Override - public Byte convert(final Object value) { - if (value == null) { - return null; - } - if (value.getClass() == Byte.class) { - return (Byte) value; - } - if (value instanceof Number) { - return Byte.valueOf(((Number)value).byteValue()); - } - if (value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? Byte.valueOf((byte) 1) : Byte.valueOf((byte) 0); - } - - try { - String stringValue = value.toString().trim(); - if (StringUtil.startsWithChar(stringValue, '+')) { - stringValue = stringValue.substring(1); - } - return Byte.valueOf(stringValue); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CalendarConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CalendarConverter.java deleted file mode 100644 index cb7d925d5..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CalendarConverter.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.time.JulianDate; -import com.fr.third.jodd.time.TimeUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; - -/** - * Converts given object to Byte. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • Date object is converted
  • - *
  • JulianDate object is converted
  • - *
  • LocalDateTime object is converted
  • - *
  • LocalDate object is converted
  • - *
  • Number is used as number of milliseconds
  • - *
  • finally, if string value contains only numbers it is parsed as milliseconds
  • - *
- */ -public class CalendarConverter implements TypeConverter { - - @Override - public Calendar convert(final Object value) { - if (value == null) { - return null; - } - - if (value instanceof Calendar) { - return (Calendar) value; - } - if (value instanceof Date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime((Date) value); - return calendar; - } - if (value instanceof JulianDate) { - return TimeUtil.toCalendar(((JulianDate)value).toLocalDateTime()); - } - if (value instanceof LocalDateTime) { - return TimeUtil.toCalendar((LocalDateTime)value); - } - if (value instanceof LocalDate) { - return TimeUtil.toCalendar((LocalDate)value); - } - - if (value instanceof Number) { - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(((Number) value).longValue()); - return calendar; - } - - String stringValue = value.toString().trim(); - - if (!StringUtil.containsOnlyDigits(stringValue)) { - // try to parse default string format - return TimeUtil.toCalendar(LocalDateTime.parse(stringValue)); - } - - try { - long milliseconds = Long.parseLong(stringValue); - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(milliseconds); - return calendar; - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CharacterArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CharacterArrayConverter.java deleted file mode 100644 index 299a1b1a3..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CharacterArrayConverter.java +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - - -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Converts given object to char[]. - */ -public class CharacterArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public CharacterArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public char[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected char convertType(final Object value) { - return typeConverterManager.convertType(value, char.class).charValue(); - } - - /** - * Creates an array with single element. - */ - protected char[] convertToSingleElementArray(final Object value) { - return new char[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected char[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final char[] target = new char[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final ArrayList charArrayList = new ArrayList<>(); - - for (final Object element : iterable) { - final char convertedValue = convertType(element); - charArrayList.add(Character.valueOf(convertedValue)); - } - - final char[] array = new char[charArrayList.size()]; - - for (int i = 0; i < charArrayList.size(); i++) { - final Character c = charArrayList.get(i); - array[i] = c.charValue(); - } - - return array; - - } - - if (value instanceof CharSequence) { - final CharSequence charSequence = (CharSequence) value; - - final char[] result = new char[charSequence.length()]; - - for (int i = 0; i < result.length; i++) { - result[i] = charSequence.charAt(i); - } - - return result; - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected char[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final char[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new char[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected char[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - char[] result = null; - - if (primitiveComponentType == char.class) { - return (char[]) value; - } - - if (primitiveComponentType == int.class) { - final int[] array = (int[]) value; - result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (char) array[i]; - } - } - else if (primitiveComponentType == long.class) { - final long[] array = (long[]) value; - result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (char) array[i]; - } - } - else if (primitiveComponentType == float.class) { - final float[] array = (float[]) value; - result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (char) array[i]; - } - } - else if (primitiveComponentType == double.class) { - final double[] array = (double[]) value; - result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (char) array[i]; - } - } - else if (primitiveComponentType == short.class) { - final short[] array = (short[]) value; - result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (char) array[i]; - } - } - else if (primitiveComponentType == byte.class) { - final byte[] array = (byte[]) value; - result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (char) array[i]; - } - } - else if (primitiveComponentType == boolean.class) { - final boolean[] array = (boolean[]) value; - result = new char[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (char) (array[i] ? 1 : 0); - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CharacterConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CharacterConverter.java deleted file mode 100644 index 55c08463e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CharacterConverter.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to Character. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • Number is converted to char value
  • - *
  • finally, toString() value of length 1 is converted to char
  • - *
  • if string is longer, and made of digits, try to convert it to int first
  • - *
- */ -public class CharacterConverter implements TypeConverter { - - public Character convert(final Object value) { - if (value == null) { - return null; - } - if (value.getClass() == Character.class) { - return (Character) value; - } - if (value instanceof Number) { - char c = (char) ((Number) value).intValue(); - return Character.valueOf(c); - } - try { - String s = value.toString(); - if (s.length() != 1) { - s = s.trim(); - if (!StringUtil.containsOnlyDigitsAndSigns(s)) { - throw new TypeConversionException(value); - } - - try { - char c = (char) Integer.parseInt(s); - return Character.valueOf(c); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - return Character.valueOf(s.charAt(0)); - } catch (IndexOutOfBoundsException ioobex) { - throw new TypeConversionException(value, ioobex); - } - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ClassArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ClassArrayConverter.java deleted file mode 100644 index 367b33fc1..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ClassArrayConverter.java +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.ArraysUtil; -import com.fr.third.jodd.util.StringPool; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to Class array. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • single Class is wrapped in 1-length array
  • - *
  • string value is converted to string array (from CSV format) and - * then each element is converted
  • - *
- * - * This converter supports custom syntax for defining array of classes in a String: - *
    - *
  • The following chars are delimiters: {@code ,;\n}.
  • - *
  • Blank lines are ignored
  • - *
  • Lines that starts with '#' (after trim) are ignored.
  • - *
- */ -public class ClassArrayConverter extends ArrayConverter { - - public ClassArrayConverter(final TypeConverterManager typeConverterManager) { - super(typeConverterManager, Class.class); - } - - @Override - protected Class[] createArray(final int length) { - return new Class[length]; - } - - @Override - protected String[] convertStringToArray(final String value) { - String[] strings = StringUtil.splitc(value, NUMBER_DELIMITERS); - - int count = 0; - - for (int i = 0; i < strings.length; i++) { - strings[count] = strings[i].trim(); - - if (strings[count].length() == 0) { - continue; - } - - if (!strings[count].startsWith(StringPool.HASH)) { - count++; - } - } - - if (count != strings.length) { - return ArraysUtil.subarray(strings, 0, count); - } - - return strings; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ClassConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ClassConverter.java deleted file mode 100644 index 6f4c5969a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ClassConverter.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.ClassLoaderUtil; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to Class. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • string value of the object is trimmed and used for class loading.
  • - *
- */ -public class ClassConverter implements TypeConverter { - - @Override - public Class convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Class.class) { - return (Class) value; - } - try { - String className = value.toString().trim(); - - if (className.endsWith(".class")) { - className = StringUtil.substring(className, 0, -6); - } - - return ClassLoaderUtil.loadClass(className); - } catch (ClassNotFoundException cnfex) { - throw new TypeConversionException(value, cnfex); - } - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CollectionConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CollectionConverter.java deleted file mode 100644 index af84fde4e..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/CollectionConverter.java +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.CsvUtil; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Collection converter. - */ -public class CollectionConverter implements TypeConverter> { - - protected final TypeConverterManager typeConverterManager; - protected final Class collectionType; - protected final Class targetComponentType; - - public CollectionConverter( - final Class collectionType, - final Class targetComponentType) { - this(TypeConverterManager.get(), collectionType, targetComponentType); - } - - public CollectionConverter( - final TypeConverterManager typeConverterManager, - final Class collectionType, - final Class targetComponentType) { - - this.typeConverterManager = typeConverterManager; - this.collectionType = collectionType; - this.targetComponentType = targetComponentType; - } - - @Override - public Collection convert(final Object value) { - if (value == null) { - return null; - } - - if (!(value instanceof Collection)) { - // source is not an array - return convertValueToCollection(value); - } - - // source is a collection - return convertCollectionToCollection((Collection)value); - } - - /** - * Converts type using type converter manager. - */ - protected T convertType(final Object value) { - return typeConverterManager.convertType(value, targetComponentType); - } - - /** - * Creates new collection of target component type. - * Default implementation uses reflection to create - * an collection of target type. Override it for better performances. - */ - @SuppressWarnings("unchecked") - protected Collection createCollection(final int length) { - if (collectionType.isInterface()) { - if (collectionType == List.class) { - if (length > 0) { - return new ArrayList<>(length); - } else { - return new ArrayList<>(); - } - } - - if (collectionType == Set.class) { - if (length > 0) { - return new HashSet<>(length); - } else { - return new HashSet<>(); - } - } - - throw new TypeConversionException("Unknown collection: " + collectionType.getName()); - } - if (length > 0) { - try { - Constructor> ctor = (Constructor>) collectionType.getConstructor(int.class); - return ctor.newInstance(Integer.valueOf(length)); - } catch (Exception ex) { - // ignore exception - } - } - - try { - return collectionType.getDeclaredConstructor().newInstance(); - } catch (Exception ex) { - throw new TypeConversionException(ex); - } - } - - /** - * Creates a collection with single element. - */ - protected Collection convertToSingleElementCollection(final Object value) { - Collection collection = createCollection(0); - - //noinspection unchecked - collection.add((T) value); - - return collection; - } - - /** - * Converts non-collection value to collection. - */ - protected Collection convertValueToCollection(Object value) { - if (value instanceof Iterable) { - Iterable iterable = (Iterable) value; - Collection collection = createCollection(0); - - for (Object element : iterable) { - collection.add(convertType(element)); - } - return collection; - } - - if (value instanceof CharSequence) { - value = CsvUtil.toStringArray(value.toString()); - } - - Class type = value.getClass(); - - if (type.isArray()) { - // convert arrays - Class componentType = type.getComponentType(); - - if (componentType.isPrimitive()) { - return convertPrimitiveArrayToCollection(value, componentType); - } else { - Object[] array = (Object[]) value; - Collection result = createCollection(array.length); - for (Object a : array) { - result.add(convertType(a)); - } - return result; - } - } - - // everything else: - return convertToSingleElementCollection(value); - } - - /** - * Converts collection value to target collection. - * Each element is converted to target component type. - */ - protected Collection convertCollectionToCollection(final Collection value) { - Collection collection = createCollection(value.size()); - - for (Object v : value) { - collection.add(convertType(v)); - } - - return collection; - } - - /** - * Converts primitive array to target collection. - */ - @SuppressWarnings("AutoBoxing") - protected Collection convertPrimitiveArrayToCollection(final Object value, final Class primitiveComponentType) { - Collection result = null; - - if (primitiveComponentType == int.class) { - int[] array = (int[]) value; - result = createCollection(array.length); - for (int a : array) { - result.add(convertType(a)); - } - } - else if (primitiveComponentType == long.class) { - long[] array = (long[]) value; - result = createCollection(array.length); - for (long a : array) { - result.add(convertType(a)); - } - } - else if (primitiveComponentType == float.class) { - float[] array = (float[]) value; - result = createCollection(array.length); - for (float a : array) { - result.add(convertType(a)); - } - } - else if (primitiveComponentType == double.class) { - double[] array = (double[]) value; - result = createCollection(array.length); - for (double a : array) { - result.add(convertType(a)); - } - } - else if (primitiveComponentType == short.class) { - short[] array = (short[]) value; - result = createCollection(array.length); - for (short a : array) { - result.add(convertType(a)); - } - } - else if (primitiveComponentType == byte.class) { - byte[] array = (byte[]) value; - result = createCollection(array.length); - for (byte a : array) { - result.add(convertType(a)); - } - } - else if (primitiveComponentType == char.class) { - char[] array = (char[]) value; - result = createCollection(array.length); - for (char a : array) { - result.add(convertType(a)); - } - } - else if (primitiveComponentType == boolean.class) { - boolean[] array = (boolean[]) value; - result = createCollection(array.length); - for (boolean a : array) { - result.add(convertType(a)); - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DateConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DateConverter.java deleted file mode 100644 index ffe33c9f9..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DateConverter.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.time.JulianDate; -import com.fr.third.jodd.time.TimeUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; - -/** - * Converts given object to java.util.Date. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • Calendar object is converted
  • - *
  • JulianDate object is converted
  • - *
  • LocalDateTime object is converted
  • - *
  • LocalDate object is converted
  • - *
  • Number is used as number of milliseconds
  • - *
  • finally, if string value contains only numbers it is parsed as milliseconds
  • - *
- */ -public class DateConverter implements TypeConverter { - - @Override - public Date convert(final Object value) { - if (value == null) { - return null; - } - - if (value instanceof Date) { - return (Date) value; - } - if (value instanceof Calendar) { - return new Date(((Calendar)value).getTimeInMillis()); - } - if (value instanceof JulianDate) { - return new Date(((JulianDate) value).toMilliseconds()); - } - if (value instanceof LocalDateTime) { - return TimeUtil.toDate((LocalDateTime)value); - } - if (value instanceof LocalDate) { - return TimeUtil.toDate((LocalDate)value); - } - if (value instanceof Number) { - return new Date(((Number) value).longValue()); - } - - final String stringValue = value.toString().trim(); - - if (!StringUtil.containsOnlyDigits(stringValue)) { - // try to parse default string format - return TimeUtil.toDate(LocalDateTime.parse(stringValue)); - } - - try { - long milliseconds = Long.parseLong(stringValue); - return new Date(milliseconds); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DoubleArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DoubleArrayConverter.java deleted file mode 100644 index 17b107447..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DoubleArrayConverter.java +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Converts given object to double[]. - */ -public class DoubleArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public DoubleArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public double[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected double convertType(final Object value) { - return typeConverterManager.convertType(value, double.class).doubleValue(); - } - - /** - * Creates an array with single element. - */ - protected double[] convertToSingleElementArray(final Object value) { - return new double[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected double[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final double[] target = new double[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final ArrayList doubleArrayList = new ArrayList<>(); - - for (final Object element : iterable) { - final double convertedValue = convertType(element); - doubleArrayList.add(Double.valueOf(convertedValue)); - } - - final double[] array = new double[doubleArrayList.size()]; - - for (int i = 0; i < doubleArrayList.size(); i++) { - final Double d = doubleArrayList.get(i); - array[i] = d.doubleValue(); - } - - return array; - } - - if (value instanceof CharSequence) { - final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected double[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final double[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new double[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected double[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - double[] result = null; - - if (primitiveComponentType == double.class) { - return (double[]) value; - } - - if (primitiveComponentType == int.class) { - final int[] array = (int[]) value; - result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == long.class) { - final long[] array = (long[]) value; - result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == float.class) { - final float[] array = (float[]) value; - result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == short.class) { - final short[] array = (short[]) value; - result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == byte.class) { - final byte[] array = (byte[]) value; - result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == char.class) { - final char[] array = (char[]) value; - result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == boolean.class) { - final boolean[] array = (boolean[]) value; - result = new double[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] ? 1 : 0; - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DoubleConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DoubleConverter.java deleted file mode 100644 index b983155eb..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/DoubleConverter.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to Double. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible.
  • - *
- * Number string may start with plus and minus sign. - */ -public class DoubleConverter implements TypeConverter { - - public Double convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Double.class) { - return (Double) value; - } - if (value instanceof Number) { - return Double.valueOf(((Number)value).doubleValue()); - } - if (value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? Double.valueOf(1) : Double.valueOf(0); - } - - try { - String stringValue = value.toString().trim(); - if (StringUtil.startsWithChar(stringValue, '+')) { - stringValue = stringValue.substring(1); - } - return Double.valueOf(stringValue); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FileConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FileConverter.java deleted file mode 100644 index 5ee9a299d..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FileConverter.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.io.FileUtil; -import com.fr.third.jodd.io.StreamUtil; -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -/** - * Converts given object into the File. - * If created, returned file is stored in the temporary folder. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • byte[] content is used for creating a file
  • - *
  • String content is used for creating a file
  • - *
- *

- * This converter is plugable and add-on file converters from - * other modules can be added. - */ -public class FileConverter implements TypeConverter { - - @Override - public File convert(final Object value) { - if (value == null) { - return null; - } - - if (value instanceof File) { - return (File) value; - } - - if (value instanceof FileUpload) { - FileUpload fileUpload = (FileUpload) value; - - InputStream in = null; - try { - in = fileUpload.getFileInputStream(); - File tempFile = FileUtil.createTempFile(); - FileUtil.writeStream(tempFile, in); - return tempFile; - } catch (IOException ioex) { - throw new TypeConversionException(ioex); - } finally { - StreamUtil.close(in); - } - } - - Class type = value.getClass(); - if (type == byte[].class) { - try { - File tempFile = FileUtil.createTempFile(); - FileUtil.writeBytes(tempFile, (byte[])value); - return tempFile; - } catch (IOException ioex) { - throw new TypeConversionException(ioex); - } - } - if (type == String.class) { - try { - File tempFile = FileUtil.createTempFile(); - FileUtil.writeString(tempFile, value.toString()); - return tempFile; - } catch (IOException ioex) { - throw new TypeConversionException(ioex); - } - } - throw new TypeConversionException(value); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FileUploadConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FileUploadConverter.java deleted file mode 100644 index ea85b84a1..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FileUploadConverter.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.io.upload.FileUpload; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; - -/** - * Converts given object to {@link FileUpload}. - * Conversion rules: - *

    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
- */ -public class FileUploadConverter implements TypeConverter { - - @Override - public FileUpload convert(final Object value) { - if (value == null) { - return null; - } - if (value instanceof FileUpload) { - return (FileUpload) value; - } - throw new TypeConversionException(value); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FloatArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FloatArrayConverter.java deleted file mode 100644 index b4fbcb178..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FloatArrayConverter.java +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Converts given object to float[]. - */ -public class FloatArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public FloatArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public float[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected float convertType(final Object value) { - return typeConverterManager.convertType(value, float.class).floatValue(); - } - - /** - * Creates an array with single element. - */ - protected float[] convertToSingleElementArray(final Object value) { - return new float[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected float[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final float[] target = new float[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final ArrayList floatArrayList = new ArrayList<>(); - - for (final Object element : iterable) { - final float convertedValue = convertType(element); - floatArrayList.add(Float.valueOf(convertedValue)); - } - - final float[] array = new float[floatArrayList.size()]; - - for (int i = 0; i < floatArrayList.size(); i++) { - final Float f = floatArrayList.get(i); - array[i] = f.floatValue(); - } - - return array; - } - - if (value instanceof CharSequence) { - final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected float[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final float[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new float[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected float[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - float[] result = null; - - if (primitiveComponentType == float.class) { - return (float[]) value; - } - - if (primitiveComponentType == int.class) { - final int[] array = (int[]) value; - result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == long.class) { - final long[] array = (long[]) value; - result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == double.class) { - final double[] array = (double[]) value; - result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (float) array[i]; - } - } - else if (primitiveComponentType == short.class) { - final short[] array = (short[]) value; - result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == byte.class) { - final byte[] array = (byte[]) value; - result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == char.class) { - final char[] array = (char[]) value; - result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == boolean.class) { - final boolean[] array = (boolean[]) value; - result = new float[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] ? 1 : 0; - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FloatConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FloatConverter.java deleted file mode 100644 index fb9155175..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/FloatConverter.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to Float. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible.
  • - *
- * Number string may start with plus and minus sign. - */ -public class FloatConverter implements TypeConverter { - - public Float convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Float.class) { - return (Float) value; - } - if (value instanceof Number) { - return Float.valueOf(((Number)value).floatValue()); - } - if (value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? Float.valueOf(1) : Float.valueOf(0); - } - - try { - String stringValue = value.toString().trim(); - if (StringUtil.startsWithChar(stringValue, '+')) { - stringValue = stringValue.substring(1); - } - return Float.valueOf(stringValue); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/IntegerArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/IntegerArrayConverter.java deleted file mode 100644 index c2ec6b475..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/IntegerArrayConverter.java +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.buffer.FastIntBuffer; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.StringUtil; - -import java.util.Collection; - -/** - * Converts given object to int[]. - */ -public class IntegerArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public IntegerArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public int[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected int convertType(final Object value) { - return typeConverterManager.convertType(value, int.class).intValue(); - } - - /** - * Creates an array with single element. - */ - protected int[] convertToSingleElementArray(final Object value) { - return new int[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected int[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final int[] target = new int[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final FastIntBuffer fastIntBuffer = new FastIntBuffer(); - - for (final Object element : iterable) { - final int convertedValue = convertType(element); - fastIntBuffer.append(convertedValue); - } - - return fastIntBuffer.toArray(); - } - - if (value instanceof CharSequence) { - final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected int[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final int[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new int[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected int[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - int[] result = null; - - if (primitiveComponentType == int.class) { - return (int[]) value; - } - - if (primitiveComponentType == long.class) { - final long[] array = (long[]) value; - result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (int) array[i]; - } - } - else if (primitiveComponentType == float.class) { - final float[] array = (float[]) value; - result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (int) array[i]; - } - } - else if (primitiveComponentType == double.class) { - final double[] array = (double[]) value; - result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (int) array[i]; - } - } - else if (primitiveComponentType == short.class) { - final short[] array = (short[]) value; - result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (int) array[i]; - } - } - else if (primitiveComponentType == byte.class) { - final byte[] array = (byte[]) value; - result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (int) array[i]; - } - } - else if (primitiveComponentType == char.class) { - final char[] array = (char[]) value; - result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (int) array[i]; - } - } - else if (primitiveComponentType == boolean.class) { - final boolean[] array = (boolean[]) value; - result = new int[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] ? 1 : 0; - } - } - return result; - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/IntegerConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/IntegerConverter.java deleted file mode 100644 index d0f05b4a2..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/IntegerConverter.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to an Integer. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible.
  • - *
- * Number string may start with plus and minus sign. - */ -public class IntegerConverter implements TypeConverter { - - public Integer convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Integer.class) { - return (Integer) value; - } - if (value instanceof Number) { - return Integer.valueOf(((Number)value).intValue()); - } - if (value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? Integer.valueOf(1) : Integer.valueOf(0); - } - - try { - String stringValue = value.toString().trim(); - if (StringUtil.startsWithChar(stringValue, '+')) { - stringValue = stringValue.substring(1); - } - return Integer.valueOf(stringValue); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalDateConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalDateConverter.java deleted file mode 100644 index 15fa6736a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalDateConverter.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.time.TimeUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.Calendar; -import java.util.Date; - -public class LocalDateConverter implements TypeConverter { - @Override - public LocalDate convert(Object value) { - if (value == null) { - return null; - } - - if (value instanceof LocalDateTime) { - return ((LocalDateTime)value).toLocalDate(); - } - if (value instanceof Calendar) { - return TimeUtil.fromCalendar((Calendar) value).toLocalDate(); - } - if (value instanceof Timestamp) { - return TimeUtil.fromMilliseconds(((Timestamp)value).getTime()).toLocalDate(); - } - if (value instanceof Date) { - return TimeUtil.fromDate((Date) value).toLocalDate(); - } - if (value instanceof Number) { - return TimeUtil.fromMilliseconds(((Number)value).longValue()).toLocalDate(); - } - if (value instanceof LocalTime) { - throw new TypeConversionException("Can't convert to date just from time: " + value); - } - - String stringValue = value.toString().trim(); - - if (!StringUtil.containsOnlyDigits(stringValue)) { - // try to parse default string format - return LocalDate.parse(stringValue); - } - - try { - return TimeUtil.fromMilliseconds(Long.parseLong(stringValue)).toLocalDate(); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalDateTimeConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalDateTimeConverter.java deleted file mode 100644 index d26dfd183..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalDateTimeConverter.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.time.TimeUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.Calendar; -import java.util.Date; - -public class LocalDateTimeConverter implements TypeConverter { - @Override - public LocalDateTime convert(Object value) { - if (value == null) { - return null; - } - - if (value instanceof LocalDate) { - return LocalDateTime.of(((LocalDate) value), LocalTime.MIDNIGHT); - } - if (value instanceof Calendar) { - return TimeUtil.fromCalendar((Calendar) value); - } - if (value instanceof Timestamp) { - return TimeUtil.fromMilliseconds(((Timestamp)value).getTime()); - } - if (value instanceof Date) { - return TimeUtil.fromDate((Date) value); - } - if (value instanceof Number) { - return TimeUtil.fromMilliseconds(((Number)value).longValue()); - } - if (value instanceof LocalTime) { - throw new TypeConversionException("Can't convert to date just from time: " + value); - } - - String stringValue = value.toString().trim(); - - if (!StringUtil.containsOnlyDigits(stringValue)) { - // try to parse default string format - return LocalDateTime.parse(stringValue); - } - - try { - return TimeUtil.fromMilliseconds(Long.parseLong(stringValue)); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalTimeConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalTimeConverter.java deleted file mode 100644 index 42982c1fe..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocalTimeConverter.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.time.TimeUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.Calendar; -import java.util.Date; - -public class LocalTimeConverter implements TypeConverter { - @Override - public LocalTime convert(Object value) { - if (value == null) { - return null; - } - - if (value instanceof LocalDateTime) { - return ((LocalDateTime)value).toLocalTime(); - } - if (value instanceof Calendar) { - return TimeUtil.fromCalendar((Calendar) value).toLocalTime(); - } - if (value instanceof Timestamp) { - return TimeUtil.fromMilliseconds(((Timestamp)value).getTime()).toLocalTime(); - } - if (value instanceof Date) { - return TimeUtil.fromDate((Date) value).toLocalTime(); - } - if (value instanceof Number) { - return TimeUtil.fromMilliseconds(((Number)value).longValue()).toLocalTime(); - } - if (value instanceof LocalDate) { - throw new TypeConversionException("Can't convert to time just from date: " + value); - } - - String stringValue = value.toString().trim(); - - if (!StringUtil.containsOnlyDigits(stringValue)) { - // try to parse default string format - return LocalTime.parse(stringValue); - } - - try { - return TimeUtil.fromMilliseconds(Long.parseLong(stringValue)).toLocalTime(); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - - } -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocaleConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocaleConverter.java deleted file mode 100644 index 5ceb40b61..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LocaleConverter.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverter; - -import java.util.Locale; - -/** - * Converts given object to Java Locale. - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • finally, string representation of the object is used for getting the locale
  • - *
- */ -public class LocaleConverter implements TypeConverter { - - @Override - public Locale convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Locale.class) { - return (Locale) value; - } - - return Locale.forLanguageTag(value.toString()); - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LongArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LongArrayConverter.java deleted file mode 100644 index 94cf2be74..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LongArrayConverter.java +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Converts given object to long[]. - */ -public class LongArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public LongArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public long[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected long convertType(final Object value) { - return typeConverterManager.convertType(value, long.class).longValue(); - } - - /** - * Creates an array with single element. - */ - protected long[] convertToSingleElementArray(final Object value) { - return new long[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected long[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final long[] target = new long[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final ArrayList longArrayList = new ArrayList<>(); - - for (final Object element : iterable) { - final long convertedValue = convertType(element); - longArrayList.add(Long.valueOf(convertedValue)); - } - - final long[] array = new long[longArrayList.size()]; - - for (int i = 0; i < longArrayList.size(); i++) { - final Long l = longArrayList.get(i); - array[i] = l.longValue(); - } - - return array; - } - - if (value instanceof CharSequence) { - final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected long[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final long[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new long[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected long[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - long[] result = null; - - if (primitiveComponentType == long.class) { - return (long[]) value; - } - - if (primitiveComponentType == int.class) { - final int[] array = (int[]) value; - result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == float.class) { - final float[] array = (float[]) value; - result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (long) array[i]; - } - } - else if (primitiveComponentType == double.class) { - final double[] array = (double[]) value; - result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (long) array[i]; - } - } - else if (primitiveComponentType == short.class) { - final short[] array = (short[]) value; - result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == byte.class) { - final byte[] array = (byte[]) value; - result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == char.class) { - final char[] array = (char[]) value; - result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == boolean.class) { - final boolean[] array = (boolean[]) value; - result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] ? 1 : 0; - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LongConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LongConverter.java deleted file mode 100644 index c4043e7a6..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/LongConverter.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to a Long. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible.
  • - *
- * Number string may start with plus and minus sign. - */ -public class LongConverter implements TypeConverter { - - public Long convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Long.class) { - return (Long) value; - } - if (value instanceof Number) { - return Long.valueOf(((Number)value).longValue()); - } - if (value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? Long.valueOf(1L) : Long.valueOf(0L); - } - - try { - String stringValue = value.toString().trim(); - if (StringUtil.startsWithChar(stringValue, '+')) { - stringValue = stringValue.substring(1); - } - return Long.valueOf(stringValue); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableByteConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableByteConverter.java deleted file mode 100644 index 54a6762f4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableByteConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.mutable.MutableByte; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; - -/** - * Converts given object to {@link MutableByte}. - */ -public class MutableByteConverter implements TypeConverter { - - protected final TypeConverter typeConverter; - - @SuppressWarnings("unchecked") - public MutableByteConverter(final TypeConverterManager typeConverterManager) { - typeConverter = typeConverterManager.lookup(Byte.class); - } - - @Override - public MutableByte convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == MutableByte.class) { - return (MutableByte) value; - } - - return new MutableByte(typeConverter.convert(value)); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableDoubleConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableDoubleConverter.java deleted file mode 100644 index 7866f14b4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableDoubleConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.mutable.MutableDouble; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; - -/** - * Converts given object to {@link MutableDouble}. - */ -public class MutableDoubleConverter implements TypeConverter { - - protected final TypeConverter typeConverter; - - @SuppressWarnings("unchecked") - public MutableDoubleConverter(final TypeConverterManager typeConverterManager) { - typeConverter = typeConverterManager.lookup(Double.class); - } - - @Override - public MutableDouble convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == MutableDouble.class) { - return (MutableDouble) value; - } - - return new MutableDouble(typeConverter.convert(value)); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableFloatConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableFloatConverter.java deleted file mode 100644 index 0b804f25f..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableFloatConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.mutable.MutableFloat; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; - -/** - * Converts given object to {@link MutableFloat}. - */ -public class MutableFloatConverter implements TypeConverter { - - protected final TypeConverter typeConverter; - - @SuppressWarnings("unchecked") - public MutableFloatConverter(final TypeConverterManager typeConverterManager) { - typeConverter = typeConverterManager.lookup(Float.class); - } - - @Override - public MutableFloat convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == MutableFloat.class) { - return (MutableFloat) value; - } - - return new MutableFloat(typeConverter.convert(value)); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableIntegerConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableIntegerConverter.java deleted file mode 100644 index 85940507b..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableIntegerConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.mutable.MutableInteger; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; - -/** - * Converts given object to an {@link MutableInteger}. - */ -public class MutableIntegerConverter implements TypeConverter { - - protected final TypeConverter typeConverter; - - @SuppressWarnings("unchecked") - public MutableIntegerConverter(final TypeConverterManager typeConverterManager) { - typeConverter = typeConverterManager.lookup(Integer.class); - } - - @Override - public MutableInteger convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == MutableInteger.class) { - return (MutableInteger) value; - } - - return new MutableInteger(typeConverter.convert(value)); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableLongConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableLongConverter.java deleted file mode 100644 index 075f00959..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableLongConverter.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.mutable.MutableLong; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; - -/** - * Converts given object to a {@link MutableLong}. - */ -public class MutableLongConverter implements TypeConverter { - - protected final TypeConverter typeConverter; - - @SuppressWarnings("unchecked") - public MutableLongConverter(final TypeConverterManager typeConverterManager) { - typeConverter = typeConverterManager.lookup(Long.class); - } - - @Override - public MutableLong convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == MutableLong.class) { - return (MutableLong) value; - } - - return new MutableLong(typeConverter.convert(value)); - } -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableShortConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableShortConverter.java deleted file mode 100644 index 14f828ebb..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/MutableShortConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.mutable.MutableShort; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; - -/** - * Converts given object to {@link MutableShort}. - */ -public class MutableShortConverter implements TypeConverter { - - protected final TypeConverter typeConverter; - - @SuppressWarnings("unchecked") - public MutableShortConverter(final TypeConverterManager typeConverterManager) { - typeConverter = typeConverterManager.lookup(Short.class); - } - - @Override - public MutableShort convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == MutableShort.class) { - return (MutableShort) value; - } - - return new MutableShort(typeConverter.convert(value)); - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ShortArrayConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ShortArrayConverter.java deleted file mode 100644 index 076789c6a..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ShortArrayConverter.java +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.typeconverter.TypeConverterManager; -import com.fr.third.jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Converts given object to short[]. - */ -public class ShortArrayConverter implements TypeConverter { - - protected final TypeConverterManager typeConverterManager; - - public ShortArrayConverter(final TypeConverterManager typeConverterManager) { - this.typeConverterManager = typeConverterManager; - } - - @Override - public short[] convert(final Object value) { - if (value == null) { - return null; - } - - final Class valueClass = value.getClass(); - - if (!valueClass.isArray()) { - // source is not an array - return convertValueToArray(value); - } - - // source is an array - return convertArrayToArray(value); - } - - /** - * Converts type using type converter manager. - */ - protected short convertType(final Object value) { - return typeConverterManager.convertType(value, short.class).shortValue(); - } - - /** - * Creates an array with single element. - */ - protected short[] convertToSingleElementArray(final Object value) { - return new short[] {convertType(value)}; - } - - /** - * Converts non-array value to array. Detects various - * collection types and iterates them to make conversion - * and to create target array. - */ - protected short[] convertValueToArray(final Object value) { - if (value instanceof Collection) { - final Collection collection = (Collection) value; - final short[] target = new short[collection.size()]; - - int i = 0; - for (final Object element : collection) { - target[i] = convertType(element); - i++; - } - - return target; - } - - if (value instanceof Iterable) { - final Iterable iterable = (Iterable) value; - - final ArrayList shortArrayList = new ArrayList<>(); - - for (final Object element : iterable) { - final short convertedValue = convertType(element); - shortArrayList.add(Short.valueOf(convertedValue)); - } - - final short[] array = new short[shortArrayList.size()]; - - for (int i = 0; i < shortArrayList.size(); i++) { - final Short s = shortArrayList.get(i); - array[i] = s.shortValue(); - } - - return array; - } - - if (value instanceof CharSequence) { - final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS); - return convertArrayToArray(strings); - } - - // everything else: - return convertToSingleElementArray(value); - } - - /** - * Converts array value to array. - */ - protected short[] convertArrayToArray(final Object value) { - final Class valueComponentType = value.getClass().getComponentType(); - - final short[] result; - - if (valueComponentType.isPrimitive()) { - result = convertPrimitiveArrayToArray(value, valueComponentType); - } else { - // convert object array to target array - final Object[] array = (Object[]) value; - result = new short[array.length]; - - for (int i = 0; i < array.length; i++) { - result[i] = convertType(array[i]); - } - } - - return result; - } - - - /** - * Converts primitive array to target array. - */ - protected short[] convertPrimitiveArrayToArray(final Object value, final Class primitiveComponentType) { - short[] result = null; - - if (primitiveComponentType == short.class) { - return (short[]) value; - } - - if (primitiveComponentType == int.class) { - final int[] array = (int[]) value; - result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (short) array[i]; - } - } - else if (primitiveComponentType == long.class) { - final long[] array = (long[]) value; - result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (short) array[i]; - } - } - else if (primitiveComponentType == float.class) { - final float[] array = (float[]) value; - result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (short) array[i]; - } - } - else if (primitiveComponentType == double.class) { - final double[] array = (double[]) value; - result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (short) array[i]; - } - } - else if (primitiveComponentType == byte.class) { - final byte[] array = (byte[]) value; - result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i]; - } - } - else if (primitiveComponentType == char.class) { - final char[] array = (char[]) value; - result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (short) array[i]; - } - } - else if (primitiveComponentType == boolean.class) { - final boolean[] array = (boolean[]) value; - result = new short[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = (short) (array[i] ? 1 : 0); - } - } - return result; - } - -} \ No newline at end of file diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ShortConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ShortConverter.java deleted file mode 100644 index 834d413e4..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/ShortConverter.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -/** - * Converts given object to Short. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • object is converted to string, trimmed, and then converted if possible.
  • - *
- * Number string may start with plus and minus sign. - */ -public class ShortConverter implements TypeConverter { - - @Override - public Short convert(final Object value) { - if (value == null) { - return null; - } - - if (value.getClass() == Short.class) { - return (Short) value; - } - if (value instanceof Number) { - return Short.valueOf(((Number)value).shortValue()); - } - if (value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? Short.valueOf((short) 1) : Short.valueOf((short) 0); - } - - try { - String stringValue = value.toString().trim(); - if (StringUtil.startsWithChar(stringValue, '+')) { - stringValue = stringValue.substring(1); - } - return Short.valueOf(stringValue); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/SqlDateConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/SqlDateConverter.java deleted file mode 100644 index 7932e47c0..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/SqlDateConverter.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.time.JulianDate; -import com.fr.third.jodd.time.TimeUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -import java.sql.Date; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Calendar; - - -/** - * Converts given object to java.sql.Date. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • Calendar object is converted
  • - *
  • Date object is converted
  • - *
  • JulianDate object is converted
  • - *
  • LocalDateTime object is converted
  • - *
  • LocalDate object is converted
  • - *
  • Number is used as number of milliseconds
  • - *
  • finally, if string value contains only numbers it is parsed as milliseconds
  • - *
- */ -public class SqlDateConverter implements TypeConverter { - - @Override - public Date convert(final Object value) { - if (value == null) { - return null; - } - - if (value instanceof Date) { - return (Date) value; - } - if (value instanceof Calendar) { - return new Date(((Calendar)value).getTimeInMillis()); - } - if (value instanceof java.util.Date) { - return new Date(((java.util.Date)value).getTime()); - } - if (value instanceof JulianDate) { - return new Date(((JulianDate) value).toMilliseconds()); - } - if (value instanceof LocalDateTime) { - return new Date(TimeUtil.toMilliseconds((LocalDateTime)value)); - } - if (value instanceof LocalDate) { - return new Date(TimeUtil.toMilliseconds((LocalDate)value)); - } - if (value instanceof Number) { - return new Date(((Number) value).longValue()); - } - - final String stringValue = value.toString().trim(); - - // try yyyy-mm-dd for valueOf - if (!StringUtil.containsOnlyDigits(stringValue)) { - try { - return Date.valueOf(stringValue); - } catch (IllegalArgumentException iaex) { - throw new TypeConversionException(value, iaex); - } - } - - // assume string to be a number - try { - long milliseconds = Long.parseLong(stringValue); - return new Date(milliseconds); - } catch (NumberFormatException nfex) { - throw new TypeConversionException(value, nfex); - } - } - -} diff --git a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/SqlTimeConverter.java b/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/SqlTimeConverter.java deleted file mode 100644 index e1bae488d..000000000 --- a/fine-jodd/src/main/java/com/fr/third/jodd/typeconverter/impl/SqlTimeConverter.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package com.fr.third.jodd.typeconverter.impl; - -import com.fr.third.jodd.time.JulianDate; -import com.fr.third.jodd.time.TimeUtil; -import com.fr.third.jodd.typeconverter.TypeConversionException; -import com.fr.third.jodd.typeconverter.TypeConverter; -import com.fr.third.jodd.util.StringUtil; - -import java.sql.Time; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; - -/** - * Converts given object to java.sql.Time. - * Conversion rules: - *
    - *
  • null value is returned as null
  • - *
  • object of destination type is simply casted
  • - *
  • Calendar object is converted
  • - *
  • Date object is converted
  • - *
  • JulianDate object is converted
  • - *
  • LocalDateTime object is converted
  • - *
  • LocalDate object is converted
  • - *
  • Number is used as number of milliseconds
  • - *
  • finally, if string value contains only numbers it is parsed as milliseconds
  • - *
- */ -public class SqlTimeConverter implements TypeConverter