jenkins-json-2.4-jenkins-3/0000775000175000017500000000000011650253660016246 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/.gitignore0000664000175000017500000000015011650253660020232 0ustar jamespagejamespage.gradle target velocity.log cobertura.ser build.properties .classpath .project .settings build.sh build jenkins-json-2.4-jenkins-3/deploy.sh0000664000175000017500000000507011650253660020100 0ustar jamespagejamespage#!/bin/sh VERSION="2.4" GROUPID="net.sf.json-lib" ARTIFACTID="json-lib" REPO_URL="scp://ssh.sf.net/home/groups/j/js/json-lib/htdocs/m2/repo/release" REPOSITORYID="sf_release" mkdir build ant source.jar mv target/${ARTIFACTID}-${VERSION}-jdk13-sources.jar build ant source.jar.jdk5 mv target/${ARTIFACTID}-${VERSION}-jdk15-sources.jar build ant javadoc mv target/${ARTIFACTID}-${VERSION}-jdk13-javadoc.jar build ant javadoc.jdk5 mv target/${ARTIFACTID}-${VERSION}-jdk15-javadoc.jar build ant jar mv target/${ARTIFACTID}-${VERSION}-jdk13.jar build ant jar.jdk5 mv target/${ARTIFACTID}-${VERSION}-jdk15.jar build mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -DgeneratePom=false \ -Dclassifier=jdk13-javadoc \ -Dfile=build/${ARTIFACTID}-${VERSION}-jdk13-javadoc.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -DgeneratePom=false \ -Dclassifier=jdk15-javadoc \ -Dfile=build/${ARTIFACTID}-${VERSION}-jdk15-javadoc.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -DgeneratePom=false \ -Dclassifier=jdk13-sources \ -Dfile=build/${ARTIFACTID}-${VERSION}-jdk13-sources.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -DgeneratePom=false \ -Dclassifier=jdk15-sources \ -Dfile=build/${ARTIFACTID}-${VERSION}-jdk15-sources.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -Dclassifier=jdk15 \ -Dfile=build/${ARTIFACTID}-${VERSION}-jdk15.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -Dclassifier=jdk13 \ -Dfile=build/${ARTIFACTID}-${VERSION}-jdk13.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=pom \ -DgeneratePom=false \ -Dfile=pom.xml jenkins-json-2.4-jenkins-3/pom.xml0000664000175000017500000003200611650253660017564 0ustar jamespagejamespage 4.0.0 org.kohsuke.stapler json-lib jar 2.4-jenkins-3 json-lib http://json-lib.sourceforge.net Java library for transforming beans, maps, collections, java arrays and XML to JSON. 2006 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo This product includes software developed by Douglas Crockford (http://www.crockford.com). Json-lib http://json-lib.sourceforge.net scm:git:git://github.com/jenkinsci/json-lib.git scm:git:ssh://git@github.com/jenkinsci/json-lib.git https://github.com/jenkinsci/json-lib SourceForge https://sourceforge.net/tracker/?group_id=171425 Json-lib User List http://lists.sourceforge.net/lists/listinfo/json-lib-user http://lists.sourceforge.net/lists/listinfo/json-lib-user http://sourceforge.net/mailarchive/forum.php?forum=json-lib-user Douglas Crockford json at JSON.org JSON.org Original source code developer Andres Almiray aalmiray aalmiray@users.sourceforge.net -5 Java Developer Matt Small WaveMaker Contributed generics support Dan Fabulich Feedback on JDK5 and JEE features Masato Nagai Patch for XMLSerializer Gino Miceli Patch for PropertySet strategy Mino Tonga Yee_Keat Phuah Patch for thread safety in JSONObject/JSONArray Oliver Zyngier Marcelo Liberato Mathias Herberst Ales Novy Patch for performance improvements in JSONUtils Patch for propagating JsonConfig to missing methods on JSONObject Peter Schubert Performance patch for JSONUtils Ian Wolfcat Atha Performance patch for JSONUtils junit junit 3.8.2 compile true xmlunit xmlunit 1.0 test commons-beanutils commons-beanutils 1.8.0 compile commons-collections commons-collections 3.2.1 compile commons-lang commons-lang 2.5 compile commons-logging commons-logging 1.1.1 compile log4j log4j logkit logkit avalon-framework avalon-framework javax.servlet servlet-api xom xom 1.1 compile true oro oro 2.0.8 compile true net.sf.ezmorph ezmorph 1.0.6 compile log4j log4j 1.2.14 runtime true org.codehaus.groovy groovy-all 1.8.0 compile true commons-httpclient commons-httpclient 3.1 test 3.0.1 install maven-compiler-plugin 1.5 1.5 org.codehaus.mojo build-helper-maven-plugin add-source generate-sources add-source src/main/jdk15 add-test-source generate-test-sources add-test-source src/test/jdk15 org.apache.maven.plugins maven-site-plugin ${basedir}/src/site org.apache.maven.plugins maven-surefire-plugin 2.8 **/Abstract*.java **/AllTests.java **/*closure* **/Test*.java org.apache.maven.plugins maven-project-info-reports-plugin org.apache.maven.plugins maven-surefire-report-plugin org.apache.maven.plugins maven-jxr-plugin org.apache.maven.plugins maven-javadoc-plugin 2.1 http://java.sun.com/j2se/1.5.0/docs/api/ http://www.junit.org/junit/javadoc/ http://jakarta.apache.org/commons/beanutils/commons-beanutils-1.7.0/docs/api/ http://jakarta.apache.org/commons/lang/api-2.2/ http://ezmorph.sourceforge.net/apidocs/ org.codehaus.mojo cobertura-maven-plugin org.codehaus.mojo changes-maven-plugin changes-report org.codehaus.mojo jdepend-maven-plugin org.codehaus.mojo javancss-maven-plugin 2.0-beta-1 maven.jenkins-ci.org http://maven.jenkins-ci.org:8081/content/repositories/releases maven.jenkins-ci.org http://maven.jenkins-ci.org:8081/content/repositories/snapshots jenkins-json-2.4-jenkins-3/.cvsignore0000664000175000017500000000014711650253660020250 0ustar jamespagejamespagetarget velocity.log cobertura.ser build.properties .classpath .project .settings .jruby build.sh build jenkins-json-2.4-jenkins-3/.hgignore0000664000175000017500000000005411650253660020050 0ustar jamespagejamespagesyntax: glob target build *.iml *.ipr *.iws jenkins-json-2.4-jenkins-3/build.gradle0000664000175000017500000000235711650253660020534 0ustar jamespagejamespageapply plugin: 'groovy' apply plugin: 'maven' // apply plugin: 'code-quality' sourceCompatibility = '1.3' targetCompatibility = '1.1' archivesBaseName = 'json-lib' group = 'net.sf.json-lib' version = '2.4.1' configurations { jdk15 { extendsFrom compile } } repositories { mavenCentral() } dependencies { groovy 'org.codehaus.groovy:groovy-all:1.8.10' compile 'junit:junit:3.8.2', 'commons-beanutils:commons-beanutils:1.8.0', 'commons-collections:commons-collections:3.2.1', 'commons-lang:commons-lang:2.5', compile('commons-logging:commons-logging:1.1.1') { exclude(module: 'log4j') exclude(module: 'logkit') exclude(module: 'avalon-framework') exclude(module: 'servlet-api') } // the following are optional compile 'xom:xom:1.1', 'oro:oro:2.0.8', 'net.sf.ezmorph:ezmorph:1.0.6', 'org.codehaus.groovy:groovy-all:1.8.10' runtime 'log4j:log4j:1.2.14' testCompile 'xmlunit:xmlunit:1.0', 'commons-httpclient:commons-httpclient:3.1' } sourceSets { jdk15 { compileClasspath = sourceSets.main.classes + configurations.jdk15 java.srcDirs = ['src/main/jdk15'] groovy.srcDirs = [] classesDir = "$buildDir/classes/jdk15" as File } } jenkins-json-2.4-jenkins-3/build.xml0000664000175000017500000003764011650253660020101 0ustar jamespagejamespage ================================= WARNING ================================ Junit isn't present in your $ANT_HOME/lib directory. Tests not executed. ========================================================================== jenkins-json-2.4-jenkins-3/src/0000775000175000017500000000000011650253660017035 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/changes/0000775000175000017500000000000011650253660020445 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/changes/changes.xml0000664000175000017500000011467011650253660022610 0ustar jamespagejamespage Json-lib::Changelog Andres Almiray JSONObject.toBean does not process Lists Groovy script JsonGroovyBuilder not working JsonGroovyBuilder does not work from Groovy script GJson.enhanceClasses() not working Permgen memory leak with ThreadLocal JSONSerializer.toJSON().toString() -> result != source String start with "[" and end with "]" parsed error. Source is not passed to the NewBeanInstanceStrategy Binaries and source files desynchronized Sources jar not match json-lib-2.3-jdk15.jar Allow bean processors to use json-lib's default processor. Thanks to Scott Bronson(provided patch) Morphing elements in JSONArray.toCollection. Thanks to Arnout Engelen (provided patch) A string starting and ending with quotes is badly parsed. Thanks to Sascha Theves (provided patch) JsonGroovyBuilder does not work from Groovy script. Thanks to Sergey Bondarenko (provided patch) Better support for parsing numbers. Thanks to Chirag Shah (provided patch) Maps with non-String keys throw ClassCastException Incorrect event firing on cycles JSONObject Map.size() implementation is incorrect. Thanks to Earl Nolan (provided testcase) Annotation filter net.sf.json.util.JSONUtils.isFunction() locks. Thanks to Ian Wolfcat Atha (provided patch) Inconsistent license between the source file and project Support for reading both properties and public fields undefined not an acceptable parser token Allow JSONArray/JSONObject to be Serializable JsonValueProcessor not processing primitive arrays (breaking change!) Memory Leak in Cycle Detection Problems detecting an unreadable property Log level: warn vs. info for skipped properties Improve exception message on NewBeanInstanceStrategy. Thanks to Henrik Johansson (provided patch) JSONUtils not thread safe Array of Maps with null key causes exception JsonSlurper.parse(Reader) does not work correctly. Thanks to Tom Nichols (provided testcase) JavaScript functions as quoted strings in values Infinite loop in JSONArray._fromJSONTokener Performance improvement for JSONUtils.quote Thanks to Peter Schubert (provided a patch) Excludes should allow for exclusions based on class JSONArray and ListIterator Define reverse PropertyNameProcessor Add class name to skipped properties messages Inner beans not deserialized when using PropertySetStrategy JsonVerifier does not account for Short values Propagation of JsonConfig in JSONObject methods. Thanks to Ales Novy (provided a patch) Performace patch in JSONUtil. Thanks to Ales Novy (provided a patch) Json-lib cannot parse functions with more than one argument Parsing error with line break after "function()" XML/JSON roundtrip looses types Does not support xml-json rules properly Add a strategy for mutating a bean's property name Interface Fields Support Added JsonSlurper Force top JSONObject while reading from XML Add a CycleDetectionStrategy that skips the property Json-lib 2.1 jar contains groovy metaclass Need configurable JsonValueProcessorMatcher Use order-preserving map in JSONObject Add a skipWhitespace flag to XMLSerializer JSONUtils.mayBeJSON is broken Add support of Sets in JSONObject.toBean Add a chained version of remove to JSONObject. Initial generics support. Many thanks to Matt Small (and WaveMaker) (provided patch and tests). (rolled-back) Don't require the user to register Enum morphs by hand Ignore getters annotated with @Transient. Thanks to Dan Fabulich (provided workaround) Use private no-arg constructors when available. Thanks to Dan Fabulich (provided workaround) Enums should be serialized by name(), not by String.valueOf. Thanks to Dan Fabulich (provided workaround) NewBeanInstanceStrategy ignored when you pass a root obj Extra quotes on string values with {} and [] JSONArray.toArray can't transform from String[] to int[] Encoding problem of XMLSerializer#writeDocument. Thanks to Masato Nagai (provided a patch) Allow direct property acces when transforming JSON to Java. Thanks to Gino Miceli (provided a patch) Allow default value to be changed when a reference is null Allow 'type' to be parsed from XML to JSON JSONObject.toBean throws NPE with JSONArray values. Thanks to Mino Togna (provided a testcase) Byte and Short arrays throw an IllegalArgumentException Customize bean instantiation in JSONObject.toBean() Enable custom selection of JsonBeanProcessors. JSONObject/JSONArray are not thread safe. Thanks to Yee_Keat Phuah (provided a patch). Allow attribute filters on method fromObject Add support for java.sql.Date in JsDate*Processors Move JSONSerializer's configuration to JsonConfig JsonConfig should not be singleton Setter always passes in Object[]. Thanks to jcue786[at]users[dot]sourceforge[dot]net JSONArray.toArray always returns array of type Object[]. Thanks to sebthom[at]users[dot]sourceforge[dot]net JSONObject.toBean() empty string error [jettison integration]. Thanks to jcue786[at]users[dot]sourceforge[dot]net JSONObject.toBean() Error with nested bean arrays JSONObject.get() doesn't follow java.util.Map contract Bean property of type String is transformed to JSONArray. Thanks to sckimos[at]gmail[dot]com Make exceptions thrown by toBean() more explicit. Thanks to Oliver Zyngier Add JRuby support Support cycle detection in static builders JDK 1.4 compatibility. Thanks to Marcelo Liberato (provided a patch) JSONArray.put(long) not behaving properly for longs > 1L<<62. Thanks to Mathias Herberst (provided a patch) Error in Attributes conversion from xml to json in 2.0a2 Add readFromFile to XMLSerializer Added StringMetaClass for type conversion Added ArrayListMetaClass for type conversion Added HashMapMetaClass for type conversion Add a JSONBuilder (like Grails) Add leftShift (Groovy) operator support Make JSONObject/JSONArray Comparable Support for preventing JavaScript Hijacking in web env Add SAX-like event support Added primitive support for JSONObject.accumulate() JSONObject.element() will not call accumulate() as it previously did Removed duplicated code on JSONObject and JSONArray Renamed JSONObject.putOpt to JSONObject.elementOpt Renamed JSONObject.put to JSONObject.element Renamed JSONArray.put to JSONArray.element Added assertNull and assertNotNull to JSONAssert Skip transient field in a class Make JSONArray an implementation of java.util.List Make JSONObject an implementation of java.util.Map Add type handler support Add POGO support option to remove the double-quote around the property name JSONAssert accepts unequal JSONArrays, JSONObjects. Thanks to dcrosta[at]users[dot]sourceforge[dot]net (provided a patch) JSONUtils.stripQuotes generates an Exception. Thanks to Rodrigo Pantoni and Thomas Spiegl Optional space trimming when reading XML Optional removal of namespace prefixes when reading XML Skip namespaces when reading from XML Updated FAQ and Getting Started guide Added NoopJavaIdentifierTransformer and made it the default (performs no conversion) XMLSerializer can not handle namespace declarations [Regression] toBean() fails with namespaced properties Allow transformation of key values to proper Java identifier Upgrade XML support Promoted length() to JSON interface Skip type information when writing XML Move child properties to parent when writing XML Allow parsing of duplicate properties [Compatibility] Constructor JSONObject( String) does not work Removed deprecated classes String property incorrectly parsed as an array. Tests provided by paulfield[at]users[dot]sourceforge[dot]net & ekeogh[at]thoughtworks[dot]com Updated javadocs Moved interface JSONTypes to net.sf.json.xml Deprecated JSONDynaBean, JSONDynaClass & DynaBeanToBeanMorpher. Use MorphDynaBean, MorphDynaClass & BeanMorpher from EZMorph instead Removed net.sf.json.util.CDL, repeated functionality JSONDynaBean nested arrays not treated as an array. Test provided by arco.vandenheuvel[at]points[dot]com JSONArray does not transforms byte[], short[] and long[] JSONArray is missing validation on float[] and double[] Validate ECMAScript max & min Number values. (rolled-back) JSONArray.put does not use excludes JSONObject.put does not use excludes JSONArray does not pass excludes Added JSONAssert for easy JSON testing Updated JSONFunction constructor for correct length of parameters Updated javadocs and site docs Only default constructors are public (JSONObject & JSONArray) Class objects are converted to Strings (toJSON) and back (toJava) Skip a property without write method Skip a property without read method Annotation should not be transformed Change IAEs for JSONException JSONObject tries to access Enum.getDeclaringClass() Inspect property's value type in factory methods Support different encodings on XmlSerializer JSONDynaClass allows multidimensional arrays Primitives support for JSONDynaBean Support Java 1.5 Enum in JSONObject and JSONArray JDK 1.3 RuntimeException is not nestable Add printer friendly methods to JSON interface JSONArray fails to convert an array of BigDecimals/BigInteger Nested Lists were not handled properly in JSONObject.toBean() Added FAQ and "Who is using it" sections Added new JSONSerializer utility class Added new interface JSON to identify a valid JSON type (JSONObject, JSONArray, JSONNull) Added support for JSONString in builders and value setters Removed JSONObject.append() as it was very similar to JSONObject.accumulate() JSONObject and JSONarray will convert Byte/Short/Long to Integer, Float to Double when needed JSONArray.fromObject now allows creation of a single element array (all valid types) Cleaned up the core API, moved mixed purpouse classes to net.sf.json.util Updated front page and howto documentation Multiple nested JSONException JSONObject.toBean() generates a ClassCastException Refactored converter package into EZMorph (http://ezmorph.sourceforge.net) Added RegexpUtils for easy regexp handling Added more tests Updated "Getting Started" documentation Moved RegexpMatchers to package net.sf.json.regexp Perl5RegexpMatcher is missing a return statement JSONObject.toBean must handle interfaces JSONObject.toBean can not process all nested beans JSONArray did not create multidimensional arrays correctly JSONObject's fromObject() and fromBean() did not support DynaBeans properly XmlSerializer writes wrong JSONFunction data JSONObject.fromObject() does not work properly when passed a boolean as parameter in JVM 1.5+ Json-lib had wrong class numbers for JDK 1.3.1 Make Json-lib JDK 1.3.1 compatible Added support for DynaBean and java bean conversions Updated the XML generated by XMLSerializer. JSONArray uses <a> for root element, JSONObject uses <o> for root element Updated usage documentation Added test suites for each package and for full project Support js functions as type Moved common methods of JSONObject, JSONArray to JSONUtils Renamed XML to XMLSerializer. Now uses XOM to parse documents Moved common assertion methods to Assertions (tests) Deleted HTTP related classes First release jenkins-json-2.4-jenkins-3/src/main/0000775000175000017500000000000011650253660017761 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/0000775000175000017500000000000011650253660020702 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/0000775000175000017500000000000011650253660021470 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/0000775000175000017500000000000011650253660022100 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/0000775000175000017500000000000011650253660023051 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/JsonConfig.java0000664000175000017500000014251111650253660025757 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.json.processors.DefaultDefaultValueProcessor; import net.sf.json.processors.DefaultValueProcessor; import net.sf.json.processors.DefaultValueProcessorMatcher; import net.sf.json.processors.JsonBeanProcessor; import net.sf.json.processors.JsonBeanProcessorMatcher; import net.sf.json.processors.JsonValueProcessor; import net.sf.json.processors.JsonValueProcessorMatcher; import net.sf.json.processors.PropertyNameProcessor; import net.sf.json.processors.PropertyNameProcessorMatcher; import net.sf.json.util.CycleDetectionStrategy; import net.sf.json.util.JavaIdentifierTransformer; import net.sf.json.util.JsonEventListener; import net.sf.json.util.NewBeanInstanceStrategy; import net.sf.json.util.PropertyExclusionClassMatcher; import net.sf.json.util.PropertyFilter; import net.sf.json.util.PropertySetStrategy; import org.apache.commons.collections.map.MultiKeyMap; import org.apache.commons.lang.StringUtils; /** * Utility class that helps configuring the serialization process. * * @author Andres Almiray */ public class JsonConfig { public static final DefaultValueProcessorMatcher DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER = DefaultValueProcessorMatcher.DEFAULT; public static final JsonBeanProcessorMatcher DEFAULT_JSON_BEAN_PROCESSOR_MATCHER = JsonBeanProcessorMatcher.DEFAULT; public static final JsonValueProcessorMatcher DEFAULT_JSON_VALUE_PROCESSOR_MATCHER = JsonValueProcessorMatcher.DEFAULT; public static final NewBeanInstanceStrategy DEFAULT_NEW_BEAN_INSTANCE_STRATEGY = NewBeanInstanceStrategy.DEFAULT; public static final PropertyExclusionClassMatcher DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER = PropertyExclusionClassMatcher.DEFAULT; public static final PropertyNameProcessorMatcher DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER = PropertyNameProcessorMatcher.DEFAULT; public static final int MODE_LIST = 1; public static final int MODE_OBJECT_ARRAY = 2; public static final int MODE_SET = 2; private static final Class DEFAULT_COLLECTION_TYPE = List.class; private static final CycleDetectionStrategy DEFAULT_CYCLE_DETECTION_STRATEGY = CycleDetectionStrategy.STRICT; private static final String[] DEFAULT_EXCLUDES = new String[] { "class", "declaringClass", "metaClass" }; private static final JavaIdentifierTransformer DEFAULT_JAVA_IDENTIFIER_TRANSFORMER = JavaIdentifierTransformer.NOOP; private static final DefaultValueProcessor DEFAULT_VALUE_PROCESSOR = new DefaultDefaultValueProcessor(); private static final String[] EMPTY_EXCLUDES = new String[0]; /** Array conversion mode */ private int arrayMode = MODE_LIST; private MultiKeyMap beanKeyMap = new MultiKeyMap(); private Map beanProcessorMap = new HashMap(); private MultiKeyMap beanTypeMap = new MultiKeyMap(); /** Map of attribute/class */ private Map classMap; private Class collectionType = DEFAULT_COLLECTION_TYPE; private CycleDetectionStrategy cycleDetectionStrategy = DEFAULT_CYCLE_DETECTION_STRATEGY; private Map defaultValueMap = new HashMap(); private DefaultValueProcessorMatcher defaultValueProcessorMatcher = DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER; private Class enclosedType; private List eventListeners = new ArrayList(); private String[] excludes = EMPTY_EXCLUDES; private Map exclusionMap = new HashMap(); private boolean handleJettisonEmptyElement; private boolean handleJettisonSingleElementArray; private boolean ignoreDefaultExcludes; //private boolean ignoreJPATransient; private boolean ignoreTransientFields; private boolean ignorePublicFields = false; private boolean ignoreUnreadableProperty = true; private boolean javascriptCompliant; private JavaIdentifierTransformer javaIdentifierTransformer = DEFAULT_JAVA_IDENTIFIER_TRANSFORMER; private PropertyFilter javaPropertyFilter; private Map javaPropertyNameProcessorMap = new HashMap(); private PropertyNameProcessorMatcher javaPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER; private JsonBeanProcessorMatcher jsonBeanProcessorMatcher = DEFAULT_JSON_BEAN_PROCESSOR_MATCHER; private PropertyFilter jsonPropertyFilter; private Map jsonPropertyNameProcessorMap = new HashMap(); private PropertyNameProcessorMatcher jsonPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER; private JsonValueProcessorMatcher jsonValueProcessorMatcher = DEFAULT_JSON_VALUE_PROCESSOR_MATCHER; private Map keyMap = new HashMap(); private NewBeanInstanceStrategy newBeanInstanceStrategy = DEFAULT_NEW_BEAN_INSTANCE_STRATEGY; private PropertyExclusionClassMatcher propertyExclusionClassMatcher = DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER; private PropertySetStrategy propertySetStrategy; /** Root class used when converting to an specific bean */ private Class rootClass; private boolean skipJavaIdentifierTransformationInMapKeys; private boolean triggerEvents; private Map typeMap = new HashMap(); private List ignoreFieldAnnotations = new ArrayList(); private boolean allowNonStringKeys = false; public JsonConfig() { } /** * Registers a listener for JSON events.
* The events will be triggered only when using the static builders and if event triggering is * enabled.
* [Java -> JSON] * * @see #enableEventTriggering * @see #disableEventTriggering * @see #removeJsonEventListener(JsonEventListener) * @param listener a listener for events */ public synchronized void addJsonEventListener( JsonEventListener listener ) { if( !eventListeners.contains( listener ) ) { eventListeners.add( listener ); } } /** * Removes all registered PropertyNameProcessors.
* [JSON -> Java] */ public void clearJavaPropertyNameProcessors() { javaPropertyNameProcessorMap.clear(); } /** * Removes all registered JsonBeanProcessors.
* [Java -> JSON] */ public void clearJsonBeanProcessors() { beanProcessorMap.clear(); } /** * Removes all registered listener for JSON Events.
* [Java -> JSON] */ public synchronized void clearJsonEventListeners() { eventListeners.clear(); } /** * Removes all registered PropertyNameProcessors.
* [Java -> JSON] */ public void clearJsonPropertyNameProcessors() { jsonPropertyNameProcessorMap.clear(); } /** * Removes all registered JsonValueProcessors.
* [Java -> JSON] */ public void clearJsonValueProcessors() { beanKeyMap.clear(); beanTypeMap.clear(); keyMap.clear(); typeMap.clear(); } /** * Removes all property exclusions registered per class.
* [Java -> JSON] */ public void clearPropertyExclusions() { exclusionMap.clear(); } /** * Removes all registered PropertyNameProcessors.
* [JSON -> Java] * * @deprecated use clearJavaPropertyNameProcessors() instead */ public void clearPropertyNameProcessors() { clearJavaPropertyNameProcessors(); } public JsonConfig copy() { JsonConfig jsc = new JsonConfig(); jsc.beanKeyMap.putAll( beanKeyMap ); jsc.beanTypeMap.putAll( beanTypeMap ); jsc.classMap = new HashMap(); if( classMap != null ) { jsc.classMap.putAll( classMap ); } jsc.cycleDetectionStrategy = cycleDetectionStrategy; if( eventListeners != null ) { jsc.eventListeners.addAll( eventListeners ); } if( excludes != null ) { jsc.excludes = new String[excludes.length]; System.arraycopy( excludes, 0, jsc.excludes, 0, excludes.length ); } jsc.handleJettisonEmptyElement = handleJettisonEmptyElement; jsc.handleJettisonSingleElementArray = handleJettisonSingleElementArray; jsc.ignoreDefaultExcludes = ignoreDefaultExcludes; jsc.ignoreTransientFields = ignoreTransientFields; jsc.ignorePublicFields = ignorePublicFields; jsc.javaIdentifierTransformer = javaIdentifierTransformer; jsc.javascriptCompliant = javascriptCompliant; jsc.keyMap.putAll( keyMap ); jsc.beanProcessorMap.putAll( beanProcessorMap ); jsc.rootClass = rootClass; jsc.skipJavaIdentifierTransformationInMapKeys = skipJavaIdentifierTransformationInMapKeys; jsc.triggerEvents = triggerEvents; jsc.typeMap.putAll( typeMap ); jsc.jsonPropertyFilter = jsonPropertyFilter; jsc.javaPropertyFilter = javaPropertyFilter; jsc.jsonBeanProcessorMatcher = jsonBeanProcessorMatcher; jsc.newBeanInstanceStrategy = newBeanInstanceStrategy; jsc.defaultValueProcessorMatcher = defaultValueProcessorMatcher; jsc.defaultValueMap.putAll( defaultValueMap ); jsc.propertySetStrategy = propertySetStrategy; //jsc.ignoreJPATransient = ignoreJPATransient; jsc.collectionType = collectionType; jsc.enclosedType = enclosedType; jsc.jsonValueProcessorMatcher = jsonValueProcessorMatcher; jsc.javaPropertyNameProcessorMatcher = javaPropertyNameProcessorMatcher; jsc.javaPropertyNameProcessorMap.putAll( javaPropertyNameProcessorMap ); jsc.jsonPropertyNameProcessorMatcher = jsonPropertyNameProcessorMatcher; jsc.jsonPropertyNameProcessorMap.putAll( jsonPropertyNameProcessorMap ); jsc.propertyExclusionClassMatcher = propertyExclusionClassMatcher; jsc.exclusionMap.putAll( exclusionMap ); jsc.ignoreFieldAnnotations.addAll( ignoreFieldAnnotations ); jsc.allowNonStringKeys = allowNonStringKeys; jsc.ignoreUnreadableProperty = ignoreUnreadableProperty; return jsc; } /** * Disables event triggering when building.
* [Java -> JSON] */ public void disableEventTriggering() { triggerEvents = false; } /** * Enables event triggering when building.
* [Java -> JSON] */ public void enableEventTriggering() { triggerEvents = true; } /** * See {@link #setIgnoreUnreadableProperty(boolean)} */ public boolean isIgnoreUnreadableProperty() { return ignoreUnreadableProperty; } /** * If true, properties found in JSON that have no corresponding Java setter/field/etc * will not raise an exception. * *

* For example, given {"x":1, "y":2, "z":3} on the following Point class, * {@link JSONObject#toBean()} would fail unless this flag is set to true, because * propety "x" in JSON has no corresponding Java counerpart. * *

    * class Point {
    *    private int x,y;
    *    public int getX() { return x; }
    *    public int getY() { return y; }
    *    public void setX(int v) { x=v; }
    *    public void setY(int v) { y=v; }
    * }
    * 
* * [JSON -> Java] */ public void setIgnoreUnreadableProperty(boolean ignoreUnreadableProperty) { this.ignoreUnreadableProperty = ignoreUnreadableProperty; } /** * Finds a DefaultValueProcessor registered to the target class.
* Returns null if none is registered.
* [Java -> JSON] * * @param target a class used for searching a DefaultValueProcessor. */ public DefaultValueProcessor findDefaultValueProcessor( Class target ) { if( !defaultValueMap.isEmpty() ) { Object key = defaultValueProcessorMatcher.getMatch( target, defaultValueMap.keySet() ); DefaultValueProcessor processor = (DefaultValueProcessor) defaultValueMap.get( key ); if( processor != null ) { return processor; } } return DEFAULT_VALUE_PROCESSOR; } /** * Finds a PropertyNameProcessor registered to the target class.
* Returns null if none is registered.
* [JSON -> Java] * * @param propertyType a class used for searching a PropertyNameProcessor. */ public PropertyNameProcessor findJavaPropertyNameProcessor( Class beanClass ) { if( !javaPropertyNameProcessorMap.isEmpty() ) { Object key = javaPropertyNameProcessorMatcher.getMatch( beanClass, javaPropertyNameProcessorMap.keySet() ); return (PropertyNameProcessor) javaPropertyNameProcessorMap.get( key ); } return null; } /** * Finds a JsonBeanProcessor registered to the target class.
* Returns null if none is registered.
* [Java -> JSON] * * @param target a class used for searching a JsonBeanProcessor. */ public JsonBeanProcessor findJsonBeanProcessor( Class target ) { if( !beanProcessorMap.isEmpty() ) { Object key = jsonBeanProcessorMatcher.getMatch( target, beanProcessorMap.keySet() ); return (JsonBeanProcessor) beanProcessorMap.get( key ); } return null; } /** * Finds a PropertyNameProcessor registered to the target class.
* Returns null if none is registered.
* [Java -> JSON] * * @param propertyType a class used for searching a PropertyNameProcessor. */ public PropertyNameProcessor findJsonPropertyNameProcessor( Class beanClass ) { if( !jsonPropertyNameProcessorMap.isEmpty() ) { Object key = jsonPropertyNameProcessorMatcher.getMatch( beanClass, jsonPropertyNameProcessorMap.keySet() ); return (PropertyNameProcessor) jsonPropertyNameProcessorMap.get( key ); } return null; } /** * Finds a JsonValueProcessor registered to the target type.
* Returns null if none is registered.
* [Java -> JSON] * * @param propertyType a class used for searching a JsonValueProcessor. */ public JsonValueProcessor findJsonValueProcessor( Class propertyType ) { if( !typeMap.isEmpty() ) { Object key = jsonValueProcessorMatcher.getMatch( propertyType, typeMap.keySet() ); return (JsonValueProcessor) typeMap.get( key ); } return null; } /** * Finds a JsonValueProcessor.
* It will search the registered JsonValueProcessors in the following order: *
    *
  1. beanClass, key
  2. *
  3. beanClass, type
  4. *
  5. key
  6. *
  7. type
  8. *
* Returns null if none is registered.
* [Java -> JSON] * * @param beanClass the class to which the property may belong * @param propertyType the type of the property * @param key the name of the property which may belong to the target class */ public JsonValueProcessor findJsonValueProcessor( Class beanClass, Class propertyType, String key ) { JsonValueProcessor jsonValueProcessor = null; jsonValueProcessor = (JsonValueProcessor) beanKeyMap.get( beanClass, key ); if( jsonValueProcessor != null ) { return jsonValueProcessor; } jsonValueProcessor = (JsonValueProcessor) beanTypeMap.get( beanClass, propertyType ); if( jsonValueProcessor != null ) { return jsonValueProcessor; } jsonValueProcessor = (JsonValueProcessor) keyMap.get( key ); if( jsonValueProcessor != null ) { return jsonValueProcessor; } Object tkey = jsonValueProcessorMatcher.getMatch( propertyType, typeMap.keySet() ); jsonValueProcessor = (JsonValueProcessor) typeMap.get( tkey ); if( jsonValueProcessor != null ) { return jsonValueProcessor; } return null; } /** * Finds a JsonValueProcessor.
* It will search the registered JsonValueProcessors in the following order: *
    *
  1. key
  2. *
  3. type
  4. *
* Returns null if none is registered.
* [Java -> JSON] * * @param propertyType the type of the property * @param key the name of the property which may belong to the target class */ public JsonValueProcessor findJsonValueProcessor( Class propertyType, String key ) { JsonValueProcessor jsonValueProcessor = null; jsonValueProcessor = (JsonValueProcessor) keyMap.get( key ); if( jsonValueProcessor != null ) { return jsonValueProcessor; } Object tkey = jsonValueProcessorMatcher.getMatch( propertyType, typeMap.keySet() ); jsonValueProcessor = (JsonValueProcessor) typeMap.get( tkey ); if( jsonValueProcessor != null ) { return jsonValueProcessor; } return null; } /** * Finds a PropertyNameProcessor registered to the target class.
* Returns null if none is registered.
* [JSON -> Java] * * @param propertyType a class used for searching a PropertyNameProcessor. * * @deprecated use findJavaPropertyNameProcessor() instead */ public PropertyNameProcessor findPropertyNameProcessor( Class beanClass ) { return findJavaPropertyNameProcessor( beanClass ); } /** * Returns the current array mode conversion.
* [JSON -> Java] * * @return MODE_OBJECT_ARRAY, MODE_LIST or MODE_SET */ public int getArrayMode() { return arrayMode; } /** * Returns the current attribute/class Map.
* [JSON -> Java] * * @return a Map of classes, every key identifies a property or a regexp */ public Map getClassMap() { return classMap; } /** * Returns the current collection type used for collection transformations.
* [JSON -> Java] * * @return the target collection class for conversion */ public Class getCollectionType() { return collectionType; } /** * Returns the configured CycleDetectionStrategy.
* Default value is CycleDetectionStrategy.STRICT
* [Java -> JSON] */ public CycleDetectionStrategy getCycleDetectionStrategy() { return cycleDetectionStrategy; } /** * Returns the configured DefaultValueProcessorMatcher.
* Default value is DefaultValueProcessorMatcher.DEFAULT
* [Java -> JSON] */ public DefaultValueProcessorMatcher getDefaultValueProcessorMatcher() { return defaultValueProcessorMatcher; } /** * Returns the current enclosed type for generic collection transformations.
* [JSON -> Java] * * @return the target type for conversion */ public Class getEnclosedType() { return enclosedType; } /** * Returns the configured properties for exclusion.
* [Java -> JSON] */ public String[] getExcludes() { return excludes; } /** * Returns the configured JavaIdentifierTransformer.
* Default value is JavaIdentifierTransformer.NOOP
* [JSON -> Java] */ public JavaIdentifierTransformer getJavaIdentifierTransformer() { return javaIdentifierTransformer; } /** * Returns the configured property filter when serializing to Java.
* [JSON -> Java] */ public PropertyFilter getJavaPropertyFilter() { return javaPropertyFilter; } /** * Returns the configured PropertyNameProcessorMatcher.
* Default value is PropertyNameProcessorMatcher.DEFAULT
* [JSON -> Java] */ public PropertyNameProcessorMatcher getJavaPropertyNameProcessorMatcher() { return javaPropertyNameProcessorMatcher; } /** * Returns the configured JsonBeanProcessorMatcher.
* Default value is JsonBeanProcessorMatcher.DEFAULT
* [JSON -> Java] */ public JsonBeanProcessorMatcher getJsonBeanProcessorMatcher() { return jsonBeanProcessorMatcher; } /** * Returns a list of registered listeners for JSON events.
* [JSON -> Java] */ public synchronized List getJsonEventListeners() { return eventListeners; } /** * Returns the configured property filter when serializing to JSON.
* [Java -> JSON] */ public PropertyFilter getJsonPropertyFilter() { return jsonPropertyFilter; } /** * Returns the configured PropertyNameProcessorMatcher.
* Default value is PropertyNameProcessorMatcher.DEFAULT
* [Java -> JSON] */ public PropertyNameProcessorMatcher getJsonPropertyNameProcessorMatcher() { return javaPropertyNameProcessorMatcher; } /** * Returns the configured JsonValueProcessorMatcher.
* Default value is JsonValueProcessorMatcher.DEFAULT
* [Java -> JSON] */ public JsonValueProcessorMatcher getJsonValueProcessorMatcher() { return jsonValueProcessorMatcher; } /** * Returns a set of default excludes with user-defined excludes.
* [Java -> JSON] */ public Collection getMergedExcludes() { Collection exclusions = new HashSet(); for( int i = 0; i < excludes.length; i++ ) { String exclusion = excludes[i]; if( !StringUtils.isBlank( excludes[i] ) ) { exclusions.add( exclusion.trim() ); } } if( !ignoreDefaultExcludes ) { for( int i = 0; i < DEFAULT_EXCLUDES.length; i++ ) { if( !exclusions.contains( DEFAULT_EXCLUDES[i] ) ) { exclusions.add( DEFAULT_EXCLUDES[i] ); } } } return exclusions; } /** * Returns a set of default excludes with user-defined excludes.
* Takes into account any additional excludes per matching class. * [Java -> JSON] */ public Collection getMergedExcludes( Class target ) { if( target == null ) { return getMergedExcludes(); } Collection exclusionSet = getMergedExcludes(); if( !exclusionMap.isEmpty() ) { Object key = propertyExclusionClassMatcher.getMatch( target, exclusionMap.keySet() ); Set set = (Set) exclusionMap.get( key ); if( set != null && !set.isEmpty() ) { for( Iterator i = set.iterator(); i.hasNext(); ) { Object e = i.next(); if( !exclusionSet.contains( e ) ) { exclusionSet.add( e ); } } } } return exclusionSet; } /** * Returns the configured NewBeanInstanceStrategy.
* Default value is NewBeanInstanceStrategy.DEFAULT
* [JSON -> Java] */ public NewBeanInstanceStrategy getNewBeanInstanceStrategy() { return newBeanInstanceStrategy; } /** * Returns the configured PropertyExclusionClassMatcher.
* Default value is PropertyExclusionClassMatcher.DEFAULT
* [JSON -> Java] */ public PropertyExclusionClassMatcher getPropertyExclusionClassMatcher() { return propertyExclusionClassMatcher; } /** * Returns the configured PropertyNameProcessorMatcher.
* Default value is PropertyNameProcessorMatcher.DEFAULT
* [JSON -> Java] * * @deprecated use getJavaPropertyNameProcessorMatcher() instead */ public PropertyNameProcessorMatcher getPropertyNameProcessorMatcher() { return getJavaPropertyNameProcessorMatcher(); } /** * Returns the configured PropertySetStrategy.
* Default value is PropertySetStrategy.DEFAULT
* [JSON -> Java] */ public PropertySetStrategy getPropertySetStrategy() { return propertySetStrategy; } /** * Returns the current root Class.
* [JSON -> Java] * * @return the target class for conversion */ public Class getRootClass() { return rootClass; } /** * Returns true if non-String keys are allowed on JSONObject.
* Default value is false
* [Java -> JSON] */ public boolean isAllowNonStringKeys() { return allowNonStringKeys; } /** * Returns true if event triggering is enabled during building.
* Default value is false
* [Java -> JSON] */ public boolean isEventTriggeringEnabled() { return triggerEvents; } /** * Returns true if this Jettison convention will be handled when converting to Java.
* Jettison assumes that "" (empty string) can be assigned to empty elements (objects), which * clearly violates the JSON spec.
* [JSON -> Java] */ public boolean isHandleJettisonEmptyElement() { return handleJettisonEmptyElement; } /** * Returns true if this jettison convention will be handled when converting to Java.
* Jettison states the following JSON {'media':{'title':'hello'}} can be set as a single element * JSONArray (media is the array).
* [JSON -> Java] */ public boolean isHandleJettisonSingleElementArray() { return handleJettisonSingleElementArray; } /** * Returns true if default excludes will not be used.
* Default value is false.
* [Java -> JSON] */ public boolean isIgnoreDefaultExcludes() { return ignoreDefaultExcludes; } /** * Returns true if JPA Transient annotated methods should be ignored.
* Default value is false.
* [Java -> JSON] */ public boolean isIgnoreJPATransient() { return ignoreFieldAnnotations.contains("javax.persistence.Transient"); } /** * Returns true if transient fields of a bean will be ignored.
* Default value is false.
* [Java -> JSON] */ public boolean isIgnoreTransientFields() { return ignoreTransientFields; } /** * Returns true if public fields of a bean will be ignored.
* Default value is true.
* [Java -> JSON] */ public boolean isIgnorePublicFields() { return ignorePublicFields; } /** * Returns true if Javascript compatibility is turned on.
* Default value is false.
* [Java -> JSON] */ public boolean isJavascriptCompliant() { return javascriptCompliant; } /** * Returns true if map keys will not be transformed.
* Default value is false.
* [JSON -> Java] */ public boolean isSkipJavaIdentifierTransformationInMapKeys() { return skipJavaIdentifierTransformationInMapKeys; } /** * Registers a DefaultValueProcessor.
* [Java -> JSON] * * @param target the class to use as key * @param defaultValueProcessor the processor to register */ public void registerDefaultValueProcessor( Class target, DefaultValueProcessor defaultValueProcessor ) { if( target != null && defaultValueProcessor != null ) { defaultValueMap.put( target, defaultValueProcessor ); } } /** * Registers a PropertyNameProcessor.
* [JSON -> Java] * * @param target the class to use as key * @param propertyNameProcessor the processor to register */ public void registerJavaPropertyNameProcessor( Class target, PropertyNameProcessor propertyNameProcessor ) { if( target != null && propertyNameProcessor != null ) { javaPropertyNameProcessorMap.put( target, propertyNameProcessor ); } } /** * Registers a JsonBeanProcessor.
* [Java -> JSON] * * @param target the class to use as key * @param jsonBeanProcessor the processor to register */ public void registerJsonBeanProcessor( Class target, JsonBeanProcessor jsonBeanProcessor ) { if( target != null && jsonBeanProcessor != null ) { beanProcessorMap.put( target, jsonBeanProcessor ); } } /** * Registers a PropertyNameProcessor.
* [Java -> JSON] * * @param target the class to use as key * @param propertyNameProcessor the processor to register */ public void registerJsonPropertyNameProcessor( Class target, PropertyNameProcessor propertyNameProcessor ) { if( target != null && propertyNameProcessor != null ) { jsonPropertyNameProcessorMap.put( target, propertyNameProcessor ); } } /** * Registers a JsonValueProcessor.
* [Java -> JSON] * * @param beanClass the class to use as key * @param propertyType the property type to use as key * @param jsonValueProcessor the processor to register */ public void registerJsonValueProcessor( Class beanClass, Class propertyType, JsonValueProcessor jsonValueProcessor ) { if( beanClass != null && propertyType != null && jsonValueProcessor != null ) { beanTypeMap.put( beanClass, propertyType, jsonValueProcessor ); } } /** * Registers a JsonValueProcessor.
* [Java -> JSON] * * @param propertyType the property type to use as key * @param jsonValueProcessor the processor to register */ public void registerJsonValueProcessor( Class propertyType, JsonValueProcessor jsonValueProcessor ) { if( propertyType != null && jsonValueProcessor != null ) { typeMap.put( propertyType, jsonValueProcessor ); } } /** * Registers a JsonValueProcessor.
* [Java -> JSON] * * @param beanClass the class to use as key * @param key the property name to use as key * @param jsonValueProcessor the processor to register */ public void registerJsonValueProcessor( Class beanClass, String key, JsonValueProcessor jsonValueProcessor ) { if( beanClass != null && key != null && jsonValueProcessor != null ) { beanKeyMap.put( beanClass, key, jsonValueProcessor ); } } /** * Registers a JsonValueProcessor.
* [Java -> JSON] * * @param key the property name to use as key * @param jsonValueProcessor the processor to register */ public void registerJsonValueProcessor( String key, JsonValueProcessor jsonValueProcessor ) { if( key != null && jsonValueProcessor != null ) { keyMap.put( key, jsonValueProcessor ); } } /** * Registers a exclusion for a target class.
* [Java -> JSON] * * @param target the class to use as key * @param propertyName the property to be excluded */ public void registerPropertyExclusion( Class target, String propertyName ) { if( target != null && propertyName != null ) { Set set = (Set) exclusionMap.get( target ); if( set == null ){ set = new HashSet(); exclusionMap.put( target, set ); } if( !set.contains( propertyName )){ set.add(propertyName ); } } } /** * Registers exclusions for a target class.
* [Java -> JSON] * * @param target the class to use as key * @param properties the properties to be excluded */ public void registerPropertyExclusions( Class target, String[] properties ) { if( target != null && properties != null && properties.length > 0 ) { Set set = (Set) exclusionMap.get( target ); if( set == null ) { set = new HashSet(); exclusionMap.put( target, set ); } for( int i = 0; i < properties.length; i++ ) { if( !set.contains( properties[i] ) ) { set.add( properties[i] ); } } } } /** * Registers a PropertyNameProcessor.
* [JSON -> Java] * * @param target the class to use as key * @param propertyNameProcessor the processor to register * * @deprecated use registerJavaPropertyNameProcessor() instead */ public void registerPropertyNameProcessor( Class target, PropertyNameProcessor propertyNameProcessor ) { registerJavaPropertyNameProcessor( target, propertyNameProcessor ); } /** * Removes a listener for JSON events.
* [Java -> JSON] * * @see #addJsonEventListener(JsonEventListener) * @param listener a listener for events */ public synchronized void removeJsonEventListener( JsonEventListener listener ) { eventListeners.remove( listener ); } /** * Resets all values to its default state. */ public void reset() { excludes = EMPTY_EXCLUDES; ignoreDefaultExcludes = false; ignoreTransientFields = false; ignorePublicFields = true; javascriptCompliant = false; javaIdentifierTransformer = DEFAULT_JAVA_IDENTIFIER_TRANSFORMER; cycleDetectionStrategy = DEFAULT_CYCLE_DETECTION_STRATEGY; skipJavaIdentifierTransformationInMapKeys = false; triggerEvents = false; handleJettisonEmptyElement = false; handleJettisonSingleElementArray = false; arrayMode = MODE_LIST; rootClass = null; classMap = null; keyMap.clear(); typeMap.clear(); beanKeyMap.clear(); beanTypeMap.clear(); jsonPropertyFilter = null; javaPropertyFilter = null; jsonBeanProcessorMatcher = DEFAULT_JSON_BEAN_PROCESSOR_MATCHER; newBeanInstanceStrategy = DEFAULT_NEW_BEAN_INSTANCE_STRATEGY; defaultValueProcessorMatcher = DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER; defaultValueMap.clear(); propertySetStrategy = null/* DEFAULT_PROPERTY_SET_STRATEGY */; //ignoreJPATransient = false; collectionType = DEFAULT_COLLECTION_TYPE; enclosedType = null; jsonValueProcessorMatcher = DEFAULT_JSON_VALUE_PROCESSOR_MATCHER; javaPropertyNameProcessorMap.clear(); javaPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER; jsonPropertyNameProcessorMap.clear(); jsonPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER; beanProcessorMap.clear(); propertyExclusionClassMatcher = DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER; exclusionMap.clear(); ignoreFieldAnnotations.clear(); allowNonStringKeys = false; } /** * Sets if non-String keys are allowed on JSONObject.
* [Java -> JSON] */ public void setAllowNonStringKeys( boolean allowNonStringKeys ) { this.allowNonStringKeys = allowNonStringKeys; } /** * Sets the current array mode for conversion.
* If the value is not MODE_LIST, MODE_OBJECT_ARRAY nor MODE_SET, then MODE_LIST will be used.
* [JSON -> Java] * * @param arrayMode array mode for conversion */ public void setArrayMode( int arrayMode ) { if( arrayMode == MODE_OBJECT_ARRAY ) { this.arrayMode = arrayMode; } else if( arrayMode == MODE_SET ) { this.arrayMode = arrayMode; this.collectionType = Set.class; } else { this.arrayMode = MODE_LIST; this.enclosedType = DEFAULT_COLLECTION_TYPE; } } /** * Sets the current attribute/Class Map
* [JSON -> Java] * * @param classMap a Map of classes, every key identifies a property or a regexp */ public void setClassMap( Map classMap ) { this.classMap = classMap; } /** * Sets the current collection type used for collection transformations.
* [JSON -> Java] * * @param collectionType the target collection class for conversion */ public void setCollectionType( Class collectionType ) { if( collectionType != null ) { if( !Collection.class.isAssignableFrom( collectionType ) ) { throw new JSONException( "The configured collectionType is not a Collection: " + collectionType.getName() ); } this.collectionType = collectionType; } else { collectionType = DEFAULT_COLLECTION_TYPE; } } /** * Sets a CycleDetectionStrategy to use.
* Will set default value (CycleDetectionStrategy.STRICT) if null.
* [Java -> JSON] */ public void setCycleDetectionStrategy( CycleDetectionStrategy cycleDetectionStrategy ) { this.cycleDetectionStrategy = cycleDetectionStrategy == null ? DEFAULT_CYCLE_DETECTION_STRATEGY : cycleDetectionStrategy; } /** * Sets a DefaultValueProcessorMatcher to use.
* Will set default value (DefaultValueProcessorMatcher.DEFAULT) if null.
* [Java -> JSON] */ public void setDefaultValueProcessorMatcher( DefaultValueProcessorMatcher defaultValueProcessorMatcher ) { this.defaultValueProcessorMatcher = defaultValueProcessorMatcher == null ? DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER : defaultValueProcessorMatcher; } /** * Sets the current enclosed type for generic collection transformations.
* [JSON -> Java] * * @param enclosedType the target type for conversion */ public void setEnclosedType( Class enclosedType ) { this.enclosedType = enclosedType; } /** * Sets the excludes to use.
* Will set default value ([]) if null.
* [Java -> JSON] */ public void setExcludes( String[] excludes ) { this.excludes = excludes == null ? EMPTY_EXCLUDES : excludes; } /** * Activate/Deactivate handling this jettison convention when converting to Java.
* Jettison states that "" (empty string) can be assigned to empty elements (objects), which * clearly violates the JSON spec.
* [JSON -> Java] */ public void setHandleJettisonEmptyElement( boolean handleJettisonEmptyElement ) { this.handleJettisonEmptyElement = handleJettisonEmptyElement; } /** * Activate/Deactivate handling this jettison convention when converting to Java.
* Jettison * states the following JSON {'media':{'title':'hello'}} can be set as a single element JSONArray * (media is the array).
* [JSON -> Java] */ public void setHandleJettisonSingleElementArray( boolean handleJettisonSingleElementArray ) { this.handleJettisonSingleElementArray = handleJettisonSingleElementArray; } /** * Sets if default excludes would be skipped when building.
* [Java -> JSON] */ public void setIgnoreDefaultExcludes( boolean ignoreDefaultExcludes ) { this.ignoreDefaultExcludes = ignoreDefaultExcludes; } /** * Sets if JPA Transient annotated methods would be skipped when building.
* [Java -> JSON] */ public void setIgnoreJPATransient( boolean ignoreJPATransient ) { if(ignoreJPATransient) { addIgnoreFieldAnnotation("javax.persistence.Transient"); } else { removeIgnoreFieldAnnotation("javax.persistence.Transient"); } } /** * Adds an annotation that marks a field to be skipped when building.
* [Java -> JSON] */ public void addIgnoreFieldAnnotation( String annotationClassName ) { if( annotationClassName != null && !ignoreFieldAnnotations.contains( annotationClassName )) { ignoreFieldAnnotations.add(annotationClassName); } } /** * Adds an annotation that marks a field to be skipped when building.
* [Java -> JSON] */ public void removeIgnoreFieldAnnotation( String annotationClassName ) { if( annotationClassName != null ) ignoreFieldAnnotations.remove(annotationClassName); } /** * Removes an annotation that marks a field to be skipped when building.
* [Java -> JSON] */ public void addIgnoreFieldAnnotation( Class annotationClass ) { if( annotationClass != null && !ignoreFieldAnnotations.contains( annotationClass.getName() )) { ignoreFieldAnnotations.add(annotationClass.getName()); } } /** * Removes an annotation that marks a field to be skipped when building.
* [Java -> JSON] */ public void removeIgnoreFieldAnnotation( Class annotationClass ) { if( annotationClass != null ) ignoreFieldAnnotations.remove(annotationClass.getName()); } /** * Returns a List of all annotations that mark a field to be skipped when building.
* [Java -> JSON] */ public List getIgnoreFieldAnnotations() { return Collections.unmodifiableList(ignoreFieldAnnotations); } /** * Sets if transient fields would be skipped when building.
* [Java -> JSON] */ public void setIgnoreTransientFields( boolean ignoreTransientFields ) { this.ignoreTransientFields = ignoreTransientFields; } /** * Sets if public fields would be skipped when building.
* [Java -> JSON] */ public void setIgnorePublicFields( boolean ignorePublicFields ) { this.ignorePublicFields = ignorePublicFields; } /** * Sets if Javascript compatibility is enabled when building.
* [Java -> JSON] */ public void setJavascriptCompliant( boolean javascriptCompliant ) { this.javascriptCompliant = javascriptCompliant; } /** * Sets the JavaIdentifierTransformer to use.
* Will set default value (JavaIdentifierTransformer.NOOP) if null.
* [JSON -> Java] */ public void setJavaIdentifierTransformer( JavaIdentifierTransformer javaIdentifierTransformer ) { this.javaIdentifierTransformer = javaIdentifierTransformer == null ? DEFAULT_JAVA_IDENTIFIER_TRANSFORMER : javaIdentifierTransformer; } /** * Sets a property filter used when serializing to Java.
* [JSON -> Java] * * @param javaPropertyFilter the property filter */ public void setJavaPropertyFilter( PropertyFilter javaPropertyFilter ) { this.javaPropertyFilter = javaPropertyFilter; } /** * Sets a PropertyNameProcessorMatcher to use.
* Will set default value (PropertyNameProcessorMatcher.DEFAULT) if null.
* [JSON -> Java] */ public void setJavaPropertyNameProcessorMatcher( PropertyNameProcessorMatcher propertyNameProcessorMatcher ) { this.javaPropertyNameProcessorMatcher = propertyNameProcessorMatcher == null ? DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER : propertyNameProcessorMatcher; } /** * Sets a JsonBeanProcessorMatcher to use.
* Will set default value (JsonBeanProcessorMatcher.DEFAULT) if null.
* [Java -> JSON] */ public void setJsonBeanProcessorMatcher( JsonBeanProcessorMatcher jsonBeanProcessorMatcher ) { this.jsonBeanProcessorMatcher = jsonBeanProcessorMatcher == null ? DEFAULT_JSON_BEAN_PROCESSOR_MATCHER : jsonBeanProcessorMatcher; } /** * Sets a property filter used when serializing to JSON.
* [Java -> JSON] * * @param jsonPropertyFilter the property filter */ public void setJsonPropertyFilter( PropertyFilter jsonPropertyFilter ) { this.jsonPropertyFilter = jsonPropertyFilter; } /** * Sets a PropertyNameProcessorMatcher to use.
* Will set default value (PropertyNameProcessorMatcher.DEFAULT) if null.
* [Java -> JSON] */ public void setJsonPropertyNameProcessorMatcher( PropertyNameProcessorMatcher propertyNameProcessorMatcher ) { this.jsonPropertyNameProcessorMatcher = propertyNameProcessorMatcher == null ? DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER : propertyNameProcessorMatcher; } /** * Sets a JsonValueProcessorMatcher to use.
* Will set default value (JsonValueProcessorMatcher.DEFAULT) if null.
* [Java -> JSON] */ public void setJsonValueProcessorMatcher( JsonValueProcessorMatcher jsonValueProcessorMatcher ) { this.jsonValueProcessorMatcher = jsonValueProcessorMatcher == null ? DEFAULT_JSON_VALUE_PROCESSOR_MATCHER : jsonValueProcessorMatcher; } /** * Sets the NewBeanInstanceStrategy to use.
* Will set default value (NewBeanInstanceStrategy.DEFAULT) if null.
* [JSON -> Java] */ public void setNewBeanInstanceStrategy( NewBeanInstanceStrategy newBeanInstanceStrategy ) { this.newBeanInstanceStrategy = newBeanInstanceStrategy == null ? DEFAULT_NEW_BEAN_INSTANCE_STRATEGY : newBeanInstanceStrategy; } /** * Sets a PropertyExclusionClassMatcher to use.
* Will set default value (PropertyExclusionClassMatcher.DEFAULT) if null.
* [Java -> JSON] */ public void setPropertyExclusionClassMatcher( PropertyExclusionClassMatcher propertyExclusionClassMatcher ) { this.propertyExclusionClassMatcher = propertyExclusionClassMatcher == null ? DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER : propertyExclusionClassMatcher; } /** * Sets a PropertyNameProcessorMatcher to use.
* Will set default value (PropertyNameProcessorMatcher.DEFAULT) if null.
* [JSON -> Java] * * @deprecated use setJavaPropertyNameProcessorMatcher() instead */ public void setPropertyNameProcessorMatcher( PropertyNameProcessorMatcher propertyNameProcessorMatcher ) { setJavaPropertyNameProcessorMatcher( propertyNameProcessorMatcher ); } /** * Sets a PropertySetStrategy to use.
* Will set default value (PropertySetStrategy.DEFAULT) if null.
* [JSON -> Java] */ public void setPropertySetStrategy( PropertySetStrategy propertySetStrategy ) { this.propertySetStrategy = propertySetStrategy; } /** * Sets the current root Class.
* [JSON -> Java] * * @param rootClass the target class for conversion */ public void setRootClass( Class rootClass ) { this.rootClass = rootClass; } /** * Sets if property name as JavaIndetifier transformations would be skipped.
* [JSON -> Java] */ public void setSkipJavaIdentifierTransformationInMapKeys( boolean skipJavaIdentifierTransformationInMapKeys ) { this.skipJavaIdentifierTransformationInMapKeys = skipJavaIdentifierTransformationInMapKeys; } /** * Removes a DefaultValueProcessor.
* [Java -> JSON] * * @param target a class used for searching a DefaultValueProcessor. */ public void unregisterDefaultValueProcessor( Class target ) { if( target != null ) { defaultValueMap.remove( target ); } } /** * Removes a PropertyNameProcessor.
* [JSON -> Java] * * @param target a class used for searching a PropertyNameProcessor. */ public void unregisterJavaPropertyNameProcessor( Class target ) { if( target != null ) { javaPropertyNameProcessorMap.remove( target ); } } /** * Removes a JsonBeanProcessor.
* [Java -> JSON] * * @param target a class used for searching a JsonBeanProcessor. */ public void unregisterJsonBeanProcessor( Class target ) { if( target != null ) { beanProcessorMap.remove( target ); } } /** * Removes a PropertyNameProcessor.
* [Java -> JSON] * * @param target a class used for searching a PropertyNameProcessor. */ public void unregisterJsonPropertyNameProcessor( Class target ) { if( target != null ) { jsonPropertyNameProcessorMap.remove( target ); } } /** * Removes a JsonValueProcessor.
* [Java -> JSON] * * @param propertyType a class used for searching a JsonValueProcessor. */ public void unregisterJsonValueProcessor( Class propertyType ) { if( propertyType != null ) { typeMap.remove( propertyType ); } } /** * Removes a JsonValueProcessor.
* [Java -> JSON] * * @param beanClass the class to which the property may belong * @param propertyType the type of the property */ public void unregisterJsonValueProcessor( Class beanClass, Class propertyType ) { if( beanClass != null && propertyType != null ) { beanTypeMap.remove( beanClass, propertyType ); } } /** * Removes a JsonValueProcessor.
* [Java -> JSON] * * @param beanClass the class to which the property may belong * @param key the name of the property which may belong to the target class */ public void unregisterJsonValueProcessor( Class beanClass, String key ) { if( beanClass != null && key != null ) { beanKeyMap.remove( beanClass, key ); } } /** * Removes a JsonValueProcessor.
* [Java -> JSON] * * @param key the name of the property which may belong to the target class */ public void unregisterJsonValueProcessor( String key ) { if( key != null ) { keyMap.remove( key ); } } /** * Removes a property exclusion assigned to the target class.
* [Java -> JSON] * * @param target a class used for searching property exclusions. * @param propertyName the name of the property to be removed from the exclusion list. */ public void unregisterPropertyExclusion( Class target, String propertyName ) { if( target != null && propertyName != null ) { Set set = (Set) exclusionMap.get( target ); if( set == null ) { set = new HashSet(); exclusionMap.put( target, set ); } set.remove( propertyName ); } } /** * Removes all property exclusions assigned to the target class.
* [Java -> JSON] * * @param target a class used for searching property exclusions. */ public void unregisterPropertyExclusions( Class target ) { if( target != null ) { Set set = (Set) exclusionMap.get( target ); if( set != null ) { set.clear(); } } } /** * Removes a PropertyNameProcessor.
* [JSON -> Java] * * @param target a class used for searching a PropertyNameProcessor. * * @deprecated use unregisterJavaPropertyNameProcessor() instead */ public void unregisterPropertyNameProcessor( Class target ) { unregisterJavaPropertyNameProcessor( target ); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/JSONNull.java0000664000175000017500000000511511650253660025322 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.io.IOException; import java.io.Writer; /** * JSONNull is equivalent to the value that JavaScript calls null, whilst Java's * null is equivalent to the value that JavaScript calls undefined. * * @author JSON.org */ public final class JSONNull implements JSON { /** singleton instance */ private static JSONNull instance; static{ instance = new JSONNull(); } /** * Returns the singleton instance of JSONNull */ public static JSONNull getInstance() { return instance; } private JSONNull() { } /** * A Null object is equal to the null value and to itself. * * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object or * null. */ public boolean equals( Object object ) { return object == null || object == this || object == instance || (object instanceof JSONObject && ((JSONObject) object).isNullObject()) ; } public int hashCode() { return 37 + "null".hashCode(); } public boolean isArray() { return false; } public boolean isEmpty() { throw new JSONException( "Object is null" ); } public int size() { throw new JSONException( "Object is null" ); } /** * Get the "null" string value. * * @return The string "null". */ public String toString() { return "null"; } public String toString( int indentFactor ) { return toString(); } public String toString( int indentFactor, int indent ) { StringBuffer sb = new StringBuffer(); for( int i = 0; i < indent; i += 1 ){ sb.append( ' ' ); } sb.append( toString() ); return sb.toString(); } public Writer write( Writer writer ) throws IOException { writer.write( toString() ); return writer; } public Writer writeCanonical(Writer w) throws IOException { return write(w); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/regexp/0000775000175000017500000000000011650253660024343 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/regexp/Perl5RegexpMatcher.java0000664000175000017500000000424511650253660030661 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; import org.apache.commons.lang.exception.NestableRuntimeException; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcher; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; /** * Jakarta-oro RegexpMatcher Implementation.
* Runs on older JVMs (1.3.1). You must have oro-2.0.8.jar configured in your classpath. * * @author Andres Almiray */ public class Perl5RegexpMatcher implements RegexpMatcher { private static final Perl5Compiler compiler = new Perl5Compiler(); private Pattern pattern; public Perl5RegexpMatcher( String pattern ) { this( pattern, false ); } public Perl5RegexpMatcher( String pattern, boolean multiline ) { try { if( multiline ) { this.pattern = compiler.compile( pattern, Perl5Compiler.READ_ONLY_MASK | Perl5Compiler.MULTILINE_MASK ); } else { this.pattern = compiler.compile( pattern, Perl5Compiler.READ_ONLY_MASK ); } } catch( MalformedPatternException mpe ) { throw new NestableRuntimeException( mpe ); } } public String getGroupIfMatches( String str, int group ) { PatternMatcher matcher = new Perl5Matcher(); if( matcher.matches( str, pattern ) ) { return matcher.getMatch().group( 1 ); } return ""; } public boolean matches( String str ) { return new Perl5Matcher().matches( str, pattern ); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/regexp/RegexpUtils.java0000664000175000017500000000375311650253660027471 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; /** * Convenience utility for working withRegexpMatcher.
* * @author Andres Almiray */ public class RegexpUtils { private static String javaVersion = "1.3.1"; static{ javaVersion = System.getProperty( "java.version" ); } /** * Returns a RegexpMatcher that works in a specific environment.
* When in a JVM 1.3.1 it will return a Perl5RegexpMatcher, if the JVM is * younger (1.4+) it will return a JdkRegexpMatcher. */ public static RegexpMatcher getMatcher( String pattern ) { if( isJDK13() ){ return new Perl5RegexpMatcher( pattern ); }else{ return new JdkRegexpMatcher( pattern ); } } /** * Returns a RegexpMatcher that works in a specific environment.
* When in a JVM 1.3.1 it will return a Perl5RegexpMatcher, if the JVM is * younger (1.4+) it will return a JdkRegexpMatcher. */ public static RegexpMatcher getMatcher( String pattern, boolean multiline ) { if( isJDK13() ){ return new Perl5RegexpMatcher( pattern, true ); }else{ return new JdkRegexpMatcher( pattern, true ); } } /** * Queries the environment for the supported JDK version. */ public static boolean isJDK13() { return javaVersion.indexOf( "1.3" ) != -1; } private RegexpUtils() { } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/regexp/package.html0000664000175000017500000000021511650253660026622 0ustar jamespagejamespage

Regexp utilities

jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/regexp/RegexpMatcher.java0000664000175000017500000000230011650253660027737 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; /** * Abstraction for regexp handling. * * @author Andres Almiray */ public interface RegexpMatcher { /** * Returns the specified group if the string matches the Pattern.
* The Pattern will be managed internally by the RegexpMatcher * implementation. */ String getGroupIfMatches( String str, int group ); /** * Returns true is the string macthes the Pattern.
* The Pattern will be managed internally by the RegexpMatcher * implementation. */ boolean matches( String str ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/regexp/JdkRegexpMatcher.java0000664000175000017500000000302211650253660030372 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * JDK 1.4+ RegexpMatcher implementation. * * @author Andres Almiray */ public class JdkRegexpMatcher implements RegexpMatcher { private final Pattern pattern; public JdkRegexpMatcher( String pattern ) { this( pattern, false ); } public JdkRegexpMatcher( String pattern, boolean multiline ) { if( multiline ) { this.pattern = Pattern.compile( pattern, Pattern.MULTILINE ); } else { this.pattern = Pattern.compile( pattern ); } } public String getGroupIfMatches( String str, int group ) { Matcher matcher = pattern.matcher( str ); if( matcher.matches() ) { return matcher.group( group ); } return ""; } public boolean matches( String str ) { return pattern.matcher( str ).matches(); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/package.html0000664000175000017500000000022411650253660025330 0ustar jamespagejamespage

The core of the library

jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/groovy/0000775000175000017500000000000011650253660024376 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/groovy/JsonSlurper.java0000664000175000017500000000460211650253660027531 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy; import groovy.lang.GroovyObjectSupport; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import net.sf.json.JSON; import net.sf.json.JSONSerializer; import net.sf.json.JsonConfig; /** * A Helper class modeled after XmlSlurper * * @author Andres Almiray */ public class JsonSlurper extends GroovyObjectSupport { private JsonConfig jsonConfig; public JsonSlurper() { this( new JsonConfig() ); } public JsonSlurper( JsonConfig jsonConfig ) { this.jsonConfig = jsonConfig != null ? jsonConfig : new JsonConfig(); } public JSON parse( File file ) throws IOException { return parse( new FileReader( file ) ); } public JSON parse( URL url ) throws IOException { return parse( url.openConnection().getInputStream() ); } public JSON parse( InputStream input ) throws IOException { return parse( new InputStreamReader( input ) ); } public JSON parse( String uri ) throws IOException { return parse( new URL( uri ) ); } public JSON parse( Reader reader ) throws IOException { // unfortunately JSONSerializer can't process the text as a stream // so we must read the full content first and then parse it StringBuffer buffer = new StringBuffer(); BufferedReader in = new BufferedReader( reader ); String line = null; while( (line = in.readLine()) != null ) { buffer.append( line ).append( "\n" ); } return parseText( buffer.toString() ); } public JSON parseText( String text ) { return JSONSerializer.toJSON( text, jsonConfig ); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/groovy/package.html0000664000175000017500000000021311650253660026653 0ustar jamespagejamespage

Groovy support

jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/groovy/JsonGroovyBuilder.java0000664000175000017500000002233711650253660030676 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy; import groovy.lang.Closure; import groovy.lang.GString; import groovy.lang.GroovyObjectSupport; import groovy.lang.MissingMethodException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import net.sf.json.*; /** * A Groovy builder for JSON values. * *
def books1 = builder.books {
   book = [title: "The Definitive Guide to Grails", author: "Graeme Rocher"]
   book = [title: "The Definitive Guide to Grails", author: "Graeme Rocher"]
}

def books2 = builder.books {
   book = new Book(title: "The Definitive Guide to Grails",
                   author: "Graeme Rocher")
   book = new Book(title: "The Definitive Guide to Grails",
                   author: "Graeme Rocher")
}

def books3 = builder.books {
   book = {
      title = "The Definitive Guide to Grails"
      author= "Graeme Rocher"
   }
   book = {
      title = "The Definitive Guide to Grails"
      author= "Graeme Rocher"
   }
}

def books4 = builder.books {
   book {
      title = "The Definitive Guide to Grails"
      author= "Graeme Rocher"
   }
   book {
      title = "The Definitive Guide to Grails"
      author= "Graeme Rocher"
   }
}

def books5 = builder.books {
   2.times {
      book = {
         title = "The Definitive Guide to Grails"
         author= "Graeme Rocher"
      }
   }
}

def books6 = builder.books {
   2.times {
      book {
         title = "The Definitive Guide to Grails"
         author= "Graeme Rocher"
      }
   }
}


 all 6 books variables output the same JSON

{"books": {
   "book": [{
         "title": "The Definitive Guide to Grails",
         "author": "Graeme Rocher"
      },{
         "title": "The Definitive Guide to Grails",
         "author": "Graeme Rocher"
      }]
   }
}
* * @author Andres Almiray */ public class JsonGroovyBuilder extends GroovyObjectSupport { private static final String JSON = "json"; private JSON current; private Map properties; private Stack stack; private JsonConfig jsonConfig; public JsonGroovyBuilder() { stack = new Stack(); properties = new HashMap(); jsonConfig = new JsonConfig(); } public JsonConfig getJsonConfig() { return jsonConfig; } public void setJsonConfig(JsonConfig jsonConfig) { this.jsonConfig = jsonConfig; } public Object getProperty( String name ) { if( !stack.isEmpty() ){ Object top = stack.peek(); if( top instanceof JSONObject ){ JSONObject json = (JSONObject) top; if( json.containsKey( name ) ){ return json.get( name ); }else{ return _getProperty( name ); } }else{ return _getProperty( name ); } }else{ return _getProperty( name ); } } public Object invokeMethod( String name, Object arg ) { if( JSON.equals( name ) && stack.isEmpty() ){ return createObject( name, arg ); } Object[] args = (Object[]) arg; if( args.length == 0 ){ throw new MissingMethodException( name, getClass(), args ); } Object value = null; if( args.length > 1 ){ JSONArray array = new JSONArray(); stack.push( array ); for( int i = 0; i < args.length; i++ ){ if( args[i] instanceof Closure ){ append( name, createObject( (Closure) args[i] ) ); }else if( args[i] instanceof Map ){ append( name, createObject( (Map) args[i] ) ); }else if( args[i] instanceof List ){ append( name, createArray( (List) args[i] ) ); }else{ _append( name, args[i], (JSON) stack.peek() ); } } stack.pop(); }else{ if( args[0] instanceof Closure ){ value = createObject( (Closure) args[0] ); }else if( args[0] instanceof Map ){ value = createObject( (Map) args[0] ); }else if( args[0] instanceof List ){ value = createArray( (List) args[0] ); } } if( stack.isEmpty() ){ JSONObject object = new JSONObject(); object.accumulate( name, current ); current = object; }else{ JSON top = (JSON) stack.peek(); if( top instanceof JSONObject ){ append( name, current == null ? value : current ); } } return current; } public void setProperty( String name, Object value ) { if( value instanceof GString ){ value = value.toString(); try{ value = JSONSerializer.toJSON( value ); }catch( JSONException jsone ){ // its a String literal } }else if( value instanceof Closure ){ value = createObject( (Closure) value ); }else if( value instanceof Map ){ value = createObject( (Map) value ); }else if( value instanceof List ){ value = createArray( (List) value ); } append( name, value ); } private Object _getProperty( String name ) { if( properties.containsKey( name ) ){ return properties.get( name ); }else{ return super.getProperty( name ); } } private void append( String key, Object value ) { Object target = null; if( !stack.isEmpty() ){ target = stack.peek(); current = (JSON) target; _append( key, value, current ); }else{ properties.put( key, value ); } } private void _append( String key, Object value, JSON target ) { if( target instanceof JSONObject ){ ((JSONObject) target).accumulate( key, value, jsonConfig ); }else if( target instanceof JSONArray ){ ((JSONArray) target).element( value, jsonConfig ); } } private JSON createArray( List list ) { JSONArray array = new JSONArray(); stack.push( array ); for( Iterator elements = list.iterator(); elements.hasNext(); ){ Object element = elements.next(); if( element instanceof Closure ){ element = createObject( (Closure) element ); }else if( element instanceof Map ){ element = createObject( (Map) element ); }else if( element instanceof List ){ element = createArray( (List) element ); } array.element( element ); } stack.pop(); return array; } private JSON createObject( Closure closure ) { JSONObject object = new JSONObject(); stack.push( object ); closure.setDelegate( this ); closure.setResolveStrategy( Closure.DELEGATE_FIRST ); closure.call(); stack.pop(); return object; } private JSON createObject( Map map ) { JSONObject object = new JSONObject(); stack.push( object ); for( Iterator properties = map.entrySet() .iterator(); properties.hasNext(); ){ Map.Entry property = (Map.Entry) properties.next(); String key = String.valueOf( property.getKey() ); Object value = property.getValue(); if( value instanceof Closure ){ value = createObject( (Closure) value ); }else if( value instanceof Map ){ value = createObject( (Map) value ); }else if( value instanceof List ){ value = createArray( (List) value ); } object.element( key, value ); } stack.pop(); return object; } private JSON createObject( String name, Object arg ) { Object[] args = (Object[]) arg; if( args.length == 0 ){ throw new MissingMethodException( name, getClass(), args ); } if( args.length == 1 ){ if( args[0] instanceof Closure ){ return createObject( (Closure) args[0] ); }else if( args[0] instanceof Map ){ return createObject( (Map) args[0] ); }else if( args[0] instanceof List ){ return createArray( (List) args[0] ); }else{ throw new JSONException( "Unsupported type" ); } }else{ JSONArray array = new JSONArray(); stack.push( array ); for( int i = 0; i < args.length; i++ ){ if( args[i] instanceof Closure ){ append( name, createObject( (Closure) args[i] ) ); }else if( args[i] instanceof Map ){ append( name, createObject( (Map) args[i] ) ); }else if( args[i] instanceof List ){ append( name, createArray( (List) args[i] ) ); }else{ _append( name, args[i], (JSON) stack.peek() ); } } stack.pop(); return array; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/xml/0000775000175000017500000000000011650253660023651 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/xml/package.html0000664000175000017500000000025411650253660026133 0ustar jamespagejamespage

Utilities for trasforming JSON to XML and back.

jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/xml/JSONTypes.java0000664000175000017500000000172511650253660026317 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.xml; /** * @author Andres Almiray */ public interface JSONTypes { String ARRAY = "array"; String BOOLEAN = "boolean"; String FLOAT = "float"; String FUNCTION = "function"; String INTEGER = "integer"; String NUMBER = "number"; String OBJECT = "object"; String STRING = "string"; }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/xml/XMLSerializer.java0000664000175000017500000014334211650253660027215 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.xml; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONFunction; import net.sf.json.JSONNull; import net.sf.json.JSONObject; import net.sf.json.util.JSONUtils; import nu.xom.Attribute; import nu.xom.Builder; import nu.xom.Document; import nu.xom.Element; import nu.xom.Elements; import nu.xom.Node; import nu.xom.Serializer; import nu.xom.Text; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Utility class for transforming JSON to XML an back.
* When transforming JSONObject and JSONArray instances to XML, this class will * add hints for converting back to JSON.
* Examples:
* *
 * JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
 * String xml = new XMLSerializer().write( json );
 * <o class="object">
 <name type="string">json</name>
 <bool type="boolean">true</bool>
 <int type="number">1</int>
 </o>
 * 
 * JSONArray json = JSONArray.fromObject("[1,2,3]");
 * String xml = new XMLSerializer().write( json );
 * <a class="array">
 <e type="number">1</e>
 <e type="number">2</e>
 <e type="number">3</e>
 </a>
 * 
* * @author Andres Almiray */ public class XMLSerializer { private static final String[] EMPTY_ARRAY = new String[0]; private static final String JSON_PREFIX = "json_"; private static final Log log = LogFactory.getLog( XMLSerializer.class ); /** the name for an JSONArray Element */ private String arrayName; /** the name for an JSONArray's element Element */ private String elementName; /** list of properties to be expanded from child to parent */ private String[] expandableProperties; private boolean forceTopLevelObject; /** flag to be tolerant for incomplete namespace prefixes */ private boolean namespaceLenient; /** Map of namespaces per element */ private Map namespacesPerElement = new TreeMap(); /** the name for an JSONObject Element */ private String objectName; /** flag for trimming namespace prefix from element name */ private boolean removeNamespacePrefixFromElements; /** the name for the root Element */ private String rootName; /** Map of namespaces for root element */ private Map rootNamespace = new TreeMap(); /** flag for skipping namespaces while reading */ private boolean skipNamespaces; /** flag for skipping whitespace elements while reading */ private boolean skipWhitespace; /** flag for trimming spaces from string values */ private boolean trimSpaces; /** flag for type hints naming compatibility */ private boolean typeHintsCompatibility; /** flag for adding JSON types hints as attributes */ private boolean typeHintsEnabled; /** * Creates a new XMLSerializer with default options.
*
    *
  • objectName: 'o'
  • *
  • arrayName: 'a'
  • *
  • elementName: 'e'
  • *
  • typeHinstEnabled: true
  • *
  • typeHinstCompatibility: true
  • *
  • namespaceLenient: false
  • *
  • expandableProperties: []
  • *
  • skipNamespaces: false
  • *
  • removeNameSpacePrefixFromElement: false
  • *
  • trimSpaces: false
  • *
*/ public XMLSerializer() { setObjectName( "o" ); setArrayName( "a" ); setElementName( "e" ); setTypeHintsEnabled( true ); setTypeHintsCompatibility( true ); setNamespaceLenient( false ); setSkipNamespaces( false ); setRemoveNamespacePrefixFromElements( false ); setTrimSpaces( false ); setExpandableProperties( EMPTY_ARRAY ); setSkipNamespaces( false ); } /** * Adds a namespace declaration to the root element. * * @param prefix namespace prefix * @param uri namespace uri */ public void addNamespace( String prefix, String uri ) { addNamespace( prefix, uri, null ); } /** * Adds a namespace declaration to an element.
* If the elementName param is null or blank, the namespace declaration will * be added to the root element. * * @param prefix namespace prefix * @param uri namespace uri * @param elementName name of target element */ public void addNamespace( String prefix, String uri, String elementName ) { if( StringUtils.isBlank( uri ) ){ return; } if( prefix == null ){ prefix = ""; } if( StringUtils.isBlank( elementName ) ){ rootNamespace.put( prefix.trim(), uri.trim() ); }else{ Map nameSpaces = (Map) namespacesPerElement.get( elementName ); if( nameSpaces == null ){ nameSpaces = new TreeMap(); namespacesPerElement.put( elementName, nameSpaces ); } nameSpaces.put( prefix, uri ); } } /** * Removes all namespaces declarations (from root an elements). */ public void clearNamespaces() { rootNamespace.clear(); namespacesPerElement.clear(); } /** * Removes all namespace declarations from an element.
* If the elementName param is null or blank, the declarations will be * removed from the root element. * * @param elementName name of target element */ public void clearNamespaces( String elementName ) { if( StringUtils.isBlank( elementName ) ){ rootNamespace.clear(); }else{ namespacesPerElement.remove( elementName ); } } /** * Returns the name used for JSONArray. */ public String getArrayName() { return arrayName; } /** * Returns the name used for JSONArray elements. */ public String getElementName() { return elementName; } /** * Returns a list of properties to be expanded from child to parent. */ public String[] getExpandableProperties() { return expandableProperties; } /** * Returns the name used for JSONArray. */ public String getObjectName() { return objectName; } /** * Returns the name used for the root element. */ public String getRootName() { return rootName; } public boolean isForceTopLevelObject() { return forceTopLevelObject; } /** * Returns wether this serializer is tolerant to namespaces without URIs or * not. */ public boolean isNamespaceLenient() { return namespaceLenient; } /** * Returns wether this serializer will remove namespace prefix from elements * or not. */ public boolean isRemoveNamespacePrefixFromElements() { return removeNamespacePrefixFromElements; } /** * Returns wether this serializer will skip adding namespace declarations to * elements or not. */ public boolean isSkipNamespaces() { return skipNamespaces; } /** * Returns wether this serializer will skip whitespace or not. */ public boolean isSkipWhitespace() { return skipWhitespace; } /** * Returns wether this serializer will trim leading and trealing whitespace * from values or not. */ public boolean isTrimSpaces() { return trimSpaces; } /** * Returns true if types hints will have a 'json_' prefix or not. */ public boolean isTypeHintsCompatibility() { return typeHintsCompatibility; } /** * Returns true if JSON types will be included as attributes. */ public boolean isTypeHintsEnabled() { return typeHintsEnabled; } /** * Creates a JSON value from a XML string. * * @param xml A well-formed xml document in a String * @return a JSONNull, JSONObject or JSONArray * @throws JSONException if the conversion from XML to JSON can't be made for * I/O or format reasons. */ public JSON read( String xml ) { JSON json = null; try{ Document doc = new Builder().build( new StringReader( xml ) ); Element root = doc.getRootElement(); if( isNullObject( root ) ){ return JSONNull.getInstance(); } String defaultType = getType( root, JSONTypes.STRING ); if( isArray( root, true ) ){ json = processArrayElement( root, defaultType ); if( forceTopLevelObject ){ String key = removeNamespacePrefix( root.getQualifiedName() ); json = new JSONObject().element( key, json ); } }else{ json = processObjectElement( root, defaultType ); if( forceTopLevelObject ) { String key = removeNamespacePrefix( root.getQualifiedName() ); json = new JSONObject().element( key, json ); } } }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( e ); } return json; } /** * Creates a JSON value from a File. * * @param file * @return a JSONNull, JSONObject or JSONArray * @throws JSONException if the conversion from XML to JSON can't be made for * I/O or format reasons. */ public JSON readFromFile( File file ) { if( file == null ){ throw new JSONException( "File is null" ); } if( !file.canRead() ){ throw new JSONException( "Can't read input file" ); } if( file.isDirectory() ){ throw new JSONException( "File is a directory" ); } try{ return readFromStream( new FileInputStream( file ) ); }catch( IOException ioe ){ throw new JSONException( ioe ); } } /** * Creates a JSON value from a File. * * @param path * @return a JSONNull, JSONObject or JSONArray * @throws JSONException if the conversion from XML to JSON can't be made for * I/O or format reasons. */ public JSON readFromFile( String path ) { return readFromStream( Thread.currentThread() .getContextClassLoader() .getResourceAsStream( path ) ); } /** * Creates a JSON value from an input stream. * * @param stream * @return a JSONNull, JSONObject or JSONArray * @throws JSONException if the conversion from XML to JSON can't be made for * I/O or format reasons. */ public JSON readFromStream( InputStream stream ) { try{ StringBuffer xml = new StringBuffer(); BufferedReader in = new BufferedReader( new InputStreamReader( stream ) ); String line = null; while( (line = in.readLine()) != null ){ xml.append( line ); } return read( xml.toString() ); }catch( IOException ioe ){ throw new JSONException( ioe ); } } /** * Removes a namespace from the root element. * * @param prefix namespace prefix */ public void removeNamespace( String prefix ) { removeNamespace( prefix, null ); } /** * Removes a namespace from the root element.
* If the elementName is null or blank, the namespace will be removed from * the root element. * * @param prefix namespace prefix * @param elementName name of target element */ public void removeNamespace( String prefix, String elementName ) { if( prefix == null ){ prefix = ""; } if( StringUtils.isBlank( elementName ) ){ rootNamespace.remove( prefix.trim() ); }else{ Map nameSpaces = (Map) namespacesPerElement.get( elementName ); nameSpaces.remove( prefix ); } } /** * Sets the name used for JSONArray.
* Default is 'a'. */ public void setArrayName( String arrayName ) { this.arrayName = StringUtils.isBlank( arrayName ) ? "a" : arrayName; } /** * Sets the name used for JSONArray elements.
* Default is 'e'. */ public void setElementName( String elementName ) { this.elementName = StringUtils.isBlank( elementName ) ? "e" : elementName; } /** * Sets the list of properties to be expanded from child to parent. */ public void setExpandableProperties( String[] expandableProperties ) { this.expandableProperties = expandableProperties == null ? EMPTY_ARRAY : expandableProperties; } public void setForceTopLevelObject( boolean forceTopLevelObject ) { this.forceTopLevelObject = forceTopLevelObject; } /** * Sets the namespace declaration to the root element.
* Any previous values are discarded. * * @param prefix namespace prefix * @param uri namespace uri */ public void setNamespace( String prefix, String uri ) { setNamespace( prefix, uri, null ); } /** * Adds a namespace declaration to an element.
* Any previous values are discarded. If the elementName param is null or * blank, the namespace declaration will be added to the root element. * * @param prefix namespace prefix * @param uri namespace uri * @param elementName name of target element */ public void setNamespace( String prefix, String uri, String elementName ) { if( StringUtils.isBlank( uri ) ){ return; } if( prefix == null ){ prefix = ""; } if( StringUtils.isBlank( elementName ) ){ rootNamespace.clear(); rootNamespace.put( prefix.trim(), uri.trim() ); }else{ Map nameSpaces = (Map) namespacesPerElement.get( elementName ); if( nameSpaces == null ){ nameSpaces = new TreeMap(); namespacesPerElement.put( elementName, nameSpaces ); } nameSpaces.clear(); nameSpaces.put( prefix, uri ); } } /** * Sets wether this serializer is tolerant to namespaces without URIs or not. */ public void setNamespaceLenient( boolean namespaceLenient ) { this.namespaceLenient = namespaceLenient; } /** * Sets the name used for JSONObject.
* Default is 'o'. */ public void setObjectName( String objectName ) { this.objectName = StringUtils.isBlank( objectName ) ? "o" : objectName; } /** * Sets if this serializer will remove namespace prefix from elements when * reading. */ public void setRemoveNamespacePrefixFromElements( boolean removeNamespacePrefixFromElements ) { this.removeNamespacePrefixFromElements = removeNamespacePrefixFromElements; } /** * Sets the name used for the root element. */ public void setRootName( String rootName ) { this.rootName = StringUtils.isBlank( rootName ) ? null : rootName; } /** * Sets if this serializer will skip adding namespace declarations to * elements when reading. */ public void setSkipNamespaces( boolean skipNamespaces ) { this.skipNamespaces = skipNamespaces; } /** * Sets if this serializer will skip whitespace when reading. */ public void setSkipWhitespace( boolean skipWhitespace ) { this.skipWhitespace = skipWhitespace; } /** * Sets if this serializer will trim leading and trealing whitespace from * values when reading. */ public void setTrimSpaces( boolean trimSpaces ) { this.trimSpaces = trimSpaces; } /** * Sets wether types hints will have a 'json_' prefix or not. */ public void setTypeHintsCompatibility( boolean typeHintsCompatibility ) { this.typeHintsCompatibility = typeHintsCompatibility; } /** * Sets wether JSON types will be included as attributes. */ public void setTypeHintsEnabled( boolean typeHintsEnabled ) { this.typeHintsEnabled = typeHintsEnabled; } /** * Writes a JSON value into a XML string with UTF-8 encoding.
* * @param json The JSON value to transform * @return a String representation of a well-formed xml document. * @throws JSONException if the conversion from JSON to XML can't be made for * I/O reasons. */ public String write( JSON json ) { return write( json, null ); } /** * Writes a JSON value into a XML string with an specific encoding.
* If the encoding string is null it will use UTF-8. * * @param json The JSON value to transform * @param encoding The xml encoding to use * @return a String representation of a well-formed xml document. * @throws JSONException if the conversion from JSON to XML can't be made for * I/O reasons or the encoding is not supported. */ public String write( JSON json, String encoding ) { if( JSONNull.getInstance() .equals( json ) ){ Element root = null; root = newElement( getRootName() == null ? getObjectName() : getRootName() ); root.addAttribute( new Attribute( addJsonPrefix( "null" ), "true" ) ); Document doc = new Document( root ); return writeDocument( doc, encoding ); }else if( json instanceof JSONArray ){ JSONArray jsonArray = (JSONArray) json; Element root = processJSONArray( jsonArray, newElement( getRootName() == null ? getArrayName() : getRootName() ), expandableProperties ); Document doc = new Document( root ); return writeDocument( doc, encoding ); }else{ JSONObject jsonObject = (JSONObject) json; Element root = null; if( jsonObject.isNullObject() ){ root = newElement( getObjectName() ); root.addAttribute( new Attribute( addJsonPrefix( "null" ), "true" ) ); }else{ root = processJSONObject( jsonObject, newElement( getRootName() == null ? getObjectName() : getRootName() ), expandableProperties, true ); } Document doc = new Document( root ); return writeDocument( doc, encoding ); } } private String addJsonPrefix( String str ) { if( !isTypeHintsCompatibility() ){ return JSON_PREFIX + str; } return str; } private void addNameSpaceToElement( Element element ) { String elementName = null; if( element instanceof CustomElement ){ elementName = ((CustomElement) element).getQName(); }else{ elementName = element.getQualifiedName(); } Map nameSpaces = (Map) namespacesPerElement.get( elementName ); if( nameSpaces != null && !nameSpaces.isEmpty() ){ setNamespaceLenient( true ); for( Iterator entries = nameSpaces.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String prefix = (String) entry.getKey(); String uri = (String) entry.getValue(); if( StringUtils.isBlank( prefix ) ){ element.setNamespaceURI( uri ); }else{ element.addNamespaceDeclaration( prefix, uri ); } } } } private boolean checkChildElements( Element element, boolean isTopLevel ) { int childCount = element.getChildCount(); Elements elements = element.getChildElements(); int elementCount = elements.size(); if( childCount == 1 && element.getChild( 0 ) instanceof Text ){ return isTopLevel; } if( childCount == elementCount ){ if( elementCount == 0 ){ return true; } if( elementCount == 1 ){ if( skipWhitespace || element.getChild( 0 ) instanceof Text ){ return true; }else{ return false; } } } if( childCount > elementCount ){ for( int i = 0; i < childCount; i++ ){ Node node = element.getChild( i ); if( node instanceof Text ){ Text text = (Text) node; if( StringUtils.isNotBlank( StringUtils.strip( text.getValue() ) ) && !skipWhitespace ){ return false; } } } } String childName = elements.get( 0 ) .getQualifiedName(); for( int i = 1; i < elementCount; i++ ){ if( childName.compareTo( elements.get( i ) .getQualifiedName() ) != 0 ){ return false; } } return true; } private String getClass( Element element ) { Attribute attribute = element.getAttribute( addJsonPrefix( "class" ) ); String clazz = null; if( attribute != null ){ String clazzText = attribute.getValue() .trim(); if( JSONTypes.OBJECT.compareToIgnoreCase( clazzText ) == 0 ){ clazz = JSONTypes.OBJECT; }else if( JSONTypes.ARRAY.compareToIgnoreCase( clazzText ) == 0 ){ clazz = JSONTypes.ARRAY; } } return clazz; } private String getType( Element element ) { return getType( element, null ); } private String getType( Element element, String defaultType ) { Attribute attribute = element.getAttribute( addJsonPrefix( "type" ) ); String type = null; if( attribute != null ){ String typeText = attribute.getValue() .trim(); if( JSONTypes.BOOLEAN.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.BOOLEAN; }else if( JSONTypes.NUMBER.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.NUMBER; }else if( JSONTypes.INTEGER.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.INTEGER; }else if( JSONTypes.FLOAT.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.FLOAT; }else if( JSONTypes.OBJECT.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.OBJECT; }else if( JSONTypes.ARRAY.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.ARRAY; }else if( JSONTypes.STRING.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.STRING; }else if( JSONTypes.FUNCTION.compareToIgnoreCase( typeText ) == 0 ){ type = JSONTypes.FUNCTION; } }else{ if( defaultType != null ){ log.info( "Using default type " + defaultType ); type = defaultType; } } return type; } private boolean hasNamespaces( Element element ) { int namespaces = 0; for( int i = 0; i < element.getNamespaceDeclarationCount(); i++ ){ String prefix = element.getNamespacePrefix( i ); String uri = element.getNamespaceURI( prefix ); if( StringUtils.isBlank( uri ) ){ continue; } namespaces++; } return namespaces > 0; } private boolean isArray( Element element, boolean isTopLevel ) { boolean isArray = false; String clazz = getClass( element ); if( clazz != null && clazz.equals( JSONTypes.ARRAY ) ){ isArray = true; }else if( element.getAttributeCount() == 0 ){ isArray = checkChildElements( element, isTopLevel ); }else if( element.getAttributeCount() == 1 && (element.getAttribute( addJsonPrefix( "class" ) ) != null || element.getAttribute( addJsonPrefix( "type" ) ) != null) ){ isArray = checkChildElements( element, isTopLevel ); }else if( element.getAttributeCount() == 2 && (element.getAttribute( addJsonPrefix( "class" ) ) != null && element.getAttribute( addJsonPrefix( "type" ) ) != null) ){ isArray = checkChildElements( element, isTopLevel ); } if( isArray ){ // check namespace for( int j = 0; j < element.getNamespaceDeclarationCount(); j++ ){ String prefix = element.getNamespacePrefix( j ); String uri = element.getNamespaceURI( prefix ); if( !StringUtils.isBlank( uri ) ){ return false; } } } return isArray; } private boolean isFunction( Element element ) { int attrCount = element.getAttributeCount(); if( attrCount > 0 ){ Attribute typeAttr = element.getAttribute( addJsonPrefix( "type" ) ); Attribute paramsAttr = element.getAttribute( addJsonPrefix( "params" ) ); if( attrCount == 1 && paramsAttr != null ){ return true; } if( attrCount == 2 && paramsAttr != null && typeAttr != null && (typeAttr.getValue() .compareToIgnoreCase( JSONTypes.STRING ) == 0 || typeAttr.getValue() .compareToIgnoreCase( JSONTypes.FUNCTION ) == 0) ){ return true; } } return false; } private boolean isNullObject( Element element ) { if( element.getChildCount() == 0 ){ if( element.getAttributeCount() == 0 ){ return true; }else if( element.getAttribute( addJsonPrefix( "null" ) ) != null ){ return true; }else if( element.getAttributeCount() == 1 && (element.getAttribute( addJsonPrefix( "class" ) ) != null || element.getAttribute( addJsonPrefix( "type" ) ) != null) ){ return true; }else if( element.getAttributeCount() == 2 && (element.getAttribute( addJsonPrefix( "class" ) ) != null && element.getAttribute( addJsonPrefix( "type" ) ) != null) ){ return true; } } if( skipWhitespace && element.getChildCount() == 1 && element.getChild( 0 ) instanceof Text ){ return true; } return false; } private boolean isObject( Element element, boolean isTopLevel ) { boolean isObject = false; if( !isArray( element, isTopLevel ) && !isFunction( element ) ){ if( hasNamespaces( element ) ){ return true; } int attributeCount = element.getAttributeCount(); if( attributeCount > 0 ){ int attrs = element.getAttribute( addJsonPrefix( "null" )) == null ? 0 : 1; attrs += element.getAttribute( addJsonPrefix( "class" )) == null ? 0: 1; attrs += element.getAttribute( addJsonPrefix( "type" ))== null ? 0 : 1; switch( attributeCount ){ case 1: if( attrs == 0){ return true; } break; case 2: if( attrs < 2 ){ return true; } break; case 3: if( attrs < 3 ){ return true; } break; default: return true; } } int childCount = element.getChildCount(); if( childCount == 1 && element.getChild( 0 ) instanceof Text ){ return isTopLevel; } isObject = true; } return isObject; } private Element newElement( String name ) { if( name.indexOf( ':' ) != -1 ){ namespaceLenient = true; } return namespaceLenient ? new CustomElement( name ) : new Element( name ); } private JSON processArrayElement( Element element, String defaultType ) { JSONArray jsonArray = new JSONArray(); // process children (including text) int childCount = element.getChildCount(); for( int i = 0; i < childCount; i++ ){ Node child = element.getChild( i ); if( child instanceof Text ){ Text text = (Text) child; if( StringUtils.isNotBlank( StringUtils.strip( text.getValue() ) ) ){ jsonArray.element( text.getValue() ); } }else if( child instanceof Element ){ setValue( jsonArray, (Element) child, defaultType ); } } return jsonArray; } private Object processElement( Element element, String type ) { if( isNullObject( element ) ){ return JSONNull.getInstance(); }else if( isArray( element, false ) ){ return processArrayElement( element, type ); }else if( isObject( element, false ) ){ return processObjectElement( element, type ); }else{ return trimSpaceFromValue( element.getValue() ); } } private Element processJSONArray( JSONArray array, Element root, String[] expandableProperties ) { int l = array.size(); for( int i = 0; i < l; i++ ){ Object value = array.get( i ); Element element = processJSONValue( value, root, null, expandableProperties ); root.appendChild( element ); } return root; } private Element processJSONObject( JSONObject jsonObject, Element root, String[] expandableProperties, boolean isRoot ) { if( jsonObject.isNullObject() ){ root.addAttribute( new Attribute( addJsonPrefix( "null" ), "true" ) ); return root; }else if( jsonObject.isEmpty() ){ return root; } if( isRoot ){ if( !rootNamespace.isEmpty() ){ setNamespaceLenient( true ); for( Iterator entries = rootNamespace.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String prefix = (String) entry.getKey(); String uri = (String) entry.getValue(); if( StringUtils.isBlank( prefix ) ){ root.setNamespaceURI( uri ); }else{ root.addNamespaceDeclaration( prefix, uri ); } } } } addNameSpaceToElement( root ); Object[] names = jsonObject.names() .toArray(); Arrays.sort( names ); Element element = null; for( int i = 0; i < names.length; i++ ){ String name = (String) names[i]; Object value = jsonObject.get( name ); if( name.startsWith( "@xmlns" ) ){ setNamespaceLenient( true ); int colon = name.indexOf( ':' ); if( colon == -1 ){ // do not override if already defined by nameSpaceMaps if( StringUtils.isBlank( root.getNamespaceURI() ) ){ root.setNamespaceURI( String.valueOf( value ) ); } }else{ String prefix = name.substring( colon + 1 ); if( StringUtils.isBlank( root.getNamespaceURI( prefix ) ) ){ root.addNamespaceDeclaration( prefix, String.valueOf( value ) ); } } }else if( name.startsWith( "@" ) ){ root.addAttribute( new Attribute( name.substring( 1 ), String.valueOf( value ) ) ); }else if( name.equals( "#text" ) ){ if( value instanceof JSONArray ){ root.appendChild( ((JSONArray) value).join( "", true ) ); }else{ root.appendChild( String.valueOf( value ) ); } }else if( value instanceof JSONArray && (((JSONArray) value).isExpandElements() || ArrayUtils.contains( expandableProperties, name )) ){ JSONArray array = (JSONArray) value; int l = array.size(); for( int j = 0; j < l; j++ ){ Object item = array.get( j ); element = newElement( name ); if( item instanceof JSONObject ){ element = processJSONValue( (JSONObject) item, root, element, expandableProperties ); }else if( item instanceof JSONArray ){ element = processJSONValue( (JSONArray) item, root, element, expandableProperties ); }else{ element = processJSONValue( item, root, element, expandableProperties ); } addNameSpaceToElement( element ); root.appendChild( element ); } }else{ element = newElement( name ); element = processJSONValue( value, root, element, expandableProperties ); addNameSpaceToElement( element ); root.appendChild( element ); } } return root; } private Element processJSONValue( Object value, Element root, Element target, String[] expandableProperties ) { if( target == null ){ target = newElement( getElementName() ); } if( JSONUtils.isBoolean( value ) ){ if( isTypeHintsEnabled() ){ target.addAttribute( new Attribute( addJsonPrefix( "type" ), JSONTypes.BOOLEAN ) ); } target.appendChild( value.toString() ); }else if( JSONUtils.isNumber( value ) ){ if( isTypeHintsEnabled() ){ target.addAttribute( new Attribute( addJsonPrefix( "type" ), JSONTypes.NUMBER ) ); } target.appendChild( value.toString() ); }else if( JSONUtils.isFunction( value ) ){ if( value instanceof String ){ value = JSONFunction.parse( (String) value ); } JSONFunction func = (JSONFunction) value; if( isTypeHintsEnabled() ){ target.addAttribute( new Attribute( addJsonPrefix( "type" ), JSONTypes.FUNCTION ) ); } String params = ArrayUtils.toString( func.getParams() ); params = params.substring( 1 ); params = params.substring( 0, params.length() - 1 ); target.addAttribute( new Attribute( addJsonPrefix( "params" ), params ) ); target.appendChild( new Text( "" ) ); }else if( JSONUtils.isString( value ) ){ if( isTypeHintsEnabled() ){ target.addAttribute( new Attribute( addJsonPrefix( "type" ), JSONTypes.STRING ) ); } target.appendChild( value.toString() ); }else if( value instanceof JSONArray ){ if( isTypeHintsEnabled() ){ target.addAttribute( new Attribute( addJsonPrefix( "class" ), JSONTypes.ARRAY ) ); } target = processJSONArray( (JSONArray) value, target, expandableProperties ); }else if( value instanceof JSONObject ){ if( isTypeHintsEnabled() ){ target.addAttribute( new Attribute( addJsonPrefix( "class" ), JSONTypes.OBJECT ) ); } target = processJSONObject( (JSONObject) value, target, expandableProperties, false ); }else if( JSONUtils.isNull( value ) ){ if( isTypeHintsEnabled() ){ target.addAttribute( new Attribute( addJsonPrefix( "class" ), JSONTypes.OBJECT ) ); } target.addAttribute( new Attribute( addJsonPrefix( "null" ), "true" ) ); } return target; } private JSON processObjectElement( Element element, String defaultType ) { if( isNullObject( element ) ){ return JSONNull.getInstance(); } JSONObject jsonObject = new JSONObject(); if( !skipNamespaces ){ for( int j = 0; j < element.getNamespaceDeclarationCount(); j++ ){ String prefix = element.getNamespacePrefix( j ); String uri = element.getNamespaceURI( prefix ); if( StringUtils.isBlank( uri ) ){ continue; } if( !StringUtils.isBlank( prefix ) ){ prefix = ":" + prefix; } setOrAccumulate( jsonObject, "@xmlns" + prefix, trimSpaceFromValue( uri ) ); } } // process attributes first int attrCount = element.getAttributeCount(); for( int i = 0; i < attrCount; i++ ){ Attribute attr = element.getAttribute( i ); String attrname = attr.getQualifiedName(); if( isTypeHintsEnabled() && (addJsonPrefix( "class" ).compareToIgnoreCase( attrname ) == 0 || addJsonPrefix( "type" ).compareToIgnoreCase( attrname ) == 0) ){ continue; } String attrvalue = attr.getValue(); setOrAccumulate( jsonObject, "@" + removeNamespacePrefix( attrname ), trimSpaceFromValue( attrvalue ) ); } // process children (including text) int childCount = element.getChildCount(); for( int i = 0; i < childCount; i++ ){ Node child = element.getChild( i ); if( child instanceof Text ){ Text text = (Text) child; if( StringUtils.isNotBlank( StringUtils.strip( text.getValue() ) ) ){ setOrAccumulate( jsonObject, "#text", trimSpaceFromValue( text.getValue() ) ); } }else if( child instanceof Element ){ setValue( jsonObject, (Element) child, defaultType ); } } return jsonObject; } private String removeNamespacePrefix( String name ) { if( isRemoveNamespacePrefixFromElements() ){ int colon = name.indexOf( ':' ); return colon != -1 ? name.substring( colon + 1 ) : name; } return name; } private void setOrAccumulate( JSONObject jsonObject, String key, Object value ) { if( jsonObject.has( key ) ){ jsonObject.accumulate( key, value ); Object val = jsonObject.get( key ); if( val instanceof JSONArray ){ ((JSONArray) val).setExpandElements( true ); } }else{ jsonObject.element( key, value ); } } private void setValue( JSONArray jsonArray, Element element, String defaultType ) { String clazz = getClass( element ); String type = getType( element ); type = (type == null) ? defaultType : type; if( hasNamespaces( element ) && !skipNamespaces ){ jsonArray.element( simplifyValue( null, processElement( element, type ) ) ); return; }else if( element.getAttributeCount() > 0 ){ if( isFunction( element ) ){ Attribute paramsAttribute = element.getAttribute( addJsonPrefix( "params" ) ); String[] params = null; String text = element.getValue(); params = StringUtils.split( paramsAttribute.getValue(), "," ); jsonArray.element( new JSONFunction( params, text ) ); return; }else{ jsonArray.element( simplifyValue( null, processElement( element, type ) ) ); return; } } boolean classProcessed = false; if( clazz != null ){ if( clazz.compareToIgnoreCase( JSONTypes.ARRAY ) == 0 ){ jsonArray.element( processArrayElement( element, type ) ); classProcessed = true; }else if( clazz.compareToIgnoreCase( JSONTypes.OBJECT ) == 0 ){ jsonArray.element( simplifyValue( null, processObjectElement( element, type ) ) ); classProcessed = true; } } if( !classProcessed ){ if( type.compareToIgnoreCase( JSONTypes.BOOLEAN ) == 0 ){ jsonArray.element( Boolean.valueOf( element.getValue() ) ); }else if( type.compareToIgnoreCase( JSONTypes.NUMBER ) == 0 ){ // try integer first try{ jsonArray.element( Integer.valueOf( element.getValue() ) ); }catch( NumberFormatException e ){ jsonArray.element( Double.valueOf( element.getValue() ) ); } }else if( type.compareToIgnoreCase( JSONTypes.INTEGER ) == 0 ){ jsonArray.element( Integer.valueOf( element.getValue() ) ); }else if( type.compareToIgnoreCase( JSONTypes.FLOAT ) == 0 ){ jsonArray.element( Double.valueOf( element.getValue() ) ); }else if( type.compareToIgnoreCase( JSONTypes.FUNCTION ) == 0 ){ String[] params = null; String text = element.getValue(); Attribute paramsAttribute = element.getAttribute( addJsonPrefix( "params" ) ); if( paramsAttribute != null ){ params = StringUtils.split( paramsAttribute.getValue(), "," ); } jsonArray.element( new JSONFunction( params, text ) ); }else if( type.compareToIgnoreCase( JSONTypes.STRING ) == 0 ){ // see if by any chance has a 'params' attribute Attribute paramsAttribute = element.getAttribute( addJsonPrefix( "params" ) ); if( paramsAttribute != null ){ String[] params = null; String text = element.getValue(); params = StringUtils.split( paramsAttribute.getValue(), "," ); jsonArray.element( new JSONFunction( params, text ) ); }else{ if( isArray( element, false ) ){ jsonArray.element( processArrayElement( element, defaultType ) ); }else if( isObject( element, false ) ){ jsonArray.element( simplifyValue( null, processObjectElement( element, defaultType ) ) ); }else{ jsonArray.element( trimSpaceFromValue( element.getValue() ) ); } } } } } private void setValue( JSONObject jsonObject, Element element, String defaultType ) { String clazz = getClass( element ); String type = getType( element ); type = (type == null) ? defaultType : type; String key = removeNamespacePrefix( element.getQualifiedName() ); if( hasNamespaces( element ) && !skipNamespaces ){ setOrAccumulate( jsonObject, key, simplifyValue( jsonObject, processElement( element, type ) ) ); return; }else if( element.getAttributeCount() > 0 ){ if( isFunction( element ) ){ Attribute paramsAttribute = element.getAttribute( addJsonPrefix( "params" ) ); String text = element.getValue(); String[] params = StringUtils.split( paramsAttribute.getValue(), "," ); setOrAccumulate( jsonObject, key, new JSONFunction( params, text ) ); return; }/*else{ setOrAccumulate( jsonObject, key, simplifyValue( jsonObject, processElement( element, type ) ) ); return; }*/ } boolean classProcessed = false; if( clazz != null ){ if( clazz.compareToIgnoreCase( JSONTypes.ARRAY ) == 0 ){ setOrAccumulate( jsonObject, key, processArrayElement( element, type ) ); classProcessed = true; }else if( clazz.compareToIgnoreCase( JSONTypes.OBJECT ) == 0 ){ setOrAccumulate( jsonObject, key, simplifyValue( jsonObject, processObjectElement( element, type ) ) ); classProcessed = true; } } if( !classProcessed ){ if( type.compareToIgnoreCase( JSONTypes.BOOLEAN ) == 0 ){ setOrAccumulate( jsonObject, key, Boolean.valueOf( element.getValue() ) ); }else if( type.compareToIgnoreCase( JSONTypes.NUMBER ) == 0 ){ // try integer first try{ setOrAccumulate( jsonObject, key, Integer.valueOf( element.getValue() ) ); }catch( NumberFormatException e ){ setOrAccumulate( jsonObject, key, Double.valueOf( element.getValue() ) ); } }else if( type.compareToIgnoreCase( JSONTypes.INTEGER ) == 0 ){ setOrAccumulate( jsonObject, key, Integer.valueOf( element.getValue() ) ); }else if( type.compareToIgnoreCase( JSONTypes.FLOAT ) == 0 ){ setOrAccumulate( jsonObject, key, Double.valueOf( element.getValue() ) ); }else if( type.compareToIgnoreCase( JSONTypes.FUNCTION ) == 0 ){ String[] params = null; String text = element.getValue(); Attribute paramsAttribute = element.getAttribute( addJsonPrefix( "params" ) ); if( paramsAttribute != null ){ params = StringUtils.split( paramsAttribute.getValue(), "," ); } setOrAccumulate( jsonObject, key, new JSONFunction( params, text ) ); }else if( type.compareToIgnoreCase( JSONTypes.STRING ) == 0 ){ // see if by any chance has a 'params' attribute Attribute paramsAttribute = element.getAttribute( addJsonPrefix( "params" ) ); if( paramsAttribute != null ){ String[] params = null; String text = element.getValue(); params = StringUtils.split( paramsAttribute.getValue(), "," ); setOrAccumulate( jsonObject, key, new JSONFunction( params, text ) ); }else{ if( isArray( element, false ) ){ setOrAccumulate( jsonObject, key, processArrayElement( element, defaultType ) ); }else if( isObject( element, false ) ){ setOrAccumulate( jsonObject, key, simplifyValue( jsonObject, processObjectElement( element, defaultType ) ) ); }else{ setOrAccumulate( jsonObject, key, trimSpaceFromValue( element.getValue() ) ); } } } } } private Object simplifyValue( JSONObject parent, Object json ) { if( json instanceof JSONObject ){ JSONObject object = (JSONObject) json; if( parent != null ){ // remove all duplicated @xmlns from child for( Iterator entries = parent.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if( key.startsWith( "@xmlns" ) && value.equals( object.opt( key ) ) ){ object.remove( key ); } } } if( object.size() == 1 && object.has( "#text" ) ){ return object.get( "#text" ); } } return json; } private String trimSpaceFromValue( String value ) { if( isTrimSpaces() ){ return value.trim(); } return value; } private String writeDocument( Document doc, String encoding ) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ XomSerializer serializer = (encoding == null) ? new XomSerializer( baos ) : new XomSerializer( baos, encoding ); serializer.write( doc ); encoding = serializer.getEncoding(); }catch( IOException ioe ){ throw new JSONException( ioe ); } String str = null; try{ str = baos.toString( encoding ); }catch( UnsupportedEncodingException uee ){ throw new JSONException( uee ); } return str; } private static class CustomElement extends Element { private static String getName( String name ) { int colon = name.indexOf( ':' ); if( colon != -1 ){ return name.substring( colon + 1 ); } return name; } private static String getPrefix( String name ) { int colon = name.indexOf( ':' ); if( colon != -1 ){ return name.substring( 0, colon ); } return ""; } private String prefix; public CustomElement( String name ) { super( CustomElement.getName( name ) ); prefix = CustomElement.getPrefix( name ); } public final String getQName() { if( prefix.length() == 0 ){ return getLocalName(); }else{ return prefix + ":" + getLocalName(); } } } private class XomSerializer extends Serializer { public XomSerializer( OutputStream out ) { super( out ); } public XomSerializer( OutputStream out, String encoding ) throws UnsupportedEncodingException { super( out, encoding ); } protected void write( Text text ) throws IOException { String value = text.getValue(); if( value.startsWith( "" ) ){ value = value.substring( 9 ); value = value.substring( 0, value.length() - 3 ); writeRaw( "" ); }else{ super.write( text ); } } protected void writeEmptyElementTag( Element element ) throws IOException { if( element instanceof CustomElement && isNamespaceLenient() ){ writeTagBeginning( (CustomElement) element ); writeRaw( "/>" ); }else{ super.writeEmptyElementTag( element ); } } protected void writeEndTag( Element element ) throws IOException { if( element instanceof CustomElement && isNamespaceLenient() ){ writeRaw( "" ); }else{ super.writeEndTag( element ); } } protected void writeNamespaceDeclaration( String prefix, String uri ) throws IOException { if( !StringUtils.isBlank( uri ) ){ super.writeNamespaceDeclaration( prefix, uri ); } } protected void writeStartTag( Element element ) throws IOException { if( element instanceof CustomElement && isNamespaceLenient() ){ writeTagBeginning( (CustomElement) element ); writeRaw( ">" ); }else{ super.writeStartTag( element ); } } private void writeTagBeginning( CustomElement element ) throws IOException { writeRaw( "<" ); writeRaw( element.getQName() ); writeAttributes( element ); writeNamespaceDeclarations( element ); } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/JSONException.java0000664000175000017500000000236711650253660026354 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import org.apache.commons.lang.exception.NestableRuntimeException; /** * The JSONException is thrown when things are amiss. * * @author JSON.org * @version 4 */ public class JSONException extends NestableRuntimeException { private static final long serialVersionUID = 6995087065217051815L; public JSONException() { super(); } public JSONException( String msg ) { super( msg, null ); } public JSONException( String msg, Throwable cause ) { super( msg, cause ); } public JSONException( Throwable cause ) { super( (cause == null ? null : cause.toString()), cause ); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/JSON.java0000664000175000017500000000615511650253660024474 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.io.IOException; import java.io.Writer; import java.io.Serializable; /** * Marker interface, identifies a valid JSON value.
* A JSON value may be a {@link JSONObject}, a {@link JSONArray} or a * {@link JSONNull}. * * @author Andres Almiray */ public interface JSON extends Serializable { /** * Returns true if this object is a JSONArray, false otherwise. */ boolean isArray(); /** * Returns true if this object has no elements or keys. * * @throws JSONException if called on a 'null' object */ boolean isEmpty(); /** * Returns the number of properties in an object or the size of the array. * * @return the size of an json object or array * @throws JSONException if called on a 'null' object */ int size(); /** * Make a prettyprinted JSON text. *

* Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable representation * of the object, beginning with { (left * brace) and ending with } (right * brace). * @throws JSONException If the object contains an invalid number. */ String toString( int indentFactor ); /** * Make a prettyprinted JSON text. *

* Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable representation of the * object, beginning with { (left brace) * and ending with } (right brace). * @throws JSONException If the object contains an invalid number. */ String toString( int indentFactor, int indent ); /** * Write the contents as JSON text to a writer. For compactness, no * whitespace is added. *

* Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ Writer write( Writer writer ) throws IOException; /** * Writes the canonicalized form of this JSON object. */ Writer writeCanonical(Writer w) throws IOException; } jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/0000775000175000017500000000000011650253660024026 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/JSONBuilder.java0000664000175000017500000002153711650253660026761 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.io.IOException; import java.io.Writer; import net.sf.json.JSONException; /** * JSONBuilder provides a quick and convenient way of producing JSON text. The * texts produced strictly conform to JSON syntax rules. No whitespace is added, * so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. *

* A JSONBuilder instance provides a value method for appending * values to the text, and a key method for adding keys before * values in objects. There are array and endArray * methods that make and bound array values, and object and * endObject methods which make and bound object values. All of * these methods return the JSONBuilder instance, permitting a cascade style. * For example, * *

 * new JSONBuilder(myWriter)
 *     .object()
 *         .key("JSON")
 *         .value("Hello, World!")
 *     .endObject();
* * which writes * *
 * {"JSON":"Hello, World!"}
* *

* The first method called must be array or object. * There are no methods for adding commas or colons. JSONBuilder adds them for * you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org * @version 1 */ public class JSONBuilder { private static final int MAXDEPTH = 20; /** * The comma flag determines if a comma should be output before the next * value. */ private boolean comma; /** * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k' * (key), 'o' (object). */ protected char mode; /** * The object/array stack. */ private char stack[]; /** * The stack top index. A value of 0 indicates that the stack is empty. */ private int top; /** * The writer that will receive the output. */ protected Writer writer; /** * Make a fresh JSONBuilder. It can be used to build one JSON text. */ public JSONBuilder( Writer w ) { this.comma = false; this.mode = 'i'; this.stack = new char[MAXDEPTH]; this.top = 0; this.writer = w; } /** * Append a value. * * @param s A string value. * @return this * @throws JSONException If the value is out of sequence. */ private JSONBuilder append( String s ) { if( s == null ){ throw new JSONException( "Null pointer" ); } if( this.mode == 'o' || this.mode == 'a' ){ try{ if( this.comma && this.mode == 'a' ){ this.writer.write( ',' ); } this.writer.write( s ); }catch( IOException e ){ throw new JSONException( e ); } if( this.mode == 'o' ){ this.mode = 'k'; } this.comma = true; return this; } throw new JSONException( "Value out of sequence." ); } /** * Begin appending a new array. All values until the balancing * endArray will be appended to this array. The * endArray method must be called to mark the array's end. * * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end * of the outermost array or object). */ public JSONBuilder array() { if( this.mode == 'i' || this.mode == 'o' || this.mode == 'a' ){ this.push( 'a' ); this.append( "[" ); this.comma = false; return this; } throw new JSONException( "Misplaced array." ); } /** * End something. * * @param m Mode * @param c Closing character * @return this * @throws JSONException If unbalanced. */ private JSONBuilder end( char m, char c ) { if( this.mode != m ){ throw new JSONException( m == 'o' ? "Misplaced endObject." : "Misplaced endArray." ); } this.pop( m ); try{ this.writer.write( c ); }catch( IOException e ){ throw new JSONException( e ); } this.comma = true; return this; } /** * End an array. This method most be called to balance calls to * array. * * @return this * @throws JSONException If incorrectly nested. */ public JSONBuilder endArray() { return this.end( 'a', ']' ); } /** * End an object. This method most be called to balance calls to * object. * * @return this * @throws JSONException If incorrectly nested. */ public JSONBuilder endObject() { return this.end( 'k', '}' ); } /** * Append a key. The key will be associated with the next value. In an * object, every value must be preceded by a key. * * @param s A key string. * @return this * @throws JSONException If the key is out of place. For example, keys do not * belong in arrays or if the key is null. */ public JSONBuilder key( String s ) { if( s == null ){ throw new JSONException( "Null key." ); } if( this.mode == 'k' ){ try{ if( this.comma ){ this.writer.write( ',' ); } this.writer.write( JSONUtils.quote( s ) ); this.writer.write( ':' ); this.comma = false; this.mode = 'o'; return this; }catch( IOException e ){ throw new JSONException( e ); } } throw new JSONException( "Misplaced key." ); } /** * Begin appending a new object. All keys and values until the balancing * endObject will be appended to this object. The * endObject method must be called to mark the object's end. * * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end * of the outermost array or object). */ public JSONBuilder object() { if( this.mode == 'i' ){ this.mode = 'o'; } if( this.mode == 'o' || this.mode == 'a' ){ this.append( "{" ); this.push( 'k' ); this.comma = false; return this; } throw new JSONException( "Misplaced object." ); } /** * Pop an array or object scope. * * @param c The scope to close. * @throws JSONException If nesting is wrong. */ private void pop( char c ) { if( this.top <= 0 || this.stack[this.top - 1] != c ){ throw new JSONException( "Nesting error." ); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1]; } /** * Push an array or object scope. * * @param c The scope to open. * @throws JSONException If nesting is too deep. */ private void push( char c ) { if( this.top >= MAXDEPTH ){ throw new JSONException( "Nesting too deep." ); } this.stack[this.top] = c; this.mode = c; this.top += 1; } /** * Append either the value true or the value * false. * * @param b A boolean. * @return this * @throws JSONException */ public JSONBuilder value( boolean b ) { return this.append( b ? "true" : "false" ); } /** * Append a double value. * * @param d A double. * @return this * @throws JSONException If the number is not finite. */ public JSONBuilder value( double d ) { return this.value( new Double( d ) ); } /** * Append a long value. * * @param l A long. * @return this * @throws JSONException */ public JSONBuilder value( long l ) { return this.append( Long.toString( l ) ); } /** * Append an object value. * * @param o The object to append. It can be null, or a Boolean, Number, * String, JSONObject, or JSONArray, or an object with a * toJSONString() method. * @return this * @throws JSONException If the value is out of sequence. */ public JSONBuilder value( Object o ) { return this.append( JSONUtils.valueToString( o ) ); } } jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/JavaIdentifierTransformer.java0000664000175000017500000001405411650253660032004 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import net.sf.json.JSONException; import org.apache.commons.lang.StringUtils; /** * Transforms a string into a valid Java identifier.
* There are five predefined strategies: *

    *
  • NOOP: does not perform transformation.
  • *
  • CAMEL_CASE: follows the camel case convention, deletes non * JavaIndentifierPart chars.
  • *
  • UNDERSCORE: transform whitespace and non JavaIdentifierPart chars to * '_'.
  • *
  • WHITESPACE: deletes whitespace and non JavaIdentifierPart chars.
  • *
  • STRICT: always throws a JSONException, does not perform transformation.
  • *
* * @author Andres Almiray */ public abstract class JavaIdentifierTransformer { /** CamelCase transformer 'camel case' => 'camelCase' */ public static final JavaIdentifierTransformer CAMEL_CASE = new CamelCaseJavaIdentifierTransformer(); /** Noop transformer '@invalid' => '@invalid' */ public static final JavaIdentifierTransformer NOOP = new NoopJavaIdentifierTransformer(); /** Strict transformer '@invalid' => JSONException */ public static final JavaIdentifierTransformer STRICT = new StrictJavaIdentifierTransformer(); /** Underscore transformer 'under score' => 'under_score' */ public static final JavaIdentifierTransformer UNDERSCORE = new UnderscoreJavaIdentifierTransformer(); /** Whitespace transformer 'white space' => 'whitespace' */ public static final JavaIdentifierTransformer WHITESPACE = new WhiteSpaceJavaIdentifierTransformer(); public abstract String transformToJavaIdentifier( String str ); /** * Removes all non JavaIdentifier chars from the start of the string. * * @throws JSONException if the resulting string has zero length. */ protected final String shaveOffNonJavaIdentifierStartChars( String str ) { String str2 = str; // shave off first char if not valid boolean ready = false; while( !ready ){ if( !Character.isJavaIdentifierStart( str2.charAt( 0 ) ) ){ str2 = str2.substring( 1 ); if( str2.length() == 0 ){ throw new JSONException( "Can't convert '" + str + "' to a valid Java identifier" ); } }else{ ready = true; } } return str2; } private static final class CamelCaseJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier( String str ) { if( str == null ){ return null; } String str2 = shaveOffNonJavaIdentifierStartChars( str ); char[] chars = str2.toCharArray(); int pos = 0; StringBuffer buf = new StringBuffer(); boolean toUpperCaseNextChar = false; while( pos < chars.length ){ if( !Character.isJavaIdentifierPart( chars[pos] ) || Character.isWhitespace( chars[pos] ) ){ toUpperCaseNextChar = true; }else{ if( toUpperCaseNextChar ){ buf.append( Character.toUpperCase( chars[pos] ) ); toUpperCaseNextChar = false; }else{ buf.append( chars[pos] ); } } pos++; } return buf.toString(); } } private static final class NoopJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier( String str ) { return str; } } private static final class StrictJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier( String str ) { throw new JSONException( "'" + str + "' is not a valid Java identifier." ); } } private static final class UnderscoreJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier( String str ) { if( str == null ){ return null; } String str2 = shaveOffNonJavaIdentifierStartChars( str ); char[] chars = str2.toCharArray(); int pos = 0; StringBuffer buf = new StringBuffer(); boolean toUnderScorePreviousChar = false; while( pos < chars.length ){ if( !Character.isJavaIdentifierPart( chars[pos] ) || Character.isWhitespace( chars[pos] ) ){ toUnderScorePreviousChar = true; }else{ if( toUnderScorePreviousChar ){ buf.append( "_" ); toUnderScorePreviousChar = false; } buf.append( chars[pos] ); } pos++; } if( buf.charAt( buf.length() - 1 ) == '_' ){ buf.deleteCharAt( buf.length() - 1 ); } return buf.toString(); } } private static final class WhiteSpaceJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier( String str ) { if( str == null ){ return null; } String str2 = shaveOffNonJavaIdentifierStartChars( str ); str2 = StringUtils.deleteWhitespace( str2 ); char[] chars = str2.toCharArray(); int pos = 0; StringBuffer buf = new StringBuffer(); while( pos < chars.length ){ if( Character.isJavaIdentifierPart( chars[pos] ) ){ buf.append( chars[pos] ); } pos++; } return buf.toString(); } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/WebUtils.java0000664000175000017500000001127411650253660026434 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.util.Iterator; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONNull; import net.sf.json.JSONObject; /** * Provides useful methods for working with JSON and web. * * @author Andres Almiray */ public class WebUtils { private static final WebHijackPreventionStrategy DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY = WebHijackPreventionStrategy.INFINITE_LOOP; private static WebHijackPreventionStrategy webHijackPreventionStrategy = DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY; /** * Returns the configured WebHijackPreventionStrategy. */ public static WebHijackPreventionStrategy getWebHijackPreventionStrategy() { return webHijackPreventionStrategy; } /** * Transforms the input Json string using the configured * WebHijackPreventionStrategy.
* * @param json the input string * @return String a transformed json string */ public static String protect( JSON json ) { return protect( json, false ); } /** * Transforms the input Json string using the configured * WebHijackPreventionStrategy.
* * @param json the input string * @param shrink if redundant key quotes may be eliminated. * @return String a transformed json string */ public static String protect( JSON json, boolean shrink ) { String output = !shrink ? json.toString( 0 ) : toString( json ); return webHijackPreventionStrategy.protect( output ); } /** * Sets a WebHijackPreventionStrategy.
* Will use default value (WebHijackPreventionStrategy.INFINITE_LOOP) if * null. */ public static void setWebHijackPreventionStrategy( WebHijackPreventionStrategy strategy ) { webHijackPreventionStrategy = strategy == null ? DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY : strategy; } /** * Returns a string represenation of a JSON value.
* When an object property name does not contain a space (' ') or a colon * (':'), the quotes are omitted. This is done to reduce the amount of bytes * sent to a web browser.
USE WITH CAUTION. */ public static String toString( JSON json ) { if( json instanceof JSONObject ){ return toString( (JSONObject) json ); }else if( json instanceof JSONArray ){ return toString( (JSONArray) json ); }else{ return toString( (JSONNull) json ); } } private static String join( JSONArray jsonArray ) { int len = jsonArray.size(); StringBuffer sb = new StringBuffer(); for( int i = 0; i < len; i += 1 ){ if( i > 0 ){ sb.append( "," ); } Object value = jsonArray.get( i ); sb.append( toString( value ) ); } return sb.toString(); } private static String quote( String str ) { if( str.indexOf( " " ) > -1 || str.indexOf( ":" ) > -1 ){ return JSONUtils.quote( str ); }else{ return str; } } private static String toString( JSONArray jsonArray ) { try{ return '[' + join( jsonArray ) + ']'; }catch( Exception e ){ return null; } } private static String toString( JSONNull jsonNull ) { return jsonNull.toString(); } private static String toString( JSONObject jsonObject ) { if( jsonObject.isNullObject() ){ return JSONNull.getInstance() .toString(); } Iterator keys = jsonObject.keys(); StringBuffer sb = new StringBuffer( "{" ); while( keys.hasNext() ){ if( sb.length() > 1 ){ sb.append( ',' ); } Object o = keys.next(); sb.append( quote( o.toString() ) ); sb.append( ':' ); sb.append( toString( jsonObject.get( String.valueOf( o ) ) ) ); } sb.append( '}' ); return sb.toString(); } private static String toString( Object object ) { if( object instanceof JSON ){ return toString( (JSON) object ); }else{ return JSONUtils.valueToString( object ); } } private WebUtils() { } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/JSONUtils.java0000664000175000017500000006724211650253660026476 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sf.ezmorph.MorphUtils; import net.sf.ezmorph.MorpherRegistry; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONFunction; import net.sf.json.JSONNull; import net.sf.json.JSONObject; import net.sf.json.JSONString; import net.sf.json.JsonConfig; import net.sf.json.regexp.RegexpUtils; import org.apache.commons.beanutils.DynaBean; /** * Provides useful methods on java objects and JSON values. * * @author Andres Almiray * @version 7 */ public final class JSONUtils { /** Constant for char " */ public static final String DOUBLE_QUOTE = "\""; /** Constant for char ' */ public static final String SINGLE_QUOTE = "'"; private static final String FUNCTION_BODY_PATTERN = "^function[ ]?\\(.*?\\)[ \n\t]*\\{(.*?)\\}$"; private static final String FUNCTION_HEADER_PATTERN = "^function[ ]?\\(.*?\\)$"; private static final String FUNCTION_PARAMS_PATTERN = "^function[ ]?\\((.*?)\\).*"; private static final String FUNCTION_PATTERN = "^function[ ]?\\(.*?\\)[ \n\t]*\\{.*?\\}$"; private static final String FUNCTION_PREFIX = "function"; private static final MorpherRegistry morpherRegistry = new MorpherRegistry(); static{ // register standard morphers MorphUtils.registerStandardMorphers( morpherRegistry ); } /** * Transforms the string into a valid Java Identifier.
* The default strategy is JavaIdentifierTransformer.NOOP * * @throws JSONException if the string can not be transformed. */ public static String convertToJavaIdentifier( String key ) { return convertToJavaIdentifier( key, new JsonConfig() ); } /** * Transforms the string into a valid Java Identifier.
* The default strategy is JavaIdentifierTransformer.NOOP * * @throws JSONException if the string can not be transformed. */ public static String convertToJavaIdentifier( String key, JsonConfig jsonConfig ) { try{ return jsonConfig.getJavaIdentifierTransformer() .transformToJavaIdentifier( key ); }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( e ); } } /** * Produce a string from a double. The string "null" will be returned if the * number is not finite. * * @param d A double. * @return A String. */ public static String doubleToString( double d ) { if( Double.isInfinite( d ) || Double.isNaN( d ) ){ return "null"; } // Shave off trailing zeros and decimal point, if possible. String s = Double.toString( d ); if( s.indexOf( '.' ) > 0 && s.indexOf( 'e' ) < 0 && s.indexOf( 'E' ) < 0 ){ while( s.endsWith( "0" ) ){ s = s.substring( 0, s.length() - 1 ); } if( s.endsWith( "." ) ){ s = s.substring( 0, s.length() - 1 ); } } return s; } /** * Returns the body of a function literal. */ public static String getFunctionBody( String function ) { return RegexpUtils.getMatcher( FUNCTION_BODY_PATTERN, true ).getGroupIfMatches( function, 1 ); } /** * Returns the params of a function literal. */ public static String getFunctionParams( String function ) { return RegexpUtils.getMatcher( FUNCTION_PARAMS_PATTERN, true ).getGroupIfMatches( function, 1 ); } /** * Returns the inner-most component type of an Array. */ public static Class getInnerComponentType( Class type ) { if( !type.isArray() ){ return type; } return getInnerComponentType( type.getComponentType() ); } /** * Returns the singleton MorpherRegistry. */ public static MorpherRegistry getMorpherRegistry() { return morpherRegistry; } /** * Creates a Map with all the properties of the JSONObject. */ public static Map getProperties( JSONObject jsonObject ) { Map properties = new HashMap(); for( Iterator keys = jsonObject.keys(); keys.hasNext(); ){ String key = (String) keys.next(); /* * String parsedKey = key; if( !JSONUtils.isJavaIdentifier( parsedKey ) ){ * parsedKey = JSONUtils.convertToJavaIdentifier( key ); } */ properties.put( key, getTypeClass( jsonObject.get( key ) ) ); } return properties; } /** * Returns the JSON type.
* Values are Object, String, Boolean, Number(subclasses) & JSONFunction. */ public static Class getTypeClass( Object obj ) { if( isNull( obj ) ){ return Object.class; }else if( isArray( obj ) ){ return List.class; }else if( isFunction( obj ) ){ return JSONFunction.class; }else if( isBoolean( obj ) ){ return Boolean.class; }else if( isNumber( obj ) ){ Number n = (Number) obj; if( isInteger( n ) ){ return Integer.class; }else if( isLong( n ) ){ return Long.class; }else if( isFloat( n ) ){ return Float.class; }else if( isBigInteger( n ) ){ return BigInteger.class; }else if( isBigDecimal( n ) ){ return BigDecimal.class; }else if( isDouble( n ) ){ return Double.class; }else{ throw new JSONException( "Unsupported type" ); } }else if( isString( obj ) ){ return String.class; }else if( isObject( obj ) ){ return Object.class; }else{ throw new JSONException( "Unsupported type" ); } } /** * Returns the hashcode of value.
* If null it will return JSONNull.getInstance().hashCode().
* If value is JSON, JSONFunction or String, value.hashCode is returned, * otherwise the value is transformed to a String an its hashcode is * returned. */ public static int hashCode( Object value ) { if( value == null ){ return JSONNull.getInstance() .hashCode(); }else if( value instanceof JSON || value instanceof String || value instanceof JSONFunction ){ return value.hashCode(); }else{ return String.valueOf( value ) .hashCode(); } } /** * Tests if a Class represents an array or Collection. */ public static boolean isArray( Class clazz ) { return clazz != null && (clazz.isArray() || Collection.class.isAssignableFrom( clazz ) || (JSONArray.class.isAssignableFrom( clazz ))); } /** * Tests if obj is an array or Collection. */ public static boolean isArray( Object obj ) { if( (obj != null && obj.getClass() .isArray()) || (obj instanceof Collection) || (obj instanceof JSONArray) ){ return true; } return false; } /** * Tests if Class represents a Boolean or primitive boolean */ public static boolean isBoolean( Class clazz ) { return clazz != null && (Boolean.TYPE.isAssignableFrom( clazz ) || Boolean.class.isAssignableFrom( clazz )); } /** * Tests if obj is a Boolean or primitive boolean */ public static boolean isBoolean( Object obj ) { if( (obj instanceof Boolean) || (obj != null && obj.getClass() == Boolean.TYPE) ){ return true; } return false; } /** * Tests if Class represents a primitive double or wrapper.
*/ public static boolean isDouble( Class clazz ) { return clazz != null && (Double.TYPE.isAssignableFrom( clazz ) || Double.class.isAssignableFrom( clazz )); } /** * Tests if obj is javaScript function.
* Obj must be a non-null String and match "^function[ ]?\\(.*\\)[ * ]?\\{.*\\}$" */ public static boolean isFunction( Object obj ) { if( obj instanceof String ){ String str = (String) obj; return str.startsWith( FUNCTION_PREFIX ) && RegexpUtils.getMatcher( FUNCTION_PATTERN, true ).matches( str ); } if( obj instanceof JSONFunction ){ return true; } return false; } /** * Tests if obj is javaScript function header.
* Obj must be a non-null String and match "^function[ ]?\\(.*\\)$" */ public static boolean isFunctionHeader( Object obj ) { if( obj instanceof String ){ String str = (String) obj; return str.startsWith( FUNCTION_PREFIX ) && RegexpUtils.getMatcher( FUNCTION_HEADER_PATTERN, true ).matches( str ); } return false; } /** * Returns trus if str represents a valid Java identifier. */ public static boolean isJavaIdentifier( String str ) { if( str.length() == 0 || !Character.isJavaIdentifierStart( str.charAt( 0 ) ) ){ return false; } for( int i = 1; i < str.length(); i++ ){ if( !Character.isJavaIdentifierPart( str.charAt( i ) ) ){ return false; } } return true; } /** * Tests if the obj is a javaScript null. */ public static boolean isNull( Object obj ) { if( obj instanceof JSONObject ){ return ((JSONObject) obj).isNullObject(); } return JSONNull.getInstance() .equals( obj ); } /** * Tests if Class represents a primitive number or wrapper.
*/ public static boolean isNumber( Class clazz ) { return clazz != null && (Byte.TYPE.isAssignableFrom( clazz ) || Short.TYPE.isAssignableFrom( clazz ) || Integer.TYPE.isAssignableFrom( clazz ) || Long.TYPE.isAssignableFrom( clazz ) || Float.TYPE.isAssignableFrom( clazz ) || Double.TYPE.isAssignableFrom( clazz ) || Number.class.isAssignableFrom( clazz )); } /** * Tests if obj is a primitive number or wrapper.
*/ public static boolean isNumber( Object obj ) { if( (obj != null && obj.getClass() == Byte.TYPE) || (obj != null && obj.getClass() == Short.TYPE) || (obj != null && obj.getClass() == Integer.TYPE) || (obj != null && obj.getClass() == Long.TYPE) || (obj != null && obj.getClass() == Float.TYPE) || (obj != null && obj.getClass() == Double.TYPE) ){ return true; } return obj instanceof Number; } /** * Tests if obj is not a boolean, number, string or array. */ public static boolean isObject( Object obj ) { return !isNumber( obj ) && !isString( obj ) && !isBoolean( obj ) && !isArray( obj ) && !isFunction( obj ) || isNull( obj ); } /** * Tests if Class represents a String or a char */ public static boolean isString( Class clazz ) { return clazz != null && (String.class.isAssignableFrom( clazz ) || (Character.TYPE.isAssignableFrom( clazz ) || Character.class.isAssignableFrom( clazz ))); } /** * Tests if obj is a String or a char */ public static boolean isString( Object obj ) { if( (obj instanceof String) || (obj instanceof Character) || (obj != null && (obj.getClass() == Character.TYPE || String.class.isAssignableFrom( obj.getClass() ))) ){ return true; } return false; } /** * Tests if the String possibly represents a valid JSON String.
* Valid JSON strings are: *
    *
  • "null"
  • *
  • starts with "[" and ends with "]"
  • *
  • starts with "{" and ends with "}"
  • *
*/ public static boolean mayBeJSON( String string ) { return string != null && ("null".equals( string ) || (string.startsWith( "[" ) && string.endsWith( "]" )) || (string.startsWith( "{" ) && string.endsWith( "}" ))); } /** * Creates a new MorphDynaBean from a JSONObject. The MorphDynaBean will have * all the properties of the original JSONObject with the most accurate type. * Values of properties are not copied. */ public static DynaBean newDynaBean( JSONObject jsonObject ) { return newDynaBean( jsonObject, new JsonConfig() ); } /** * Creates a new MorphDynaBean from a JSONObject. The MorphDynaBean will have * all the properties of the original JSONObject with the most accurate type. * Values of properties are not copied. */ public static DynaBean newDynaBean( JSONObject jsonObject, JsonConfig jsonConfig ) { Map props = getProperties( jsonObject ); for( Iterator entries = props.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String key = (String) entry.getKey(); if( !JSONUtils.isJavaIdentifier( key ) ){ String parsedKey = JSONUtils.convertToJavaIdentifier( key, jsonConfig ); if( parsedKey.compareTo( key ) != 0 ){ props.put( parsedKey, props.remove( key ) ); } } } MorphDynaClass dynaClass = new MorphDynaClass( props ); MorphDynaBean dynaBean = null; try{ dynaBean = (MorphDynaBean) dynaClass.newInstance(); dynaBean.setDynaBeanClass( dynaClass ); }catch( Exception e ){ throw new JSONException( e ); } return dynaBean; } /** * Produce a string from a Number. * * @param n A Number * @return A String. * @throws JSONException If n is a non-finite number. */ public static String numberToString( Number n ) { if( n == null ){ throw new JSONException( "Null pointer" ); } testValidity( n ); // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); if( s.indexOf( '.' ) > 0 && s.indexOf( 'e' ) < 0 && s.indexOf( 'E' ) < 0 ){ while( s.endsWith( "0" ) ){ s = s.substring( 0, s.length() - 1 ); } if( s.endsWith( "." ) ){ s = s.substring( 0, s.length() - 1 ); } } return s; } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within * * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote( String string ) { if( string == null || string.length() == 0 ) { return "\"\""; } char b; char c = 0; int i; int len = string.length(); StringBuffer sb = new StringBuffer( len * 2 ); String t; char[] chars = string.toCharArray(); char[] buffer = new char[1030]; int bufferIndex = 0; sb.append( '"' ); for( i = 0; i < len; i += 1 ) { if( bufferIndex > 1024 ) { sb.append( buffer, 0, bufferIndex ); bufferIndex = 0; } b = c; c = chars[i]; switch( c ) { case '\\': case '"': buffer[bufferIndex++] = '\\'; buffer[bufferIndex++] = c; break; case '/': if( b == '<' ) { buffer[bufferIndex++] = '\\'; } buffer[bufferIndex++] = c; break; default: if( c < ' ' ) { switch( c ) { case '\b': buffer[bufferIndex++] = '\\'; buffer[bufferIndex++] = 'b'; break; case '\t': buffer[bufferIndex++] = '\\'; buffer[bufferIndex++] = 't'; break; case '\n': buffer[bufferIndex++] = '\\'; buffer[bufferIndex++] = 'n'; break; case '\f': buffer[bufferIndex++] = '\\'; buffer[bufferIndex++] = 'f'; break; case '\r': buffer[bufferIndex++] = '\\'; buffer[bufferIndex++] = 'r'; break; default: t = "000" + Integer.toHexString( c ); int tLength = t.length(); buffer[bufferIndex++] = '\\'; buffer[bufferIndex++] = 'u'; buffer[bufferIndex++] = t.charAt( tLength - 4 ); buffer[bufferIndex++] = t.charAt( tLength - 3 ); buffer[bufferIndex++] = t.charAt( tLength - 2 ); buffer[bufferIndex++] = t.charAt( tLength - 1 ); } } else { buffer[bufferIndex++] = c; } } } sb.append( buffer, 0, bufferIndex ); sb.append( '"' ); return sb.toString(); } /** * Minimal escape form. */ public static String quoteCanonical(String s) { if (s == null || s.length() == 0) { return "\"\""; } int len = s.length(); StringBuilder sb = new StringBuilder(len + 4); sb.append('"'); for (int i = 0; i < len; i += 1) { char c = s.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; default: if (c < ' ') { String t = "000" + Integer.toHexString(c); sb.append("\\u") .append(t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } /** * Strips any single-quotes or double-quotes from both sides of the string. */ public static String stripQuotes( String input ) { if( input.length() < 2 ){ return input; }else if( input.startsWith( SINGLE_QUOTE ) && input.endsWith( SINGLE_QUOTE ) ){ return input.substring( 1, input.length() - 1 ); }else if( input.startsWith( DOUBLE_QUOTE ) && input.endsWith( DOUBLE_QUOTE ) ){ return input.substring( 1, input.length() - 1 ); }else{ return input; } } /** * Returns true if the input has single-quotes or double-quotes at both sides. */ public static boolean hasQuotes( String input ) { if( input == null || input.length() < 2 ){ return false; } return input.startsWith( SINGLE_QUOTE ) && input.endsWith( SINGLE_QUOTE ) || input.startsWith( DOUBLE_QUOTE ) && input.endsWith( DOUBLE_QUOTE ); } public static boolean isJsonKeyword( String input, JsonConfig jsonConfig ) { if( input == null ){ return false; } return "null".equals( input ) || "true".equals( input ) || "false".equals( input ) || (jsonConfig.isJavascriptCompliant() && "undefined".equals( input )); } /** * Throw an exception if the object is an NaN or infinite number. * * @param o The object to test. * @throws JSONException If o is a non-finite number. */ public static void testValidity( Object o ) { if( o != null ){ if( o instanceof Double ){ if( ((Double) o).isInfinite() || ((Double) o).isNaN() ){ throw new JSONException( "JSON does not allow non-finite numbers" ); } }else if( o instanceof Float ){ if( ((Float) o).isInfinite() || ((Float) o).isNaN() ){ throw new JSONException( "JSON does not allow non-finite numbers." ); } }else if( o instanceof BigDecimal || o instanceof BigInteger ){ // ok return; } } } /** * Transforms a Number into a valid javascript number.
* Float gets promoted to Double.
* Byte and Short get promoted to Integer.
* Long gets downgraded to Integer if possible.
*/ public static Number transformNumber( Number input ) { if( input instanceof Float ){ return new Double( input.toString() ); }else if( input instanceof Short ){ return new Integer( input.intValue() ); }else if( input instanceof Byte ){ return new Integer( input.intValue() ); }else if( input instanceof Long ){ Long max = new Long( Integer.MAX_VALUE ); if( input.longValue() <= max.longValue() && input.longValue() >= Integer.MIN_VALUE ){ return new Integer( input.intValue() ); } } return input; } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce the * JSON text. The method is required to produce a strictly conforming text. * If the object does not contain a toJSONString method (which is the most * common case), then a text will be produced by the rules. *

* Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. * @return a printable, displayable, transmittable representation of the * object, beginning with { (left brace) * and ending with } (right brace). * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString( Object value ) { if( value == null || isNull( value ) ){ return "null"; } if( value instanceof JSONFunction ){ return value.toString(); } if( value instanceof JSONString ){ return ((JSONString) value).toJSONString(); } if( value instanceof Number ){ return numberToString( (Number) value ); } if( value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray ){ return value.toString(); } return quote( value.toString() ); } public static String valueToCanonicalString( Object value ) { if( value == null || isNull( value ) ){ return "null"; } if( value instanceof JSONFunction ){ return value.toString(); // there's really no canonical form for functions } if( value instanceof JSONString ){ return ((JSONString) value).toJSONString(); } if( value instanceof Number ){ return numberToString( (Number) value ).toLowerCase(); } if( value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray ){ return value.toString(); } return quoteCanonical(value.toString()); } /** * Make a prettyprinted JSON text of an object value. *

* Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable representation of the * object, beginning with { (left brace) * and ending with } (right brace). * @throws JSONException If the object contains an invalid number. */ public static String valueToString( Object value, int indentFactor, int indent ) { if( value == null || isNull( value ) ){ return "null"; } if( value instanceof JSONFunction ){ return value.toString(); } if( value instanceof JSONString ){ return ((JSONString) value).toJSONString(); } if( value instanceof Number ){ return numberToString( (Number) value ); } if( value instanceof Boolean ){ return value.toString(); } if( value instanceof JSONObject ){ return ((JSONObject) value).toString( indentFactor, indent ); } if( value instanceof JSONArray ){ return ((JSONArray) value).toString( indentFactor, indent ); } return quote( value.toString() ); } /** * Finds out if n represents a BigInteger * * @return true if n is instanceOf BigInteger or the literal value can be * evaluated as a BigInteger */ private static boolean isBigDecimal( Number n ) { if( n instanceof BigDecimal ){ return true; } try{ new BigDecimal( String.valueOf( n ) ); return true; }catch( NumberFormatException e ){ return false; } } /** * Finds out if n represents a BigInteger * * @return true if n is instanceOf BigInteger or the literal value can be * evaluated as a BigInteger */ private static boolean isBigInteger( Number n ) { if( n instanceof BigInteger ){ return true; } try{ new BigInteger( String.valueOf( n ) ); return true; }catch( NumberFormatException e ){ return false; } } /** * Finds out if n represents a Double. * * @return true if n is instanceOf Double or the literal value can be * evaluated as a Double. */ private static boolean isDouble( Number n ) { if( n instanceof Double ){ return true; } try{ double d = Double.parseDouble( String.valueOf( n ) ); return !Double.isInfinite( d ); }catch( NumberFormatException e ){ return false; } } /** * Finds out if n represents a Float. * * @return true if n is instanceOf Float or the literal value can be * evaluated as a Float. */ private static boolean isFloat( Number n ) { if( n instanceof Float ){ return true; } try{ float f = Float.parseFloat( String.valueOf( n ) ); return !Float.isInfinite( f ); }catch( NumberFormatException e ){ return false; } } /** * Finds out if n represents an Integer. * * @return true if n is instanceOf Integer or the literal value can be * evaluated as an Integer. */ private static boolean isInteger( Number n ) { if( n instanceof Integer ){ return true; } try{ Integer.parseInt( String.valueOf( n ) ); return true; }catch( NumberFormatException e ){ return false; } } /** * Finds out if n represents a Long. * * @return true if n is instanceOf Long or the literal value can be evaluated * as a Long. */ private static boolean isLong( Number n ) { if( n instanceof Long ){ return true; } try{ Long.parseLong( String.valueOf( n ) ); return true; }catch( NumberFormatException e ){ return false; } } private JSONUtils() { super(); } } jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/WebHijackPreventionStrategy.java0000664000175000017500000000357611650253660032330 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; /** * Defines base implementations for preventing WebHijack in AJAX applications. * The default implementations are: *

    *
  • COMMENTS - wraps the string with /* *\/
  • *
  • INFINITE_LOOP - prepends "while(1);"
  • *
* * @author Andres Almiray */ public abstract class WebHijackPreventionStrategy { /** Wraps the string with /* *\/ */ public static final WebHijackPreventionStrategy COMMENTS = new CommentWebHijackPreventionStrategy(); /** Prepends "while(1);" */ public static final WebHijackPreventionStrategy INFINITE_LOOP = new InfiniteLoopWebHijackPreventionStrategy(); /** * Transforms the input with the desired strategy.
* * @param str a json string * @return String - the transformed json string */ public abstract String protect( String str ); private static final class CommentWebHijackPreventionStrategy extends WebHijackPreventionStrategy { public String protect( String str ) { return "/*" + str + "*/"; } } private static final class InfiniteLoopWebHijackPreventionStrategy extends WebHijackPreventionStrategy { public String protect( String str ) { return "while(1);" + str; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/package.html0000664000175000017500000000022311650253660026304 0ustar jamespagejamespage

Miscelaneous utilities

jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/NewBeanInstanceStrategy.java0000664000175000017500000000542411650253660031425 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import net.sf.json.JSONObject; /** * Base class for creating Bean instances.
*
    *
  • DEFAULT - calls Class.newInstance().
  • *
* * @author Andres Almiray */ public abstract class NewBeanInstanceStrategy { /** Calls Class.newInstance() */ public static final NewBeanInstanceStrategy DEFAULT = new DefaultNewBeanInstanceStrategy(); /** * Creates a new instance. * * @param target the source class * @param source additional properties that may be needed to create the * instance */ public abstract Object newInstance( Class target, JSONObject source ) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, InvocationTargetException; private static final class DefaultNewBeanInstanceStrategy extends NewBeanInstanceStrategy { private static final Object[] EMPTY_ARGS = new Object[0]; private static final Class[] EMPTY_PARAM_TYPES = new Class[0]; public Object newInstance( Class target, JSONObject source ) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, InvocationTargetException { if( target != null ){ Constructor c = target.getDeclaredConstructor( EMPTY_PARAM_TYPES ); c.setAccessible( true ); try { return c.newInstance( EMPTY_ARGS ); } catch ( InstantiationException e ) { // getCause() was added on jdk 1.4 String cause = ""; try { cause = e.getCause() != null ? "\n"+e.getCause().getMessage() : ""; } catch( Throwable t ) { /* ignore */ } throw new InstantiationException( "Instantiation of \"" + target + "\" failed. " + "It's probably because class is an interface, " + "abstract class, array class, primitive type or void." + cause ); } } return null; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/JSONTokener.java0000664000175000017500000003404111650253660026774 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONNull; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.regexp.RegexpUtils; import org.apache.commons.lang.math.NumberUtils; /** * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse JSON * source strings. * * @author JSON.org * @version 4 */ public class JSONTokener { /** * Get the hex value of a character (base16). * * @param c A character between '0' and '9' or between 'A' and 'F' or between * 'a' and 'f'. * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar( char c ) { if( c >= '0' && c <= '9' ){ return c - '0'; } if( c >= 'A' && c <= 'F' ){ return c - ('A' - 10); } if( c >= 'a' && c <= 'f' ){ return c - ('a' - 10); } return -1; } /** * The index of the next character. */ private int myIndex; /** * The source string being tokenized. */ private String mySource; /** * Construct a JSONTokener from a string. * * @param s A source string. */ public JSONTokener( String s ) { this.myIndex = 0; if( s!= null ) { s = s.trim(); } else { s = ""; } if( s.length() > 0 ){ char first = s.charAt( 0 ); char last = s.charAt( s.length() - 1 ); if( first == '[' && last != ']' ) { throw syntaxError( "Found starting '[' but missing ']' at the end." ); } if( first == '{' && last != '}' ) { throw syntaxError( "Found starting '{' but missing '}' at the end." ); } } this.mySource = s; } /** * Back up one character. This provides a sort of lookahead capability, so * that you can test for a digit or letter before attempting to parse the * next number or identifier. */ public void back() { if( this.myIndex > 0 ){ this.myIndex -= 1; } } public int length() { if( this.mySource == null ){ return 0; } return this.mySource.length(); } public boolean matches( String pattern ) { String str = this.mySource.substring( this.myIndex ); return RegexpUtils.getMatcher( pattern ) .matches( str ); } /** * Determine if the source string still contains characters that next() can * consume. * * @return true if not yet at the end of the source. */ public boolean more() { return this.myIndex < this.mySource.length(); } /** * Get the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char next() { if( more() ){ char c = this.mySource.charAt( this.myIndex ); this.myIndex += 1; return c; } return 0; } /** * Consume the next character, and check that it matches a specified * character. * * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ public char next( char c ) { char n = next(); if( n != c ){ throw syntaxError( "Expected '" + c + "' and instead saw '" + n + "'." ); } return n; } /** * Get the next n characters. * * @param n The number of characters to take. * @return A string of n characters. * @throws JSONException Substring bounds error if there are not n characters * remaining in the source string. */ public String next( int n ) { int i = this.myIndex; int j = i + n; if( j >= this.mySource.length() ){ throw syntaxError( "Substring bounds error" ); } this.myIndex += n; return this.mySource.substring( i, j ); } /** * Get the next char in the string, skipping whitespace and comments * (slashslash, slashstar, and hash). * * @throws JSONException * @return A character, or 0 if there are no more characters. */ public char nextClean() { for( ;; ){ char c = next(); if( c == '/' ){ switch( next() ){ case '/': do{ c = next(); }while( c != '\n' && c != '\r' && c != 0 ); break; case '*': for( ;; ){ c = next(); if( c == 0 ){ throw syntaxError( "Unclosed comment." ); } if( c == '*' ){ if( next() == '/' ){ break; } back(); } } break; default: back(); return '/'; } }else if( c == '#' ){ do{ c = next(); }while( c != '\n' && c != '\r' && c != 0 ); }else if( c == 0 || c > ' ' ){ return c; } } } /** * Return the characters up to the next close quote character. Backslash * processing is done. The formal JSON format does not allow strings in * single quotes, but an implementation is allowed to accept them. * * @param quote The quoting character, either " (double * quote) or ' (single quote). * @return A String. * @throws JSONException Unterminated string. */ public String nextString( char quote ) { char c; StringBuffer sb = new StringBuffer(); for( ;; ){ c = next(); switch( c ){ case 0: case '\n': case '\r': throw syntaxError( "Unterminated string" ); case '\\': c = next(); switch( c ){ case 'b': sb.append( '\b' ); break; case 't': sb.append( '\t' ); break; case 'n': sb.append( '\n' ); break; case 'f': sb.append( '\f' ); break; case 'r': sb.append( '\r' ); break; case 'u': sb.append( (char) Integer.parseInt( next( 4 ), 16 ) ); break; case 'x': sb.append( (char) Integer.parseInt( next( 2 ), 16 ) ); break; default: sb.append( c ); } break; default: if( c == quote ){ return sb.toString(); } sb.append( c ); } } } /** * Get the text up but not including the specified character or the end of * line, whichever comes first. * * @param d A delimiter character. * @return A string. */ public String nextTo( char d ) { StringBuffer sb = new StringBuffer(); for( ;; ){ char c = next(); if( c == d || c == 0 || c == '\n' || c == '\r' ){ if( c != 0 ){ back(); } return sb.toString() .trim(); } sb.append( c ); } } /** * Get the text up but not including one of the specified delimeter * characters or the end of line, whichever comes first. * * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ public String nextTo( String delimiters ) { char c; StringBuffer sb = new StringBuffer(); for( ;; ){ c = next(); if( delimiters.indexOf( c ) >= 0 || c == 0 || c == '\n' || c == '\r' ){ if( c != 0 ){ back(); } return sb.toString() .trim(); } sb.append( c ); } } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * * @throws JSONException If syntax error. * @return An object. */ public Object nextValue() { return nextValue( new JsonConfig() ); } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * * @throws JSONException If syntax error. * @return An object. */ public Object nextValue( JsonConfig jsonConfig ) { char c = nextClean(); String s; switch( c ){ case '"': case '\'': return nextString( c ); case '{': back(); return JSONObject.fromObject( this, jsonConfig ); case '[': back(); return JSONArray.fromObject( this, jsonConfig ); default: // empty } /* * Handle unquoted text. This could be the values true, false, or null, or * it can be a number. An implementation (such as this one) is allowed to * also accept non-standard forms. Accumulate characters until we reach * the end of the text or a formatting character. */ StringBuffer sb = new StringBuffer(); char b = c; while( c >= ' ' && ",:]}/\\\"[{;=#".indexOf( c ) < 0 ){ sb.append( c ); c = next(); } back(); /* * If it is true, false, or null, return the proper value. */ s = sb.toString() .trim(); if( s.equals( "" ) ){ throw syntaxError( "Missing value." ); } if( s.equalsIgnoreCase( "true" ) ){ return Boolean.TRUE; } if( s.equalsIgnoreCase( "false" ) ){ return Boolean.FALSE; } if( s.equals( "null" ) || (jsonConfig.isJavascriptCompliant() && s.equals("undefined"))){ return JSONNull.getInstance(); } /* * If it might be a number, try converting it. We support the 0- and 0x- * conventions. If a number cannot be produced, then the value will just * be a string. Note that the 0-, 0x-, plus, and implied string * conventions are non-standard. A JSON parser is free to accept non-JSON * forms as long as it accepts all correct JSON forms. */ if( (b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+' ){ if( b == '0' ){ if( s.length() > 2 && (s.charAt( 1 ) == 'x' || s.charAt( 1 ) == 'X') ){ try{ return new Integer( Integer.parseInt( s.substring( 2 ), 16 ) ); }catch( Exception e ){ /* Ignore the error */ } }else{ try{ return new Integer( Integer.parseInt( s, 8 ) ); }catch( Exception e ){ /* Ignore the error */ } } } try{ return NumberUtils.createNumber(s); }catch( Exception e ){ return s; } } if( JSONUtils.isFunctionHeader( s ) || JSONUtils.isFunction( s ) ){ return s; } switch( peek() ){ case ',': case '}': case '{': case '[': case ']': throw new JSONException( "Unquotted string '" + s + "'" ); } return s; } /** * Look at the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char peek() { if( more() ){ char c = this.mySource.charAt( this.myIndex ); return c; } return 0; } public void reset() { this.myIndex = 0; } /** * Skip characters until past the requested string. If it is not found, we * are left at the end of the source. * * @param to A string to skip past. */ public void skipPast( String to ) { this.myIndex = this.mySource.indexOf( to, this.myIndex ); if( this.myIndex < 0 ){ this.myIndex = this.mySource.length(); }else{ this.myIndex += to.length(); } } /** * Skip characters until the next character is the requested character. If * the requested character is not found, no characters are skipped. * * @param to A character to skip to. * @return The requested character, or zero if the requested character is not * found. */ public char skipTo( char to ) { char c; int index = this.myIndex; do{ c = next(); if( c == 0 ){ this.myIndex = index; return c; } }while( c != to ); back(); return c; } /** * Make a JSONException to signal a syntax error. * * @param message The error message. * @return A JSONException object, suitable for throwing */ public JSONException syntaxError( String message ) { return new JSONException( message + toString() ); } /** * Make a printable string of this JSONTokener. * * @return " at character [this.myIndex] of [this.mySource]" */ public String toString() { return " at character " + this.myIndex + " of " + this.mySource; } } jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/JSONStringer.java0000664000175000017500000000523011650253660027160 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.io.StringWriter; /** * JSONStringer provides a quick and convenient way of producing JSON text. The * texts produced strictly conform to JSON syntax rules. No whitespace is added, * so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. *

* A JSONStringer instance provides a value method for appending * values to the text, and a key method for adding keys before * values in objects. There are array and endArray * methods that make and bound array values, and object and * endObject methods which make and bound object values. All of * these methods return the JSONWriter instance, permitting cascade style. For * example, * *

 * myString = new JSONStringer()
 *     .object()
 *         .key("JSON")
 *         .value("Hello, World!")
 *     .endObject()
 *     .toString();
* * which produces the string * *
 * {"JSON":"Hello, World!"}
* *

* The first method called must be array or object. * There are no methods for adding commas or colons. JSONStringer adds them for * you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org * @version 2 */ public class JSONStringer extends JSONBuilder { /** * Make a fresh JSONStringer. It can be used to build one JSON text. */ public JSONStringer() { super( new StringWriter() ); } /** * Return the JSON text. This method is used to obtain the product of the * JSONStringer instance. It will return null if there was a * problem in the construction of the JSON text (such as the calls to * array were not properly balanced with calls to * endArray). * * @return The JSON text. */ public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } } jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/PropertyFilter.java0000664000175000017500000000201211650253660027656 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; /** * @author Andres Almiray */ public interface PropertyFilter { /** * @param source the owner of the property * @param name the name of the property * @param value the value of the property * @return true if the property will be filtered out, false otherwise */ boolean apply( Object source, String name, Object value ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/JsonEventListener.java0000664000175000017500000000404111650253660030311 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import net.sf.json.JSONException; /** * Defines the contract to handle JsonEvents when building an object or array. * * @author Andres Almiray */ public interface JsonEventListener { /** * Ttriggered when reaching the end of an array. */ void onArrayEnd(); /** * triggered when the start of an array is encountered. */ void onArrayStart(); /** * Triggered when an element has been added to the current array. * * @param index the index where the element was added * @param element the added element */ void onElementAdded( int index, Object element ); /** * Triggered when an exception is thrown. * * @param jsone the thrown exception */ void onError( JSONException jsone ); /** * triggered when reaching the end of an object. */ void onObjectEnd(); /** * Triggered when the start of an object is encountered. */ void onObjectStart(); /** * Triggered when a property is set on an object * * @param key the name of the property * @param value the value of the property * @param accumulated if the value has been accumulated over 'key' */ void onPropertySet( String key, Object value, boolean accumulated ); /** * Triggered when a warning is encountered. * * @param warning the warning message */ void onWarning( String warning ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/PropertySetStrategy.java0000664000175000017500000000532611650253660030722 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.lang.reflect.Field; import java.util.Map; import net.sf.json.JSONException; import net.sf.json.JsonConfig; import org.apache.commons.beanutils.PropertyUtils; /** * Defines a custom setter to be used when setting object values.
* Specify with JsonConfig.setJsonPropertySetter(). * * @author Gino Miceli * @author Andres Almiray */ public abstract class PropertySetStrategy { public static final PropertySetStrategy DEFAULT = new DefaultPropertySetStrategy(); public abstract void setProperty( Object bean, String key, Object value ) throws JSONException; public void setProperty( Object bean, String key, Object value, JsonConfig jsonConfig ) throws JSONException { setProperty( bean, key, value ); } private static final class DefaultPropertySetStrategy extends PropertySetStrategy { public void setProperty( Object bean, String key, Object value ) throws JSONException { setProperty( bean, key, value, new JsonConfig()); } public void setProperty( Object bean, String key, Object value, JsonConfig jsonConfig ) throws JSONException { if( bean instanceof Map ){ ((Map) bean).put( key, value ); } else { if( !jsonConfig.isIgnorePublicFields() ) { try { Field field = bean.getClass().getField( key ); if( field != null ) { field.set( bean, value ); return; } } catch( Exception e ){ // fall through } } try { PropertyUtils.setSimpleProperty( bean, key, value ); } catch( NoSuchMethodException e ) { if (jsonConfig.isIgnoreUnreadableProperty()) { // ignore missing properties return; } throw new JSONException( e ); } catch( Exception e ) { throw new JSONException( e ); } } } } } jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/PropertyExclusionClassMatcher.java0000664000175000017500000000317511650253660032707 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.util.Set; /** * Base class for finding a matching property exlucsion.
*

    *
  • DEFAULT - matches the target class with equals().
  • *
* * @author Andres Almiray */ public abstract class PropertyExclusionClassMatcher { /** Matches the target with equals() */ public static final PropertyExclusionClassMatcher DEFAULT = new DefaultPropertyExclusionClassMatcher(); /** * Returns the matching class calculated with the target class and the * provided set. * * @param target the target class to match * @param set a set of possible matches */ public abstract Object getMatch( Class target, Set set ); private static final class DefaultPropertyExclusionClassMatcher extends PropertyExclusionClassMatcher { public Object getMatch( Class target, Set set ) { if( target != null && set != null && set.contains( target ) ){ return target; } return null; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/util/CycleDetectionStrategy.java0000664000175000017500000000707711650253660031325 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONObject; /** * Base class for cycle detection in a hierarchy.
* The JSON spec forbides cycles in a hierarchy and most parsers will raise and * error when a cycle is detected. This class defines a contract for handling * those cycles and two base implementations: *
    *
  • STRICT - will throw a JSONException if a cycle is found.
  • *
  • LENIENT - will return an empty array or null object if a cycle is found.
  • *
* * @author Andres Almiray */ public abstract class CycleDetectionStrategy { public static final JSONArray IGNORE_PROPERTY_ARR = new JSONArray(); public static final JSONObject IGNORE_PROPERTY_OBJ = new JSONObject(); /** Returns empty array and null object */ public static final CycleDetectionStrategy LENIENT = new LenientCycleDetectionStrategy(); /** * Returns a special object (IGNORE_PROPERTY_OBJ) that indicates the entire * property should be ignored */ public static final CycleDetectionStrategy NOPROP = new LenientNoRefCycleDetectionStrategy(); /** Throws a JSONException */ public static final CycleDetectionStrategy STRICT = new StrictCycleDetectionStrategy(); /** * Handle a repeated reference
* Must return a valid JSONArray or null. * * @param reference the repeated reference. */ public abstract JSONArray handleRepeatedReferenceAsArray( Object reference ); /** * Handle a repeated reference
* Must return a valid JSONObject or null. * * @param reference the repeated reference. */ public abstract JSONObject handleRepeatedReferenceAsObject( Object reference ); private static final class LenientCycleDetectionStrategy extends CycleDetectionStrategy { public JSONArray handleRepeatedReferenceAsArray( Object reference ) { return new JSONArray(); } public JSONObject handleRepeatedReferenceAsObject( Object reference ) { return new JSONObject( true ); } } /** * A cycle detection strategy that prevents any mention of the possible * conflict from appearing. * * @author small */ private static final class LenientNoRefCycleDetectionStrategy extends CycleDetectionStrategy { public JSONArray handleRepeatedReferenceAsArray( Object reference ) { return IGNORE_PROPERTY_ARR; } public JSONObject handleRepeatedReferenceAsObject( Object reference ) { return IGNORE_PROPERTY_OBJ; } } private static final class StrictCycleDetectionStrategy extends CycleDetectionStrategy { public JSONArray handleRepeatedReferenceAsArray( Object reference ) { throw new JSONException( "There is a cycle in the hierarchy!" ); } public JSONObject handleRepeatedReferenceAsObject( Object reference ) { throw new JSONException( "There is a cycle in the hierarchy!" ); } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/JSONString.java0000664000175000017500000000246211650253660025660 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * The JSONString interface allows a toJSONString() * method so that a class can change the behavior of * JSONObject.toString(), JSONArray.toString(), * and JSONWriter.value(Object). The * toJSONString method will be used instead of the default * behavior of using the Object's toString() method and quoting * the result. */ public interface JSONString { /** * The toJSONString method allows a class to produce its own * JSON serialization. * * @return A strictly syntactically correct JSON text. */ public String toJSONString(); } jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/0000775000175000017500000000000011650253660024521 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/OrPropertyFilter.java0000664000175000017500000000243011650253660030656 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public class OrPropertyFilter implements PropertyFilter { private PropertyFilter filter1; private PropertyFilter filter2; public OrPropertyFilter( PropertyFilter filter1, PropertyFilter filter2 ) { this.filter1 = filter1; this.filter2 = filter2; } public boolean apply( Object source, String name, Object value ) { if( (filter1 != null && filter1.apply( source, name, value )) || (filter2 != null && filter2.apply( source, name, value )) ){ return true; } return false; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/AndPropertyFilter.java0000664000175000017500000000242611650253660031005 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public class AndPropertyFilter implements PropertyFilter { private PropertyFilter filter1; private PropertyFilter filter2; public AndPropertyFilter( PropertyFilter filter1, PropertyFilter filter2 ) { this.filter1 = filter1; this.filter2 = filter2; } public boolean apply( Object source, String name, Object value ) { if( filter1 != null && filter1.apply( source, name, value ) && filter2 != null && filter2.apply( source, name, value ) ){ return true; } return false; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/TruePropertyFilter.java0000664000175000017500000000162311650253660031220 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public class TruePropertyFilter implements PropertyFilter { public boolean apply( Object source, String name, Object value ) { return true; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/MappingPropertyFilter.java0000664000175000017500000000441111650253660031672 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public abstract class MappingPropertyFilter implements PropertyFilter { private Map filters = new HashMap(); public MappingPropertyFilter() { this( null ); } public MappingPropertyFilter( Map filters ) { if( filters != null ){ for( Iterator i = filters.entrySet() .iterator(); i.hasNext(); ){ Map.Entry entry = (Map.Entry) i.next(); Object key = entry.getKey(); Object filter = entry.getValue(); if( filter instanceof PropertyFilter ){ this.filters.put( key, filter ); } } } } public void addPropertyFilter( Object target, PropertyFilter filter ) { if( filter != null ){ filters.put( target, filter ); } } public boolean apply( Object source, String name, Object value ) { for( Iterator i = filters.entrySet() .iterator(); i.hasNext(); ){ Map.Entry entry = (Map.Entry) i.next(); Object key = entry.getKey(); if( keyMatches( key, source, name, value ) ){ PropertyFilter filter = (PropertyFilter) entry.getValue(); return filter.apply( source, name, value ); } } return false; } public void removePropertyFilter( Object target ) { if( target != null ){ filters.remove( target ); } } protected abstract boolean keyMatches( Object key, Object source, String name, Object value ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/package.html0000664000175000017500000000023511650253660027002 0ustar jamespagejamespage

Support for custom serialization

jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/FalsePropertyFilter.java0000664000175000017500000000162511650253660031335 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public class FalsePropertyFilter implements PropertyFilter { public boolean apply( Object source, String name, Object value ) { return false; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/NotPropertyFilter.java0000664000175000017500000000215111650253660031036 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public class NotPropertyFilter implements PropertyFilter { private PropertyFilter filter; public NotPropertyFilter( PropertyFilter filter ) { this.filter = filter; } public boolean apply( Object source, String name, Object value ) { if( filter != null ){ return !filter.apply( source, name, value ); } return false; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/filters/CompositePropertyFilter.java0000664000175000017500000000357211650253660032250 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public class CompositePropertyFilter implements PropertyFilter { private List filters = new ArrayList(); public CompositePropertyFilter() { this( null ); } public CompositePropertyFilter( List filters ) { if( filters != null ){ for( Iterator i = filters.iterator(); i.hasNext(); ){ Object filter = i.next(); if( filter instanceof PropertyFilter ){ this.filters.add( filter ); } } } } public void addPropertyFilter( PropertyFilter filter ) { if( filter != null ){ filters.add( filter ); } } public boolean apply( Object source, String name, Object value ) { for( Iterator i = filters.iterator(); i.hasNext(); ){ PropertyFilter filter = (PropertyFilter) i.next(); if( filter.apply( source, name, value ) ){ return true; } } return false; } public void removePropertyFilter( PropertyFilter filter ) { if( filter != null ){ filters.remove( filter ); } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/JSONFunction.java0000664000175000017500000001112011650253660026166 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.io.Serializable; import net.sf.json.util.JSONUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * JSONFunction represents a javaScript function's text. * * @author Andres Almiray */ public class JSONFunction implements Serializable { /** constant array for empty parameters */ private static final String[] EMPTY_PARAM_ARRAY = new String[0]; /** * Constructs a JSONFunction from a text representation */ public static JSONFunction parse( String str ) { if( !JSONUtils.isFunction( str ) ) { throw new JSONException( "String is not a function. " + str ); } else { String params = JSONUtils.getFunctionParams( str ); String text = JSONUtils.getFunctionBody( str ); return new JSONFunction( (params != null) ? StringUtils.split( params, "," ) : null, text != null ? text : "" ); } } /** the parameters of this function */ private String[] params; /** the text of this function */ private String text; /** * Constructs a JSONFunction with no parameters. * * @param text The text of the function */ public JSONFunction( String text ) { this( null, text ); } /** * Constructs a JSONFunction with parameters. * * @param params The parameters of the function * @param text The text of the function */ public JSONFunction( String[] params, String text ) { this.text = (text != null) ? text.trim() : ""; if( params != null ){ if( params.length == 1 && params[0].trim() .equals( "" ) ){ this.params = EMPTY_PARAM_ARRAY; }else{ this.params = new String[params.length]; System.arraycopy( params, 0, this.params, 0, params.length ); // remove empty spaces for( int i = 0; i < params.length; i++ ){ this.params[i] = this.params[i].trim(); } } }else{ this.params = EMPTY_PARAM_ARRAY; } } public boolean equals( Object obj ) { if( this == obj ){ return true; } if( obj == null ){ return false; } if( obj instanceof String ){ try{ JSONFunction other = parse( (String) obj ); return equals( other ); }catch( JSONException e ){ return false; } } if( !(obj instanceof JSONFunction) ){ return false; } JSONFunction other = (JSONFunction) obj; if( params.length != other.params.length ){ return false; } EqualsBuilder builder = new EqualsBuilder(); for( int i = 0; i < params.length; i++ ){ builder.append( params[i], other.params[i] ); } builder.append( text, other.text ); return builder.isEquals(); } /** * Returns the parameters of this function. */ public String[] getParams() { return params; } /** * Reeturns the text of this function. */ public String getText() { return text; } public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); for( int i = 0; i < params.length; i++ ){ builder.append( params[i] ); } builder.append( text ); return builder.toHashCode(); } /** * Returns the string representation of this function. */ public String toString() { StringBuffer b = new StringBuffer( "function(" ); if( params.length > 0 ){ for( int i = 0; i < params.length - 1; i++ ){ b.append( params[i] ) .append( ',' ); } b.append( params[params.length - 1] ); } b.append( "){" ); if( text.length() > 0 ){ b.append( ' ' ) .append( text ) .append( ' ' ); } b.append( '}' ); return b.toString(); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/JSONSerializer.java0000664000175000017500000001170311650253660026521 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import net.sf.json.util.JSONTokener; import net.sf.json.util.JSONUtils; /** * Transforms java objects into JSON and back.
* Transformation from java to JSON is pretty straightforward, but the other way * around needs certain configuration, otherwise the java objects produced will * be DynaBeans and Lists, because the JSON notation does not carry any * information on java classes.
* * @author Andres Almiray */ public class JSONSerializer { /** * Transform a JSON value to a java object.
* Depending on the configured values for conversion this will return a * DynaBean, a bean, a List, or and array. * * @param json a JSON value * @return depends on the nature of the source object (JSONObject, JSONArray, * JSONNull). */ public static Object toJava( JSON json ) { return toJava( json, new JsonConfig() ); } /** * Transform a JSON value to a java object.
* Depending on the configured values for conversion this will return a * DynaBean, a bean, a List, or and array. * * @param json a JSON value * @param jsonConfig additional configuration * @return depends on the nature of the source object (JSONObject, JSONArray, * JSONNull) and the configured rootClass, classMap and arrayMode */ public static Object toJava( JSON json, JsonConfig jsonConfig ) { if( JSONUtils.isNull( json ) ){ return null; } Object object = null; if( json instanceof JSONArray ){ if( jsonConfig.getArrayMode() == JsonConfig.MODE_OBJECT_ARRAY ){ object = JSONArray.toArray( (JSONArray) json, jsonConfig ); }else{ object = JSONArray.toCollection( (JSONArray) json, jsonConfig ); } }else{ object = JSONObject.toBean( (JSONObject) json, jsonConfig ); } return object; } /** * Creates a JSONObject, JSONArray or a JSONNull from object.
* Accepts JSON formatted strings, Maps, arrays, Collections, DynaBeans and * JavaBeans. * * @param object any java Object * @throws JSONException if the object can not be converted */ public static JSON toJSON( Object object ) { return toJSON( object, new JsonConfig() ); } /** * Creates a JSONObject, JSONArray or a JSONNull from object.
* Accepts JSON formatted strings, Maps, arrays, Collections, DynaBeans and * JavaBeans. * * @param object any java Object * @param jsonConfig additional configuration * @throws JSONException if the object can not be converted */ public static JSON toJSON( Object object, JsonConfig jsonConfig ) { JSON json = null; if( object == null ){ json = JSONNull.getInstance(); }else if( object instanceof JSONString ){ json = toJSON( (JSONString) object, jsonConfig ); }else if( object instanceof String ){ json = toJSON( (String) object, jsonConfig ); }else if( JSONUtils.isArray( object ) ){ json = JSONArray.fromObject( object, jsonConfig ); }else{ try{ json = JSONObject.fromObject( object, jsonConfig ); }catch( JSONException e ){ if( object instanceof JSONTokener ){ ((JSONTokener) object).reset(); } json = JSONArray.fromObject( object, jsonConfig ); } } return json; } /** * Creates a JSONObject, JSONArray or a JSONNull from a JSONString. * * @throws JSONException if the string is not a valid JSON string */ private static JSON toJSON( JSONString string, JsonConfig jsonConfig ) { return toJSON( string.toJSONString(), jsonConfig ); } /** * Creates a JSONObject, JSONArray or a JSONNull from a JSONString. * * @throws JSONException if the string is not a valid JSON string */ private static JSON toJSON( String string, JsonConfig jsonConfig ) { JSON json = null; if( string.startsWith( "[" ) ){ json = JSONArray.fromObject( string, jsonConfig ); }else if( string.startsWith( "{" ) ){ json = JSONObject.fromObject( string, jsonConfig ); }else if( "null".equals( string ) ){ json = JSONNull.getInstance(); }else{ throw new JSONException( "Invalid JSON String" ); } return json; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/AbstractJSON.java0000664000175000017500000002322611650253660026156 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.io.IOException; import java.io.Writer; import java.lang.ref.SoftReference; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import net.sf.json.util.JSONUtils; import net.sf.json.util.JsonEventListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Base class for JSONObject and JSONArray. * * @author Andres Almiray */ abstract class AbstractJSON implements JSON { private static class CycleSet extends ThreadLocal { protected Object initialValue() { return new SoftReference(new HashSet()); } public Set getSet() { Set set = (Set) ((SoftReference)get()).get(); if( set == null ) { set = new HashSet(); set(new SoftReference(set)); } return set; } } private static CycleSet cycleSet = new CycleSet(); private static final Log log = LogFactory.getLog( AbstractJSON.class ); /** * Adds a reference for cycle detection check. * * @param instance the reference to add * @return true if the instance has not been added previously, false * otherwise. */ protected static boolean addInstance( Object instance ) { return getCycleSet().add( instance ); } /** * Fires an end of array event. */ protected static void fireArrayEndEvent( JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onArrayEnd(); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Fires a start of array event. */ protected static void fireArrayStartEvent( JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onArrayStart(); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Fires an element added event. * * @param index the index where the element was added * @param element the added element */ protected static void fireElementAddedEvent( int index, Object element, JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onElementAdded( index, element ); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Fires an error event. * * @param jsone the thrown exception */ protected static void fireErrorEvent( JSONException jsone, JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onError( jsone ); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Fires an end of object event. */ protected static void fireObjectEndEvent( JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onObjectEnd(); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Fires a start of object event. */ protected static void fireObjectStartEvent( JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onObjectStart(); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Fires a property set event. * * @param key the name of the property * @param value the value of the property * @param accumulated if the value has been accumulated over 'key' */ protected static void firePropertySetEvent( String key, Object value, boolean accumulated, JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onPropertySet( key, value, accumulated ); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Fires a warning event. * * @param warning the warning message */ protected static void fireWarnEvent( String warning, JsonConfig jsonConfig ) { if( jsonConfig.isEventTriggeringEnabled() ){ for( Iterator listeners = jsonConfig.getJsonEventListeners() .iterator(); listeners.hasNext(); ){ JsonEventListener listener = (JsonEventListener) listeners.next(); try{ listener.onWarning( warning ); }catch( RuntimeException e ){ log.warn( e ); } } } } /** * Removes a reference for cycle detection check. */ protected static void removeInstance( Object instance ) { Set set = getCycleSet(); set.remove( instance ); if(set.size() == 0) { cycleSet.remove(); } } protected Object _processValue( Object value, JsonConfig jsonConfig ) { if( JSONNull.getInstance().equals( value ) ) { return JSONNull.getInstance(); } else if( Class.class.isAssignableFrom( value.getClass() ) || value instanceof Class ) { return ((Class) value).getName(); } else if( value instanceof JSONFunction ) { return value; } else if( value instanceof JSONString ) { return JSONSerializer.toJSON( (JSONString) value, jsonConfig ); } else if( value instanceof JSON ) { return JSONSerializer.toJSON( value, jsonConfig ); } else if( JSONUtils.isArray( value ) ) { return JSONArray.fromObject( value, jsonConfig ); } else if( JSONUtils.isString( value ) ) { return value.toString(); } else if( JSONUtils.isNumber( value ) ) { JSONUtils.testValidity( value ); return JSONUtils.transformNumber( (Number) value ); } else if( JSONUtils.isBoolean( value ) ) { return value; } else { JSONObject jsonObject = JSONObject.fromObject( value, jsonConfig ); if( jsonObject.isNullObject() ) { return JSONNull.getInstance(); } else { return jsonObject; } } } private static Set getCycleSet() { return cycleSet.getSet(); } public final Writer write(Writer writer) throws IOException { write(writer,NORMAL); return writer; } public final Writer writeCanonical(Writer writer) throws IOException { write(writer,CANONICAL); return writer; } protected abstract void write(Writer w, WritingVisitor v) throws IOException; interface WritingVisitor { Collection keySet(JSONObject o); void on(JSON o, Writer w) throws IOException; void on(Object value, Writer w) throws IOException; } private static final WritingVisitor NORMAL = new WritingVisitor() { public Collection keySet(JSONObject o) { return o.keySet(); } public void on(JSON o, Writer w) throws IOException { o.write(w); } public void on(Object value, Writer w) throws IOException { w.write(JSONUtils.valueToString(value)); } }; private static final WritingVisitor CANONICAL = new WritingVisitor() { public Collection keySet(JSONObject o) { return new TreeSet(o.keySet()); // sort them alphabetically } public void on(JSON o, Writer w) throws IOException { o.writeCanonical(w); } public void on(Object value, Writer w) throws IOException { w.write(JSONUtils.valueToCanonicalString(value)); } }; }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/0000775000175000017500000000000011650253660025253 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/JsDateJsonBeanProcessor.java0000664000175000017500000000411111650253660032605 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Calendar; import java.util.Date; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; /** * Transforms a java.util.Date into a JSONObject ideal for JsDate conversion.
* Example:
* *
 {
 "minutes": 13,
 "seconds": 14,
 "hours": 12,
 "month": 5,
 "year": 2007,
 "day": 17,
 "milliseconds": 150
 }
 
* * @author Andres Almiray */ public class JsDateJsonBeanProcessor implements JsonBeanProcessor { /** * Processes the input bean into a compatible JsDate.
*/ public JSONObject processBean( Object bean, JsonConfig jsonConfig ) { JSONObject jsonObject = null; if( bean instanceof java.sql.Date ){ bean = new Date( ((java.sql.Date) bean).getTime() ); } if( bean instanceof Date ){ Calendar c = Calendar.getInstance(); c.setTime( (Date) bean ); jsonObject = new JSONObject().element( "year", c.get( Calendar.YEAR ) ) .element( "month", c.get( Calendar.MONTH ) ) .element( "day", c.get( Calendar.DAY_OF_MONTH ) ) .element( "hours", c.get( Calendar.HOUR_OF_DAY ) ) .element( "minutes", c.get( Calendar.MINUTE ) ) .element( "seconds", c.get( Calendar.SECOND ) ) .element( "milliseconds", c.get( Calendar.MILLISECOND ) ); }else{ jsonObject = new JSONObject( true ); } return jsonObject; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/JsonBeanProcessorMatcher.java0000664000175000017500000000315111650253660033021 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Set; /** * Base class for finding a matching JsonBeanProcessor.
*
    *
  • DEFAULT - matches the target class with equals().
  • *
* * @author Andres Almiray */ public abstract class JsonBeanProcessorMatcher { /** Matches the target with equals() */ public static final JsonBeanProcessorMatcher DEFAULT = new DefaultJsonBeanProcessorMatcher(); /** * Returns the matching class calculated with the target class and the * provided set. * * @param target the target class to match * @param set a set of possible matches */ public abstract Object getMatch( Class target, Set set ); private static final class DefaultJsonBeanProcessorMatcher extends JsonBeanProcessorMatcher { public Object getMatch( Class target, Set set ) { if( target != null && set != null && set.contains( target ) ){ return target; } return null; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/JsonVerifier.java0000664000175000017500000000320411650253660030522 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.math.BigDecimal; import java.math.BigInteger; import net.sf.json.JSON; import net.sf.json.JSONFunction; import net.sf.json.JSONNull; import net.sf.json.JSONString; /** * Verifies if a value is a valid JSON value. * * @author Andres Almiray */ public final class JsonVerifier { /** * Verifies if value is a valid JSON value. * * @param value the value to verify */ public static boolean isValidJsonValue( Object value ) { if( JSONNull.getInstance() .equals( value ) || value instanceof JSON || value instanceof Boolean || value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Double || value instanceof BigInteger || value instanceof BigDecimal || value instanceof JSONFunction || value instanceof JSONString || value instanceof String ){ return true; } return false; } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/DefaultDefaultValueProcessor.java0000664000175000017500000000266311650253660033713 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import net.sf.json.JSONArray; import net.sf.json.JSONNull; import net.sf.json.util.JSONUtils; /** * Base implementation for DefaultDefaultValueProcessor. * * @author Andres Almiray */ public class DefaultDefaultValueProcessor implements DefaultValueProcessor { public Object getDefaultValue( Class type ) { if( JSONUtils.isArray( type ) ){ return new JSONArray(); }else if( JSONUtils.isNumber( type ) ){ if( JSONUtils.isDouble( type ) ){ return new Double( 0 ); }else{ return new Integer( 0 ); } }else if( JSONUtils.isBoolean( type ) ){ return Boolean.FALSE; }else if( JSONUtils.isString( type ) ){ return ""; } return JSONNull.getInstance(); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/package.html0000664000175000017500000000023511650253660027534 0ustar jamespagejamespage

Support for custom serialization

jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/PropertyNameProcessor.java0000664000175000017500000000206011650253660032441 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; /** * Base interface for mutating property names of a Bean. * * @author Andres Almiray */ public interface PropertyNameProcessor { /** * Processes the property name. * * @param beanClass the input bean's class * @param name the current property name * @return an updated property name */ String processPropertyName( Class beanClass, String name ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/PropertyNameProcessorMatcher.java0000664000175000017500000000320111650253660033743 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Set; /** * Base class for finding a matching PropertyNameProcessor.
*
    *
  • DEFAULT - matches the target class with equals().
  • *
* * @author Andres Almiray */ public abstract class PropertyNameProcessorMatcher { /** Matches the target with equals() */ public static final PropertyNameProcessorMatcher DEFAULT = new DefaultPropertyNameProcessorMatcher(); /** * Returns the matching class calculated with the target class and the * provided set. * * @param target the target class to match * @param set a set of possible matches */ public abstract Object getMatch( Class target, Set set ); private static final class DefaultPropertyNameProcessorMatcher extends PropertyNameProcessorMatcher { public Object getMatch( Class target, Set set ) { if( target != null && set != null && set.contains( target ) ){ return target; } return null; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/DefaultValueProcessor.java0000664000175000017500000000177311650253660032407 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; /** * Defines the default value for a type when its value is null. * * @author Andres Almiray */ public interface DefaultValueProcessor { /** * Returns an appropriate default value for a type. * * @param type * @return the default value for instances of type */ Object getDefaultValue( Class type ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/JsonValueProcessor.java0000664000175000017500000000306611650253660031731 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import net.sf.json.JSONException; import net.sf.json.JsonConfig; /** * Base interface for custom serialization per property. * * @author Andres Almiray */ public interface JsonValueProcessor { /** * Processes the value an returns a suitable JSON value. * * @param value the input value * @return a valid JSON value that represents the input value * @throws JSONException if an error occurs during transformation */ Object processArrayValue( Object value, JsonConfig jsonConfig ); /** * Processes the value an returns a suitable JSON value. * * @param key the name of the property * @param value the value of the property * @return a valid JSON value that represents the input property * @throws JSONException if an error occurs during transformation */ Object processObjectValue( String key, Object value, JsonConfig jsonConfig ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/JsonValueProcessorMatcher.java0000664000175000017500000000315711650253660033236 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Set; /** * Base class for finding a matching JsonValueProcessor.
*
    *
  • DEFAULT - matches the target class with equals().
  • *
* * @author Andres Almiray */ public abstract class JsonValueProcessorMatcher { /** Matches the target with equals() */ public static final JsonValueProcessorMatcher DEFAULT = new DefaultJsonValueProcessorMatcher(); /** * Returns the matching class calculated with the target class and the * provided set. * * @param target the target class to match * @param set a set of possible matches */ public abstract Object getMatch( Class target, Set set ); private static final class DefaultJsonValueProcessorMatcher extends JsonValueProcessorMatcher { public Object getMatch( Class target, Set set ) { if( target != null && set != null && set.contains( target ) ){ return target; } return null; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/JsonBeanProcessor.java0000664000175000017500000000241611650253660031520 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import net.sf.json.JSONException; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; /** * Base interface for custom serialization per Bean. * * @author Andres Almiray */ public interface JsonBeanProcessor { /** * Processes the bean an returns a suitable JSONObject representation. * * @param bean the input bean * @param jsonConfig the current configuration environment * @return a JSONObject that represents the input bean * @throws JSONException if an error occurs during transformation */ JSONObject processBean( Object bean, JsonConfig jsonConfig ); }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/JsDateJsonValueProcessor.java0000664000175000017500000000264511650253660033026 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import net.sf.json.JsonConfig; /** * Transforms a java.util.Date property into a JSONObject ideal for JsDate * conversion * * @author Andres Almiray */ public class JsDateJsonValueProcessor implements JsonValueProcessor { private JsonBeanProcessor processor; public JsDateJsonValueProcessor() { processor = new JsDateJsonBeanProcessor(); } public Object processArrayValue( Object value, JsonConfig jsonConfig ) { return process( value, jsonConfig ); } public Object processObjectValue( String key, Object value, JsonConfig jsonConfig ) { return process( value, jsonConfig ); } private Object process( Object value, JsonConfig jsonConfig ) { return processor.processBean( value, jsonConfig ); } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/processors/DefaultValueProcessorMatcher.java0000664000175000017500000000321211650253660033701 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Set; /** * Base class for finding a matching DefaultValueProcessor.
*
    *
  • DEFAULT - matches the target class with equals().
  • *
* * @author Andres Almiray */ public abstract class DefaultValueProcessorMatcher { /** Matches the target with equals() */ public static final DefaultValueProcessorMatcher DEFAULT = new DefaultDefaultValueProcessorMatcher(); /** * Returns the matching class calculated with the target class and the * provided set. * * @param target the target class to match * @param set a set of possible matches */ public abstract Object getMatch( Class target, Set set ); private static final class DefaultDefaultValueProcessorMatcher extends DefaultValueProcessorMatcher { public Object getMatch( Class target, Set set ) { if( target != null && set != null && set.contains( target ) ){ return target; } return null; } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/test/0000775000175000017500000000000011650253660024030 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/test/JSONAssert.java0000664000175000017500000005024211650253660026631 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.test; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.lang.StringUtils; import junit.framework.Assert; import net.sf.ezmorph.Morpher; import net.sf.ezmorph.object.IdentityObjectMorpher; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONFunction; import net.sf.json.JSONNull; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import net.sf.json.util.JSONUtils; /** * Provides assertions on equality for JSON strings and JSON types. * * @author Andres Almiray */ public class JSONAssert extends Assert { /** * Asserts that two JSON values are equal. */ public static void assertEquals( JSON expected, JSON actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONArrays are equal. */ public static void assertEquals( JSONArray expected, JSONArray actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONArrays are equal. */ public static void assertEquals( JSONArray expected, String actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONFunctions are equal. */ public static void assertEquals( JSONFunction expected, String actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONNulls are equal. */ public static void assertEquals( JSONNull expected, String actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONObjects are equal. */ public static void assertEquals( JSONObject expected, JSONObject actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONObjects are equal. */ public static void assertEquals( JSONObject expected, String actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSON values are equal. */ public static void assertEquals( String message, JSON expected, JSON actual ) { String header = message == null ? "" : message + ": "; if( expected == null ){ fail( header + "expected was null" ); } if( actual == null ){ fail( header + "actual was null" ); } if( expected == actual || expected.equals( actual ) ){ return; } if( expected instanceof JSONArray ){ if( actual instanceof JSONArray ){ assertEquals( header, (JSONArray) expected, (JSONArray) actual ); }else{ fail( header + "actual is not a JSONArray" ); } }else if( expected instanceof JSONObject ){ if( actual instanceof JSONObject ){ assertEquals( header, (JSONObject) expected, (JSONObject) actual ); }else{ fail( header + "actual is not a JSONObject" ); } }else if( expected instanceof JSONNull ){ if( actual instanceof JSONNull ){ return; }else{ fail( header + "actual is not a JSONNull" ); } } } /** * Asserts that two JSONArrays are equal. */ public static void assertEquals( String expected, JSONArray actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONArrays are equal. */ public static void assertEquals( String message, JSONArray expected, JSONArray actual ) { String header = message == null ? "" : message + ": "; if( expected == null ){ fail( header + "expected array was null" ); } if( actual == null ){ fail( header + "actual array was null" ); } if( expected == actual || expected.equals( actual ) ){ return; } if( actual.size() != expected.size() ){ fail( header + "arrays sizes differed, expected.length()=" + expected.size() + " actual.length()=" + actual.size() ); } int max = expected.size(); for( int i = 0; i < max; i++ ){ Object o1 = expected.get( i ); Object o2 = actual.get( i ); // handle nulls if( JSONNull.getInstance() .equals( o1 ) ){ if( JSONNull.getInstance() .equals( o2 ) ){ continue; }else{ fail( header + "arrays first differed at element [" + i + "];" ); } }else{ if( JSONNull.getInstance() .equals( o2 ) ){ fail( header + "arrays first differed at element [" + i + "];" ); } } if( o1 instanceof JSONArray && o2 instanceof JSONArray ){ JSONArray e = (JSONArray) o1; JSONArray a = (JSONArray) o2; assertEquals( header + "arrays first differed at element " + i + ";", e, a ); }else{ if( o1 instanceof String && o2 instanceof JSONFunction ){ assertEquals( header + "arrays first differed at element [" + i + "];", (String) o1, (JSONFunction) o2 ); }else if( o1 instanceof JSONFunction && o2 instanceof String ){ assertEquals( header + "arrays first differed at element [" + i + "];", (JSONFunction) o1, (String) o2 ); }else if( o1 instanceof JSONObject && o2 instanceof JSONObject ){ assertEquals( header + "arrays first differed at element [" + i + "];", (JSONObject) o1, (JSONObject) o2 ); }else if( o1 instanceof JSONArray && o2 instanceof JSONArray ){ assertEquals( header + "arrays first differed at element [" + i + "];", (JSONArray) o1, (JSONArray) o2 ); }else if( o1 instanceof JSONFunction && o2 instanceof JSONFunction ){ assertEquals( header + "arrays first differed at element [" + i + "];", (JSONFunction) o1, (JSONFunction) o2 ); }else{ if( o1 instanceof String ){ assertEquals( header + "arrays first differed at element [" + i + "];", (String) o1, String.valueOf( o2 ) ); }else if( o2 instanceof String ){ assertEquals( header + "arrays first differed at element [" + i + "];", String.valueOf( o1 ), (String) o2 ); }else{ Morpher m1 = JSONUtils.getMorpherRegistry() .getMorpherFor( o1.getClass() ); Morpher m2 = JSONUtils.getMorpherRegistry() .getMorpherFor( o2.getClass() ); if( m1 != null && m1 != IdentityObjectMorpher.getInstance() ){ assertEquals( header + "arrays first differed at element [" + i + "];", o1, JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o2 ) ); }else if( m2 != null && m2 != IdentityObjectMorpher.getInstance() ){ assertEquals( header + "arrays first differed at element [" + i + "];", JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o1 ), o2 ); }else{ assertEquals( header + "arrays first differed at element [" + i + "];", o1, o2 ); } } } } } } /** * Asserts that two JSONArrays are equal. */ public static void assertEquals( String message, JSONArray expected, String actual ) { try{ assertEquals( message, expected, JSONArray.fromObject( actual ) ); }catch( JSONException e ){ String header = message == null ? "" : message + ": "; fail( header + "actual is not a JSONArray" ); } } /** * Asserts that two JSONFunctions are equal. */ public static void assertEquals( String expected, JSONFunction actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONFunctions are equal. */ public static void assertEquals( String message, JSONFunction expected, String actual ) { String header = message == null ? "" : message + ": "; if( expected == null ){ fail( header + "expected function was null" ); } if( actual == null ){ fail( header + "actual string was null" ); } try{ assertEquals( header, expected, JSONFunction.parse( actual ) ); }catch( JSONException jsone ){ fail( header + "'" + actual + "' is not a function" ); } } /** * Asserts that two JSONNulls are equal. */ public static void assertEquals( String expected, JSONNull actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONNulls are equal. */ public static void assertEquals( String message, JSONNull expected, String actual ) { String header = message == null ? "" : message + ": "; if( actual == null ){ fail( header + "actual string was null" ); }else if( expected == null ){ assertEquals( header, "null", actual ); }else{ assertEquals( header, expected.toString(), actual ); } } /** * Asserts that two JSONObjects are equal. */ public static void assertEquals( String expected, JSONObject actual ) { assertEquals( null, expected, actual ); } /** * Asserts that two JSONObjects are equal. */ public static void assertEquals( String message, JSONObject expected, JSONObject actual ) { String header = message == null ? "" : message + ": "; if( expected == null ){ fail( header + "expected object was null" ); } if( actual == null ){ fail( header + "actual object was null" ); } if( expected == actual /* || expected.equals( actual ) */){ return; } if( expected.isNullObject() ){ if( actual.isNullObject() ){ return; }else{ fail( header + "actual is not a null JSONObject" ); } }else{ if( actual.isNullObject() ){ fail( header + "actual is a null JSONObject" ); } } if( expected.names().size() != actual.names().size() ){ fail( header + missingAndUnexpectedNames( expected, actual )); } for( Iterator keys = expected.keys(); keys.hasNext(); ){ String key = (String) keys.next(); Object o1 = expected.opt( key ); Object o2 = actual.opt( key ); if( JSONNull.getInstance() .equals( o1 ) ){ if( JSONNull.getInstance() .equals( o2 ) ){ continue; }else{ fail( header + "objects differed at key [" + key + "];" ); } }else{ if( JSONNull.getInstance() .equals( o2 ) ){ fail( header + "objects differed at key [" + key + "];" ); } } if( o1 instanceof String && o2 instanceof JSONFunction ){ assertEquals( header + "objects differed at key [" + key + "];", (String) o1, (JSONFunction) o2 ); }else if( o1 instanceof JSONFunction && o2 instanceof String ){ assertEquals( header + "objects differed at key [" + key + "];", (JSONFunction) o1, (String) o2 ); }else if( o1 instanceof JSONObject && o2 instanceof JSONObject ){ assertEquals( header + "objects differed at key [" + key + "];", (JSONObject) o1, (JSONObject) o2 ); }else if( o1 instanceof JSONArray && o2 instanceof JSONArray ){ assertEquals( header + "objects differed at key [" + key + "];", (JSONArray) o1, (JSONArray) o2 ); }else if( o1 instanceof JSONFunction && o2 instanceof JSONFunction ){ assertEquals( header + "objects differed at key [" + key + "];", (JSONFunction) o1, (JSONFunction) o2 ); }else{ if( o1 instanceof String ){ assertEquals( header + "objects differed at key [" + key + "];", (String) o1, String.valueOf( o2 ) ); }else if( o2 instanceof String ){ assertEquals( header + "objects differed at key [" + key + "];", String.valueOf( o1 ), (String) o2 ); }else{ Morpher m1 = JSONUtils.getMorpherRegistry() .getMorpherFor( o1.getClass() ); Morpher m2 = JSONUtils.getMorpherRegistry() .getMorpherFor( o2.getClass() ); if( m1 != null && m1 != IdentityObjectMorpher.getInstance() ){ assertEquals( header + "objects differed at key [" + key + "];", o1, JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o2 ) ); }else if( m2 != null && m2 != IdentityObjectMorpher.getInstance() ){ assertEquals( header + "objects differed at key [" + key + "];", JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o1 ), o2 ); }else{ assertEquals( header + "objects differed at key [" + key + "];", o1, o2 ); } } } } } private static String missingAndUnexpectedNames(JSONObject expected, JSONObject actual) { String missingExpectedNames = missingExpectedNames( expected, actual ); String unexpectedNames = unexpectedNames( expected, actual ); if( missingExpectedNames != null && unexpectedNames != null ){ return missingExpectedNames + ", " + unexpectedNames; }else if( missingExpectedNames != null ){ return missingExpectedNames; }else{ return unexpectedNames; } } private static String missingExpectedNames(JSONObject expected, JSONObject actual) { SortedSet keysInExpectedButNotInActual = new TreeSet( expected.keySet() ); keysInExpectedButNotInActual.removeAll( actual.keySet() ); if ( keysInExpectedButNotInActual.isEmpty() ) { return null; } else { return "missing expected names: [" + StringUtils.join( keysInExpectedButNotInActual, ", " ) + "]"; } } private static String unexpectedNames(JSONObject expected, JSONObject actual) { SortedSet keysInActualButNotInExpected = new TreeSet( actual.keySet() ); keysInActualButNotInExpected.removeAll( expected.keySet() ); if ( keysInActualButNotInExpected.isEmpty() ) { return null; } else { return "unexpected names: [" + StringUtils.join( keysInActualButNotInExpected, ", " ) + "]"; } } /** * Asserts that two JSONObjects are equal. */ public static void assertEquals( String message, JSONObject expected, String actual ) { try{ assertEquals( message, expected, JSONObject.fromObject( actual ) ); }catch( JSONException e ){ String header = message == null ? "" : message + ": "; fail( header + "actual is not a JSONObject" ); } } /** * Asserts that two JSONArrays are equal. */ public static void assertEquals( String message, String expected, JSONArray actual ) { try{ assertEquals( message, JSONArray.fromObject( expected ), actual ); }catch( JSONException e ){ String header = message == null ? "" : message + ": "; fail( header + "expected is not a JSONArray" ); } } /** * Asserts that two JSONFunctions are equal. */ public static void assertEquals( String message, String expected, JSONFunction actual ) { String header = message == null ? "" : message + ": "; if( expected == null ){ fail( header + "expected string was null" ); } if( actual == null ){ fail( header + "actual function was null" ); } try{ assertEquals( header, JSONFunction.parse( expected ), actual ); }catch( JSONException jsone ){ fail( header + "'" + expected + "' is not a function" ); } } /** * Asserts that two JSONNulls are equal. */ public static void assertEquals( String message, String expected, JSONNull actual ) { String header = message == null ? "" : message + ": "; if( expected == null ){ fail( header + "expected was null" ); }else if( actual == null ){ assertEquals( header, expected, "null" ); }else{ assertEquals( header, expected, actual.toString() ); } } /** * Asserts that two JSONObjects are equal. */ public static void assertEquals( String message, String expected, JSONObject actual ) { try{ assertEquals( message, JSONObject.fromObject( expected ), actual ); }catch( JSONException e ){ String header = message == null ? "" : message + ": "; fail( header + "expected is not a JSONObject" ); } } /** * Asserts that two JSON strings are equal. */ public static void assertJsonEquals( String expected, String actual ) { assertJsonEquals( null, expected, actual ); } /** * Asserts that two JSON strings are equal. */ public static void assertJsonEquals( String message, String expected, String actual ) { String header = message == null ? "" : message + ": "; if( expected == null ){ fail( header + "expected was null" ); } if( actual == null ){ fail( header + "actual was null" ); } JSON json1 = null; JSON json2 = null; try{ json1 = JSONSerializer.toJSON( expected ); }catch( JSONException jsone ){ fail( header + "expected is not a valid JSON string" ); } try{ json2 = JSONSerializer.toJSON( actual ); }catch( JSONException jsone ){ fail( header + "actual is not a valid JSON string" ); } assertEquals( header, json1, json2 ); } /** * Asserts that a JSON value is not null.
* Fails if: *
    *
  • JSONNull.getInstance().equals( json )
  • *
  • ((JSONObject) json).isNullObject()
  • *
*/ public static void assertNotNull( JSON json ) { assertNotNull( null, json ); } /** * Asserts that a JSON value is not null.
* Fails if: *
    *
  • JSONNull.getInstance().equals( json )
  • *
  • ((JSONObject) json).isNullObject()
  • *
*/ public static void assertNotNull( String message, JSON json ) { String header = message == null ? "" : message + ": "; if( json instanceof JSONObject ){ assertFalse( header + "Object is null", ((JSONObject) json).isNullObject() ); }else if( JSONNull.getInstance() .equals( json ) ){ fail( header + "Object is null" ); } } /** * Asserts that a JSON value is null.
* Fails if: *
    *
  • !JSONNull.getInstance().equals( json )
  • *
  • !((JSONObject) json).isNullObject()
  • *
*/ public static void assertNull( JSON json ) { assertNull( null, json ); } /** * Asserts that a JSON value is null.
* Fails if: *
    *
  • !JSONNull.getInstance().equals( json )
  • *
  • !((JSONObject) json).isNullObject()
  • *
*/ public static void assertNull( String message, JSON json ) { String header = message == null ? "" : message + ": "; if( json instanceof JSONObject ){ assertTrue( header + "Object is not null", ((JSONObject) json).isNullObject() ); }else if( !JSONNull.getInstance() .equals( json ) ){ fail( header + "Object is not null" ); } } }jenkins-json-2.4-jenkins-3/src/main/java/net/sf/json/test/package.html0000664000175000017500000000021611650253660026310 0ustar jamespagejamespage

Testing utilities

jenkins-json-2.4-jenkins-3/src/main/groovy/0000775000175000017500000000000011650253660021306 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/groovy/net/0000775000175000017500000000000011650253660022074 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/groovy/net/sf/0000775000175000017500000000000011650253660022504 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/groovy/net/sf/json/0000775000175000017500000000000011650253660023455 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/groovy/net/sf/json/groovy/0000775000175000017500000000000011650253660025002 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/groovy/net/sf/json/groovy/GJson.groovy0000664000175000017500000001010411650253660027265 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy import net.sf.json.JSON import net.sf.json.JSONArray import net.sf.json.JSONObject import net.sf.json.JSONFunction import net.sf.json.JSONSerializer /** * @author Andres Almiray */ class GJson { public static void enhanceClasses(){ def s = enhanceString() def l = enhanceCollection() def m = enhanceMap() def j = enhanceJSONObject() if( s || l || m || j ){ ExpandoMetaClass.enableGlobally() } } private static boolean enhanceString(){ if( !String.metaClass.methods.find{ it.name == "isJsonEnhanced" } ){ def asType = String.metaClass.&asType String.metaClass.asType = { Class clazz -> switch( clazz ){ case JSON: return JSONSerializer.toJSON( delegate ) case JSONArray: return JSONArray.fromObject( delegate ) case JSONObject: return JSONObject.fromObject( delegate ) case JSONFunction: return JSONFunction.parse( delegate ) default: return asType(clazz) } } String.metaClass.isJsonEnhanced = { true } return true } return false } private static boolean enhanceCollection(){ if( !Collection.metaClass.methods.find{ it.name == "isJsonEnhanced" } ){ def asType = Collection.metaClass.&asType def typeConverter = { Class clazz -> switch( clazz ){ case JSONArray: return JSONArray.fromObject( delegate ) default: return asType(clazz) } } // FIXME why won't Collection.metaClass.asType work ? ArrayList.metaClass.asType = typeConverter HashSet.metaClass.asType = typeConverter Collection.metaClass.isJsonEnhanced = { true } return true } return false } private static boolean enhanceMap(){ if( !Map.metaClass.methods.find{ it.name == "isJsonEnhanced" } ){ def asType = Map.metaClass.&asType Map.metaClass.asType = { Class clazz -> switch( clazz ){ case JSONObject: return JSONObject.fromObject( delegate ) default: return asType(clazz) } } Map.metaClass.isJsonEnhanced = { true } return true } return false } private static boolean enhanceJSONObject(){ if( !JSONObject.metaClass.methods.find{ it.name == "isJsonEnhanced" } ){ JSONObject.metaClass.leftShift = { args -> if( args instanceof Map ){ delegate.putAll( args ) delegate }else if( args instanceof List && args.size() >= 2 ){ def key = args.remove(0) if( args.size() == 1 ){ delegate.element( key, args.get(0) ) }else{ delegate.element( key, args ) } } } JSONObject.metaClass.get = { String key, defaultValue -> def previousValue = delegate.opt( key ) if( !previousValue ){ delegate.element( key, defaultValue ) previousValue = delegate.get( key ) } return previousValue } JSONObject.metaClass.isJsonEnhanced = { true } return true } return false } }jenkins-json-2.4-jenkins-3/src/main/jdk15/0000775000175000017500000000000011650253660020677 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/jdk15/net/0000775000175000017500000000000011650253660021465 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/jdk15/net/sf/0000775000175000017500000000000011650253660022075 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/jdk15/net/sf/json/0000775000175000017500000000000011650253660023046 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/jdk15/net/sf/json/JSONArray.java0000664000175000017500000025376711650253660025505 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import net.sf.ezmorph.Morpher; import net.sf.ezmorph.object.IdentityObjectMorpher; import net.sf.json.processors.JsonValueProcessor; import net.sf.json.processors.JsonVerifier; import net.sf.json.util.JSONTokener; import net.sf.json.util.JSONUtils; import org.apache.commons.lang.StringUtils; /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The * internal form is an object having get and opt * methods for accessing the values by index, and element methods * for adding or replacing values. The values can be any of these types: * Boolean, JSONArray, JSONObject, * Number, String, or the * JSONNull object. *

* The constructor can convert a JSON text into a Java object. The * toString method converts to JSON text. *

* A get method returns a value if one can be found, and throws * an exception if one cannot be found. An opt method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. *

* The generic get() and opt() methods return an * object which you can cast or query for type. There are also typed * get and opt methods that do type checking and * type coersion for you. *

* The texts produced by the toString methods strictly conform to * JSON syntax rules. The constructors are more forgiving in the texts they will * accept: *

    *
  • An extra , (comma) may appear just * before the closing bracket.
  • *
  • The null value will be inserted when there is * , (comma) elision.
  • *
  • Strings may be quoted with ' (single quote).
  • *
  • Strings do not need to be quoted at all if they do not begin with a * quote or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * { } [ ] / \ : , = ; # and if they do not look like numbers and * if they are not the reserved words true, false, * or null.
  • *
  • Values can be separated by ; (semicolon) * as well as by , (comma).
  • *
  • Numbers may have the 0- (octal) or * 0x- (hex) prefix.
  • *
  • Comments written in the slashshlash, slashstar, and hash conventions * will be ignored.
  • *
* * @author JSON.org */ public final class JSONArray extends AbstractJSON implements JSON, List, Comparable { /** * Creates a JSONArray.
* Inspects the object type to call the correct JSONArray factory method. * Accepts JSON formatted strings, arrays, Collections and Enums. * * @param object * @throws JSONException if the object can not be converted to a proper * JSONArray. */ public static JSONArray fromObject( Object object ) { return fromObject( object, new JsonConfig() ); } /** * Creates a JSONArray.
* Inspects the object type to call the correct JSONArray factory method. * Accepts JSON formatted strings, arrays, Collections and Enums. * * @param object * @throws JSONException if the object can not be converted to a proper * JSONArray. */ public static JSONArray fromObject( Object object, JsonConfig jsonConfig ) { if( object instanceof JSONString ){ return _fromJSONString( (JSONString) object, jsonConfig ); }else if( object instanceof JSONArray ){ return _fromJSONArray( (JSONArray) object, jsonConfig ); }else if( object instanceof Collection ){ return _fromCollection( (Collection) object, jsonConfig ); }else if( object instanceof JSONTokener ){ return _fromJSONTokener( (JSONTokener) object, jsonConfig ); }else if( object instanceof String ){ return _fromString( (String) object, jsonConfig ); }else if( object != null && object.getClass() .isArray() ){ Class type = object.getClass() .getComponentType(); if( !type.isPrimitive() ){ return _fromArray( (Object[]) object, jsonConfig ); }else{ if( type == Boolean.TYPE ){ return _fromArray( (boolean[]) object, jsonConfig ); }else if( type == Byte.TYPE ){ return _fromArray( (byte[]) object, jsonConfig ); }else if( type == Short.TYPE ){ return _fromArray( (short[]) object, jsonConfig ); }else if( type == Integer.TYPE ){ return _fromArray( (int[]) object, jsonConfig ); }else if( type == Long.TYPE ){ return _fromArray( (long[]) object, jsonConfig ); }else if( type == Float.TYPE ){ return _fromArray( (float[]) object, jsonConfig ); }else if( type == Double.TYPE ){ return _fromArray( (double[]) object, jsonConfig ); }else if( type == Character.TYPE ){ return _fromArray( (char[]) object, jsonConfig ); }else{ throw new JSONException( "Unsupported type" ); } } }else if( JSONUtils.isBoolean( object ) || JSONUtils.isFunction( object ) || JSONUtils.isNumber( object ) || JSONUtils.isNull( object ) || JSONUtils.isString( object ) || object instanceof JSON ){ fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray().element( object, jsonConfig ); fireElementAddedEvent( 0, jsonArray.get( 0 ), jsonConfig ); fireArrayStartEvent( jsonConfig ); return jsonArray; }else if( object instanceof Enum ){ return _fromArray( (Enum) object, jsonConfig ); }else if( object instanceof Annotation || (object != null && object.getClass() .isAnnotation()) ){ throw new JSONException( "Unsupported type" ); }else if( JSONUtils.isObject( object ) ){ fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray().element( JSONObject.fromObject( object, jsonConfig ) ); fireElementAddedEvent( 0, jsonArray.get( 0 ), jsonConfig ); fireArrayStartEvent( jsonConfig ); return jsonArray; }else{ throw new JSONException( "Unsupported type" ); } } /** * Get the collection type from a getter or setter, or null if no type was * found.
* Contributed by [Matt Small @ WaveMaker]. */ public static Class[] getCollectionType( PropertyDescriptor pd, boolean useGetter ) throws JSONException { Type type; if( useGetter ){ Method m = pd.getReadMethod(); type = m.getGenericReturnType(); }else{ Method m = pd.getWriteMethod(); Type[] gpts = m.getGenericParameterTypes(); if( 1 != gpts.length ){ throw new JSONException( "method " + m + " is not a standard setter" ); } type = gpts[0]; } if( !(type instanceof ParameterizedType) ){ return null; // throw new JSONException("type not instanceof ParameterizedType: // "+type.getClass()); } ParameterizedType pType = (ParameterizedType) type; Type[] actualTypes = pType.getActualTypeArguments(); Class[] ret = new Class[actualTypes.length]; for( int i = 0; i < ret.length; i++ ){ ret[i] = (Class) actualTypes[i]; } return ret; } /** * Returns the number of dimensions suited for a java array. */ public static int[] getDimensions( JSONArray jsonArray ) { // short circuit for empty arrays if( jsonArray == null || jsonArray.isEmpty() ){ return new int[] { 0 }; } List dims = new ArrayList(); processArrayDimensions( jsonArray, dims, 0 ); int[] dimensions = new int[dims.size()]; int j = 0; for( Iterator i = dims.iterator(); i.hasNext(); ){ dimensions[j++] = ((Integer) i.next()).intValue(); } return dimensions; } /** * Creates a java array from a JSONArray. */ public static Object toArray( JSONArray jsonArray ) { return toArray( jsonArray, new JsonConfig() ); } /** * Creates a java array from a JSONArray. */ public static Object toArray( JSONArray jsonArray, Class objectClass ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( objectClass ); return toArray( jsonArray, jsonConfig ); } /** * Creates a java array from a JSONArray.
* Any attribute is a JSONObject and matches a key in the classMap, it will * be converted to that target class.
* The classMap has the following conventions: *
    *
  • Every key must be an String.
  • *
  • Every value must be a Class.
  • *
  • A key may be a regular expression.
  • *
*/ public static Object toArray( JSONArray jsonArray, Class objectClass, Map classMap ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( objectClass ); jsonConfig.setClassMap( classMap ); return toArray( jsonArray, jsonConfig ); } /** * Creates a java array from a JSONArray.
*/ public static Object toArray( JSONArray jsonArray, JsonConfig jsonConfig ) { Class objectClass = jsonConfig.getRootClass(); Map classMap = jsonConfig.getClassMap(); if( jsonArray.size() == 0 ){ return Array.newInstance( objectClass == null ? Object.class : objectClass, 0 ); } int[] dimensions = JSONArray.getDimensions( jsonArray ); Object array = Array.newInstance( objectClass == null ? Object.class : objectClass, dimensions ); int size = jsonArray.size(); for( int i = 0; i < size; i++ ){ Object value = jsonArray.get( i ); if( JSONUtils.isNull( value ) ){ Array.set( array, i, null ); }else{ Class type = value.getClass(); if( JSONArray.class.isAssignableFrom( type ) ){ Array.set( array, i, toArray( (JSONArray) value, objectClass, classMap ) ); }else if( String.class.isAssignableFrom( type ) || Boolean.class.isAssignableFrom( type ) || Character.class.isAssignableFrom( type ) || JSONFunction.class.isAssignableFrom( type ) ){ if( objectClass != null && !objectClass.isAssignableFrom( type ) ){ value = JSONUtils.getMorpherRegistry() .morph( objectClass, value ); } Array.set( array, i, value ); }else if( JSONUtils.isNumber( type ) ){ if( objectClass != null && (Byte.class.isAssignableFrom( objectClass ) || Byte.TYPE.isAssignableFrom( objectClass )) ){ Array.set( array, i, Byte.valueOf( String.valueOf( value ) ) ); }else if( objectClass != null && (Short.class.isAssignableFrom( objectClass ) || Short.TYPE.isAssignableFrom( objectClass )) ){ Array.set( array, i, Short.valueOf( String.valueOf( value ) ) ); }else{ Array.set( array, i, value ); } }else{ if( objectClass != null ){ JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( objectClass ); jsc.setClassMap( classMap ); Array.set( array, i, JSONObject.toBean( (JSONObject) value, jsc ) ); }else{ Array.set( array, i, JSONObject.toBean( (JSONObject) value ) ); } } } } return array; } /** * Creates a java array from a JSONArray.
*/ public static Object toArray( JSONArray jsonArray, Object root, JsonConfig jsonConfig ) { Class objectClass = root.getClass(); if( jsonArray.size() == 0 ){ return Array.newInstance( objectClass, 0 ); } int[] dimensions = JSONArray.getDimensions( jsonArray ); Object array = Array.newInstance( objectClass == null ? Object.class : objectClass, dimensions ); int size = jsonArray.size(); for( int i = 0; i < size; i++ ){ Object value = jsonArray.get( i ); if( JSONUtils.isNull( value ) ){ Array.set( array, i, null ); }else{ Class type = value.getClass(); if( JSONArray.class.isAssignableFrom( type ) ){ Array.set( array, i, toArray( (JSONArray) value, root, jsonConfig ) ); }else if( String.class.isAssignableFrom( type ) || Boolean.class.isAssignableFrom( type ) || JSONUtils.isNumber( type ) || Character.class.isAssignableFrom( type ) || JSONFunction.class.isAssignableFrom( type ) ){ if( objectClass != null && !objectClass.isAssignableFrom( type ) ){ value = JSONUtils.getMorpherRegistry() .morph( objectClass, value ); } Array.set( array, i, value ); }else{ try{ Object newRoot = jsonConfig.getNewBeanInstanceStrategy() .newInstance( root.getClass(), null ); Array.set( array, i, JSONObject.toBean( (JSONObject) value, newRoot, jsonConfig ) ); }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( e ); } } } } return array; } /** * Returns a List or a Set taking generics into account.
*/ public static Collection toCollection( JSONArray jsonArray ) { return toCollection( jsonArray, new JsonConfig() ); } /** * Returns a List or a Set taking generics into account.
*/ public static Collection toCollection( JSONArray jsonArray, Class objectClass ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( objectClass ); return toCollection( jsonArray, jsonConfig ); } /** * Returns a List or a Set taking generics into account.
* Contributed by [Matt Small @ WaveMaker]. */ public static Collection toCollection( JSONArray jsonArray, JsonConfig jsonConfig ) { Collection collection = null; Class collectionType = jsonConfig.getCollectionType(); if( collectionType.isInterface() ){ if( collectionType.equals( List.class ) ){ collection = new ArrayList(); }else if( collectionType.equals( Set.class ) ){ collection = new HashSet(); }else{ throw new JSONException( "unknown interface: " + collectionType ); } }else{ try{ collection = (Collection) collectionType.newInstance(); }catch( InstantiationException e ){ throw new JSONException( e ); }catch( IllegalAccessException e ){ throw new JSONException( e ); } } Class objectClass = jsonConfig.getRootClass(); Map classMap = jsonConfig.getClassMap(); int size = jsonArray.size(); for( int i = 0; i < size; i++ ){ Object value = jsonArray.get( i ); if( JSONUtils.isNull( value ) ){ collection.add( null ); }else{ Class type = value.getClass(); if( JSONArray.class.isAssignableFrom( value.getClass() ) ){ collection.add( toCollection( (JSONArray) value, jsonConfig ) ); }else if( String.class.isAssignableFrom( type ) || Boolean.class.isAssignableFrom( type ) || JSONUtils.isNumber( type ) || Character.class.isAssignableFrom( type ) || JSONFunction.class.isAssignableFrom( type ) ){ if( objectClass != null && !objectClass.isAssignableFrom( type ) ){ value = JSONUtils.getMorpherRegistry() .morph( objectClass, value ); } collection.add( value ); }else{ if( objectClass != null ){ JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( objectClass ); jsc.setClassMap( classMap ); collection.add( JSONObject.toBean( (JSONObject) value, jsc ) ); }else{ collection.add( JSONObject.toBean( (JSONObject) value ) ); } } } } return collection; } /* public static Collection toCollection( JSONArray jsonArray, JsonConfig jsonConfig ) { Collection collection = null; Class collectionType = jsonConfig.getCollectionType(); Class enclosedType = jsonConfig.getEnclosedType(); if( collectionType.isInterface() ){ if( collectionType.equals( List.class ) ){ collection = new ArrayList(); }else if( collectionType.equals( Set.class ) ){ collection = new HashSet(); }else{ throw new JSONException( "unknown interface: " + collectionType ); } }else{ try{ collection = (Collection) collectionType.newInstance(); }catch( InstantiationException e ){ throw new JSONException( e ); }catch( IllegalAccessException e ){ throw new JSONException( e ); } } Class objectClass = jsonConfig.getRootClass(); Map classMap = jsonConfig.getClassMap(); int size = jsonArray.size(); for( int i = 0; i < size; i++ ){ Object value = jsonArray.get( i ); Class enclosedTypeE = enclosedType; if( null == enclosedTypeE ){ enclosedTypeE = value.getClass(); } if( JSONUtils.isNull( value ) ){ collection.add( null ); }else{ if( JSONArray.class.isAssignableFrom( value.getClass() ) ){ //throw new RuntimeException( "can't have nested collections" ); collection.add( toCollection( (JSONArray) value, jsonConfig ) ); }else if( String.class.isAssignableFrom( enclosedTypeE ) || Boolean.class.isAssignableFrom( enclosedTypeE ) || JSONUtils.isNumber( enclosedTypeE ) || Character.class.isAssignableFrom( enclosedTypeE ) || JSONFunction.class.isAssignableFrom( enclosedTypeE ) ){ if( !value.getClass() .isAssignableFrom( enclosedTypeE ) ){ throw new JSONException( "can't assign value " + value + " of type " + value.getClass() + " to Collection of type " + enclosedTypeE ); } collection.add( value ); }else{ try{ if( JSON.class.isAssignableFrom( enclosedTypeE ) ){ ret.add( JSONObject.toBean( (JSONObject) value ) ); }else{ Object newRoot = enclosedTypeE.newInstance(); ret.add( JSONObject.toBean( (JSONObject) value, newRoot, jsonConfig ) ); } }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( e ); } if( objectClass != null ){ JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( objectClass ); jsc.setClassMap( classMap ); collection.add( JSONObject.toBean( (JSONObject) value, jsc ) ); }else{ collection.add( JSONObject.toBean( (JSONObject) value ) ); } } } } return collection; } */ /** * Creates a List from a JSONArray.
* * @deprecated replaced by toCollection * @see #toCollection(JSONArray) */ public static List toList( JSONArray jsonArray ) { return toList( jsonArray, new JsonConfig() ); } /** * Creates a List from a JSONArray. * * @deprecated replaced by toCollection * @see #toCollection(JSONArray,Class) */ public static List toList( JSONArray jsonArray, Class objectClass ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( objectClass ); return toList( jsonArray, jsonConfig ); } /** * Creates a List from a JSONArray.
* Any attribute is a JSONObject and matches a key in the classMap, it will * be converted to that target class.
* The classMap has the following conventions: *
    *
  • Every key must be an String.
  • *
  • Every value must be a Class.
  • *
  • A key may be a regular expression.
  • *
* * @deprecated replaced by toCollection * @see #toCollection(JSONArray,Class,Map) */ public static List toList( JSONArray jsonArray, Class objectClass, Map classMap ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( objectClass ); jsonConfig.setClassMap( classMap ); return toList( jsonArray, jsonConfig ); } /** * Creates a List from a JSONArray.
* * @deprecated replaced by toCollection * @see #toCollection(JSONArray,JsonConfig) */ public static List toList( JSONArray jsonArray, JsonConfig jsonConfig ) { if( jsonArray.size() == 0 ){ return new ArrayList(); } Class objectClass = jsonConfig.getRootClass(); Map classMap = jsonConfig.getClassMap(); List list = new ArrayList(); int size = jsonArray.size(); for( int i = 0; i < size; i++ ){ Object value = jsonArray.get( i ); if( JSONUtils.isNull( value ) ){ list.add( null ); }else{ Class type = value.getClass(); if( JSONArray.class.isAssignableFrom( type ) ){ list.add( toList( (JSONArray) value, objectClass, classMap ) ); }else if( String.class.isAssignableFrom( type ) || Boolean.class.isAssignableFrom( type ) || JSONUtils.isNumber( type ) || Character.class.isAssignableFrom( type ) || JSONFunction.class.isAssignableFrom( type ) ){ if( objectClass != null && !objectClass.isAssignableFrom( type ) ){ value = JSONUtils.getMorpherRegistry() .morph( objectClass, value ); } list.add( value ); }else{ if( objectClass != null ){ JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( objectClass ); jsc.setClassMap( classMap ); list.add( JSONObject.toBean( (JSONObject) value, jsc ) ); }else{ list.add( JSONObject.toBean( (JSONObject) value ) ); } } } } return list; } /** * Creates a List from a JSONArray.
*/ public static List toList( JSONArray jsonArray, Object root, JsonConfig jsonConfig ) { if( jsonArray.size() == 0 || root == null ){ return new ArrayList(); } List list = new ArrayList(); int size = jsonArray.size(); for( int i = 0; i < size; i++ ){ Object value = jsonArray.get( i ); if( JSONUtils.isNull( value ) ){ list.add( null ); }else{ Class type = value.getClass(); if( JSONArray.class.isAssignableFrom( type ) ){ list.add( toList( (JSONArray) value, root, jsonConfig ) ); }else if( String.class.isAssignableFrom( type ) || Boolean.class.isAssignableFrom( type ) || JSONUtils.isNumber( type ) || Character.class.isAssignableFrom( type ) || JSONFunction.class.isAssignableFrom( type ) ){ list.add( value ); }else{ try{ Object newRoot = jsonConfig.getNewBeanInstanceStrategy() .newInstance( root.getClass(), null ); list.add( JSONObject.toBean( (JSONObject) value, newRoot, jsonConfig ) ); }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( e ); } } } } return list; } /** * Construct a JSONArray from an boolean[].
* * @param array An boolean[] array. */ private static JSONArray _fromArray( boolean[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); for( int i = 0; i < array.length; i++ ){ Boolean b = array[i] ? Boolean.TRUE : Boolean.FALSE; jsonArray.addValue( b, jsonConfig ); fireElementAddedEvent( i, b, jsonConfig ); } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an byte[].
* * @param array An byte[] array. */ private static JSONArray _fromArray( byte[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); for( int i = 0; i < array.length; i++ ){ Number n = JSONUtils.transformNumber( new Byte( array[i] ) ); jsonArray.addValue( n, jsonConfig ); fireElementAddedEvent( i, n, jsonConfig ); } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an char[].
* * @param array An char[] array. */ private static JSONArray _fromArray( char[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); for( int i = 0; i < array.length; i++ ){ Character c = new Character( array[i] ); jsonArray.addValue( c, jsonConfig ); fireElementAddedEvent( i, c, jsonConfig ); } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an double[].
* * @param array An double[] array. */ private static JSONArray _fromArray( double[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); try{ for( int i = 0; i < array.length; i++ ){ Double d = array[i]; JSONUtils.testValidity( d ); jsonArray.addValue( d, jsonConfig ); fireElementAddedEvent( i, d, jsonConfig ); } }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an Enum value. * * @param e A enum value. * @throws JSONException If there is a syntax error. */ private static JSONArray _fromArray( Enum e, JsonConfig jsonConfig ) { if( !addInstance( e ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( e ); }catch( JSONException jsone ){ removeInstance( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException re ){ removeInstance( e ); JSONException jsone = new JSONException( re ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); if( e != null ){ jsonArray.addValue( e, jsonConfig ); fireElementAddedEvent( 0, jsonArray.get( 0 ), jsonConfig ); }else{ JSONException jsone = new JSONException( "enum value is null" ); removeInstance( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( e ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an float[].
* * @param array An float[] array. */ private static JSONArray _fromArray( float[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); try{ for( int i = 0; i < array.length; i++ ){ Float f = array[i]; JSONUtils.testValidity( f ); jsonArray.addValue( f, jsonConfig ); fireElementAddedEvent( i, f, jsonConfig ); } }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an int[].
* * @param array An int[] array. */ private static JSONArray _fromArray( int[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); for( int i = 0; i < array.length; i++ ){ Number n = new Integer( array[i] ); jsonArray.addValue( n, jsonConfig ); fireElementAddedEvent( i, n, jsonConfig ); } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an long[].
* * @param array An long[] array. */ private static JSONArray _fromArray( long[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); for( int i = 0; i < array.length; i++ ){ Number n = JSONUtils.transformNumber( new Long( array[i] ) ); jsonArray.addValue( n, jsonConfig ); fireElementAddedEvent( i, n, jsonConfig ); } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } // ------------------------------------------------------ private static JSONArray _fromArray( Object[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); try{ for( int i = 0; i < array.length; i++ ){ Object element = array[i]; jsonArray.addValue( element, jsonConfig ); fireElementAddedEvent( i, jsonArray.get( i ), jsonConfig ); } }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } /** * Construct a JSONArray from an short[].
* * @param array An short[] array. */ private static JSONArray _fromArray( short[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); for( int i = 0; i < array.length; i++ ){ Number n = JSONUtils.transformNumber( new Short( array[i] ) ); jsonArray.addValue( n, jsonConfig ); fireElementAddedEvent( i, n, jsonConfig ); } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } private static JSONArray _fromCollection( Collection collection, JsonConfig jsonConfig ) { if( !addInstance( collection ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( collection ); }catch( JSONException jsone ){ removeInstance( collection ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( collection ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); try{ int i = 0; for( Iterator elements = collection.iterator(); elements.hasNext(); ){ Object element = elements.next(); jsonArray.addValue( element, jsonConfig ); fireElementAddedEvent( i, jsonArray.get( i++ ), jsonConfig ); } }catch( JSONException jsone ){ removeInstance( collection ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( collection ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( collection ); fireArrayEndEvent( jsonConfig ); return jsonArray; } private static JSONArray _fromJSONArray( JSONArray array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); int index = 0; for( Iterator elements = array.iterator(); elements.hasNext(); ){ Object element = elements.next(); jsonArray.addValue( element, jsonConfig ); fireElementAddedEvent( index++, element, jsonConfig ); } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; } private static JSONArray _fromJSONString( JSONString string, JsonConfig jsonConfig ) { return _fromJSONTokener( new JSONTokener( string.toJSONString() ), jsonConfig ); } private static JSONArray _fromJSONTokener( JSONTokener tokener, JsonConfig jsonConfig ) { JSONArray jsonArray = new JSONArray(); int index = 0; try{ if( tokener.nextClean() != '[' ){ throw tokener.syntaxError( "A JSONArray text must start with '['" ); } fireArrayStartEvent( jsonConfig ); if( tokener.nextClean() == ']' ){ fireArrayEndEvent( jsonConfig ); return jsonArray; } tokener.back(); for( ;; ){ if( tokener.nextClean() == ',' ){ tokener.back(); jsonArray.elements.add( JSONNull.getInstance() ); fireElementAddedEvent( index, jsonArray.get( index++ ), jsonConfig ); }else{ tokener.back(); Object v = tokener.nextValue( jsonConfig ); if( !JSONUtils.isFunctionHeader( v ) ){ jsonArray.addValue( v, jsonConfig ); fireElementAddedEvent( index, jsonArray.get( index++ ), jsonConfig ); }else{ // read params if any String params = JSONUtils.getFunctionParams( (String) v ); // read function text int i = 0; StringBuffer sb = new StringBuffer(); for( ;; ){ char ch = tokener.next(); if( ch == 0 ){ break; } if( ch == '{' ){ i++; } if( ch == '}' ){ i--; } sb.append( ch ); if( i == 0 ){ break; } } if( i != 0 ){ throw tokener.syntaxError( "Unbalanced '{' or '}' on prop: " + v ); } // trim '{' at start and '}' at end String text = sb.toString(); text = text.substring( 1, text.length() - 1 ) .trim(); jsonArray.addValue( new JSONFunction( (params != null) ? StringUtils.split( params, "," ) : null, text ), jsonConfig ); fireElementAddedEvent( index, jsonArray.get( index++ ), jsonConfig ); } } switch( tokener.nextClean() ){ case ';': case ',': if( tokener.nextClean() == ']' ){ fireArrayEndEvent( jsonConfig ); return jsonArray; } tokener.back(); break; case ']': fireArrayEndEvent( jsonConfig ); return jsonArray; default: throw tokener.syntaxError( "Expected a ',' or ']'" ); } } }catch( JSONException jsone ){ fireErrorEvent( jsone, jsonConfig ); throw jsone; } } private static JSONArray _fromString( String string, JsonConfig jsonConfig ) { return _fromJSONTokener( new JSONTokener( string ), jsonConfig ); } private static void processArrayDimensions( JSONArray jsonArray, List dims, int index ) { if( dims.size() <= index ){ dims.add(jsonArray.size()); }else{ int i = ((Integer) dims.get( index )).intValue(); if( jsonArray.size() > i ){ dims.set( index, jsonArray.size()); } } for( Iterator i = jsonArray.iterator(); i.hasNext(); ){ Object item = i.next(); if( item instanceof JSONArray ){ processArrayDimensions( (JSONArray) item, dims, index + 1 ); } } } // ------------------------------------------------------ /** * The List where the JSONArray's properties are kept. */ private List elements; /** * A flag for XML processing. */ private boolean expandElements; /** * Construct an empty JSONArray. */ public JSONArray() { this.elements = new ArrayList(); } public void add( int index, Object value ) { add( index, value, new JsonConfig() ); } public void add( int index, Object value, JsonConfig jsonConfig ) { this.elements.add( index, processValue( value, jsonConfig ) ); } public boolean add( Object value ) { return add( value, new JsonConfig() ); } public boolean add( Object value, JsonConfig jsonConfig ) { element( value, jsonConfig ); return true; } public boolean addAll( Collection collection ) { return addAll( collection, new JsonConfig() ); } public boolean addAll( Collection collection, JsonConfig jsonConfig ) { if( collection == null || collection.size() == 0 ){ return false; } for (Object a : collection) { element(a, jsonConfig); } return true; } public boolean addAll( int index, Collection collection ) { return addAll( index, collection, new JsonConfig() ); } public boolean addAll( int index, Collection collection, JsonConfig jsonConfig ) { if( collection == null || collection.size() == 0 ){ return false; } int offset = 0; for (Object a : collection) { this.elements.add(index + (offset++), processValue(a, jsonConfig)); } return true; } public void clear() { elements.clear(); } public int compareTo( Object obj ) { if( obj != null && (obj instanceof JSONArray) ){ JSONArray other = (JSONArray) obj; int size1 = size(); int size2 = other.size(); if( size1 < size2 ){ return -1; }else if( size1 > size2 ){ return 1; }else if( this.equals( other ) ){ return 0; } } return -1; } public boolean contains( Object o ) { return contains( o, new JsonConfig() ); } public boolean contains( Object o, JsonConfig jsonConfig ) { return elements.contains( processValue( o, jsonConfig ) ); } public boolean containsAll( Collection collection ) { return containsAll( collection, new JsonConfig() ); } public boolean containsAll( Collection collection, JsonConfig jsonConfig ) { return elements.containsAll( fromObject( collection, jsonConfig ) ); } /** * Remove an element, if present. * * @param index the index of the element. * @return this. */ public JSONArray discard( int index ) { elements.remove( index ); return this; } /** * Remove an element, if present. * * @param index the element. * @return this. */ public JSONArray discard( Object o ) { elements.remove( o ); return this; } /** * Append a boolean value. This increases the array's length by one. * * @param value A boolean value. * @return this. */ public JSONArray element( boolean value ) { return element( value ? Boolean.TRUE : Boolean.FALSE ); } /** * Append a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param value A Collection value. * @return this. */ public JSONArray element( Collection value ) { return element( value, new JsonConfig() ); } /** * Append a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param value A Collection value. * @return this. */ public JSONArray element( Collection value, JsonConfig jsonConfig ) { if( value instanceof JSONArray ){ elements.add( value ); return this; }else{ return element( _fromCollection( value, jsonConfig ) ); } } /** * Append a double value. This increases the array's length by one. * * @param value A double value. * @throws JSONException if the value is not finite. * @return this. */ public JSONArray element( double value ) { Double d = value; JSONUtils.testValidity( d ); return element( d ); } /** * Append an int value. This increases the array's length by one. * * @param value An int value. * @return this. */ public JSONArray element( int value ) { return element( new Integer( value ) ); } /** * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * * @param index The subscript. * @param value A boolean value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray element( int index, boolean value ) { return element( index, value ? Boolean.TRUE : Boolean.FALSE ); } /** * Put a value in the JSONArray, where the value will be a JSONArray which is * produced from a Collection. * * @param index The subscript. * @param value A Collection value. * @return this. * @throws JSONException If the index is negative or if the value is not * finite. */ public JSONArray element( int index, Collection value ) { return element( index, value, new JsonConfig() ); } /** * Put a value in the JSONArray, where the value will be a JSONArray which is * produced from a Collection. * * @param index The subscript. * @param value A Collection value. * @return this. * @throws JSONException If the index is negative or if the value is not * finite. */ public JSONArray element( int index, Collection value, JsonConfig jsonConfig ) { if( value instanceof JSONArray ){ if( index < 0 ){ throw new JSONException( "JSONArray[" + index + "] not found." ); } if( index < size() ){ elements.set( index, value ); }else{ while( index != size() ){ element( JSONNull.getInstance() ); } element( value, jsonConfig ); } return this; }else{ return element( index, _fromCollection( value, jsonConfig ) ); } } /** * Put or replace a double value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index The subscript. * @param value A double value. * @return this. * @throws JSONException If the index is negative or if the value is not * finite. */ public JSONArray element( int index, double value ) { return element( index, new Double( value ) ); } /** * Put or replace an int value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index The subscript. * @param value An int value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray element( int index, int value ) { return element( index, new Integer( value ) ); } /** * Put or replace a long value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index The subscript. * @param value A long value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray element( int index, long value ) { return element( index, new Long( value ) ); } /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param index The subscript. * @param value The Map value. * @return this. * @throws JSONException If the index is negative or if the the value is an * invalid number. */ public JSONArray element( int index, Map value ) { return element( index, value, new JsonConfig() ); } /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param index The subscript. * @param value The Map value. * @return this. * @throws JSONException If the index is negative or if the the value is an * invalid number. */ public JSONArray element( int index, Map value, JsonConfig jsonConfig ) { if( value instanceof JSONObject ){ if( index < 0 ){ throw new JSONException( "JSONArray[" + index + "] not found." ); } if( index < size() ){ elements.set( index, value ); }else{ while( index != size() ){ element( JSONNull.getInstance() ); } element( value, jsonConfig ); } return this; }else{ return element( index, JSONObject.fromObject( value, jsonConfig ) ); } } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * * @param index The subscript. * @param value An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, JSONFunction, Long, String, * JSONString or the JSONNull object. * @return this. * @throws JSONException If the index is negative or if the the value is an * invalid number. */ public JSONArray element( int index, Object value ) { return element( index, value, new JsonConfig() ); } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * * @param index The subscript. * @param value An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, JSONFunction, Long, String, * JSONString or the JSONNull object. * @return this. * @throws JSONException If the index is negative or if the the value is an * invalid number. */ public JSONArray element( int index, Object value, JsonConfig jsonConfig ) { JSONUtils.testValidity( value ); if( index < 0 ){ throw new JSONException( "JSONArray[" + index + "] not found." ); } if( index < size() ){ this.elements.set( index, processValue( value, jsonConfig ) ); }else{ while( index != size() ){ element( JSONNull.getInstance() ); } element( value, jsonConfig ); } return this; } /** * Put or replace a String value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out.
* The string may be a valid JSON formatted string, in tha case, it will be * transformed to a JSONArray, JSONObject or JSONNull. * * @param index The subscript. * @param value A String value. * @return this. * @throws JSONException If the index is negative or if the the value is an * invalid number. */ public JSONArray element( int index, String value ) { return element( index, value, new JsonConfig() ); } /** * Put or replace a String value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out.
* The string may be a valid JSON formatted string, in tha case, it will be * transformed to a JSONArray, JSONObject or JSONNull. * * @param index The subscript. * @param value A String value. * @return this. * @throws JSONException If the index is negative or if the the value is an * invalid number. */ public JSONArray element( int index, String value, JsonConfig jsonConfig ) { if( index < 0 ){ throw new JSONException( "JSONArray[" + index + "] not found." ); } if( index < size() ){ if( value == null ){ this.elements.set( index, "" ); }else if( JSONUtils.mayBeJSON( value ) ){ try{ this.elements.set( index, JSONSerializer.toJSON( value, jsonConfig ) ); }catch( JSONException jsone ){ this.elements.set( index, JSONUtils.stripQuotes( value ) ); } }else{ this.elements.set( index, JSONUtils.stripQuotes( value ) ); } }else{ while( index != size() ){ element( JSONNull.getInstance() ); } element( value, jsonConfig ); } return this; } /** * Append an JSON value. This increases the array's length by one. * * @param value An JSON value. * @return this. */ public JSONArray element( JSONNull value ) { this.elements.add( value ); return this; } /** * Append an JSON value. This increases the array's length by one. * * @param value An JSON value. * @return this. */ public JSONArray element( JSONObject value ) { this.elements.add( value ); return this; } /** * Append an long value. This increases the array's length by one. * * @param value A long value. * @return this. */ public JSONArray element( long value ) { return element( JSONUtils.transformNumber(value) ); } /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param value A Map value. * @return this. */ public JSONArray element( Map value ) { return element( value, new JsonConfig() ); } /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param value A Map value. * @return this. */ public JSONArray element( Map value, JsonConfig jsonConfig ) { if( value instanceof JSONObject ){ elements.add( value ); return this; }else{ return element( JSONObject.fromObject( value, jsonConfig ) ); } } /** * Append an object value. This increases the array's length by one. * * @param value An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, JSONFunction, Long, String, * JSONString or the JSONNull object. * @return this. */ public JSONArray element( Object value ) { return element( value, new JsonConfig() ); } /** * Append an object value. This increases the array's length by one. * * @param value An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, JSONFunction, Long, String, * JSONString or the JSONNull object. * @return this. */ public JSONArray element( Object value, JsonConfig jsonConfig ) { return addValue( value, jsonConfig ); } /** * Append a String value. This increases the array's length by one.
* The string may be a valid JSON formatted string, in tha case, it will be * transformed to a JSONArray, JSONObject or JSONNull. * * @param value A String value. * @return this. */ public JSONArray element( String value ) { return element( value, new JsonConfig() ); } /** * Append a String value. This increases the array's length by one.
* The string may be a valid JSON formatted string, in tha case, it will be * transformed to a JSONArray, JSONObject or JSONNull. * * @param value A String value. * @return this. */ public JSONArray element( String value, JsonConfig jsonConfig ) { if( value == null ) { this.elements.add(""); } else if( JSONUtils.hasQuotes( value )) { this.elements.add(value); } else if( JSONNull.getInstance().equals( value )) { this.elements.add( JSONNull.getInstance() ); } else if( JSONUtils.isJsonKeyword(value,jsonConfig)) { this.elements.add(value); } else if( JSONUtils.mayBeJSON( value ) ){ try{ this.elements.add( JSONSerializer.toJSON( value, jsonConfig ) ); }catch( JSONException jsone ){ this.elements.add( value ); } } else { this.elements.add(value); } return this; } public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null ){ return false; } if( !(obj instanceof JSONArray) ){ return false; } JSONArray other = (JSONArray) obj; if( other.size() != size() ){ return false; } int max = size(); for( int i = 0; i < max; i++ ){ Object o1 = get( i ); Object o2 = other.get( i ); // handle nulls if( JSONNull.getInstance() .equals( o1 ) ){ if( JSONNull.getInstance() .equals( o2 ) ){ continue; }else{ return false; } }else{ if( JSONNull.getInstance() .equals( o2 ) ){ return false; } } if( o1 instanceof JSONArray && o2 instanceof JSONArray ){ JSONArray e = (JSONArray) o1; JSONArray a = (JSONArray) o2; if( !a.equals( e ) ){ return false; } }else{ if( o1 instanceof String && o2 instanceof JSONFunction ){ if( !o1.equals( String.valueOf( o2 ) ) ){ return false; } }else if( o1 instanceof JSONFunction && o2 instanceof String ){ if( !o2.equals( String.valueOf( o1 ) ) ){ return false; } }else if( o1 instanceof JSONObject && o2 instanceof JSONObject ){ if( !o1.equals( o2 ) ){ return false; } }else if( o1 instanceof JSONArray && o2 instanceof JSONArray ){ if( !o1.equals( o2 ) ){ return false; } }else if( o1 instanceof JSONFunction && o2 instanceof JSONFunction ){ if( !o1.equals( o2 ) ){ return false; } }else{ if( o1 instanceof String ){ if( !o1.equals( String.valueOf( o2 ) ) ){ return false; } }else if( o2 instanceof String ){ if( !o2.equals( String.valueOf( o1 ) ) ){ return false; } }else{ Morpher m1 = JSONUtils.getMorpherRegistry() .getMorpherFor( o1.getClass() ); Morpher m2 = JSONUtils.getMorpherRegistry() .getMorpherFor( o2.getClass() ); if( m1 != null && m1 != IdentityObjectMorpher.getInstance() ){ if( !o1.equals( JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o2 ) ) ){ return false; } }else if( m2 != null && m2 != IdentityObjectMorpher.getInstance() ){ if( !JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o1 ) .equals( o2 ) ){ return false; } }else{ if( !o1.equals( o2 ) ){ return false; } } } } } } return true; } /** * Get the object value associated with an index. * * @param index The index must be between 0 and size() - 1. * @return An object value. */ public Object get( int index ) { /* * Object o = opt( index ); if( o == null ){ throw new JSONException( * "JSONArray[" + index + "] not found." ); } return o; */ return this.elements.get( index ); } /** * Get the boolean value associated with an index. The string values "true" * and "false" are converted to boolean. * * @param index The index must be between 0 and size() - 1. * @return The truth. * @throws JSONException If there is no value for the index or if the value * is not convertable to boolean. */ public boolean getBoolean( int index ) { Object o = get( index ); if( o != null ){ if( o.equals( Boolean.FALSE ) || (o instanceof String && ((String) o).equalsIgnoreCase( "false" )) ){ return false; }else if( o.equals( Boolean.TRUE ) || (o instanceof String && ((String) o).equalsIgnoreCase( "true" )) ){ return true; } } throw new JSONException( "JSONArray[" + index + "] is not a Boolean." ); } /** * Get the double value associated with an index. * * @param index The index must be between 0 and size() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot be * converted to a number. */ public double getDouble( int index ) { Object o = get( index ); if( o != null ){ try{ return o instanceof Number ? ((Number) o).doubleValue() : Double.parseDouble( (String) o ); }catch( Exception e ){ throw new JSONException( "JSONArray[" + index + "] is not a number." ); } } throw new JSONException( "JSONArray[" + index + "] is not a number." ); } /** * Get the int value associated with an index. * * @param index The index must be between 0 and size() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot be * converted to a number. if the value cannot be converted to a * number. */ public int getInt( int index ) { Object o = get( index ); if( o != null ){ return o instanceof Number ? ((Number) o).intValue() : (int) getDouble( index ); } throw new JSONException( "JSONArray[" + index + "] is not a number." ); } /** * Get the JSONArray associated with an index. * * @param index The index must be between 0 and size() - 1. * @return A JSONArray value. * @throws JSONException If there is no value for the index. or if the value * is not a JSONArray */ public JSONArray getJSONArray( int index ) { Object o = get( index ); if( o != null && o instanceof JSONArray ){ return (JSONArray) o; } throw new JSONException( "JSONArray[" + index + "] is not a JSONArray." ); } /** * Get the JSONObject associated with an index. * * @param index subscript * @return A JSONObject value. * @throws JSONException If there is no value for the index or if the value * is not a JSONObject */ public JSONObject getJSONObject( int index ) { Object o = get( index ); if( JSONNull.getInstance() .equals( o ) ){ return new JSONObject( true ); }else if( o instanceof JSONObject ){ return (JSONObject) o; } throw new JSONException( "JSONArray[" + index + "] is not a JSONObject." ); } /** * Get the long value associated with an index. * * @param index The index must be between 0 and size() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot be * converted to a number. */ public long getLong( int index ) { Object o = get( index ); if( o != null ){ return o instanceof Number ? ((Number) o).longValue() : (long) getDouble( index ); } throw new JSONException( "JSONArray[" + index + "] is not a number." ); } /** * Get the string associated with an index. * * @param index The index must be between 0 and size() - 1. * @return A string value. * @throws JSONException If there is no value for the index. */ public String getString( int index ) { Object o = get( index ); if( o != null ){ return o.toString(); } throw new JSONException( "JSONArray[" + index + "] not found." ); } public int hashCode() { int hashcode = 29; for( Iterator e = elements.iterator(); e.hasNext(); ){ Object element = e.next(); hashcode += JSONUtils.hashCode( element ); } return hashcode; } public int indexOf( Object o ) { return elements.indexOf( o ); } public boolean isArray() { return true; } public boolean isEmpty() { return this.elements.isEmpty(); } public boolean isExpandElements() { return expandElements; } /** * Returns an Iterator for this JSONArray */ public Iterator iterator() { return new JSONArrayListIterator(); } /** * Make a string from the contents of this JSONArray. The * separator string is inserted between each element. Warning: * This method assumes that the data structure is acyclical. * * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ public String join( String separator ) { return join( separator, false ); } /** * Make a string from the contents of this JSONArray. The * separator string is inserted between each element. Warning: * This method assumes that the data structure is acyclical. * * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ public String join( String separator, boolean stripQuotes ) { int len = size(); StringBuffer sb = new StringBuffer(); for( int i = 0; i < len; i += 1 ){ if( i > 0 ){ sb.append( separator ); } String value = JSONUtils.valueToString( this.elements.get( i ) ); sb.append( stripQuotes ? JSONUtils.stripQuotes( value ) : value ); } return sb.toString(); } public int lastIndexOf( Object o ) { return elements.lastIndexOf( o ); } public ListIterator listIterator() { return listIterator( 0 ); } public ListIterator listIterator( int index ) { if( index < 0 || index > size() ) throw new IndexOutOfBoundsException( "Index: " + index ); return new JSONArrayListIterator( index ); } /** * Get the optional object value associated with an index. * * @param index The index must be between 0 and size() - 1. * @return An object value, or null if there is no object at that index. */ public Object opt( int index ) { return (index < 0 || index >= size()) ? null : this.elements.get( index ); } /** * Get the optional boolean value associated with an index. It returns false * if there is no value at that index, or if the value is not Boolean.TRUE or * the String "true". * * @param index The index must be between 0 and size() - 1. * @return The truth. */ public boolean optBoolean( int index ) { return optBoolean( index, false ); } /** * Get the optional boolean value associated with an index. It returns the * defaultValue if there is no value at that index or if it is not a Boolean * or the String "true" or "false" (case insensitive). * * @param index The index must be between 0 and size() - 1. * @param defaultValue A boolean default. * @return The truth. */ public boolean optBoolean( int index, boolean defaultValue ) { try{ return getBoolean( index ); }catch( Exception e ){ return defaultValue; } } /** * Get the optional double value associated with an index. NaN is returned if * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index The index must be between 0 and size() - 1. * @return The value. */ public double optDouble( int index ) { return optDouble( index, Double.NaN ); } /** * Get the optional double value associated with an index. The defaultValue * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index subscript * @param defaultValue The default value. * @return The value. */ public double optDouble( int index, double defaultValue ) { try{ return getDouble( index ); }catch( Exception e ){ return defaultValue; } } /** * Get the optional int value associated with an index. Zero is returned if * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index The index must be between 0 and size() - 1. * @return The value. */ public int optInt( int index ) { return optInt( index, 0 ); } /** * Get the optional int value associated with an index. The defaultValue is * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index The index must be between 0 and size() - 1. * @param defaultValue The default value. * @return The value. */ public int optInt( int index, int defaultValue ) { try{ return getInt( index ); }catch( Exception e ){ return defaultValue; } } /** * Get the optional JSONArray associated with an index. * * @param index subscript * @return A JSONArray value, or null if the index has no value, or if the * value is not a JSONArray. */ public JSONArray optJSONArray( int index ) { Object o = opt( index ); return o instanceof JSONArray ? (JSONArray) o : null; } /** * Get the optional JSONObject associated with an index. Null is returned if * the key is not found, or null if the index has no value, or if the value * is not a JSONObject. * * @param index The index must be between 0 and size() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject( int index ) { Object o = opt( index ); return o instanceof JSONObject ? (JSONObject) o : null; } /** * Get the optional long value associated with an index. Zero is returned if * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index The index must be between 0 and size() - 1. * @return The value. */ public long optLong( int index ) { return optLong( index, 0 ); } /** * Get the optional long value associated with an index. The defaultValue is * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index The index must be between 0 and size() - 1. * @param defaultValue The default value. * @return The value. */ public long optLong( int index, long defaultValue ) { try{ return getLong( index ); }catch( Exception e ){ return defaultValue; } } /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value is not a * string and is not null, then it is coverted to a string. * * @param index The index must be between 0 and size() - 1. * @return A String value. */ public String optString( int index ) { return optString( index, "" ); } /** * Get the optional string associated with an index. The defaultValue is * returned if the key is not found. * * @param index The index must be between 0 and size() - 1. * @param defaultValue The default value. * @return A String value. */ public String optString( int index, String defaultValue ) { Object o = opt( index ); return o != null ? o.toString() : defaultValue; } public Object remove( int index ) { return elements.remove( index ); } public boolean remove( Object o ) { return elements.remove( o ); } public boolean removeAll( Collection collection ) { return removeAll( collection, new JsonConfig() ); } public boolean removeAll( Collection collection, JsonConfig jsonConfig ) { return elements.removeAll( fromObject( collection, jsonConfig ) ); } public boolean retainAll( Collection collection ) { return retainAll( collection, new JsonConfig() ); } public boolean retainAll( Collection collection, JsonConfig jsonConfig ) { return elements.retainAll( fromObject( collection, jsonConfig ) ); } public Object set( int index, Object value ) { return set( index, value, new JsonConfig() ); } public Object set( int index, Object value, JsonConfig jsonConfig ) { Object previous = get( index ); element( index, value, jsonConfig ); return previous; } public void setExpandElements( boolean expandElements ) { this.expandElements = expandElements; } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int size() { return this.elements.size(); } public List subList( int fromIndex, int toIndex ) { return elements.subList( fromIndex, toIndex ); } /** * Produce an Object[] with the contents of this JSONArray. */ public Object[] toArray() { return this.elements.toArray(); } public Object[] toArray( Object[] array ) { return elements.toArray( array ); } /** * Produce a JSONObject by combining a JSONArray of names with the values of * this JSONArray. * * @param names A JSONArray containing a list of key strings. These will be * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject( JSONArray names ) { if( names == null || names.size() == 0 || size() == 0 ){ return null; } JSONObject jo = new JSONObject(); for( int i = 0; i < names.size(); i++ ){ jo.element( names.getString( i ), this.opt( i ) ); } return jo; } /** * Make a JSON text of this JSONArray. For compactness, no unnecessary * whitespace is added. If it is not possible to produce a syntactically * correct JSON text then null will be returned instead. This could occur if * the array contains an invalid number. *

* Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable representation of the * array. */ public String toString() { try{ return '[' + join( "," ) + ']'; }catch( Exception e ){ return null; } } /** * Make a prettyprinted JSON text of this JSONArray. Warning: This method * assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, transmittable representation of the * object, beginning with [ (left * bracket) and ending with ] (right * bracket). * @throws JSONException */ public String toString( int indentFactor ) { if( indentFactor == 0 ){ return this.toString(); } return toString( indentFactor, 0 ); } /** * Make a prettyprinted JSON text of this JSONArray. Warning: This method * assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indention of the top level. * @return a printable, displayable, transmittable representation of the * array. * @throws JSONException */ public String toString( int indentFactor, int indent ) { int len = size(); if( len == 0 ){ return "[]"; } if( indentFactor == 0 ){ return this.toString(); } int i; StringBuffer sb = new StringBuffer( "[" ); if( len == 1 ){ sb.append( JSONUtils.valueToString( this.elements.get( 0 ), indentFactor, indent ) ); }else{ int newindent = indent + indentFactor; sb.append( '\n' ); for( i = 0; i < len; i += 1 ){ if( i > 0 ){ sb.append( ",\n" ); } for( int j = 0; j < newindent; j += 1 ){ sb.append( ' ' ); } sb.append( JSONUtils.valueToString( this.elements.get( i ), indentFactor, newindent ) ); } sb.append( '\n' ); for( i = 0; i < indent; i += 1 ){ sb.append( ' ' ); } for( i = 0; i < indent; i += 1 ){ sb.insert( 0, ' ' ); } } sb.append( ']' ); return sb.toString(); } protected void write(Writer writer, WritingVisitor visitor) throws IOException { boolean b = false; int len = size(); writer.write( '[' ); for( int i = 0; i < len; i += 1 ){ if( b ){ writer.write( ',' ); } Object v = this.elements.get( i ); if( v instanceof JSON ){ visitor.on((JSON)v,writer); }else{ visitor.on(v,writer); } b = true; } writer.write( ']' ); } /** * Adds a String without performing any conversion on it. */ protected JSONArray addString( String str ) { if( str != null ){ elements.add( str ); } return this; } /** * Append an object value. This increases the array's length by one. * * @param value An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, JSONFunction, Long, String, * JSONString or the JSONNull object. * @return this. */ private JSONArray _addValue( Object value, JsonConfig jsonConfig ) { this.elements.add(value); return this; } protected Object _processValue( Object value, JsonConfig jsonConfig ) { if( value instanceof JSONTokener ) { return _fromJSONTokener( (JSONTokener) value, jsonConfig ); }else if( value != null && Enum.class.isAssignableFrom( value.getClass() ) ){ return ((Enum) value).name(); }else if( value instanceof Annotation || (value != null && value.getClass() .isAnnotation()) ){ throw new JSONException( "Unsupported type" ); } return super._processValue( value, jsonConfig ); } /** * Append an object value. This increases the array's length by one. * * @param value An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, JSONFunction, Long, String, * JSONString or the JSONNull object. * @return this. */ private JSONArray addValue( Object value, JsonConfig jsonConfig ) { return _addValue( processValue( value, jsonConfig ), jsonConfig ); } private Object processValue( Object value, JsonConfig jsonConfig ) { if( value != null ){ JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor( value.getClass() ); if( jsonValueProcessor != null ){ value = jsonValueProcessor.processArrayValue( value, jsonConfig ); if( !JsonVerifier.isValidJsonValue( value ) ){ throw new JSONException( "Value is not a valid JSON value. " + value ); } } } return _processValue( value, jsonConfig ); } private class JSONArrayListIterator implements ListIterator { int currentIndex = 0; int lastIndex = -1; JSONArrayListIterator() { } JSONArrayListIterator( int index ) { currentIndex = index; } public boolean hasNext() { return currentIndex != size(); } public Object next() { try { Object next = get( currentIndex ); lastIndex = currentIndex++; return next; } catch( IndexOutOfBoundsException e ) { throw new NoSuchElementException(); } } public void remove() { if( lastIndex == -1 ) throw new IllegalStateException(); try { JSONArray.this.remove( lastIndex ); if( lastIndex < currentIndex ){ currentIndex--; } lastIndex = -1; } catch( IndexOutOfBoundsException e ) { throw new ConcurrentModificationException(); } } public boolean hasPrevious() { return currentIndex != 0; } public Object previous() { try { int index = currentIndex - 1; Object previous = get( index ); lastIndex = currentIndex = index; return previous; } catch( IndexOutOfBoundsException e ) { throw new NoSuchElementException(); } } public int nextIndex() { return currentIndex; } public int previousIndex() { return currentIndex - 1; } public void set( Object obj ) { if( lastIndex == -1 ){ throw new IllegalStateException(); } try { JSONArray.this.set( lastIndex, obj ); } catch( IndexOutOfBoundsException ex ) { throw new ConcurrentModificationException(); } } public void add( Object obj ) { try { JSONArray.this.add( currentIndex++, obj ); lastIndex = -1; } catch( IndexOutOfBoundsException ex ) { throw new ConcurrentModificationException(); } } } } jenkins-json-2.4-jenkins-3/src/main/jdk15/net/sf/json/JSONObject.java0000664000175000017500000027757511650253660025640 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.lang.reflect.AnnotatedElement; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.ezmorph.Morpher; import net.sf.ezmorph.array.ObjectArrayMorpher; import net.sf.ezmorph.bean.BeanMorpher; import net.sf.ezmorph.object.IdentityObjectMorpher; import net.sf.json.processors.JsonBeanProcessor; import net.sf.json.processors.JsonValueProcessor; import net.sf.json.processors.JsonVerifier; import net.sf.json.processors.PropertyNameProcessor; import net.sf.json.regexp.RegexpUtils; import net.sf.json.util.CycleDetectionStrategy; import net.sf.json.util.EnumMorpher; import net.sf.json.util.JSONTokener; import net.sf.json.util.JSONUtils; import net.sf.json.util.PropertyFilter; import net.sf.json.util.PropertySetStrategy; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.DynaProperty; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.map.ListOrderedMap; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A JSONObject is an unordered collection of name/value pairs. Its external * form is a string wrapped in curly braces with colons between the names and * values, and commas between the values and names. The internal form is an * object having get and opt methods for accessing * the values by name, and put methods for adding or replacing * values by name. The values can be any of these types: Boolean, * JSONArray, JSONObject, Number, * String, or the JSONNull object. A JSONObject * constructor can be used to convert an external form JSON text into an * internal form whose values can be retrieved with the get and * opt methods, or to convert values into a JSON text using the * element and toString methods. A * get method returns a value if one can be found, and throws an * exception if one cannot be found. An opt method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. *

* The generic get() and opt() methods return an * object, which you can cast or query for type. There are also typed * get and opt methods that do type checking and * type coercion for you. *

* The put methods adds values to an object. For example, * *

 *     myString = new JSONObject().put("JSON", "Hello, World!").toString();
* * produces the string {"JSON": "Hello, World"}. *

* The texts produced by the toString methods strictly conform to * the JSON syntax rules. The constructors are more forgiving in the texts they * will accept: *

    *
  • An extra , (comma) may appear just * before the closing brace.
  • *
  • Strings may be quoted with ' (single quote).
  • *
  • Strings do not need to be quoted at all if they do not begin with a * quote or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * { } [ ] / \ : , = ; # and if they do not look like numbers and * if they are not the reserved words true, false, * or null.
  • *
  • Keys can be followed by = or => as well as * by :.
  • *
  • Values can be followed by ; (semicolon) * as well as by , (comma).
  • *
  • Numbers may have the 0- (octal) or * 0x- (hex) prefix.
  • *
  • Comments written in the slashshlash, slashstar, and hash conventions * will be ignored.
  • *
* * @author JSON.org */ public final class JSONObject extends AbstractJSON implements JSON, Map, Comparable { private static final Log log = LogFactory.getLog( JSONObject.class ); /** * Creates a JSONObject.
* Inspects the object type to call the correct JSONObject factory method. * Accepts JSON formatted strings, Maps, DynaBeans and JavaBeans. * * @param object * @throws JSONException if the object can not be converted to a proper * JSONObject. */ public static JSONObject fromObject( Object object ) { return fromObject( object, new JsonConfig() ); } /** * Creates a JSONObject.
* Inspects the object type to call the correct JSONObject factory method. * Accepts JSON formatted strings, Maps, DynaBeans and JavaBeans. * * @param object * @throws JSONException if the object can not be converted to a proper * JSONObject. */ public static JSONObject fromObject( Object object, JsonConfig jsonConfig ) { if( object == null || JSONUtils.isNull( object ) ){ return new JSONObject( true ); }else if( object instanceof Enum ){ throw new JSONException( "'object' is an Enum. Use JSONArray instead" ); }else if(object instanceof Annotation || (object.getClass().isAnnotation())){ throw new JSONException( "'object' is an Annotation." ); }else if( object instanceof JSONObject ){ return _fromJSONObject( (JSONObject) object, jsonConfig ); }else if( object instanceof DynaBean ){ return _fromDynaBean( (DynaBean) object, jsonConfig ); }else if( object instanceof JSONTokener ){ return _fromJSONTokener( (JSONTokener) object, jsonConfig ); }else if( object instanceof JSONString ){ return _fromJSONString( (JSONString) object, jsonConfig ); }else if( object instanceof Map ){ return _fromMap( (Map) object, jsonConfig ); }else if( object instanceof String ){ return _fromString( (String) object, jsonConfig ); }else if( JSONUtils.isNumber( object ) || JSONUtils.isBoolean( object ) || JSONUtils.isString( object ) ){ return new JSONObject(); }else if( JSONUtils.isArray( object ) ){ throw new JSONException( "'object' is an array. Use JSONArray instead" ); }else{ return _fromBean( object, jsonConfig ); } } /** * Creates a JSONDynaBean from a JSONObject. */ public Object toBean() { return toBean(this); } public static Object toBean( JSONObject jsonObject ) { if( jsonObject == null || jsonObject.isNullObject() ){ return null; } DynaBean dynaBean; JsonConfig jsonConfig = new JsonConfig(); Map props = JSONUtils.getProperties( jsonObject ); dynaBean = JSONUtils.newDynaBean( jsonObject, jsonConfig ); for( Iterator entries = jsonObject.names( jsonConfig ) .iterator(); entries.hasNext(); ){ String name = (String) entries.next(); String key = JSONUtils.convertToJavaIdentifier( name, jsonConfig ); Class type = (Class) props.get( name ); Object value = jsonObject.get( name ); try{ if( !JSONUtils.isNull( value ) ){ if( value instanceof JSONArray ){ dynaBean.set( key, JSONArray.toCollection( (JSONArray) value ) ); }else if( String.class.isAssignableFrom( type ) || Boolean.class.isAssignableFrom( type ) || JSONUtils.isNumber( type ) || Character.class.isAssignableFrom( type ) || JSONFunction.class.isAssignableFrom( type ) ){ dynaBean.set( key, value ); }else{ dynaBean.set( key, toBean( (JSONObject) value ) ); } }else{ if( type.isPrimitive() ){ // assume assigned default value log.warn( "Tried to assign null value to " + key + ":" + type.getName() ); dynaBean.set( key, JSONUtils.getMorpherRegistry() .morph( type, null ) ); }else{ dynaBean.set( key, null ); } } }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( "Error while setting property=" + name + " type" + type, e ); } } return dynaBean; } public Object toBean( Class beanClass ) { return toBean(this,beanClass); } /** * Creates a bean from a JSONObject, with a specific target class.
*/ public static Object toBean( JSONObject jsonObject, Class beanClass ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( beanClass ); return toBean( jsonObject, jsonConfig ); } /** * Creates a bean from a JSONObject, with a specific target class.
* If beanClass is null, this method will return a graph of DynaBeans. Any * attribute that is a JSONObject and matches a key in the classMap will be * converted to that target class.
* The classMap has the following conventions: *
    *
  • Every key must be an String.
  • *
  • Every value must be a Class.
  • *
  • A key may be a regular expression.
  • *
*/ public static Object toBean( JSONObject jsonObject, Class beanClass, Map classMap ) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( beanClass ); jsonConfig.setClassMap( classMap ); return toBean( jsonObject, jsonConfig ); } private interface Property { boolean isWritable(); Class getPropertyType(); String name(); void set(Object bean, Object value, JsonConfig jsonConfig) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException; } private static class PropertyOnMap implements Property { private final String name; private PropertyOnMap(String name) { this.name = name; } public boolean isWritable() { return true; } public String name() { return name; } public Class getPropertyType() { return Object.class; } public void set(Object bean, Object value, JsonConfig jsonConfig) { ((Map)bean).put(name,value); } } private static class MethodProperty implements Property { private final PropertyDescriptor pd; private MethodProperty(PropertyDescriptor pd) { this.pd = pd; } public boolean isWritable() { return pd.getWriteMethod() != null; } public String name() { return pd.getName(); } public Class getPropertyType() { return pd.getPropertyType(); } public void set(Object bean, Object value, JsonConfig jsonConfig) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { PropertyUtils.setSimpleProperty( bean, pd.getName(), value ); } } private static class FieldProperty implements Property { private final Field f; private FieldProperty(Field f) { this.f = f; } public boolean isWritable() { return true; } public Class getPropertyType() { return f.getType(); } public String name() { return f.getName(); } public void set(Object bean, Object value, JsonConfig jsonConfig) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { f.set(bean,value); } } /** * Uses {@link PropertySetStrategy} instead of the normal set method. */ private static class PropertySetterStrategyDecorator implements Property { private final Property inner; private final PropertySetStrategy strategy; private PropertySetterStrategyDecorator(Property inner, PropertySetStrategy strategy) { this.inner = inner; this.strategy = strategy; } public boolean isWritable() { return inner.isWritable(); } public Class getPropertyType() { return inner.getPropertyType(); } public String name() { return inner.name(); } public void set(Object bean, Object value, JsonConfig jsonConfig) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { strategy.setProperty( bean, name(), value, jsonConfig ); } } /** * Creates a bean from a JSONObject, with the specific configuration. */ public static Object toBean( JSONObject jsonObject, JsonConfig jsonConfig ) { if( jsonObject == null || jsonObject.isNullObject() ){ return null; } Class beanClass = jsonConfig.getRootClass(); if( beanClass == null ){ return toBean( jsonObject ); } Object bean; try{ if( beanClass.isInterface() ){ if( !Map.class.isAssignableFrom( beanClass ) ){ throw new JSONException( "beanClass is an interface. " + beanClass ); }else{ bean = new HashMap(); } }else{ bean = jsonConfig.getNewBeanInstanceStrategy() .newInstance( beanClass, jsonObject ); } }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( e ); } return toBean(jsonObject,bean,jsonConfig); } private static Property getProperty(Class beanClass, Object bean, String key, JsonConfig jsonConfig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { key = jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? key : JSONUtils.convertToJavaIdentifier( key, jsonConfig ); try { if (!jsonConfig.isIgnorePublicFields()) return new FieldProperty(bean.getClass().getField(key)); } catch (NoSuchFieldException e) { // fall through } PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key); if (pd!=null) return new MethodProperty(pd); if( Map.class.isAssignableFrom( beanClass )) return new PropertyOnMap(key); return null; } /** * Creates a bean from a JSONObject, with the specific configuration. */ public static Object toBean( JSONObject jsonObject, Object bean, JsonConfig jsonConfig ) { if( jsonObject == null || jsonObject.isNullObject() || bean == null ){ return bean; } Class rootClass = bean.getClass(); Class beanClass = rootClass; Map classMap = jsonConfig.getClassMap(); if( classMap == null ){ classMap = Collections.EMPTY_MAP; } Map props = JSONUtils.getProperties( jsonObject ); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for( Iterator entries = jsonObject.names( jsonConfig ) .iterator(); entries.hasNext(); ){ String name = (String) entries.next(); Class type = (Class) props.get( name ); Object value = jsonObject.get( name ); if( javaPropertyFilter != null && javaPropertyFilter.apply( bean, name, value ) ){ continue; } String key = Map.class.isAssignableFrom( beanClass ) && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name : JSONUtils.convertToJavaIdentifier( name, jsonConfig ); PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor( beanClass ); if( propertyNameProcessor != null ){ key = propertyNameProcessor.processPropertyName( beanClass, key ); } try{ Property pd = getProperty(rootClass,bean,key,jsonConfig); if( pd != null ){ if( !pd.isWritable() ){ log.info( "Property '" + key + "' of "+ bean.getClass()+" has no write method. SKIPPED." ); continue; } if (jsonConfig.getPropertySetStrategy()!=null) pd = new PropertySetterStrategyDecorator(pd,jsonConfig.getPropertySetStrategy()); Class targetType = pd.getPropertyType(); if( !JSONUtils.isNull( value ) ){ if( value instanceof JSONArray ){ if( List.class.isAssignableFrom( pd.getPropertyType() ) ){ pd.set( bean, convertPropertyValueToCollection( key, value, jsonConfig, name, classMap, pd.getPropertyType() ), jsonConfig); }else if( Set.class.isAssignableFrom( pd.getPropertyType() ) ){ pd.set( bean, convertPropertyValueToCollection( key, value, jsonConfig, name, classMap, pd.getPropertyType() ), jsonConfig); }else{ pd.set( bean, convertPropertyValueToArray( key, value, targetType, jsonConfig, classMap ), jsonConfig); } }else if( String.class.isAssignableFrom( type ) || JSONUtils.isBoolean( type ) || JSONUtils.isNumber( type ) || JSONUtils.isString( type ) || JSONFunction.class.isAssignableFrom( type ) ){ if( pd != null ){ if( jsonConfig.isHandleJettisonEmptyElement() && "".equals( value ) ){ pd.set( bean, null, jsonConfig ); }else if( !targetType.isInstance( value ) ){ pd.set( bean, morphPropertyValue( key, value, type, targetType ), jsonConfig ); }else{ pd.set( bean, value, jsonConfig ); } }else if( beanClass == null || bean instanceof Map ){ pd.set( bean, value, jsonConfig ); }else{ log.warn( "Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass() .getName() ); } }else{ if( jsonConfig.isHandleJettisonSingleElementArray() ){ JSONArray array = new JSONArray().element( value, jsonConfig ); Class newTargetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( newTargetClass ); jsc.setClassMap( classMap ); if( targetType.isArray() ){ pd.set( bean, JSONArray.toArray( array, jsc ), jsonConfig ); }else if( JSONArray.class.isAssignableFrom( targetType ) ){ pd.set( bean, array, jsonConfig ); }else if( List.class.isAssignableFrom( targetType ) || Set.class.isAssignableFrom( targetType ) ){ jsc.setCollectionType( targetType ); pd.set( bean, JSONArray.toCollection( array, jsc ), jsonConfig ); }else{ pd.set( bean, toBean( (JSONObject) value, jsc ), jsonConfig ); } }else{ if( targetType == Object.class || targetType.isInterface() ) { Class targetTypeCopy = targetType; targetType = findTargetClass( key, classMap ); targetType = targetType == null ? findTargetClass( name, classMap ) : targetType; targetType = targetType == null && targetTypeCopy.isInterface() ? targetTypeCopy : targetType; } JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( targetType ); jsc.setClassMap( classMap ); pd.set( bean, toBean( (JSONObject) value, jsc ), jsonConfig ); } } }else{ if( type.isPrimitive() ){ // assume assigned default value log.warn( "Tried to assign null value to " + key + ":" + type.getName() ); pd.set( bean, JSONUtils.getMorpherRegistry() .morph( type, null ), jsonConfig ); }else{ pd.set( bean, null, jsonConfig ); } } }else{ if( !JSONUtils.isNull( value ) ){ if( value instanceof JSONArray ){ setProperty( bean, name, convertPropertyValueToCollection( key, value, jsonConfig, name, classMap, List.class ), jsonConfig ); }else if( String.class.isAssignableFrom( type ) || JSONUtils.isBoolean( type ) || JSONUtils.isNumber( type ) || JSONUtils.isString( type ) || JSONFunction.class.isAssignableFrom( type ) ){ if( beanClass == null || bean instanceof Map || jsonConfig.getPropertySetStrategy() != null || !jsonConfig.isIgnorePublicFields() ){ setProperty( bean, name, value, jsonConfig ); }else{ log.warn( "Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass() .getName() ); } }else{ if( jsonConfig.isHandleJettisonSingleElementArray() ){ Class newTargetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( newTargetClass ); jsc.setClassMap( classMap ); setProperty( bean, name, toBean( (JSONObject) value, jsc ), jsonConfig ); }else{ setProperty( bean, name, value, jsonConfig ); } } }else{ if( type.isPrimitive() ){ // assume assigned default value log.warn( "Tried to assign null value to " + key + ":" + type.getName() ); setProperty( bean, name, JSONUtils.getMorpherRegistry() .morph( type, null ), jsonConfig ); }else{ setProperty( bean, name, null, jsonConfig ); } } } }catch( JSONException jsone ){ throw jsone; }catch( Exception e ){ throw new JSONException( "Error while setting property=" + name + " type " + type, e ); } } return bean; } /** * Creates a JSONObject from a POJO.
* Supports nested maps, POJOs, and arrays/collections. * * @param bean An object with POJO conventions * @throws JSONException if the bean can not be converted to a proper * JSONObject. */ private static JSONObject _fromBean( Object bean, JsonConfig jsonConfig ) { if( !addInstance( bean ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsObject( bean ); }catch( JSONException jsone ){ removeInstance( bean ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( bean ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireObjectStartEvent( jsonConfig ); JsonBeanProcessor processor = jsonConfig.findJsonBeanProcessor( bean.getClass() ); if( processor != null ){ JSONObject json = null; try{ json = processor.processBean( bean, jsonConfig ); if( json == null ){ json = (JSONObject) jsonConfig.findDefaultValueProcessor( bean.getClass() ) .getDefaultValue( bean.getClass() ); if( json == null ){ json = new JSONObject( true ); } } removeInstance( bean ); fireObjectEndEvent( jsonConfig ); }catch( JSONException jsone ){ removeInstance( bean ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( bean ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } return json; } JSONObject jsonObject = defaultBeanProcessing(bean, jsonConfig); removeInstance( bean ); fireObjectEndEvent( jsonConfig ); return jsonObject; } private static JSONObject defaultBeanProcessing(Object bean, JsonConfig jsonConfig) { Class beanClass = bean.getClass(); PropertyNameProcessor propertyNameProcessor = jsonConfig.findJsonPropertyNameProcessor( beanClass ); Collection exclusions = jsonConfig.getMergedExcludes( beanClass ); JSONObject jsonObject = new JSONObject(); try{ PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors( bean ); PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter(); for( int i = 0; i < pds.length; i++ ){ boolean bypass = false; String key = pds[i].getName(); if( exclusions.contains( key ) ){ continue; } if( jsonConfig.isIgnoreTransientFields() && isTransientField( key, beanClass, jsonConfig ) ){ continue; } Class type = pds[i].getPropertyType(); try { pds[i].getReadMethod(); } catch( Exception e ) { // bug 2565295 String warning = "Property '" + key + "' of "+ beanClass+" has no read method. SKIPPED"; fireWarnEvent( warning, jsonConfig ); log.info( warning ); continue; } if( pds[i].getReadMethod() != null ){ /* if( jsonConfig.isIgnoreJPATransient() ){ try{ Class transientClass = Class.forName( "javax.persistence.Transient" ); if( pds[i].getReadMethod() .getAnnotation( transientClass ) != null ){ continue; } }catch( ClassNotFoundException cnfe ){ // ignore } } */ if(isTransient(pds[i].getReadMethod(), jsonConfig)) continue; Object value = PropertyUtils.getProperty( bean, key ); if( jsonPropertyFilter != null && jsonPropertyFilter.apply( bean, key, value ) ){ continue; } JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor( beanClass, type, key ); if( jsonValueProcessor != null ){ value = jsonValueProcessor.processObjectValue( key, value, jsonConfig ); bypass = true; if( !JsonVerifier.isValidJsonValue( value ) ){ throw new JSONException( "Value is not a valid JSON value. " + value ); } } if( propertyNameProcessor != null ){ key = propertyNameProcessor.processPropertyName( beanClass, key ); } setValue( jsonObject, key, value, type, jsonConfig, bypass ); }else{ String warning = "Property '" + key + "' of "+ beanClass+" has no read method. SKIPPED"; fireWarnEvent( warning, jsonConfig ); log.info( warning ); } } // inspect public fields, this operation may fail under // a SecurityManager so we will eat all exceptions try { if( !jsonConfig.isIgnorePublicFields() ) { Field[] fields = beanClass.getFields(); for( int i = 0; i < fields.length; i++ ) { boolean bypass = false; Field field = fields[i]; String key = field.getName(); if( exclusions.contains( key ) ) { continue; } if (Modifier.isStatic(field.getModifiers())) { continue; } if( jsonConfig.isIgnoreTransientFields() && isTransientField(field, jsonConfig) ) { continue; } Class type = field.getType(); Object value = field.get( bean ); if( jsonPropertyFilter != null && jsonPropertyFilter.apply( bean, key, value ) ) { continue; } JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor( beanClass, type, key ); if( jsonValueProcessor != null ) { value = jsonValueProcessor.processObjectValue( key, value, jsonConfig ); bypass = true; if( !JsonVerifier.isValidJsonValue( value ) ) { throw new JSONException( "Value is not a valid JSON value. " + value ); } } if( propertyNameProcessor != null ) { key = propertyNameProcessor.processPropertyName( beanClass, key ); } setValue( jsonObject, key, value, type, jsonConfig, bypass ); } } } catch( Exception e ){ log.trace( "Couldn't read public fields.", e ); } }catch( JSONException jsone ){ removeInstance( bean ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( Exception e ){ removeInstance( bean ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } return jsonObject; } private static JSONObject _fromDynaBean( DynaBean bean, JsonConfig jsonConfig ) { if( bean == null ){ fireObjectStartEvent( jsonConfig ); fireObjectEndEvent( jsonConfig ); return new JSONObject( true ); } if( !addInstance( bean ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsObject( bean ); }catch( JSONException jsone ){ removeInstance( bean ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( bean ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireObjectStartEvent( jsonConfig ); JSONObject jsonObject = new JSONObject(); try{ DynaProperty[] props = bean.getDynaClass() .getDynaProperties(); Collection exclusions = jsonConfig.getMergedExcludes(); PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter(); for( int i = 0; i < props.length; i++ ){ boolean bypass = false; DynaProperty dynaProperty = props[i]; String key = dynaProperty.getName(); if( exclusions.contains( key ) ){ continue; } Class type = dynaProperty.getType(); Object value = bean.get( dynaProperty.getName() ); if( jsonPropertyFilter != null && jsonPropertyFilter.apply( bean, key, value ) ){ continue; } JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor( type, key ); if( jsonValueProcessor != null ){ value = jsonValueProcessor.processObjectValue( key, value, jsonConfig ); bypass = true; if( !JsonVerifier.isValidJsonValue( value ) ){ throw new JSONException( "Value is not a valid JSON value. " + value ); } } setValue( jsonObject, key, value, type, jsonConfig, bypass ); } }catch( JSONException jsone ){ removeInstance( bean ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( bean ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( bean ); fireObjectEndEvent( jsonConfig ); return jsonObject; } private static JSONObject _fromJSONObject( JSONObject object, JsonConfig jsonConfig ) { if( object == null || object.isNullObject() ){ fireObjectStartEvent( jsonConfig ); fireObjectEndEvent( jsonConfig ); return new JSONObject( true ); } if( !addInstance( object ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsObject( object ); }catch( JSONException jsone ){ removeInstance( object ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( object ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireObjectStartEvent( jsonConfig ); JSONArray sa = object.names(jsonConfig); Collection exclusions = jsonConfig.getMergedExcludes(); JSONObject jsonObject = new JSONObject(); PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter(); for( Iterator i = sa.iterator(); i.hasNext(); ){ Object k = i.next(); if( k == null ){ throw new JSONException("JSON keys cannot be null."); } if( !(k instanceof String) && !jsonConfig.isAllowNonStringKeys() ) { throw new ClassCastException("JSON keys must be strings."); } String key = String.valueOf( k ); if( "null".equals( key )){ throw new NullPointerException("JSON keys must not be null nor the 'null' string."); } if( exclusions.contains( key ) ){ continue; } Object value = object.opt( key ); if( jsonPropertyFilter != null && jsonPropertyFilter.apply( object, key, value ) ){ continue; } if( jsonObject.properties.containsKey( key ) ){ jsonObject.accumulate( key, value, jsonConfig ); firePropertySetEvent( key, value, true, jsonConfig ); }else{ jsonObject.setInternal( key, value, jsonConfig ); firePropertySetEvent( key, value, false, jsonConfig ); } } removeInstance( object ); fireObjectEndEvent( jsonConfig ); return jsonObject; } private static JSONObject _fromJSONString( JSONString string, JsonConfig jsonConfig ) { return _fromJSONTokener( new JSONTokener( string.toJSONString() ), jsonConfig ); } private static JSONObject _fromJSONTokener( JSONTokener tokener, JsonConfig jsonConfig ) { try{ char c; String key; Object value; if( tokener.matches( "null.*" ) ){ fireObjectStartEvent( jsonConfig ); fireObjectEndEvent( jsonConfig ); return new JSONObject( true ); } if( tokener.nextClean() != '{' ){ throw tokener.syntaxError( "A JSONObject text must begin with '{'" ); } fireObjectStartEvent( jsonConfig ); Collection exclusions = jsonConfig.getMergedExcludes(); PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter(); JSONObject jsonObject = new JSONObject(); for( ;; ){ c = tokener.nextClean(); switch( c ){ case 0: throw tokener.syntaxError( "A JSONObject text must end with '}'" ); case '}': fireObjectEndEvent( jsonConfig ); return jsonObject; default: tokener.back(); key = tokener.nextValue( jsonConfig ) .toString(); } /* * The key is followed by ':'. We will also tolerate '=' or '=>'. */ c = tokener.nextClean(); if( c == '=' ){ if( tokener.next() != '>' ){ tokener.back(); } }else if( c != ':' ){ throw tokener.syntaxError( "Expected a ':' after a key" ); } char peek = tokener.peek(); boolean quoted = peek == '"' || peek == '\''; Object v = tokener.nextValue( jsonConfig ); if( quoted || !JSONUtils.isFunctionHeader( v ) ){ if( exclusions.contains( key ) ){ switch( tokener.nextClean() ){ case ';': case ',': if( tokener.nextClean() == '}' ){ fireObjectEndEvent( jsonConfig ); return jsonObject; } tokener.back(); break; case '}': fireObjectEndEvent( jsonConfig ); return jsonObject; default: throw tokener.syntaxError( "Expected a ',' or '}'" ); } continue; } if( jsonPropertyFilter == null || !jsonPropertyFilter.apply( tokener, key, v ) ){ if( jsonObject.properties.containsKey( key ) ){ jsonObject.accumulate( key, v, jsonConfig ); firePropertySetEvent( key, v, true, jsonConfig ); }else{ jsonObject.element( key, v, jsonConfig ); firePropertySetEvent( key, v, false, jsonConfig ); } } }else{ // read params if any String params = JSONUtils.getFunctionParams( (String) v ); // read function text int i = 0; StringBuffer sb = new StringBuffer(); for( ;; ){ char ch = tokener.next(); if( ch == 0 ){ break; } if( ch == '{' ){ i++; } if( ch == '}' ){ i--; } sb.append( ch ); if( i == 0 ){ break; } } if( i != 0 ){ throw tokener.syntaxError( "Unbalanced '{' or '}' on prop: " + v ); } // trim '{' at start and '}' at end String text = sb.toString(); text = text.substring( 1, text.length() - 1 ) .trim(); value = new JSONFunction( (params != null) ? StringUtils.split( params, "," ) : null, text ); if( jsonPropertyFilter == null || !jsonPropertyFilter.apply( tokener, key, value ) ){ if( jsonObject.properties.containsKey( key ) ){ jsonObject.accumulate( key, value, jsonConfig ); firePropertySetEvent( key, value, true, jsonConfig ); }else{ jsonObject.element( key, value, jsonConfig ); firePropertySetEvent( key, value, false, jsonConfig ); } } } /* * Pairs are separated by ','. We will also tolerate ';'. */ switch( tokener.nextClean() ){ case ';': case ',': if( tokener.nextClean() == '}' ){ fireObjectEndEvent( jsonConfig ); return jsonObject; } tokener.back(); break; case '}': fireObjectEndEvent( jsonConfig ); return jsonObject; default: throw tokener.syntaxError( "Expected a ',' or '}'" ); } } }catch( JSONException jsone ){ fireErrorEvent( jsone, jsonConfig ); throw jsone; } } private static JSONObject _fromMap( Map map, JsonConfig jsonConfig ) { if( map == null ){ fireObjectStartEvent( jsonConfig ); fireObjectEndEvent( jsonConfig ); return new JSONObject( true ); } if( !addInstance( map ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsObject( map ); }catch( JSONException jsone ){ removeInstance( map ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( map ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireObjectStartEvent( jsonConfig ); Collection exclusions = jsonConfig.getMergedExcludes(); JSONObject jsonObject = new JSONObject(); PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter(); try{ for( Iterator entries = map.entrySet() .iterator(); entries.hasNext(); ){ boolean bypass = false; Map.Entry entry = (Map.Entry) entries.next(); Object k = entry.getKey(); if( k == null ){ throw new JSONException("JSON keys cannot be null."); } if( !(k instanceof String) && !jsonConfig.isAllowNonStringKeys() ) { throw new ClassCastException("JSON keys must be strings."); } String key = String.valueOf( k ); if( "null".equals( key )){ throw new NullPointerException("JSON keys must not be null nor the 'null' string."); } if( exclusions.contains( key ) ){ continue; } Object value = entry.getValue(); if( jsonPropertyFilter != null && jsonPropertyFilter.apply( map, key, value ) ){ continue; } if( value != null ){ JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor( value.getClass(), key ); if( jsonValueProcessor != null ){ value = jsonValueProcessor.processObjectValue( key, value, jsonConfig ); bypass = true; if( !JsonVerifier.isValidJsonValue( value ) ){ throw new JSONException( "Value is not a valid JSON value. " + value ); } } setValue( jsonObject, key, value, value.getClass(), jsonConfig, bypass ); }else{ if( jsonObject.properties.containsKey( key ) ){ jsonObject.accumulate( key, JSONNull.getInstance() ); firePropertySetEvent( key, JSONNull.getInstance(), true, jsonConfig ); }else{ jsonObject.element( key, JSONNull.getInstance() ); firePropertySetEvent( key, JSONNull.getInstance(), false, jsonConfig ); } } } }catch( JSONException jsone ){ removeInstance( map ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( map ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( map ); fireObjectEndEvent( jsonConfig ); return jsonObject; } private static JSONObject _fromString( String str, JsonConfig jsonConfig ) { if( str == null || "null".equals( str ) ){ fireObjectStartEvent( jsonConfig ); fireObjectEndEvent( jsonConfig ); return new JSONObject( true ); } return _fromJSONTokener( new JSONTokener( str ), jsonConfig ); } private static Object convertPropertyValueToArray( String key, Object value, Class targetType, JsonConfig jsonConfig, Map classMap ) { Class innerType = JSONUtils.getInnerComponentType( targetType ); Class targetInnerType = findTargetClass( key, classMap ); if( innerType.equals( Object.class ) && targetInnerType != null && !targetInnerType.equals( Object.class ) ){ innerType = targetInnerType; } JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( innerType ); jsc.setClassMap( classMap ); Object array = JSONArray.toArray( (JSONArray) value, jsc ); if( innerType.isPrimitive() || JSONUtils.isNumber( innerType ) || Boolean.class.isAssignableFrom( innerType ) || JSONUtils.isString( innerType ) ){ array = JSONUtils.getMorpherRegistry() .morph( Array.newInstance( innerType, 0 ) .getClass(), array ); }else if( !array.getClass() .equals( targetType ) ){ if( !targetType.equals( Object.class ) ){ Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor( Array.newInstance( innerType, 0 ) .getClass() ); if( IdentityObjectMorpher.getInstance() .equals( morpher ) ){ ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher( new BeanMorpher( innerType, JSONUtils.getMorpherRegistry() ) ); JSONUtils.getMorpherRegistry() .registerMorpher( beanMorpher ); } array = JSONUtils.getMorpherRegistry() .morph( Array.newInstance( innerType, 0 ) .getClass(), array ); } } return array; } private static List convertPropertyValueToList( String key, Object value, JsonConfig jsonConfig, String name, Map classMap ) { Class targetClass = findTargetClass( key, classMap ); targetClass = targetClass == null ? findTargetClass( name, classMap ) : targetClass; JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( targetClass ); jsc.setClassMap( classMap ); List list = (List) JSONArray.toCollection( (JSONArray) value, jsc ); return list; } private static Collection convertPropertyValueToCollection( String key, Object value, JsonConfig jsonConfig, String name, Map classMap, Class collectionType ) { Class targetClass = findTargetClass( key, classMap ); targetClass = targetClass == null ? findTargetClass( name, classMap ) : targetClass; JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( targetClass ); jsc.setClassMap( classMap ); jsc.setCollectionType( collectionType ); return JSONArray.toCollection( (JSONArray) value, jsc ); } /* private static Collection convertPropertyValueToCollection( String key, Object value, JsonConfig jsonConfig, String name, Map classMap, Object bean ) { Class targetClass = findTargetClass( key, classMap ); targetClass = targetClass == null ? findTargetClass( name, classMap ) : targetClass; PropertyDescriptor pd; try{ pd = PropertyUtils.getPropertyDescriptor( bean, key ); }catch( IllegalAccessException e ){ throw new JSONException( e ); }catch( InvocationTargetException e ){ throw new JSONException( e ); }catch( NoSuchMethodException e ){ throw new JSONException( e ); } if( null == targetClass ){ Class[] cType = JSONArray.getCollectionType( pd, false ); if( null != cType && cType.length == 1 ){ targetClass = cType[0]; } } JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass( targetClass ); jsc.setClassMap( classMap ); jsc.setCollectionType( pd.getPropertyType() ); jsc.setEnclosedType( targetClass ); Collection collection = JSONArray.toCollection( (JSONArray) value, jsonConfig ); return collection; } */ private static Class resolveClass(Map classMap, String key, String name, Class type) { Class targetClass = findTargetClass(key, classMap); if (targetClass == null) { targetClass = findTargetClass(name, classMap); } if(targetClass == null && type != null) { if(List.class.equals(type)) { targetClass = ArrayList.class; } else if(Map.class.equals(type)) { targetClass = LinkedHashMap.class; } else if(Set.class.equals(type)) { targetClass = LinkedHashSet.class; } else if(!type.isInterface() && !Object.class.equals(type)) { targetClass = type; } } return targetClass; } /** * Locates a Class associated to a specifi key.
* The key may be a regexp. */ private static Class findTargetClass( String key, Map classMap ) { // try get first Class targetClass = (Class) classMap.get( key ); if( targetClass == null ){ // try with regexp // this will hit performance as it must iterate over all the keys // and create a RegexpMatcher for each key for( Iterator i = classMap.entrySet() .iterator(); i.hasNext(); ){ Map.Entry entry = (Map.Entry) i.next(); if( RegexpUtils.getMatcher( (String) entry.getKey() ) .matches( key ) ){ targetClass = (Class) entry.getValue(); break; } } } return targetClass; } private static boolean isTransientField( String name, Class beanClass, JsonConfig jsonConfig ) { try{ return isTransientField(beanClass.getDeclaredField(name), jsonConfig); }catch( Exception e ){ log.info( "Error while inspecting field "+beanClass+"."+name+" for transient status." ,e ); } return false; } private static boolean isTransientField( Field field, JsonConfig jsonConfig ) { try{ if((field.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT) return true; return isTransient(field, jsonConfig); }catch( Exception e ){ log.info( "Error while inspecting field "+field+" for transient status." ,e ); } return false; } private static boolean isTransient( AnnotatedElement element, JsonConfig jsonConfig ) { for( Iterator annotations = jsonConfig.getIgnoreFieldAnnotations().iterator(); annotations.hasNext(); ) { try { String annotationClassName = (String) annotations.next(); if( element.getAnnotation((Class) Class.forName( annotationClassName )) != null ) return true; } catch( Exception e ){ log.info( "Error while inspecting "+element+" for transient status." ,e ); } } return false; } private static Object morphPropertyValue( String key, Object value, Class type, Class targetType ) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor( targetType ); if( IdentityObjectMorpher.getInstance() .equals( morpher ) ){ log.warn( "Can't transform property '" + key + "' from " + type.getName() + " into " + targetType.getName() + ". Will register a default Morpher" ); if( Enum.class.isAssignableFrom( targetType ) ){ JSONUtils.getMorpherRegistry() .registerMorpher( new EnumMorpher( targetType ) ); }else{ JSONUtils.getMorpherRegistry() .registerMorpher( new BeanMorpher( targetType, JSONUtils.getMorpherRegistry() ) ); } } value = JSONUtils.getMorpherRegistry() .morph( targetType, value ); return value; } /** * Sets a property on the target bean.
* Bean may be a Map or a POJO. */ private static void setProperty( Object bean, String key, Object value, JsonConfig jsonConfig ) throws Exception { PropertySetStrategy propertySetStrategy = jsonConfig.getPropertySetStrategy() != null ? jsonConfig.getPropertySetStrategy() : PropertySetStrategy.DEFAULT; propertySetStrategy.setProperty( bean, key, value, jsonConfig ); } private static void setValue( JSONObject jsonObject, String key, Object value, Class type, JsonConfig jsonConfig, boolean bypass ) { boolean accumulated = false; if( value == null ){ value = jsonConfig.findDefaultValueProcessor( type ) .getDefaultValue( type ); if( !JsonVerifier.isValidJsonValue( value ) ){ throw new JSONException( "Value is not a valid JSON value. " + value ); } } if( jsonObject.properties.containsKey( key ) ){ if( String.class.isAssignableFrom( type ) ){ Object o = jsonObject.opt( key ); if( o instanceof JSONArray ){ ((JSONArray) o).addString( (String) value ); }else{ jsonObject.properties.put( key, new JSONArray().element( o ) .addString( (String) value ) ); } }else{ jsonObject.accumulate( key, value, jsonConfig ); } accumulated = true; }else{ if( bypass || String.class.isAssignableFrom( type ) ){ jsonObject.properties.put( key, value ); }else{ jsonObject.setInternal( key, value, jsonConfig ); } } value = jsonObject.opt( key ); if( accumulated ){ JSONArray array = (JSONArray) value; value = array.get( array.size() - 1 ); } firePropertySetEvent( key, value, accumulated, jsonConfig ); } // ------------------------------------------------------ /** identifies this object as null */ private boolean nullObject; /** * The Map where the JSONObject's properties are kept. */ private Map properties; /** * Construct an empty JSONObject. */ public JSONObject() { this.properties = new ListOrderedMap(); } /** * Creates a JSONObject that is null. */ public JSONObject( boolean isNull ) { this(); this.nullObject = isNull; } /** * Accumulate values under a key. It is similar to the element method except * that if there is already an object stored under the key then a JSONArray * is stored under the key to hold all of the accumulated values. If there is * already a JSONArray, then the new value is appended to it. In contrast, * the replace method replaces the previous value. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is * null. */ public JSONObject accumulate( String key, boolean value ) { return _accumulate( key, value ? Boolean.TRUE : Boolean.FALSE, new JsonConfig() ); } /** * Accumulate values under a key. It is similar to the element method except * that if there is already an object stored under the key then a JSONArray * is stored under the key to hold all of the accumulated values. If there is * already a JSONArray, then the new value is appended to it. In contrast, * the replace method replaces the previous value. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is * null. */ public JSONObject accumulate( String key, double value ) { return _accumulate( key, Double.valueOf( value ), new JsonConfig() ); } /** * Accumulate values under a key. It is similar to the element method except * that if there is already an object stored under the key then a JSONArray * is stored under the key to hold all of the accumulated values. If there is * already a JSONArray, then the new value is appended to it. In contrast, * the replace method replaces the previous value. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is * null. */ public JSONObject accumulate( String key, int value ) { return _accumulate( key, Integer.valueOf( value ), new JsonConfig() ); } /** * Accumulate values under a key. It is similar to the element method except * that if there is already an object stored under the key then a JSONArray * is stored under the key to hold all of the accumulated values. If there is * already a JSONArray, then the new value is appended to it. In contrast, * the replace method replaces the previous value. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is * null. */ public JSONObject accumulate( String key, long value ) { return _accumulate( key, Long.valueOf( value ), new JsonConfig() ); } /** * Accumulate values under a key. It is similar to the element method except * that if there is already an object stored under the key then a JSONArray * is stored under the key to hold all of the accumulated values. If there is * already a JSONArray, then the new value is appended to it. In contrast, * the replace method replaces the previous value. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is * null. */ public JSONObject accumulate( String key, Object value ) { return _accumulate( key, value, new JsonConfig() ); } /** * Accumulate values under a key. It is similar to the element method except * that if there is already an object stored under the key then a JSONArray * is stored under the key to hold all of the accumulated values. If there is * already a JSONArray, then the new value is appended to it. In contrast, * the replace method replaces the previous value. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is * null. */ public JSONObject accumulate( String key, Object value, JsonConfig jsonConfig ) { return _accumulate( key, value, jsonConfig ); } public void accumulateAll( Map map ) { accumulateAll( map, new JsonConfig() ); } public void accumulateAll( Map map, JsonConfig jsonConfig ) { if( map instanceof JSONObject ){ for( Iterator entries = map.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); accumulate( key, value, jsonConfig ); } }else{ for( Iterator entries = map.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String key = String.valueOf( entry.getKey() ); Object value = entry.getValue(); accumulate( key, value, jsonConfig ); } } } public void clear() { properties.clear(); } public int compareTo( Object obj ) { if( obj != null && (obj instanceof JSONObject) ){ JSONObject other = (JSONObject) obj; int size1 = size(); int size2 = other.size(); if( size1 < size2 ){ return -1; }else if( size1 > size2 ){ return 1; }else if( this.equals( other ) ){ return 0; } } return -1; } public boolean containsKey( Object key ) { return properties.containsKey( key ); } public boolean containsValue( Object value ) { return containsValue( value, new JsonConfig() ); } public boolean containsValue( Object value, JsonConfig jsonConfig ) { try{ value = processValue( value, jsonConfig ); }catch( JSONException e ){ return false; } return properties.containsValue( value ); } /** * Remove a name and its value, if present. * * @param key A key string. * @return this. */ public JSONObject discard( String key ) { verifyIsNull(); this.properties.remove( key ); return this; } /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject element( String key, boolean value ) { verifyIsNull(); return element( key, value ? Boolean.TRUE : Boolean.FALSE ); } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject element( String key, Collection value ) { return element( key, value, new JsonConfig() ); } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject element( String key, Collection value, JsonConfig jsonConfig ) { if( !(value instanceof JSONArray) ){ value = JSONArray.fromObject( value, jsonConfig ); } return setInternal( key, value, jsonConfig ); } /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. * @return this. * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject element( String key, double value ) { verifyIsNull(); Double d = new Double( value ); JSONUtils.testValidity( d ); return element( key, d ); } /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject element( String key, int value ) { verifyIsNull(); return element( key, new Integer( value ) ); } /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject element( String key, long value ) { verifyIsNull(); return element( key, new Long( value ) ); } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject element( String key, Map value ) { return element( key, value, new JsonConfig() ); } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject element( String key, Map value, JsonConfig jsonConfig ) { verifyIsNull(); if( value instanceof JSONObject ){ return setInternal( key, value, jsonConfig ); }else{ return element( key, JSONObject.fromObject( value, jsonConfig ), jsonConfig ); } } /** * Put a key/value pair in the JSONObject. If the value is null, then the key * will be removed from the JSONObject if it is present.
* If there is a previous value assigned to the key, it will call accumulate. * * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, * String, or the JSONNull object. * @return this. * @throws JSONException If the value is non-finite number or if the key is * null. */ public JSONObject element( String key, Object value ) { return element( key, value, new JsonConfig() ); } /** * Put a key/value pair in the JSONObject. If the value is null, then the key * will be removed from the JSONObject if it is present.
* If there is a previous value assigned to the key, it will call accumulate. * * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, * String, or the JSONNull object. * @return this. * @throws JSONException If the value is non-finite number or if the key is * null. */ public JSONObject element( String key, Object value, JsonConfig jsonConfig ) { verifyIsNull(); if( key == null ){ throw new JSONException( "Null key." ); } if( value != null ){ value = processValue( key, value, jsonConfig ); _setInternal( key, value, jsonConfig ); }else{ remove( key ); } return this; } /** * Put a key/value pair in the JSONObject, but only if the key and the value * are both non-null. * * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, * String, or the JSONNull object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject elementOpt( String key, Object value ) { return elementOpt( key, value, new JsonConfig() ); } /** * Put a key/value pair in the JSONObject, but only if the key and the value * are both non-null. * * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, * String, or the JSONNull object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject elementOpt( String key, Object value, JsonConfig jsonConfig ) { verifyIsNull(); if( key != null && value != null ){ element( key, value, jsonConfig ); } return this; } public Set entrySet() { return Collections.unmodifiableSet( properties.entrySet() ); } public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null ){ return false; } if( !(obj instanceof JSONObject) ){ return false; } JSONObject other = (JSONObject) obj; if( isNullObject() ){ return other.isNullObject(); }else{ if( other.isNullObject() ){ return false; } } if( other.size() != size() ){ return false; } for( Iterator keys = properties.keySet() .iterator(); keys.hasNext(); ){ String key = (String) keys.next(); if( !other.properties.containsKey( key ) ){ return false; } Object o1 = properties.get( key ); Object o2 = other.properties.get( key ); if( JSONNull.getInstance() .equals( o1 ) ){ if( JSONNull.getInstance() .equals( o2 ) ){ continue; }else{ return false; } }else{ if( JSONNull.getInstance() .equals( o2 ) ){ return false; } } if( o1 instanceof String && o2 instanceof JSONFunction ){ if( !o1.equals( String.valueOf( o2 ) ) ){ return false; } }else if( o1 instanceof JSONFunction && o2 instanceof String ){ if( !o2.equals( String.valueOf( o1 ) ) ){ return false; } }else if( o1 instanceof JSONObject && o2 instanceof JSONObject ){ if( !o1.equals( o2 ) ){ return false; } }else if( o1 instanceof JSONArray && o2 instanceof JSONArray ){ if( !o1.equals( o2 ) ){ return false; } }else if( o1 instanceof JSONFunction && o2 instanceof JSONFunction ){ if( !o1.equals( o2 ) ){ return false; } }else{ if( o1 instanceof String ){ if( !o1.equals( String.valueOf( o2 ) ) ){ return false; } }else if( o2 instanceof String ){ if( !o2.equals( String.valueOf( o1 ) ) ){ return false; } }else{ Morpher m1 = JSONUtils.getMorpherRegistry() .getMorpherFor( o1.getClass() ); Morpher m2 = JSONUtils.getMorpherRegistry() .getMorpherFor( o2.getClass() ); if( m1 != null && m1 != IdentityObjectMorpher.getInstance() ){ if( !o1.equals( JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o2 ) ) ){ return false; } }else if( m2 != null && m2 != IdentityObjectMorpher.getInstance() ){ if( !JSONUtils.getMorpherRegistry() .morph( o1.getClass(), o1 ) .equals( o2 ) ){ return false; } }else{ if( !o1.equals( o2 ) ){ return false; } } } } } return true; } public Object get( Object key ) { if( key instanceof String ){ return get( (String) key ); } return null; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if this.isNull() returns true. */ public Object get( String key ) { verifyIsNull(); return this.properties.get( key ); } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws JSONException if the value is not a Boolean or the String "true" * or "false". */ public boolean getBoolean( String key ) { verifyIsNull(); Object o = get( key ); if( o != null ){ if( o.equals( Boolean.FALSE ) || (o instanceof String && ((String) o).equalsIgnoreCase( "false" )) ){ return false; }else if( o.equals( Boolean.TRUE ) || (o instanceof String && ((String) o).equalsIgnoreCase( "true" )) ){ return true; } } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a Boolean." ); } /** * Get the double value associated with a key. * * @param key A key string. * @return The numeric value. * @throws JSONException if the key is not found or if the value is not a * Number object and cannot be converted to a number. */ public double getDouble( String key ) { verifyIsNull(); Object o = get( key ); if( o != null ){ try{ return o instanceof Number ? ((Number) o).doubleValue() : Double.parseDouble( (String) o ); }catch( Exception e ){ throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a number." ); } } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a number." ); } /** * Get the int value associated with a key. If the number value is too large * for an int, it will be clipped. * * @param key A key string. * @return The integer value. * @throws JSONException if the key is not found or if the value cannot be * converted to an integer. */ public int getInt( String key ) { verifyIsNull(); Object o = get( key ); if( o != null ){ return o instanceof Number ? ((Number) o).intValue() : (int) getDouble( key ); } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a number." ); } /** * Get the JSONArray value associated with a key. * * @param key A key string. * @return A JSONArray which is the value. * @throws JSONException if the key is not found or if the value is not a * JSONArray. */ public JSONArray getJSONArray( String key ) { verifyIsNull(); Object o = get( key ); if( o != null && o instanceof JSONArray ){ return (JSONArray) o; } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a JSONArray." ); } /** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or if the value is not a * JSONObject. */ public JSONObject getJSONObject( String key ) { verifyIsNull(); Object o = get( key ); if( JSONNull.getInstance() .equals( o ) ){ return new JSONObject( true ); }else if( o instanceof JSONObject ){ return (JSONObject) o; } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a JSONObject." ); } /** * Get the long value associated with a key. If the number value is too long * for a long, it will be clipped. * * @param key A key string. * @return The long value. * @throws JSONException if the key is not found or if the value cannot be * converted to a long. */ public long getLong( String key ) { verifyIsNull(); Object o = get( key ); if( o != null ){ return o instanceof Number ? ((Number) o).longValue() : (long) getDouble( key ); } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a number." ); } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if the key is not found. */ public String getString( String key ) { verifyIsNull(); Object o = get( key ); if( o != null ){ return o.toString(); } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] not found." ); } /** * Determine if the JSONObject contains a specific key. * * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has( String key ) { verifyIsNull(); return this.properties.containsKey( key ); } public int hashCode() { int hashcode = 19; if( isNullObject() ){ return hashcode + JSONNull.getInstance() .hashCode(); } for( Iterator entries = properties.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); Object key = entry.getKey(); Object value = entry.getValue(); hashcode += key.hashCode() + JSONUtils.hashCode( value ); } return hashcode; } public boolean isArray() { return false; } public boolean isEmpty() { // verifyIsNull(); return this.properties.isEmpty(); } /** * Returs if this object is a null JSONObject. */ public boolean isNullObject() { return nullObject; } /** * Get an enumeration of the keys of the JSONObject. * * @return An iterator of the keys. */ public Iterator keys() { verifyIsNull(); return keySet().iterator(); } public Set keySet() { return Collections.unmodifiableSet( properties.keySet() ); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { verifyIsNull(); JSONArray ja = new JSONArray(); Iterator keys = keys(); while( keys.hasNext() ){ ja.element( keys.next() ); } return ja; } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names( JsonConfig jsonConfig ) { verifyIsNull(); JSONArray ja = new JSONArray(); Iterator keys = keys(); while( keys.hasNext() ){ ja.element( keys.next(), jsonConfig ); } return ja; } /** * Get an optional value associated with a key. * * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt( String key ) { verifyIsNull(); return key == null ? null : this.properties.get( key ); } /** * Get an optional boolean associated with a key. It returns false if there * is no such key, or if the value is not Boolean.TRUE or the String "true". * * @param key A key string. * @return The truth. */ public boolean optBoolean( String key ) { verifyIsNull(); return optBoolean( key, false ); } /** * Get an optional boolean associated with a key. It returns the defaultValue * if there is no such key, or if it is not a Boolean or the String "true" or * "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. * @return The truth. */ public boolean optBoolean( String key, boolean defaultValue ) { verifyIsNull(); try{ return getBoolean( key ); }catch( Exception e ){ return defaultValue; } } /** * Get an optional double associated with a key, or NaN if there is no such * key or if its value is not a number. If the value is a string, an attempt * will be made to evaluate it as a number. * * @param key A string which is the key. * @return An object which is the value. */ public double optDouble( String key ) { verifyIsNull(); return optDouble( key, Double.NaN ); } /** * Get an optional double associated with a key, or the defaultValue if there * is no such key or if its value is not a number. If the value is a string, * an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public double optDouble( String key, double defaultValue ) { verifyIsNull(); try{ Object o = opt( key ); return o instanceof Number ? ((Number) o).doubleValue() : Double.parseDouble((String) o); }catch( Exception e ){ return defaultValue; } } /** * Get an optional int value associated with a key, or zero if there is no * such key or if the value is not a number. If the value is a string, an * attempt will be made to evaluate it as a number. * * @param key A key string. * @return An object which is the value. */ public int optInt( String key ) { verifyIsNull(); return optInt( key, 0 ); } /** * Get an optional int value associated with a key, or the default if there * is no such key or if the value is not a number. If the value is a string, * an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public int optInt( String key, int defaultValue ) { verifyIsNull(); try{ return getInt( key ); }catch( Exception e ){ return defaultValue; } } /** * Get an optional JSONArray associated with a key. It returns null if there * is no such key, or if its value is not a JSONArray. * * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray( String key ) { verifyIsNull(); Object o = opt( key ); return o instanceof JSONArray ? (JSONArray) o : null; } /** * Get an optional JSONObject associated with a key. It returns null if there * is no such key, or if its value is not a JSONObject. * * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject( String key ) { verifyIsNull(); Object o = opt( key ); return o instanceof JSONObject ? (JSONObject) o : null; } /** * Get an optional long value associated with a key, or zero if there is no * such key or if the value is not a number. If the value is a string, an * attempt will be made to evaluate it as a number. * * @param key A key string. * @return An object which is the value. */ public long optLong( String key ) { verifyIsNull(); return optLong( key, 0 ); } /** * Get an optional long value associated with a key, or the default if there * is no such key or if the value is not a number. If the value is a string, * an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public long optLong( String key, long defaultValue ) { verifyIsNull(); try{ return getLong( key ); }catch( Exception e ){ return defaultValue; } } /** * Get an optional string associated with a key. It returns an empty string * if there is no such key. If the value is not a string and is not null, * then it is coverted to a string. * * @param key A key string. * @return A string which is the value. */ public String optString( String key ) { verifyIsNull(); return optString( key, "" ); } /** * Get an optional string associated with a key. It returns the defaultValue * if there is no such key. * * @param key A key string. * @param defaultValue The default. * @return A string which is the value. */ public String optString( String key, String defaultValue ) { verifyIsNull(); Object o = opt( key ); return o != null ? o.toString() : defaultValue; } public Object put( String key, Object value ) { if( key == null ){ throw new IllegalArgumentException( "key is null." ); } Object previous = properties.get( key ); element( String.valueOf( key ), value ); return previous; } public void putAll( Map map ) { putAll( map, new JsonConfig() ); } public void putAll( Map map, JsonConfig jsonConfig ) { if( map instanceof JSONObject ){ for( Iterator entries = map.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); this.properties.put( key, value ); } }else{ for( Iterator entries = map.entrySet() .iterator(); entries.hasNext(); ){ Map.Entry entry = (Map.Entry) entries.next(); String key = String.valueOf( entry.getKey() ); Object value = entry.getValue(); element( key, value, jsonConfig ); } } } public Object remove( Object key ) { return properties.remove( key ); } /** * Remove a name and its value, if present. * * @param key The name to be removed. * @return The value that was associated with the name, or null if there was * no value. */ public Object remove( String key ) { verifyIsNull(); return this.properties.remove( key ); } /** * Get the number of keys stored in the JSONObject. * * @return The number of keys in the JSONObject. */ public int size() { // verifyIsNull(); return this.properties.size(); } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * * @param names A JSONArray containing a list of key strings. This determines * the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray( JSONArray names ) { verifyIsNull(); if( names == null || names.size() == 0 ){ return null; } JSONArray ja = new JSONArray(); for( int i = 0; i < names.size(); i += 1 ){ ja.element( this.opt( names.getString( i ) ) ); } return ja; } /** * Make a JSON text of this JSONObject. For compactness, no whitespace is * added. If this would not result in a syntactically correct JSON text, then * null will be returned instead. *

* Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable representation * of the object, beginning with { (left * brace) and ending with } (right * brace). */ public String toString() { if( isNullObject() ){ return JSONNull.getInstance() .toString(); } try{ Iterator keys = keys(); StringBuffer sb = new StringBuffer( "{" ); while( keys.hasNext() ){ if( sb.length() > 1 ){ sb.append( ',' ); } Object o = keys.next(); sb.append( JSONUtils.quote( o.toString() ) ); sb.append( ':' ); sb.append( JSONUtils.valueToString( this.properties.get( o ) ) ); } sb.append( '}' ); return sb.toString(); }catch( Exception e ){ return null; } } /** * Make a prettyprinted JSON text of this JSONObject. *

* Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable representation * of the object, beginning with { (left * brace) and ending with } (right * brace). * @throws JSONException If the object contains an invalid number. */ public String toString( int indentFactor ) { if( isNullObject() ){ return JSONNull.getInstance() .toString(); } if( indentFactor == 0 ){ return this.toString(); } return toString( indentFactor, 0 ); } /** * Make a prettyprinted JSON text of this JSONObject. *

* Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable representation of the * object, beginning with { (left brace) * and ending with } (right brace). * @throws JSONException If the object contains an invalid number. */ public String toString( int indentFactor, int indent ) { if( isNullObject() ){ return JSONNull.getInstance() .toString(); } int i; int n = size(); if( n == 0 ){ return "{}"; } if( indentFactor == 0 ){ return this.toString(); } Iterator keys = keys(); StringBuffer sb = new StringBuffer( "{" ); int newindent = indent + indentFactor; Object o; if( n == 1 ){ o = keys.next(); sb.append( JSONUtils.quote( o.toString() ) ); sb.append( ": " ); sb.append( JSONUtils.valueToString( this.properties.get( o ), indentFactor, indent ) ); }else{ while( keys.hasNext() ){ o = keys.next(); if( sb.length() > 1 ){ sb.append( ",\n" ); }else{ sb.append( '\n' ); } for( i = 0; i < newindent; i += 1 ){ sb.append( ' ' ); } sb.append( JSONUtils.quote( o.toString() ) ); sb.append( ": " ); sb.append( JSONUtils.valueToString( this.properties.get( o ), indentFactor, newindent ) ); } if( sb.length() > 1 ){ sb.append( '\n' ); for( i = 0; i < indent; i += 1 ){ sb.append( ' ' ); } } for( i = 0; i < indent; i += 1 ){ sb.insert( 0, ' ' ); } } sb.append( '}' ); return sb.toString(); } public Collection values() { return Collections.unmodifiableCollection( properties.values() ); } /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. *

* Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ protected void write(Writer writer, WritingVisitor visitor) throws IOException { try{ if( isNullObject() ){ writer.write( JSONNull.getInstance() .toString()); } boolean b = false; Iterator keys = visitor.keySet(this).iterator(); writer.write( '{' ); while( keys.hasNext() ){ if( b ){ writer.write( ',' ); } Object k = keys.next(); writer.write( JSONUtils.quote( k.toString() ) ); writer.write( ':' ); Object v = this.properties.get( k ); if( v instanceof JSON ){ visitor.on( (JSON) v, writer ); }else{ visitor.on( v, writer ); } b = true; } writer.write( '}' ); }catch( IOException e ){ throw new JSONException( e ); } } private JSONObject _accumulate( String key, Object value, JsonConfig jsonConfig ) { if( isNullObject() ){ throw new JSONException( "Can't accumulate on null object" ); } if( !has( key ) ){ setInternal( key, value, jsonConfig ); }else{ Object o = opt( key ); if( o instanceof JSONArray ){ ((JSONArray) o).element( value, jsonConfig ); }else{ setInternal( key, new JSONArray().element( o ) .element( value, jsonConfig ), jsonConfig ); } } return this; } protected Object _processValue( Object value, JsonConfig jsonConfig ) { if( value instanceof JSONTokener ) { return _fromJSONTokener( (JSONTokener) value, jsonConfig ); }else if( value != null && Enum.class.isAssignableFrom( value.getClass() ) ){ return ((Enum) value).name(); } return super._processValue( value, jsonConfig ); } /** * Put a key/value pair in the JSONObject. * * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, * String, or the JSONNull object. * @return this. * @throws JSONException If the value is non-finite number or if the key is * null. */ private JSONObject _setInternal( String key, Object value, JsonConfig jsonConfig ) { verifyIsNull(); if( key == null ){ throw new JSONException( "Null key." ); } if( JSONUtils.isString( value ) && JSONUtils.mayBeJSON( String.valueOf( value ) ) ){ this.properties.put( key, value ); }else{ /* Object jo = _processValue( value, jsonConfig ); if( CycleDetectionStrategy.IGNORE_PROPERTY_OBJ == jo || CycleDetectionStrategy.IGNORE_PROPERTY_ARR == jo ){ // do nothing }else{ this.properties.put( key, jo ); } */ if( CycleDetectionStrategy.IGNORE_PROPERTY_OBJ == value || CycleDetectionStrategy.IGNORE_PROPERTY_ARR == value ){ // do nothing }else{ this.properties.put( key, value ); } } return this; } private Object processValue( Object value, JsonConfig jsonConfig ) { if( value != null ){ JsonValueProcessor processor = jsonConfig.findJsonValueProcessor( value.getClass() ); if( processor != null ){ value = processor.processObjectValue( null, value, jsonConfig ); if( !JsonVerifier.isValidJsonValue( value ) ){ throw new JSONException( "Value is not a valid JSON value. " + value ); } } } return _processValue( value, jsonConfig ); } private Object processValue( String key, Object value, JsonConfig jsonConfig ) { if( value != null ){ JsonValueProcessor processor = jsonConfig.findJsonValueProcessor( value.getClass(), key ); if( processor != null ){ value = processor.processObjectValue( null, value, jsonConfig ); if( !JsonVerifier.isValidJsonValue( value ) ){ throw new JSONException( "Value is not a valid JSON value. " + value ); } } } return _processValue( value, jsonConfig ); } /** * Put a key/value pair in the JSONObject. * * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, * String, or the JSONNull object. * @return this. * @throws JSONException If the value is non-finite number or if the key is * null. */ private JSONObject setInternal( String key, Object value, JsonConfig jsonConfig ) { return _setInternal( key, processValue( key, value, jsonConfig ), jsonConfig ); } /** * Checks if this object is a "null" object. */ private void verifyIsNull() { if( isNullObject() ){ throw new JSONException( "null object" ); } } } jenkins-json-2.4-jenkins-3/src/main/jdk15/net/sf/json/util/0000775000175000017500000000000011650253660024023 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/main/jdk15/net/sf/json/util/EnumMorpher.java0000664000175000017500000000277211650253660027137 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import net.sf.ezmorph.ObjectMorpher; /** * @author Andres Almiray */ public class EnumMorpher implements ObjectMorpher { private Class enumClass; public EnumMorpher( Class enumClass ) { if( enumClass == null ){ throw new IllegalArgumentException( "enumClass is null" ); } if( !Enum.class.isAssignableFrom( enumClass ) ){ throw new IllegalArgumentException( "enumClass is not an Enum class" ); } this.enumClass = enumClass; } public Object morph( Object value ) { if( value == null ){ return enumClass.cast( null ); } return Enum.valueOf( enumClass, String.valueOf( value ) ); } public Class morphsTo() { return enumClass; } public boolean supports( Class clazz ) { return String.class.isAssignableFrom( clazz ); } }jenkins-json-2.4-jenkins-3/src/site/0000775000175000017500000000000011650253660020001 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/site/site.vm0000664000175000017500000002734611650253660021325 0ustar jamespagejamespage #macro ( banner $banner $id ) #if ( $banner ) #if( $banner.href ) #else #end #if( $banner.src ) #set ( $src = $banner.src ) #if ( ! ( $src.toLowerCase().startsWith("http") || $src.toLowerCase().startsWith("https") ) ) #set ( $src = $PathTool.calculateLink( $src, $relativePath ) ) #set ( $src = $src.replaceAll( "\\", "/" ) ) #end #if ( $banner.alt ) #set ( $alt = $banner.alt ) #else #set ( $alt = "" ) #end $alt #else $banner.name #end #if( $banner.href ) #else #end #end #end #macro ( links $links ) #set ( $counter = 0 ) #foreach( $item in $links ) #set ( $counter = $counter + 1 ) #set ( $currentItemHref = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $currentItemHref = $currentItemHref.replaceAll( "\\", "/" ) ) $item.name #if ( $links.size() > $counter ) | #end #end #end #macro ( breadcrumbs $breadcrumbs ) #set ( $counter = 0 ) #foreach( $item in $breadcrumbs ) #set ( $counter = $counter + 1 ) #set ( $currentItemHref = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $currentItemHref = $currentItemHref.replaceAll( "\\", "/" ) ) #if ( $currentItemHref == $alignedFileName || $currentItemHref == "" ) $item.name #else $item.name #end #if ( $breadcrumbs.size() > $counter ) > #end #end #end #macro ( displayTree $display $item ) #if ( $item && $item.items && $item.items.size() > 0 ) #foreach( $subitem in $item.items ) #set ( $subitemHref = $PathTool.calculateLink( $subitem.href, $relativePath ) ) #set ( $subitemHref = $subitemHref.replaceAll( "\\", "/" ) ) #if ( $alignedFileName == $subitemHref ) #set ( $display = true ) #end #displayTree( $display $subitem ) #end #end #end #macro ( menuItem $item ) #set ( $collapse = "none" ) #set ( $currentItemHref = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $currentItemHref = $currentItemHref.replaceAll( "\\", "/" ) ) #if ( $item && $item.items && $item.items.size() > 0 ) #if ( $item.collapse == false ) #set ( $collapse = "expanded" ) #else ## By default collapsed #set ( $collapse = "collapsed" ) #end #set ( $display = false ) #displayTree( $display $item ) #if ( $alignedFileName == $currentItemHref || $display ) #set ( $collapse = "expanded" ) #end #end

  • #if ( $item.img ) #if ( ! ( $item.img.toLowerCase().startsWith("http") || $item.img.toLowerCase().startsWith("https") ) ) #set ( $src = $PathTool.calculateLink( $item.img, $relativePath ) ) #set ( $src = $item.img.replaceAll( "\\", "/" ) ) #else #end #end #if ( $alignedFileName == $currentItemHref ) $item.name #else $item.name #end #if ( $item && $item.items && $item.items.size() > 0 ) #if ( $collapse == "expanded" )
      #foreach( $subitem in $item.items ) #menuItem( $subitem ) #end
    #end #end
  • #end #macro ( mainMenu $menus ) #foreach( $menu in $menus ) #if ( $menu.name )
    $menu.name
    #end
      #foreach( $item in $menu.items ) #menuItem( $item ) #end
    #end #end #macro ( copyright ) #if ( $project ) #set ( $currentYear = ${currentDate.year} + 1900 ) #if ( ${project.inceptionYear} && ( ${project.inceptionYear} != ${currentYear.toString()} ) ) ${project.inceptionYear}-${currentYear} #else ${currentYear} #end #if ( ${project.organization} && ${project.organization.name} ) ${project.organization.name} #end #end #end #macro ( publishDate $position $publishDate $version ) #if ( $publishDate && $publishDate.format ) #set ( $format = $publishDate.format ) #else #set ( $format = "MM/dd/yyyy" ) #end $dateFormat.applyPattern( $format ) #set ( $dateToday = $dateFormat.format( $currentDate ) ) #if ( $publishDate && $publishDate.position ) #set ( $datePosition = $publishDate.position ) #else #set ( $datePosition = "left" ) #end #if ( $version ) #if ( $version.position ) #set ( $versionPosition = $version.position ) #else #set ( $versionPosition = "left" ) #end #end #set ( $breadcrumbs = $decoration.body.breadcrumbs ) #set ( $links = $decoration.body.links ) #if ( $datePosition.equalsIgnoreCase( "right" ) && $links && $links.size() > 0 ) #set ( $prefix = " |" ) #else #set ( $prefix = "" ) #end #if ( $datePosition.equalsIgnoreCase( $position ) ) #if ( ( $datePosition.equalsIgnoreCase( "right" ) ) || ( $datePosition.equalsIgnoreCase( "bottom" ) ) ) $prefix $i18n.getString( "site-renderer", $locale, "template.lastpublished" ): $dateToday #if ( $versionPosition.equalsIgnoreCase( $position ) )  | $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #end #elseif ( ( $datePosition.equalsIgnoreCase( "navigation-bottom" ) ) || ( $datePosition.equalsIgnoreCase( "navigation-top" ) ) )
    $i18n.getString( "site-renderer", $locale, "template.lastpublished" ): $dateToday #if ( $versionPosition.equalsIgnoreCase( $position ) )  | $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #end
    #elseif ( $datePosition.equalsIgnoreCase("left") )
    $i18n.getString( "site-renderer", $locale, "template.lastpublished" ): $dateToday #if ( $versionPosition.equalsIgnoreCase( $position ) )  | $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #end #if ( $breadcrumbs && $breadcrumbs.size() > 0 ) | #breadcrumbs( $breadcrumbs ) #end
    #end #elseif ( $versionPosition.equalsIgnoreCase( $position ) ) #if ( ( $versionPosition.equalsIgnoreCase( "right" ) ) || ( $versionPosition.equalsIgnoreCase( "bottom" ) ) ) $prefix $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #elseif ( ( $versionPosition.equalsIgnoreCase( "navigation-bottom" ) ) || ( $versionPosition.equalsIgnoreCase( "navigation-top" ) ) )
    $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version}
    #elseif ( $versionPosition.equalsIgnoreCase("left") )
    $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #if ( $breadcrumbs && $breadcrumbs.size() > 0 ) | #breadcrumbs( $breadcrumbs ) #end
    #end #elseif ( $position.equalsIgnoreCase( "left" ) ) #if ( $breadcrumbs && $breadcrumbs.size() > 0 )
    #breadcrumbs( $breadcrumbs )
    #end #end #end #macro ( poweredByLogo $poweredBy ) #if( $poweredBy ) #foreach ($item in $poweredBy) #if( $item.href ) #set ( $href = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $href = $href.replaceAll( "\\", "/" ) ) #else #set ( $href="http://maven.apache.org/" ) #end #if( $item.name ) #set ( $name = $item.name ) #else #set ( $name = $i18n.getString( "site-renderer", $locale, "template.builtby" ) ) #set ( $name = "${name} Maven" ) #end #if( $item.img ) #set ( $img = $item.img ) #else #set ( $img = "images/logos/maven-feather.png" ) #end #set ( $img = $PathTool.calculateLink( $img, $relativePath ) ) #set ( $img = $img.replaceAll( "\\", "/" ) ) $name #end #if( $poweredBy.isEmpty() ) $i18n.getString( #end #else $i18n.getString( #end #end $title #foreach( $author in $authors ) #end #if ( $decoration.body.head ) #foreach( $item in $decoration.body.head.getChildren() ) #if ( $item.name == "script" ) $item.toUnescapedString() #else $item.toString() #end #end #end
    $bodyContent

    jenkins-json-2.4-jenkins-3/src/site/resources/0000775000175000017500000000000011650253660022013 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/site/resources/images/0000775000175000017500000000000011650253660023260 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/site/resources/images/external.png0000664000175000017500000000034611650253660025613 0ustar jamespagejamespage‰PNG  IHDR Óº&gAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe< PLTEuuuÿÿÿ™ÿÿÿÑðPtRNSÿÿÿ@*©ôPIDATxÚb`&& @ P6#@ `ÀÄÄäX˜Ć2™Ê« ›‰d@AÔ3ƒ (± *‡½ÜtIEND®B`‚jenkins-json-2.4-jenkins-3/src/site/resources/images/json-lib.png0000664000175000017500000001750711650253660025515 0ustar jamespagejamespage‰PNG  IHDRá5·ŒCbKGDùC» pHYs  šœtIMEÖ;8Çw4tEXtCommentCreated with The GIMPïd%n«IDATxÚí]yœTÅÿV½£¯™„”KN#‡Šcd£ñ¬¬àI4ƒÇŠ£l6‚JÖhÜÄMØ°Š‰7Äx ˆºQrjTc¸ä>–C䘞£û]UûGWõT¿éîéžé§>ŸúÌLÏëzõª~ßß]¿t´ŽÖÑ:ZGëh­£u´ŽvÌéX‚ŽÖš­"¨ I€‹ÎœX%?‘ïOŽÃÍÉ5g~´7¯£µz)€ ~KtljU²ñþmÂ,À) Ê☢´<@èpØ¢»ÅXÀ<˜AÑ@[qåbìK‘éD{[ “è1Ç8€Ãˆ°ó ÿó!׳ûþí„<’«(ÀmŽ»ˆ…ÔÅ┉ãÑ·gbìz5Žˆß¼BQ™‹&ž)3ð3Gü]Ð}3¬Ÿ&ƶųÙ-|–VíK1ê€ üzsîžÂ݆p÷£>Ì[ÓlG#ú·oØ Þ‰UzÍì“)Æ4Åß{ÐdíŠyÿÖ6½ ÖÐ@¹&£@µä.F´*»(߈ïwГóúžÌ~ùî®ÈÙöSÀë"@"p˜ˆi¥u„ž¼Ð>»‰1úïT¾Àç¾÷kÄVˆŠb f ¡TÌÍÌÀ ˜ØäzµêÄ=F´*/‰œaý:‰µ«œù0€#Zåä ÄÖîK5*@PîÖßqç‡*Á¾è$LßuåÊþekšØ£Nâù¢bß pLŒqD¡ƒbÞ¿ý€Py°.N¬r}¢8Mp&WJ(¥*ôã<>˜%fcβ³X(óhñ0x< ÔtâÞîS¸·|$œß]áÑSwQã²7´ÀÄE’ÛѪœD_@€.*€P ËàÞç®]»†aÀ4Mhš–êœs<ðÀ8p Æ]ßm‚ظjšuF´ª9‰œuýˆ1î=4ý·vØ'@é¶õ¾´±?ÂЙ{ŸÜ㺈Ø’ƒÁ˜€}˜óÞ×=ë™Ávö@{oÑ“çRã¢ÅW\#Zåëþí„RÄ—7s]&®0ˆ¹+Ïóß¶³K‹æÁ¶õfÖ“ßgβ3’ùw nhe"® *pgÝôpb• 5M!›7k‡Ã䤦#(9kÖ,hš†GfÜ6÷ÔSOEMM n¿gøx¡Îì l’†²~ÜYú]¦£šç-ª®cD«òT[³/m B]ìys4Js€ Å`˜óÞ×½øÌ‡;ШŸlýŠèÇ¢ÆEu‚yYE¼»a>–Æ]„ U¢s«Î÷¦ÝÔZ?¥x…–‘i!³¨À½œXåBt]O\¦N)…a©¿_|ñEpÎqÿý÷ã™Ùë^®©©Á½3F°À~¡òe’Š9ÖÏÕ½Äc·íô}„–× ÇkD«¬×’"Þ¿(êã±XX?wÑPºsoÛ/>ý{Å @µQk³=§Oî `ð}w¾þ¾«\ it]Ï >Ó4SÝÿw8ÆìÙ³áyLÓĬŸ®X `€è¥ 1‡üÖï/óâÓ'èŸcŒbîËñе¶³v—Ý΂Ñkííùh.L^ÿWtú2=½Ä/®?\R¤ÇcÔ¼®JJ áeÌ @'V¹ô±Ç!„PJÓÔM]סë:@êo]×S’P¢iš˜?>\×…ã8xì¡¿¾ðÓÿòƒ…G.ˆ²®÷>ì%þçÄnŠƒ¥¨ûrâµö2ÖÛ #0”1÷áÜ[qzŽé2b\ºê—®%Úé{AãÞÎÎÖUpwÅ î~Ú¨k” ´ÿ.¢õÙ)ì[8h2p«|@ xÒ¦}æwÈø?SÕR зß~^x!\×…mÛ¸÷__[ú_O^}¥âU-ÄÉf/Mô³¶QýŸdX¡ûðDD— Ú{+ضÓ2SYŸ-ÂSê‰ï¦s_@„ÙoJ†25“i¡ÿXD‹ÞNŽŒèÃ(0,s|”³Ã§0ë73ç­s€x€j#>×Ö"ÿâ>'PwXå«Òù¢0ÐTù?WA¨þ¯¶¶†aÀqBpûMs=õâ„1‚98F´ªgˆ£yñGn$‘y»-¯•n÷<íÄ6€˜øÞ¼&Ž@ÀÒ“ç çœÝÞÄb{¡ À½uC²ŠKcÌZÀÕÂÛØ p4@ ¡·i¡n ÆèÞ^|æÔ÷ºa”4>'P_'VùšŠ Â\v`> óÿoãÆ8p <σã8Ðu7ÿÍÒ^¾õ|4Æ®ò'aê‘9Äó9X!ñäÉCÔ¸ä€ýسž¶«?ÚG QײTøTZ›­Ê&A[•uÔ^@˜tð#eY/2ƬA2>&Ýý …heFË{¨~Æ&ZúÆq×2¿è¾;__úóŸ'— ¥ƒÆ²L ËäÌ‘×>|¡P¶mÃóR‘’~‚C'DÏ[M’ö¡œR‡Æø^AªíñÚ”5é×h°—£ÿHÑG2lá8à ’ñZ[dÌä{«ˆðWp±®$‡Jì°óMÎhO TZ<œ„Ú€j…PN¬ÒòmŠ…ÆìŽp¥º'^Æ”:èõøã§À§‚G†%TuS×uX–…`0BHêÿÍى긖eAÓ40Æà8cøöØ_½ðÛÅß+Fu¡Î²/£}˜!ÏTö\jš"%kFWhBACñÎLºd¾É턺xZf®¿¥3чÉdnÝŸZ%ˆÎ6¢U޲PW®“R°›«\ ª‹Ò#?SÁ3yòd 2Œ1xž§J1ÀóÏ?ßlìPvÇqày^Jº®‹¹ø§‹ß\ö£óÄf§ûrÙ‡9Rð E2ÊõsscD-qÆ áÞ†žýÛÓ¸·®ؾ®€%²·L ¤,FhÏ}Dº™š×¬ ´ÇE[; ¾9¡}DêÁ­`fŽ?ÿlª?ö±XøZ^¦Ìñ°Ù²bL±y=‚Á`š×3xlÛNÅú8ç`Œ1†ºº:Ü~Ï𛄊C‡»_zÞ̧³9kTÉxðàA˜¦™’†  { êL,_.û0¯¼ ûš¢Sˆ4tþ}wÿÔ `$£æÆãaîííνOG0{Á•D«üL Þù*Ñ àÿ¤c0×^Ðv°¨)ƒ–î²^äþa°g¿|!’ñ±S Ñ*=`µ´ƒ:{u_]è‹?ðÎÜ9sRàs]®ëJ^` €ÏD_õîû3o0M³‰£FS×uTTTÀ¶í”:ê8lÛÆÅ_{ðea{˜-Ù—VƧ–o ž¿•‹ïÄà¸û‡ŠÌÌY{ wë'=à%fMB2ÜÍ$U´z,¢Ÿ¹.×â³Ä¬qžõµ†(ôõ(€€°ša@yII (¥Mï†aÀ0 B0{öl€çy) ÈÃmS‡}ÀF»LAÛ‹d:Úæ×ß¹ï5 ¯ŽiÊÊÊR*­eYp]žç¡¾¾òYZº/Ì^0š¹~@_¡1óX—ㄺØËBÚQLɳ fÏ¿Êm˜z€Aͱ½€ÐPOÍ«WA'§¡Ìzb¬Û0m*ç±sœ  ¸#Zef":ÅŽ(Ð%“3EÍ~yòÉ'Á9OI?™ñ2á¶wØ.€§z4k<2µ@Æ46õ~®ë²¬”MhY–tö”¢1µª-irV}ºØø(s%¿ìí¨§äq÷o£Ü†éS„ÀèžM;i ”çðjíµ—®hþáþ<Ü­»îAÏzé;Hæc*j‘ `”Y9¥g¹s®_] ªä€ÇS’OJ-Æ<Ÿ¸Jð_èù¶ølÿÂ7J×Lj©tÊØ¶Ö…: #»(ÐGÇ›³áË/m'{],¦í¢ð“Ç„q÷Ýó=kÞ•¹´“c¾1 ר£¿¿´÷ÁæŸîP ³þû:§îšG=ûµñ΢?“½(]Ú‘U«V¥©‹~ Lž<9<XwœsoWÒ³o¤gÖÏpÀ¶í´1%è%Ø¥ê8Nš´ýæ¹Ó-¤µ™S¯M_Ú+Þûœ ´ ç ?'Ú¨mZpú½dÑ“zéßþK/ys¶~êy¸mÑÎÚžÓŒ²ž¾–³ýÃí$M-m/ÞQéJþ‚²uzègO¹ ÿ:¼ºùDn¶£KƒlžRàj¸bÆ PÜíÙw•„ÖiÁïö´lö¡?äBã8¤a*CFx<+ãìÄ*(öÍ´àC‹©ùφ’* Ò„v§ÐG†ø^Wæ®>ÃKüøZ°Y’MâÏúõ8=ôÀnÁ<ê… ÆÛ X%ÍjÛ‰ÖzøÉ„ŸqØ–^ùmÍÖ^^bææ,¾X Þ»Àç"¶i HŸœ6mZš#F:M„*šŠÁeq5Ëê\±ŸÍ7iƽo?çO]SmBiª?E’@>6Ü&ªKðÀ$ƒYs¾•Ë>ñC[0³%ûS`Å;Õã]ôâQ"éÂAch­ j£Mä`€jª$S´È €rª?D"/rëoº=¹³ì,œÚÒÝHfv¥ÆjOœQÖ:Ù`Ñú¿o”,|€šßY D¬ü]õÿâÖOžîYÏ|G¨§=T»HõVʘ ìÒêWEÇÒ‹7eS«]$cQõ~UT=g¨Ž«ª¤BåÍÇyð9€ÍZ`Ò¢mmžöaas @iOGÌ4: @×fúIâÚ³ØZ™˜!´'YíHÑå^4ß÷ ¿ïŽºõ„”¬Ô‚3^Í®š6ÜYv’e8‚*öÚM°^ápµ‚ØãbZpêaj^÷7/1ëZî¾?póðÆÌúõõœí颇|JРåJ¸–Ivù·pšæŠË’ÒF)Mi’ãKµT€=Ÿ&½±õZèáÝú›~¶«<»}8ç*-xÇ{h,~TˆÌ”’ËÕ/™Q›’IF´ÊUd[´Ñ3¥Jª÷ RýÌ0mÄ.î­ìQYsW  æ•aÿúµI+ÖÇz\áþ¯#´gµþÙæ­ÊOåÞò¯ä@åΛ—z¤¼F NY(8fЯ‚ª@ñƒ1¦&[˰Z‚Õ‘¬Žɤ†jš†%K–¤$ŸŒJ ' ió4÷lÒ‘UKH©©šë5L¹H™íÃy}T‚êgÔª¡Ù)¾u9ZÅ£Ú*3ˆ‰ÎsÉpíìÍÙ@ÈÙÖ i©{Üê(mí¸Š·1&Ô€-VRí+ïê‘_=ª…gÿ‚hö嵂öKW3wÅW…’vZ¦.Á'C>u4*<—FõJ÷›­ÏI¬?V¸uëÖ´°„ zB[±;rFBH™ÿ£úˆiàÖ%9VTóâ3/á¼á+-`¦-ÉNQ[‹2UÚ™7¶YÁ!ö#Nô‘;³TÊ´Å¡Z$·Õꆫ”ñ j»l°’êç¼­Gž{„§½RÞL¼È£Ìšs­aز¬4àƒÁT–ŒœL'Síµ¿{ɳ>u,Ó³‡t>xð t]O%…ËÒBR-•`¼à‚  xΚ# iCï°U ÜøÑ/Z™ýŸ½ø#§µ„-ÉNQ[G¯xÔ±*ÀíY—ýªº`6©U”æSÇJ‹i„;±JYT÷ãF«4óºWõÈ‹OmèÞÜΚµ§2wÅ@úe—]–5†'!ãxþŸHÆy:ÃpUŽH•è*% ¿Íý÷ßÛ¶SãÉX¡Ì}÷ý™· gC>F(`­ÚÂV-4sh¿ù·ï†ÐÑÚŒä¤ND[oS¢1 ^ÂyíI9„¥×J0Ö 0î°Ðî+´ðSÏ팜@dÎÿÀÿû7ã˜-­Ì/¥ü^ÌÉß}~>³PL#ZE”Ó¥ºÍþÙߟ—ãË‚Qº®cýúõ)§Œßñ£„Aj„äw àÀ2ü°‡àF=ôs ñ&ç1~K²SüŽÂª×0Œåð³„ì¶acýN^›£`¯Þ*/–/;ås› ¬ÑB¾Rfe—†kú‰ïÉV-Ͳ¬4é§Òi_áîï$T-Y~½€>¡P( à†a bÁ‚M$  øÚÚZ©VÐÁS±)ûhC–Óà”7ŠDôÅÈN©c|@HÀ«³{ I8#}ê>•Rzm¨¬|¯©¬Îö”ç˜H¼ö¢ÎØ Dhד¨qùgÌ^pVfr:R*ˆ¡^-e4f¶H… ü”!„ëÇÍ~váw}W¬Ýa1zgýŸ{bóš–tPJ;0‰àî»ïN þ«cÊN)3r =¯Ú‡ͼæ÷Ü[ÛŸ;o]Ï šÒÒEKž©Užö£>áäÞú숔$21#*í9#Z¥#GŠŠÅö^K<2¤åPG5÷6wÍ>‘hms¶¥­Ò”Nrx¥ÒÝÃúÅÙBñúˆ‡ßúãô j°^JÅmÛ¶5QAýsޱ—þçKF8Kô‘Ï?¹ñ%Uý”Àž:ujЩ¿Ëqµ’åã…t· %Xe-íÃàŒ ƒö¶–Ù‰qcH¦7X‹dɪ,}µ¸f³øN ¾\Û£ím/Àòñ…„¸·þä¬Ñ>ÃL yèÊL6ù6 y¤Frµ#‚«ÕˆÒ ,ûDÖôÎ:Òý 2 1^ùz+ùj+†dÍ”Œ…s„D”ÁZ›hça?Õàœó&-2¯S•|jÀ^þNÁ?ó'ÿÓ·o_ :R•=‰à®»îJ+g¡ÆU›P¦ÈiI‚­ëÈ[±NÂ>ÔKõÐOæº ßû>x,Ø 2¹þ¾;ÚikêëèŽEó—ÌðP¾B¡@WæU ÎJûÚ°í™ldÝç^¯pb£þ ¸MÞY …~r75F$&ê WÜØ2«¢+÷V È>‘;<±©¯·ê$¼¬2±;Q«Ãg/üdgûJs¨uÊxñ×Þ¾wì-7<»Ø´÷'U«Ù,êa\Ïó°qãF¬^½:õ™z yøìOpF´j,K3–´Ô~Rrp…}Ø/¬îyÍK<|Cþ§Ã³JDï TЂnD«È1(×!íþ ¨ÐÆÚ“ï÷è sÞ•ãFœêç­FÓê)ÊdÔn åGÀ÷7!³ßš@ÑGg:€dZW€ÐÀÏzéRðýÙK&'’–Eî«ÚÛ­Ÿø#Ð^µZðÁ?¢B2Ÿ´JýeÞa:¨`Î;C³ƒ°Û4¦ÃYŒgÜró“æ¿ –,¬®®n"ýª¤_ªÉÏT§ ”vj²6€”4¢U7 O¯¬&n%ѤهÔóî­éÏœ×Ï=.’{.‚·VwÝ5RóÚ¨ùí ¡{38.$»3烯1ûå3²êú¨Uâá-…H·—••Á²¬”:Ú³gOìÞ½; H*èäOµP“_mõÿ_-Å9OûLK&Ëõä­õ"fpZ•ÐàÇÙ¦^Ü[{òq‡B¶¿;´Þ¥Ç „Ì^r!5¯’ç2ý t¿ül/þÈÕà{³½£ÆUï yÄN2Û&ꨌø»Äøæî}<<„˜5ç[Ü]~:1.]MµÊ] ÝÀ«ƒÜÛØ¹<;ï š}"ß\Žd…²ÔÉtßKOöìWnr^|w9³~y9³ç]@´‘Û©^¹…hƒ€öª8ÛaÞêžÜýà4î~|*àeQ¹"qj^÷ßM']æ{ýå˜1÷ÝùúRÕ.¬¨¨ÀÎ;Ó¤—ÿØ‘ Jõ3|~ ª¶ !ZÉò1ŠóÂF‘ry›Ú‡´T =2×­Ÿx7xuø¸’„lc¢õNU0¢UîÑTI½Ä£ÿÂ܆PãòUDñˆá‚r¶³”{+{sïÓÜû,7s£vRóŠ÷Ñør×4G•®¸¢ScL³žýøþÒÌñ¶O{sïÓÞû›ÉI540ùŽ&ÊD9w»s÷¯#›Þô`„»¿깿Ú"ËÚ¼þ-B»n!™LÌ„j°ýñ'®ºrúÞZ$ …ðÙgŸ¥ÔRiú¥^¦X¢ª¢f²“Î)­dù•HJÁCHf質BnÒž-xßB/þÀDÀkg‡{u7Åxý[ï~:Æ%Ý„³ðˆ`VG±Â¸G¸û§Ažû§A-û~IBÍ|F•‚~#Uìˆ8€ý„˜›©yÃ’";˜¸¸íw„„· ƦÒݘýÒȼNÓ‚}íœÕZð¶EbŽ YÁw~ñ‘_\>¦S§N)'Í%—\’\WÓ×dêY6ªUÔüŽƘ”€›Ä½ëÛPŒϸÀj\ò.5®úcû‹²E²æ[2÷ÏC8oè-l³2ˆL¥ãCŽSNƒ·/ÌÓÞ‰’ „\Hƒ¶iï,"úïi"Œš7¾AÍqï YL7Ñ<œ¥_-:ÿú%’§0ö«ï‹­}`ã÷yþ¦Ÿ{³Ì¨¹æškP__ß$M­ªJ=UmÍÔµ’å7k%ËÏG2÷õ‹Lª‰²Í…òõjªÏ¸U ýÛ¢ØÚšq‹¥iŠîÒ#{<“ y ÿvçñîh¬G[0w~tŸYg4pë+š9þM$+<Ê$S TŽcÔ‰ÍÚ¤‡>‹èçÿ¥u“ Ú4øƒ¹ZpÊ<$ƒ·™8ŠPí»&Z¿!›šë‘'þ“m’émM‚Æ‚Ü[¬ºýžác¥}8iÒ$444¤$_¦ñêï–e¥Uë–]/]1É`öd~][šmÞÌJuš· ˆ< rR¬5ã „€Ñ¿ö÷œz˹õ¦ sÕ¸–®Y3ßÓ[¾¤kL =ük-pËoÝïÍ¥ñèYŒy€éáÇîY ×0{áµà_T>‡è|ªo]Lh¯ÕPÊg <™U­‡ŸÃ½xÖÓWsÀXŽ¡$Aôs×h‰omÐJáúß'½ª™¸P¶ƒÄ7Ý>ð<=—¾Rýò´iÓÀÃŒ3R9¦þ˜¡¿[V2MP+Y>^k,P-ìa;Ë [Ô”¯\­$EûöösB+VkÁiÏyñéS|¶XAã„6€ L^ÆÜ?lkŸÌ—Fk´À­/!sú[K×,û÷ÈIõzä™÷<ë©!ÜY60¿jH§ª_REƒw-!$´±ºoüšÿ_@'ñìßâîÇ#¹·½_òf‰ À(H€„ ¥õ„žº›hgn¡ÆèÕ„–ï‚ïÅÙ&"Ræd >U«„ÙKG0ï“að¶÷â|_Wðxïª0 A ¤ü¡ý?'ÚÐíÔûBÂ{Nôò¾Íú’”¬ ’Aó2Ñ£HËú÷¼ñy8|8™œãº.‰<ÏCß¾}±uϼ‰§ÞѧÞÒ#ãCÙ6C¤FôÌu’]äqîPïÄ*ó¶'Å:—"y¶²x¥¢GÐüûZtß&_ )Sèb^a±þ9ÉÂCõâ¾ hŒIÚÒ£×#ð½´F­é¢)N–TÝ–,¶usãâ9:£ñ$ˆ+lõê–ŒÛ ªÌ·‹xnµ¹‡Æ×ÝÉbN â°w«Ö,Ã÷: ¦À•½ƒØûP34Ø*ú#£Ìá#ÍèùN!Ä—Œê ýæîÙêû63™;(çdd˜“zÙe¢.+(þwïÉòíÒ~‘qN§%Ïçcxr|©¶xÜV¬¯:3ËºÚ CkBÔ-]³ ßÓ5Ujš¯ÍèžHŒÍÕ,Zânµ.Û¬Îežs*êý³Ü§-ï¶^»¶^×–®Y†ï©ßo7›IDATxÚí]y|eþ~Þ™Éähš¦MSzЖ´´È¥\‚‚ŠâXÄqAðA]/vÑõXñXåAA@DØÅ[D@A-PZ ÷}§9gæýý1™6IïR,bžÏçý$&oæzæ{_B)ÅÅ•$Tž?ÏS§S BX"®î=À€aXGv6slôh5çr©€ !A* ˆ'$ˆŒ”#!ÄÈF† JH“ã‚’(ÕÖrI:¬þ«¾úêo#7l( ‚PÉuéâäŒÆ‹vl~øq¡ ‹|%§N¡²  zçôéÿ'TVƳ¤R©Œ*žâ8ÎÀ1Œe=˲  cAŰ,aX–0 ²„0 –%Ë‚eYÂ2 À0„aYˆ„ÁfƒýèQUUHZBª4<€q:¿Œ|úé#æ;ïÌ¥‚Pا‹Ñh:û\ûá‡. ùòOœ ïO™Òï܉s={Ž5DD¨Y† ÔBþM) Š ¢$QPQ„$Š\.‚žç ÓA­ÓÂ~ò$œ‚€Jyà«Ríéµxñ Ù|Vm6ç† æìì“î‡ÀE _öÑ£º ?|sæ‘#sÍ))W£¢ŽaêÈFDp¹AÀå‚$ܯ¢ËÁé„Ës¸\p9(@Å0Òëd4B«ÓËÉW[ py  P(a€ÃÁ ‡z?úèqêrýuýõYæ¾}ýDô£ÓÐaä+>sû×® ;±ÿýé?þøpxrrlHt48†\.8 @­Ö:âÁåu¹dÒ¹‰G)À¸ñx%>2¹D†Ãq N'ÈR@ш(P àDÒðáÿ³|ùû¡©©e}üøs¢CÈW‘›‹µ÷Ý—xè›oærjõ­]BLÑÑàXŒËUf&˜ìlPAð"RSI¿›ÚK õÜÃéÞ®|WÙ®|NÀe=‡}ñÎuëÖ„$&Z;ûBøñçÓ¯º¸˜]zçC~÷Ý‹Ï6'$¨CcbÀ±,xA@`F´ÙÙàÁë{´‰÷ýÝšmÄý·B2';«û½è~Uþ/Py=||òÖ­Û11®ß÷ÔûñgG»ÉG)…¥´Tµpܸ[Nüøã+„ã»ÄÅs\T, ­$!4=Úìlfˆ×`ÞVnki;…,áDÕõÍjx«¢àLb¿~=´sç¾ ÈH‰?üø=ÐnòU1‹o¿}Äñ–SŽKíÖtIHÏq0RŠðôthΟ—í;´…LAT…ˆUÒTÂKRðKrŸ>÷Mß¹ó¸1:úâœi?üðA»ÈW‘›‹•'þeß¾•Çõ6ÆÄðîÝ¡áy˜D¥§C“‘ˆ"€ö©‘íÝÞY …LD…€°»çUW=|ïÖ­gƒãâ:ú<ûáG´™|¥çÎaÝ´i½|óÍR‰e¯ Œ‰!]ºw‡N­F$Ë"úÔ)hÏœ‘ãuMÌñ{K>e;¬jf8 YUä²p„[ßvÛS>þ¸°ãOµ~xƒkˇK23±é‘G’Ž~óÍË`˜¡†èhš˜µZpBú4ôéé€$¸ødjÏg €ÈΘC0P[€ÛJ22 œ1hPeŸk?üðB›$ßžU«bÞž1ãeBÈÝ11ªîÝÁk4ˆb¤ž> ã™3 ͯ­Û;bŽÆ¶µ¾ð d{  Jûöë7ÿ/Ë—¯<ØÞagÚ?|ÐjÉ—ÿë¯aÖ­{‚wè»vU…$$€uK¼^'O"43Œ›xÀ…äbKH5€á%_:êƒ÷. ôÌÑ£ízøáâ›W¯þÐ<`€ØAçÚ?¼Ð*ÉW’‘´j„ÇO9òX`TT 1) ¬N‡pB00- áçÏw(ñ:jŽ–æ&Š| rfŒ ² N§^qÅßFlÚôUpïÞr²ýðÃ-’¯ìüyÝÊqã¦fœ8ñ/]DDHpr2­¡®IKCtv¶ñ€Î#S{·çøä8 ™€]€C‰ÉÉ3¯Û¾ýˆ!%å‚N´~ø¢IòQJQ‘•ů3füÙ“'¨Ã‚SR£Ó!D’pý©Sˆs¯5„ø½-JÆKk÷-2k “ ¤®À—±‰‰ ?pà¬Úlî¸3ïÇŸMÚ|ågϲïŒ72+-íeÙ\O<— 7¤§#)'§Ä.®„óÝî›÷éI8eÏXÿÓfæNóû²'” L9pcPAÁ³ÖŒŒgx“©ˆ0 üð£#Шä+9u ïßsÏðô_~YÁšL=‚{ö$¬^£ÃëÏœAÏœ0”¢5~ÒÖ&kµÖçJPB@9”ã ±,\¢§ÃA’à``L¼ z:Ȫ$Eã‘BNC;`d"º= Ô8’»tY4è£^3 ZåOAó£#Ѐ|E'N`ëÔ©O:´„ `LM%¬Á€ »×9ƒ^99m"”Äq ,+ŽX`˜º9«hP¾[7X’J‘ã ò¼ÈWqìvÌšÕëèþý Ùàà‚zô`TF# µµ¸îÌ\QP‘e!pD7$• ÇAT$‘Jp¨J%“M¥T*W–eÁÞ•ìu`% Ås*µ.µQ„­¤Ö¢"ÔæçÃR\ ‡(ÖU2ø‡Ç`˜Ĉáþ;õ%L€œûù €“ûÅè$%&>´lÙýÈ‘}íüøƒÃ‹|‡/NÜò÷¿¿"ÝjèуS…„€aÄ ++!q7Éàñ ŽQ^‚1 8!à(­¨/xå|ëÞÁgˆJa/*BMZ¬ÅŰY,pP db)äS¤^c$Têü8ȪhÈQy5CVS%v¡>ÁAV[#ÓÝ“’æÄ,Yò©ÎO@?.u—ÜC‡"÷­\ù´06()‰ãCB–E¨^F«EzL Dw+ˆ:Âx‰À;,+ƒ¡¤úÒR°¢—ѧÉÑdÕëÁRW©ÞXź™ Ê $I‚#75GŽÀZVVWŸ'ù¼ú¾÷õR Ê!{7s»Gdõ4 À5í¿RÔ;nÊä‚ôô¹¦~(ÒùSg_@?þ¸à ðèÑÍ'þ­ ?ÿ¯Æ”µ:4ÃÀƒN‰aJÁzJ/J¡¢µµ..FpQËÊÀÛlà°N¹= eYˆj5$µ¢^!4¢Ù ˜L`4BÀ"{* ©#\×’R¸**`9xŽªªF ç;¤&¶Þj®Pg!;iÈd,…,ñDBNEsW¿CP­²¶ê‡íWôË/†n¿ýÁâ™AÉÉ:MX(!Ñé`Ôé@¥ ’N’ q¹`¬¨€¹°!EEÐWWƒs¹Àº\†ˆ(‚±ZA­VHPÈ6¢Jj4aa€Ù "Û #7%I‚#'®ššÄó”-P!§ ©L@e(Î ™ŒdUÕ³¯ HÁÀž î@g_|\µÝþŒ¾{÷@md$(!Òj¢×ƒaY”BS[‹Èœt),DHq146Iª#[SÞOϸZ )°ÛA-Ðü|Ø”çAL& , 4, b` LFB TWC¢´]ÒÎSê) –b €lß)­%|ɬìwêUN€89iÒfãœ9þ¶~\¸½ÕÕaWh4\€Z JT‡ ËB€œéTQ”ãÇXSSW×¼TGW/[ŽÒºžœÔå‚T[ )'GV?u:P³’É$·„7AÚB@ 2qt®p-dOgsÍ™dõÓéþ^‘<‡#L§û*²gÏïà¶ûq`¯¸é¦\Ë™3Q‡ã >$„‘8Nn~ÄóHlz=žGHI T´…ð„r#7F8Ég{Sÿ—(…ätBª¬„TT!&Öâb”zyA=;–5·]„ìÉ`(#diæÛ–Ðsˆí¾J÷p“ðtâ7>µbEQg_8?þø`^[º4÷'•jyIeåÑê¬,.ʬVÔ8Üa‰e‘Ì^½àT«ÈSÒ5çlÉCÙÀ®c°€ÁÐ*Iר|±†èÙ®kM6MdÒ)ÐÀj þ8jìØã}Ñü¸<À„……Ñ[¦O?ú“$­*ËÏ/R‚Ö% n)ÇR ‰ç‘œŒìäd\}J¨/éZòD¶&4à»  Ô‰‰­V5•ÁH…¬fvóÙ_Eò6d•Ó¹Õh ÁÑãµ×ÞÕϘÑÙ×ÌË쫯¾Šƒ‹¥v{ΑýûMG?ÞhdE• "¥äy° #¯£ RÁ Í}Eˆ;¿³95’6ñ^já³uƒe=@Q›› §ÓÙ¨ªéÙS±ÓR ÛxJà\ñt2¯Ù¯%ò!§šÕÈŸq„›Í¯÷\µê†ç%øáG€€à` >¼$x· ¢âûÊœ¸TÛí¨¶Ù@(CXI‚+ çûõCi×®ÜဦÔɦ[¶|Ë›Í~©çG‡Â+XÅqþ=¾¥ßí·¯ÍµX¾«þâ­íÇŸ’ï©§ž¢÷ýóŸßVéõkÊΞ­vVWÃ)Š(«­…S¼+Ž˜ÔöéA£i`éá.¢jI’­Ñº0ƒgÐ]! .8¸ÉüM¥jÁ“\½÷µ‹ K;;d•“Jc† û0 ::¿³/’—'šÌ‘züñÇíQQ ¬ÖOª23Eêp Öá@ym-$I’3D(C)ÇÁÙ½;©©T*™„ €õî|ž/'Mkì@Eí”(Ö#àî)9•’!MKºÆ$_-ä‚JU vÆL›ö½¦{÷ξF~\¦h’|,Ëâñü£0S¯_V^Zz¬67—‚RTØl¨¶Ûwøq{@ ÏCJM…””‘e¡fY¸ÕS¼$A#Š „´Éû)IRɈV ¦ —@v¶´D8_©—Yâ)ROdu»õÖíÁ×^[ÚÙèÏŽ={ö`âĉì.»dÚ&»—1 ƒ{ò÷óÂ)S–çä¼`0˜9³¥ 5Ï˪'!`$ D«éÝà ðÌ™ b–K)\î…Tš Æ{ÖôeÀ X¢ ÉB.ò­LhnTA.ªÜï ø2zðàÝ|ll£ç†ºcí!„ ž§¥ùÿ(ð<„‘éÓ§›DQìþüù¿ýö[ðÈ‘#2ä²Jík¶]<Çq¸úšk…zý§ç**úeg?¢ÕëY›V‹’ÚZ°,Tî~,Šdôzè ÅF³Gt‚5!°¸ÿnªâÁ+kÆM¾:»/ D£X[ëE>ê%Ð2ñDÈRÏz§Hïz×]ÛBz¨¶©ó²}ûvã³Ï>Éó¼çjÓJ>·òêY¨” j\.;f̘Ò×^{­báÂ…êwÞy'Šçy5šÎP¯Q76”6£€]ÅšÖ,]ºTEQ ¨Õjp\›ÖÄù]ñú믿÷Þ{=xžïAIq8É'OžìF) œ_àýÎÞÏŽF‹W$ºkW¬Ù²¥äñ»îZg..¾"À`¡NH@¥ÝŽJ• Ú€¹Ý~à¬V¨ Àº\Mþ –a@(…àV'›’zä§¢cTì>¸;¢5V,ëfhÉÖ+Cý:}•à2ßD$&~C‚ƒ›<'eeeÃÒÒÒºN!XS)£ TiÏž=_ðannntZZÚÈžáP_‘2OSKØ+¯1==½æ«¯¾:M)= Âo¾ùfÆøñãm„KÎk»fÍnÞ¼yO ‚ð€{“r—Ïã»,SúZ$!7Ýx#^ûàƒÿ¹÷ÞÕa99 º  nª°0Z,0¨Tæy™€„€/(€ª¤¤Ù9õî4OìÅÅæö?888;!!á¿<Ï›˜Ïž=íp8âPÓx¢š’¥R©J].W~TTT&„‡‡W%$$ìåy¾R’¤ÐŒŒŒn¢(ÆBv{‚¢¾À†ú4VŠúgŽr+ëp8hNNNwÿ`Îý÷ßÿ!˲+ûöí{:..Nb/¡LžçiLLÌ1µZ½ €K’$CFFÆÿ‰¢Ø¥³÷íb£MK„­_±"胙3Ÿa6ÿ=855€@0Ï#)8:–çp èÐ!èNŸnv @:àØÝj¾¹?°,´Ã‡ƒíÖ Ã@$U……8·?*ËË뺖Èí£!«žÍ ä4²|ÈR¯PžÃ7pàò?ü0§¥®Ô’$AE†I’ÈôéÓ 7n|A„Õ@O¼~õÕW¿¶uëÖÊððpYŠ3ŒÄºmVI’!„X,Ü}÷Ý!_ýõ³”Ò¿ùÌQ9`À€uz½þ'Jé9Ô///B£Fˆ¢˜rèСá‡c€DÔ7ƒ£(Ã0?˜Íæ'Nž¿å°@ç–”‚;†×”ãEé^æÛ Þ7M!VkÔMä»W±õœtZí¹˜›nz»5íà†Ã0uªÐÒ¥K+¿þúëóòò€7ù*† öźuëÊ£¢¢È^d,Ë‚eY €Flܸ±ôØöÉ'ŸÌô¼6,Ë–¾ûî»Kzöìy¶‘Ý)pÖápìòÉ'ßÍÌ̼úóÏ?ŸM)‹úH‘$éêÚÚÚù_~ùå”ñãÇç0—H%¾û\Ö]ŽãœN£¡ú~Ù¡MWà†ë®Ã?–-;]Û£ÇÊÂsçÒÅÒR@’Pfµ¢ªºê‚p55­šK/Š`Ѻ3ɇ .§.—Ë+˜ï™ÙÒRh¡²­'BŽë°›ÂÃ7%Ì›w¦ç‘B&¯mRþøãÛâZ¹Æ»ÙlƼyóªëw«-º.Õj5/^,®[·îû &< `3¼o`Æb± zî¹çîáÒ`^ÓP,’Ëm¾7ÝàÁ»Åuµ™™•Ôj…‹RÁuî\«æ p»ÿ¦u•Jr{A—Ó —»¯‹ÒŸEiºÛX¨ÂSêY!K=ä42'@´ÚÓ©O<±‘á8±ÅoµWrÀÛ²}×.˜Íf¼ñÆ'N\yá]Oh o_²d‰æŽó÷À'Nrh×pæßÿn·ôêµñLeåçÎsç\Äé„£¸…UUhMK/å̈ò}ÙbŠ™âu“Ða³ÁépxõâäѰ!Rc¡… ÔK6ù;®`fEøøñù¤îxµZ×_Ý¥Ñh|ŸÖŠS¤- @«Nc“ˆˆˆÀÍ7ß|r×{¯S_SSµ}ûöËÞ™ñG@»Èweß¾XòÁygâãß*ÎËûM*,”(!(…iíݦÀzH¿& lµ“.lÕÕpIR]â¶gêÖØzd èÀqû­Yó™*8¸Ý7<Çq¸þúë©;–ÖØHmmÇwà–[nqNŸ>ý4dg®'Tcg~t2Ú­û§ôè[däу¢¸Ä–•U)hµÔ†|È1³– qx·Tk¶°Ö-ñ(!°[,°VUÕérží!š³õȶ^­û½{áGhPЊ ¾}ó/b¡l{T¨ V»‚‚‚[‰†ö#ð'°§þh7ù†Áû[¶8+û÷ßyÜbyßUXè"#Q£Õ"²”i ž¹˜ÍV¾{ãmÕÕ¨­¬¬kbëÙ…º9òÙ!{D(dâ ôÀW}7lد¿[ïRFBì‘‘‘…½c~\ù!ˆˆˆÀ†ÿý¯äü€«‹JJ~ìvHQQ(%Åh§…œšÖT•ƒDiÚ)ª‹‹a­­m@>%Ť©42%´ äq@u×ÄÄ÷»vÍîì‹p1PUU…¬¬,#ƒÇf)!!áÌ»ï¾ë'ß%€ Nø‹ŒˆÀË«WŸ|¢oߥ÷ççÇñqq1’ÙŒ¼âb@î¥Ò”¥lç(­#[£q>JA ­º•ùùru¼=iNêY!«œ€L< @0ðiÒüù´½zuö5¸(øßÿþ§^µjUx¯j#„|¤R©Z-éûí7¤¥¥°,Ëq3räÈSš66’úå—_‘‘¡c&–çy~äÈ‘¿ò<AÚFUUvïÞÍRJÍA¶g]j(¥yf³¹pذaMÎQVVÆìÝ»WçþžW )êéʳÀBl7Üpƒ-((¨nž¬¬,>|XÇ0Œ ­'ߥ(mÇ·›L¦ '…… ¦qãvíÚ±cýí¥¥#,,Àa± Ûj…Þ5}¾PH¤H¨Æ2^DJ!RŠÚòrT—”ÔåTyдÔ+q_%ÁRv»úêŒ=z\–…²øòË/û¸Ác³¤V«?~ü'ž ¡¨¨[¶l1p·}ûö䯿þº€kôz}Vzzú¬ˆˆˆ*´€ÜÜ\lÛ¶-çùø>ø é»ï¾ë`ˆÉd*OOOŸbiiަ`µZÙ ¤¼üòËÃ)¥WCnÏùV³A.Ï<ž˜˜¸ÿ‘Gùºÿþ™C‡m0ÏéÓ§ƒî¸ãŽIú@¶L<“Û•\[Ïutx†av=zô‹Þ½{;•yvïÞÍ<ðÀcŒ‚ìVP–ƒTÚÇ*9ÿ:8p`×ÕW_-vù"ÃÃñÂâÅ•ËYvãoÛ¶õêx«Ô¥ ª³³‘#ŠHp…'}—…šÎr)…ÓnGEn.\îlOu³9•³rhAÉ#ðE×ñã¿U_†R¯¤¤sæÌ ýàƒî‡|S8Ž;9wîÜùÏ<óLIc+V¬Pgffå8..???zÆ qÓÔR /]H!‡F}ŽRJ±xñbUnnî0ŽãbÏŸ?ýá‡ÆûÌ!8€ p(-Z´ˆKOO¿{íÚµÓ(¥ƒ g z"òZ§½322n{ôÑG÷\yå•Ë—/_þå Aƒ|¥-Üir€4¾ì…Üa$2±›’%â +{‰¨ïã÷qg8ëþ¾|MÚ}•}+þò—ôuÛ¶­ŽÊÉI2&&¦ÂhDqY™œ|ØÌw•´‰¹O'.Ži·XPž›ÛÀÖkIê•¡¾· ‘¯Ô¹n7ßü±yìØŠŽ:öKUUUxøá‡Ã?þøã§Üƒú›äW–eŸ½÷Þ{¿S«ÕJ½÷ß?ôûï¿@oÈù¢Ý`MzI)¥X¿~}ÀÑ£Gÿ ™l†¶ÎÑX–Åo¼çŸ~–Åbyr¯gÖacþ‹c~þùçî3fÌøçÚµk·_yå•uìÞ½{åÆW©Tªÿ®_¿~ÔgŸ}6rа'Žßpà OOŸ>ý¼ËårBÊ¢££ž6l˜´~ýúY–ÝÀ8oÞ¼›ÎŸ?ÿŒû¸|6f̘“'OÎw¹\%‰‰‰"Ðä€1cÇâÐìùòwÞø¤&*ÊD,ä:€üHj Þ™,ž6Ÿ ¨-(€Ýj•/Zv´r Y-êÉÍb0°;¢wï¯T yè¿„† ÕJ)™9s¦þ×_½ñðáÃÓݪX ä ¿ëßÿþ÷ë×]wÝþˆˆˆ&c™,ËVXβl 5¥t$Iw ¡dA3sØ,eY6€ÂK’4X’¤Ûàmw¶ óçÏ犊ŠfX,–'²,»EÅ=·ÝvÛÙ.]º8W®\²ì@QoƒÜ/ÙóÞNúå—_ž›GåùXôM˜ö,ŒsÚí(u;Z<-`Eš5F<'äx£Yáv‡5ÎÆÞzëÆÈgži,ì’!ÅÅÅdÔ¨Q±6›M±#Œ—¡è{öìÙkG†YÚ5++%"5µk4’ŠòräA^1ÈW?Pì> õeÛž{m-,ååuåÜžRO/«!K=¥Ó 8" ÚÕwýú}ŒÁ€?"A0ž:uj•Õj½Ò½É3Á‡c&;""b— ŸŒ7nßüùóKµZ­S£iYxuëÖ ðˆ¥¥¥å86/>>ÞkŽÈÈÈ<È+­](ºèb6›? yqûöíçzôèáÕ*#44”RJk¾øâ‹ùùùs‡ "X,–ûá]erÛ¤I“ÞûᇊÝÇë“Ét€ò3¥TqS@ךššv»ýxkÎcii)çt:oƒ\“ùS\\Ü{O¹xŽ¿ôú=üðO{YY%Öèh8ÕjA¶Á€¦%à`¯­ª‚è®f÷õr6ÖþÝŽú uÅ9£å¸ìˆÔÔÕœÁð‡¬Š¦”‚çùʤ¤¤•îC …ÜßÙ¸¯0›Í3;ö@ffæ–Å‹ç›L&§N×nODãÉâm$îÀáwÞyç?Ço@<„˜L&DEE÷èÑc€c>1VTTÜ$ŠbcŽ,Z´H2dÈ6Ôߦ`~ÿý÷¯yë­·Z¥~Ϙ1£ÿ¯¿þÚ€3))é½wß}·¬©Ï^ò±,‹7/v†OúÑi›m[Me¥Ó +!ȇw«;a>¯Jó[Ï€»Í'¨®´¬k-oiYãñn’ÚÍññÛ®X±âÄÅ8Þß ¡¡¡ô£>ú|À€¯@Î÷•J…ÇæÌná…]‡-–wËkjlÕááp0 òаÖE¹[œîá©÷4fïy¦¤²¨†WÛxªS©Žõš7ï#N§» ¹K qqqX¼xqæèÑ£ßà«JçääüýÑGµcÇŽÎÞÕŽD{&UÛuE‘}ûí·ù¦ÈDz,¦Nš¯×ë?7ᇮY³¦÷©S§ýÞîÝ»ƒŽ;v“J¥Ú2mÚ´ü–Tÿ‹ÞN@«Ñàæqãª~6fQƲ°††¢õê§ç™%¨o‚éI.ߨ‹ú EêÕ@& R-¡Ç­ˆ7.ŸáùVìíñññX¶lÙ÷7Þxã2Èe”žHÌÊÊzüǼ¢³÷³“့m •J%¼ùæ›VCóo!äCÔ­ Û¿ÿœœœ€&¾3@¥ÿùÏþ^‹ð»ôòHHHÀ³«WŸÝ'«óJK- ‚+ ðV?H\-åoò)CqÌ(eBÊ™òH¤Û×o͚ݚ®]/©ç‰nݺIÝ»wß`+¼«¸€á«V­š½iÓ¦?sá¬Y‰ªÃ0…C† q4g‹ lذáŒZ­Þåó¯Gƒ6æ;wîdßzë­aã;œÑ‡×ïB>•J…{'O–¦¾ùæ¾]ë ŽŠ*“ "Ë¢²úéK@¥ua‡ÆRÊ ©x;«QïÄÑж.FãZcjêecë5†W_}µvܸq¯CΙôô¬q•••1cƽ[¶lQ_Œ¶ô(+xâ4Z0 ƒÔÔÔ*“É´ÞÞÚ«¦NÚëÔ©S^*pfffJYYÙp£Ñø?•JÕª5>~·.V,à &!ÁZj4n>‘›ûi±F#:‚‚à‚Ü7S!Nc!å,úÚ{Êÿì-õÝc€Ï{¯\¹_ß·ïe}× lÚ´)gìØ±Ï3 sÞÏ1½Åbyô¾ûîyäÈ‘ËÉÓZ¨!gyâ€+*ºví*½ÿþûGüè±™-))ùKzzz¨èî?´{÷n<ùä“ý!‡0v­ZµêXïÞ½[µs¿k ¹Ñ£Fáù•+s2M¦·Oçå­ …¨ÕÂ9ª©<¶= èٖٓ€žÞÐÔ‡´t@yl|ü–àØØË²PÖ:7nü1""bä¬:OFÛl¶§úé§ÞN§³}?PK½å / + ÔôíÛ÷{NךF Èð_Ïm’$ÝÛ¶m[ðàÁõN§óËÇ{,¯¤¤›6m2q74;;{²(Š)*•êSžç×ÖÖ>î1-‘$)¸ººš nê8d'ç?ÙÌÌÌ¿fffö9r䦮]»~¾uëÖb­V«„z ÇqììÙ³Í{öìy8??2§^¯Ÿû—¿üeÓÒ¥K+ PÃŒèèè}Ò\¥œ Èm*~ˆÿ"<<¼í+ëawæ8òóÏLWž¿én“éÔÃ11ô.†¡ãz/@gô%€.èj€®è?z@Çô>€¾Ø?îÑc‰£¼œë¬cÈÏÏ×ëõUð®pú|ÇŽ M}§¤¤D“žžš‘‘þóÏ?w½ À64¬ |””Ô÷ĉ]Ïœ9žžžn*++S7·O¢(âø?¿52g9!äµ_|±GVVV¨Õjmpî6mÚ¤×jµoÁ»xDÙ+€ ­V›§V«s!wg´(cfɤI“Œ«W¯ðÏw«zõêu÷É“'£ÝÇa¬¨¨`•߬¨¨P‡††þõm—ÏïÖBò‚ƒƒ? y>$$dfHHÈœ5*•*@!d×õ×_?´¨¨ˆ¯©©éë»páB†çùU>ÇRqÝu×ýÝf³µkÎN'¥¹¹¹Я_@O†™ó@DDÕ”ÐP:ÎM°ú<@—t-@Wô€ÞÐÛ:V°lÆ¡ R%Aè´ch‚|ïïØ±#²©ï<ñÄ7ø˜çùC<ÏgBŽœ4µªµÀÆó|Ïó|ôâ‹/^×Ò~-X°³PŸÉç5X–-Q©TŸ|ÿý÷‰}éÒ¥)ƒA)±i®=ª‹a˜Œ¾}ûΛ0aB (ŠØ°aC,€í|ÖÉóü9žçX´hÑ¢näÓ†††*åRG!/uvõ¾5ÏóáÕ_@n¯^½Œ=:¢¼¼œH’Ô¡×xÒ¤IwÈUöçù_þö·¿ukï|—DÞUTT6nÞ\ûФI[Ï?Þ+54t’F§cíV+jÜw¤âåô\¼Î(WhXØÆ¾«WŸ¹ˆë-´î]n‚ ¨0N§³ ²ä84è!¥ôbÜŸ­súŠbË­çÌ™—Ëõîüùó£jjj®B}Ón 'Š¢JE›$IÚÿ³fÍ:)IÒ“Ï=÷ܱÊÊÊám=d»L‚ìt.2dÈñnݺ}øÖ[oí UT'd©ˆz\tÙ¶eDQô¼p”Rj1û®¿þúùö2 sÍáÇïÌÎÎî ÙÊ0 ÞvTd 2dÓÆ?‰‹‹k³ýÕ°,»@&ägöäää/.\˜ÕÞù. ò@R÷îX¼vmö‹=´¶*--Õ4ÀåtÂ)¨€Ü%ÈÙýæn÷Ž.5rÜ™äñãßcy¾Ól=—Ë…Í›7w»ÎV¹æškÎuïÞ½ÉT¦k¯½v—ÝnßÏqœòW¶ú.-¦„8e‚@hE+ðÌ3ÏX9Ž{áܹsj†a”†®ŠÉ¬¡”ò‘‘‘MîçìÙ³ÏBþ}òäÉ5 äB&€Ö½Ÿe’$eÌœ9ó\Ïž=½bÉÉÉÅ3fÌxÍÄì@½ ÈäQ ‚€~ýúÕ‡Z­v=øàƒï„††ŠO<ñÄ ·]¸oÆ û8Еã¸È}9uîý¯+Šâo³fͪjíB¤íÁ˜1c wíÚõS^^Þ@Èš„¢R·­rúŽ%‹«’é3## &ôV€þU¶ëèB€>Ð;: ¯®Í³­¹¹|gî³ÅbATTTê +(€³Ë–-ÙÙçÓ?:nìØ±111‹Xôzý:%a¡½ó]r¹z£ÆŒq¥ŒõñÉ‚‚íÁƒW«á‚¬“Y ?j äþxFBõý׿>U›Lœ´Ø€·‡îøTQûñÇÆöíÛ£²³³€Á`X7iÒ$ç…¬mÉ‘/!>‹V®, ¿îº•%¥¥?™CC)a˜º&ú.È ¿ p†°ìÛá7ߜŴ¢¥ÛE†òþ×4«u)ïrå Zm]uƒ @ð͕˗ï LMýÝš"‰¢ˆªª*Ƴ¥µµµ¬$I} Ûc.ŸôèÑcg{ƒº~\zX²d‰zëÖ­73 ï 0 š½@ß%I>X¸h‘”xË-_dVTl®åFHs8Í€%Ê`x?49ùìïY(›––Ãc=–PTT¤ÏÉÉQggg«ï¸ãލ‚‚‚»!7®ýzã™gži÷*<~\Zp¹\HOO¿Ön·aæçÍ›7Œˆˆ¸ð‡~g±Íšš\•œ?M§ûì?©©Â‹ÌÿôSSgìË‘#Gb !ßÁ;Ó"›eÙ%Ó§OO´Ùl¤³Ï—tÜ(//ÇìÙ³ÍÖ¸¯õ+_}õ•¾£æ¿äÑZ­¯,XPûÏtnÙ²!7ÜðsÄèÑe>s»P à ä°B-€´‰'îºâŠ+>›9sfmkÒðãÒÃ?þ¨úä“ObY–-¿ÿþûË»uë†êêjÌ›7O¿|ùò©îpzìØ±Ÿ%%%u˜-É“‚ Ü>yrÞs{ö,J¹ï¾ŽXx£]ˆ‰‰©\½zõ[Ø%I:7zôèš¶húqiáàÁƒq/¿üò\ôÈ‘#DFFž¬®®Žøè£îp/ä4¸­·ß~ûáØØØ û1Ot¶hoµ PQC‡wú~øÇå7-ZtäJur÷ÈÀ•dò¯'Mš”\TTÔ¡¿ÛéîþÑ™ã›o¾Q………½ˆ¦«5~ž0aÂõeeeþÛµÓ?.ÊËËË‹‹!'Gxv­´øñŽ;îxqÕªU‡.¤·)øÉçÇŸƒ!/11qJ¥:yù0 [’¤}©©©{Þ{ï½jNwQ/J/ë†Î~øÑ,$I‚$I€w‡8ÏbãÛv´~òùáG'á’ÍíôÃË~òùáG'ÁO>?üè$øÉç‡?ùüð£“ðÿ"µÆHÌA5tEXtSoftwarewww.inkscape.org›î<IEND®B`‚jenkins-json-2.4-jenkins-3/src/site/resources/images/logos/maven-feather.png0000664000175000017500000000553311650253660027641 0ustar jamespagejamespage‰PNG  IHDRZ¬a xgAMA± üatIMEÓ:–“¬bKGDÿÿÿ ½§“ pHYs."."ªâÝ’ ØIDAThÞíZPTYýÝM4¡¸Î8怎¡\§TŒ¨¥ŽŠ#IADPaÁ芨ëÎè:cÆÌvÌR–»ˆŠŠ™†$Ó€‚Š`fÌY1žýçUý®²[–;;cºU¯úýûo¿þÿ¼ûλ÷¾–ðI~‘”ÎÙ³g‘žžþVƒDEEáÙ³g8xð îܹ#t‡ÆÍ›7_³åoœ9sæã::: .|«Aúö틇ÂÛÛÛâ˜1cŸŸÿší¢E‹°sçÎO@Ó³W®\‰Õ«WãâÅ‹FÃÄÄD<}úÔx}ÿþ}¤¦¦Š~||<ž?.€>yò$öíÛ‡>}ú`É’%HKK«謬,,_¾ëׯÇ7ĽóçÏ#;;»œ}ff&®\¹òaMpŒ­[· ºwï.è€B½š áããóšGçååaݺuèÒ¥ ÂÂÂpèС׀0`<==±}ûv¬ZµJØ`;"¤£N:áöíÛbâ8ð__æñãÇïÐݺu/§µ³³/ð¦@¿ uä—/_–ËÞÞ¯^½‚»»;’’’„ž+cüøñ¢‡ÜÜ\ÑçJb£½"—¯þ‚Tyõœ+.AÙã2ܾPŠ;—~Áó§ÏÞŽ9r$N:õ«]‘£ ú Aƒ…Ðkýüü„ÎÅÅEPQE!……‡‡‹I9zô¨pŽ,C>–¯Ù†ÃÇõˆŽCæò„™{!ÍÆ‰ÿ‚³«w¡t¿·å QOòïô”)S^3à2/--…““JJJŒz.u//¯·š4PqÉ÷êÕ eee¢ÙÚÚâĉüÿ$=6ýúõô²lÙ2Ì_‘Q˜UgViü%yãˆÜâ¤È–†!U3éU]‘o‚s›öâöå ¿è倶²²Â®]»Ä’|ñâV¬X!ãà   ¡çÆ <êm€nذ¡Ø\)–\>kÖ,£Í¼yóдiSAŠìÙ³G[q%\»vMì)|†Ï>ûÎÎ.ð¬å‹qU'á[ó‰˜eò'DJ£±Cûä‡ã’R¤!ÈÕ9!ÕÚ9A(˜µWOdË4Söÿúøñ㈈ˆÀرcѹsgÑfΜ)€P ú=zš3gޏ7qâDᕳgÏ6F*sçÎEqqñk?)€1b„Øøºví*ƪÈÙ-Z´“ªÈ¶mÛÄ3V:Å±ã ø~á2¸zøÂ¹—3êjêâ m}t5ï o ?Lµœ‚?[†"Ô,Fa—Ü?K®²·;@oã}ëáH šŠ¼ˆm¸‹ónáÙ“¿Ðï’ø¥K—¾‘mIÉylŽÜ [v zÏ~ÄÚNÂVSÌ4óF ;Ô×|ŽzÚ°5ëGKwL2‹ øA;[e°wÈÔ+¹#^þÌ’#ÉÄ™’3rdð j:"ï2å|å…ܰy8s䟸VRˆçÏž¿ÿ@scsvv®4«¬LèõŒý ²÷Bÿ…‡ì¡ŽH”A;¤óÂ’ša± }{|iÚ Õ¥ÂÛ»è:ÁÞtæj}0Ílþ%ÓËÉW¦/™×ÇÈ^ï!O‚‡Ü÷ y"²µƒñSKoüh5‰¼‘6a6ŠÂ6¡ìÞý÷×£ßfr8?óé‘5ȧ8#ÏÔ «OÂꪰ J0þVe¦×œŠ€*ÞhÖGo­³†•Æ í5ÍÑݤÜL1^3 -Æ#Ä"kešùI‰ ZoW Ã.­6êFË|FnÈóö…Áã[6.Çͳ{qùR–¼Qßÿ0®èá%犻§ÂCap ƒä„dÉMŽ></ƒx@¦‰ÃºáXo>kLü.ƒ`êW]oؙ٢½É—h"{}#]C´Õ4E7Éu1LÛ º¯`>\öô¡ˆ–ù=Nöø\Sœ51ÈJAÒ±`œÌÝŽ'~¸@S¸A2ü+-½ C¦ÙÑ+qry²ë E±ƒ²þà†Â֮ȫí&(ægi¸Ü< —'c¯ì¹{L±Sã‹ðjX#{óT3_Œ6…Å2%9›ÙÃYÓ}uÝÐOk G©=FX…ïíþ×~Ø<߻׸áðžˆÛˆ«%Y.Ð=œÅ‹‹‘qä(römG¦¼Ì“ý&ðvÒë¹ Ëê¤k¿ÁÒ†VnÈÑ F¡ÎEææ!H•[’ p¤–ñøp¤iÜ#Çäqò†¹GöæDÙ«ÈñyÒ×rg÷8d'!=ƱÛ}ñ¤¥D@WärzúƒDzùòe²‘ÃÁxd®ÞÄuGâì%HóÒ"æ ¥ÍHd´pCÊøÑÈpðEr7Od‡ ÁÆ éþ~H5I¡K2ç$»„ !f>ôñHÕG!×*ò‹èÊ„ñ;0z>S{V%Ù¸ 8¬žÙqAAH®_¿.uŒŽ”ï°Ïï±ÿäÉ“r¹ÁÍXÔaNOؽ{·È"y­d’ "ÃÜ¿¥áíøð±±±ÂŽåU>“ŽÍ{EEE¢áÂ…rߥg(E¥÷QÞh–4%IBãÆQ§NÑg«Zµª¨]°ú¦ÑhŒúÚµk—+Ñk/^Œš5kmØzöì)êì¯]»¡¡¡¢ßºuër™!ËÔ7jÔHx%##íÛ·/7ž………ÈX•*$ÏX£F ‘ÕªmÛ¶m+²ÐwhåeYÌ騱£¸Öjµd‚C}³fÍ„¾Aƒb©QX£¦ m;¾¸©©)LLLŒ@ó  Zµj077/whÀ ¡ Ó}® ÖQ8éÔµjÕJŒÇ «^½ºø–Ô@ÓÎÒÒRÔØYw'ðÔ±d«.·¾3@ó“““…îÞ½{èСƒÐ7oÞ\p%''ÖÖÖDžÞºuK‰ˮʉ ë# ,€™™™hz>Aãõ´iÓ„3?z*KII:a3dÈãdò»ÇŽv\u,p©ž>}ºàaËâuuëÖß{瀦·ªIÞßß_è  âü´±±z‘øò³V­Z8wî\¹q ¶²24eË–-Âó[¶l)6z§B3¤ŽO¯Wt,ײrH YäJâ=Ž£Í¦>|晲BÕGtï Ðô\µ°\J=W «o ÐÜ4Ù¯_¿~¥õ_WW×r@3ü¢-'‡GaœN‡Í›7‹ûÜŒy­æÛÊ SjŽæJS„õôh½^/ø‘/Ëӵܽ{Wp¶hÊäÉ“…Ž¥Tò.—8)ˆÂM’µsÞ §,l,¿rcVý¨€fhÆž×4‚Í088XÐDE yÈKŽWÀࡃZÆ'ô}Úø—4E¸ù’¢ØÔ“Å>ÇVBÍwèOò¿É¿6úû·"¹UQIEND®B`‚jenkins-json-2.4-jenkins-3/src/site/resources/images/logos/groovy-logo.png0000664000175000017500000004223011650253660027375 0ustar jamespagejamespage‰PNG  IHDRËd§ÓS_gAMAÙBÖO¡ pHYs  šœD IDATxÚí]w\Çö?3»{/\z¥*š‚Ø°¡b7jŒ-¶Ä5½¾˜Ÿ±Ä$æ©)¶g‹Dнklˆ½RDŠ)ÒoÛÝ™ßÃݬ ‰//ßïy>|øÜ»wwföÌwÎ9sæÌD)…gôÄ…¢”"„º9ÿ5„ºÿ¤ ê¼þ]z†°ß'†*5È”ÿÏèwé‹(¥”R£Ñ(I!¤¡›óßDÏö;¤0HJJZ¼x1Çqê‹Ïè·é›~‡Ô:1::úúõëçÎkÖ¬Ó˜Ïl²ß¥g2ì·ˆÉ*Y–1ÆË–-KNN®ªªš9s&ƘéÊgãówéÂI ¼xž¿}ûöÂ… !¡íÛ·oݺ•ã8Y–ŸéÊߥg{81x }þùÜŒŒ ÌaŒ±Á`˜ûùE÷îñ<Ï0÷ d¿AÏöH¢”ʲ,BBB† qT¦²,sˆ;ŸrnÞW_QBdY~¯ß¦g{81&Baaá·ß}k2™4ZAçèìàêŽ0FýðÃÇOœá™®ümz†°‡ó~€Ñh\±byʹ /Æ–Ñ]£†¿$QÂc®  `ÑâÅUUU€Ð3ÙoÐ3„Õ%ÅÃçää¬X±’áÔËÅ©yÇØ&;FteIàùû÷Ÿ:uŠç¸gÖØoÐ3„Õ%e!´sçÎÜÜ\#I–ƒ»÷uhì/Ê$rн#%¤¢¢bÅŠUU•ÌyñÌ7öPz†°ºÄDÆøØ±csçÎåyÁ,I­"}b{K„ÈÕ®þMÛôyN,ð|bbâªU«ŸÉ°‡Ò¨ŠþºZôzýŒ3îß¿OdIkcÞw¨µ³ÑWB&IjÛÓ78T”$Y–çÌ™“žžÎö dõé¿aÊÒM"„(ýúö®µ¡„„„cÇŽixPÓͳeˆA_¼8^4›9{ÇV½‡hu¶B¥¥¥_ýµ$IêÈ‹g¤ÐS0µTeBøA†³ÿ\O)XQQÑôéÓÀ,‰Î|[vëK(PIÌ!J1%’ÉäÞ¢S7‰ŽÃK—.KJÚ¥¬T>™šž^„)â„yÕ9ŽCÕÔÔdee]ºtéìٳׯ_¿wïBˆã¸?d  §OŸÎJƘ ëÑßÑ·‰±¦šG@¢a„¨ÉHîÚËÁÍC– ÷嗃ᙢ¬OOé€Sà%IÃÖ;wvìÜy.9ùÂ… ùùù•••nnnAAA½zõ5j”¿¿?›Íý±(ge ’ã¸ÄÄÄ‘#G ðnÖçéÀq²("ŒñÊbrélí’^“²k ¥(ýä“OfÏž]'\ñ=Sº‡u9!dÕêÕËÿõ¯””å%º:tè°råÊÐÐPå]þÂÄÇÇ߸quÜ+oùuˆ1WW×b°ÿD–y+k±ªb÷׳‹²2B666lÛ¶-²PC3ò© §QK2Àà•››;nܸ©S§¦¤¤ðHO#˜8að1bĆ dIbÑ2¢(šÍfI’¥’$I’d6›9ŽK9—¼råÊ?¨èÇüüümÛ¶±Ål[»vƒ^¥„ÀCŠ¥€y^_YÐ16 Mvõرc)))DZ©å3ÁS…0ÅéÀ&ŒiiiÆ ;uê”  ”RooïyóæK9wóÆ 4nܘ=‚Z¾beUUÕèWÐkÖ¬¹pá0¥Ðª×gß@³¾ºÎAíw„`ŽB1nݳ¿­½PXX8kölQIÖÐLmxâ>ýôÓ†nÀƒáð¡sçÎ=ÿüóW®\aö¥ÔÆÆføðácÇŽ•$)7'·Eóæýú÷×ëõGŽaWVVÄÆÆ6mÚôñ­luŒá±cÇÞÿýêêj Ô+08jô+²,ÁC6HÖ~‹ë_6›½¼E£!/õHKKsssëС‹¹x²§B†)ðbã~Û¶m½â㙣œýðé§ŸbŒßyçwß}÷wÞK¸ÇqGŽ™ôê«åeeŠ7µ]»v“&MÚ¶mÛºuëjjjØýwïÞ=q℟ŸŸ££#XŒ$6|L§”²ÎCÙôÓO{÷îåyA¥ .ñöý̮͢ÿ ȲÙ%B”Pž×Dö*h´<ϧ§§ûÝwf³™µÿ\Œ5<ÂÔªêæÍ›¯¼òJIq1ó×SJÛwèЫW¯%K–œ:uŠã8°t¹Éd*))qss³³³S.VVV>~¥ì?Æ8++kÁ‚Ç%Ž^>a=úSÀTäãH J)FF“Ñ­yH‹ènlNúÓ¦M‡bûÞþÇݰ Œ0^¡ÒÒÒ÷ßÿöíÛ I’$µhÑ"&:zÕªU¹¹¹<ϳ…#Ö[f³¹¦¦FE“ɤ”ÆnxRÔ!dÑ¢EéiiÇK²gëî%˜RdÙù[åPJ„ Yâ9¾ELœÆZÇq|UUÕܹŸß¿Ÿ“ÿe1ÖSúDQüä“OvïÞÍÆ=!Ä××·W|üŽI………<ÏK’Äžb½¥ÕjM&“ÚÖ±··üªÙ‡“'O.]ºTÃóF³É¥‘¯_ëv²,ÅCñûd* zgÿ¦¡{˜Í&­Fsâĉ 6<ó5$¼˜6gΜ•+W2ë˜Ò²eËQ£FíÛ·/#= x)dmmíîî^VV¦×ë•‹ Â~[f(ýM™={¶Ñh” ±¶wìøüX{Ÿ³ÉT».ô˜øÌ[@ AœÐªç@ÿ@³( ¼0﫯 òóëTú¿F /Ã8ŽÛ¸qã¼yó¶(¥ŽŽŽãÆÛ¿Zjª££cÓÀÀúÏÚÚÚúøø”””0„±þcî±Ç©BIII‡FË„4 ÷nÝF4j}]ÿÎgmq‰½Î³q«Þƒy•,Kywï®\µJ)ád ƒ0u$Ö©S§ÞyçQ€©¼>úè—'.\¸`oo¿téÒ¾}ú[)‹|ruuõóó+((`Ö=ƒB@@ü¦S{Ý §M›F¡”Ø»º…ö@9$K ¬p?Ækµü1HŠFƒx;ÿ°pB)‡ñW_}•’’¢ìy(ÎþÀlà¿eÑS †ÊÊÊO>ù„YÄÌ=ñÞ{ïåççïÚ½&¼ôÒˆ#‚‚‚@%ØoooŽãÊÊÊŒF#»Îqœ¯¯¯úžGÕÎ&K–,¹yó&kH«ƒÜ‚Zõ5œÊ®¢ &yàZ™·‚R¤Zq7XgÓº÷;7™½^ÿÁ(‘’uâ­•™¦r½ÕyõOõ‹Rö?êñ¡'0u´*BhùòåGŽaÌ’$©Gk×®€=z|:ctîÜ9$$„yËÀÐæÍ›@VV–Édb×ÝÝ=XxE,_uj¤”ò<íÚµeË–¥àÕ,$¨sœ±¦šC€¼n(!Ài´¼•oeÍk­8sXÇàȪd5ñZ-%Ô¯u›Vqý0æàèÑ£+W®d“J¶ö¥vÅÉbà•¨cÕ¬SÖ ˆe3°â©fžFê‹ >ÏhÆÞ™mµ˜7o°µYöññéիתÕßWTTøøø,Y²ÄÑÑ‘RÚ´iS†'…lllºtéb6›™‹Õ2»Ô°uIåŠd!%>–}®ªªúàƒX,†N§k?x²¶kªÕð¢J° h­­©ÙT]\T^kªª ¢™C hµÖvöX%a¶\I8k¦´èÖ•k“ªËK8†5xÁ‚ÉÉÉc¶(κœ…U²Žãد¬å (<Ï3Î0¬›S³•¸K¶ñc\]]]YY©×ëEQd¥©ÇUC!Œ’•QU2ˆâââwÞy§¸¸˜ñT§Ó½û޻ׯ]O½uæÌ™Ó¬Y3I’xž/..ÎÉÉQ£ÓÍÍ-66655599,ÖÛ;wÆŒ³ÿ~+++vE1Ý@ñ<ÏóÍ7‡bK‹¡1ÝýÚt4 ÖŽ&£$sAH¬±³#UeWî*¸u¥¢´X2mœœuvö­½‹k£fANAZ¹ª q°vp,½}ëÒî­9—Ï 5êOMM5jÔ¨Q£ÆŒÓ¬Y3Ö&JSSS­¬¬š4iâìì|óæÍcÇŽÕTWÛÙÛÛØØ„†††‡‡»»»³wÄïܹsÏž=<Ï·hÑ"..®eË–L´çåå%%%?~\’$+++N×´iÓèè訨(E.6²½â¯#†-Q)¥S_{ ,ƒ^ýõ ööö㸸¸êêjY–%I2™L3fÌ`w*m:t(¥tãÆ‚ ‚Àô›–þøãJu\¼xñ?üpíÚ5vÅd2mܸÑßߟ•cçî5fÞ²‘Ÿ-:ýŸ#ç,š´jÛÄÕÛ_Z²qŠ-“Wn7m–«ÈGñÍÆÚºi›Ž#?[ôÚÚãÿ8ymÒàiŸ»xûà9žãxÖ0u‡‡‡¯^½š5fÁ‚ÌÄÔh4!!!Ý»wwuuUW¡Óézöì¹bÅ ŸýÑ´iZ­Vù5,,lË–-”ÒÛqqqõ[ظqã¥K—>Ô>{’Tk!ªÛñ×¥”ÁkïÞ½6¶¶,JZŸ8q"6¶3cÍöíÛ©Åd9uꔳ³³DµeË–‰¢È0Z‡&Ož,ËrNNΤI“Øè×h4AAA .cç¯zuõöWWlé;å}'à8óžý Ö¼ ås<óQ¸6ööɼ×~<ð§ ìœÝsŒyÌý*>ÓY†IÖ·ß~û£>zh4 ±T¢,ÙýcÆŒyã7”Ø=àï““ýê«“@àyå'öaôÀO gëw´è?(ÃÔ ¬ÿáQĬ¢ÒÒÒ.]º³ÐµZí¶íÛ/^ÌØšŸŸÏî/++2d<¨ïlíìrssïܹãíí ïðA×®]•®óâ‹”Ò‘#G*pd4ŸŸ_Ý‹‚P -:ÄN]³sðßfkmícfý?„ƘçÀÙÝ£ÿ[{4Œ8e1 QãÆAAA!!!sÊSêa-aÒ—AP-§Ù¯êû‰€ã^ß¾}ÝÜÝÕ#P!vCÿþýÿ˜ø¨ó”4Ê•[†•——•–– ³Ùl6›M#³ÙL1Œ’$RJÍf3“7&³Y)WEfÒ>€K‹vPssêÔ©ywï6iÒ„±oÚ´iŠm{üøqµýËhÈ!”Ò… €««kZZÚßÿþwåטØÎL«ò§¬”«åßC,&K0fZõèÚØG D±cÇþãÿ˜2eò+¯¼Ò­[7&B!Œ0h¬uµGZ´h1þ‚ëׯ—””ìÞ½{íÚµÓ§OoÛ¶m|?”œCBB‚ƒƒmmm-­«d¦ÑZ=ôYAºté2hÐ _åYW7·ªªª? ADQdAÅì ët“Éd4ÙOF£‘áD¯×•••10(¬"ìRIIɪU«¶nO¼WP€9Ìó‚N§ã9Î$ŠÇaŒxžg32 ²L Çs^$Q£Ñ2_$ ¬´Z³(jµI’1ÆZ+íåËWج|üüæÏŸ¿páÂÌÌL+++£ÑØ¡CÖ”ÒC‡BØœHáã´iÓnݺ5{ölÖ÷666JFÂ3§Oýrâ8H–Upöž¬:R/IίŽ{J™õÊÀ#Ìžï?`àûï½ÖÊÙÙùÀÉÉÉ/¿ü²N§{õÕWOŸ>8 Ì=€€’:¼ÿþûîîîÁÁÁË—/Ÿ9k%¤]»vŸ~úivvöÇ\QQ¡lcÑh4“&M*++KHH@¹¹¹%$$0ó¼´´tïÞ½ß|óÍ­[·Ô6lØØ±c Dë¹»DQìØ±ãìÙ³7lH˜:uŠÑhD•••õèÑÃÆÚJ”$“É„f!à•e"ÉÇqD&Z­Öh2ɲ€DQäyÞl6Q ˜ç‰$q<¯ðuŠ(Š!½Ñ$J’$š:¶o÷òË/GGG³¨0öWaÈ3.\øä“OÂÃí¬1V¬¬}Z„…µòkíÑÉ£YH£ pŸÐHæ¡ÍBjÿƒ=š…x4 u÷ ðhäîãçî×Ô#0Xke ײlÆŒ555:t`ƒÛÉÉéüùóŠÅöæ›o*Òžý0`€(ŠLu@Ÿ>}jjjNž<éàà*›F‘[S§NõððP ‡ï¾ûŽÕÈŒ•Þ½{O|åà¸_¥ ‡1ÄDÇüôÓOk×®•eyñâÅŒq¶¶¶K–,ÉÏω‰QŠE€§§çŽ;fÍšµuëVBÈk*KÑÖÖö»ï¾[´h³ÖYSÛ¶kG)MIIa6~||üýû÷)¥999ƒþì³Ï6mÚÔºukµä›ñé§”Ò‰'ƒ:—Ýàãã“‘‘qûöíÀÀ@åÁÊÚŸ»¿»¿»o€»¿GÓ ×Æ¾î>þî>~Íkÿš…ºû5ñhäÞ4È£Yh£6þ¡Í"£Ã"œ]\ Žã5öž8qâž={ C}­Ê×鈈ˆˆˆˆ˜>}ú±cÇ~øá‡£Gæææ2—ÇqQDrlÔªU['ŸžçDI–a€)¡$3åD)øI± %D>þ¯7ÏGSœ^{íµœœœ‹/2!¤Óé´Z-“+Çyxx0ÿœ<Ïýõ×6lغu«F£1›ÍÞÞÞ:.<<¼qãÆTå['„<÷Üs_}õÕ¥K—”»¡©S§¾þúëVVVÉÉÉ¢(¬ZµjÏž=+W¬À˜“ež— ñöö~íõן{î9ŒqâÎl×IuuõÔ©S ÃìÙ³ûöík0B”V{{û„„„­[·À‡~øË/¿\¾|™9«Þzë­o¾ùföìÙü1ãgFzúž={ºwïŸ`mmÍTŒÝùóç·mÛÖ¹sçwß}÷›¯¿¾pñ"“|_ýM¯ž='Mš´nÝ:õ~BB(77÷믿þî»ïüýý322˜TnÒííOE“ 0F”P^Ce‰}@’0G! Ë¢Ì H’x†×Z™DQW’“ýÊ…ŒL)7‹Ç<à_£<==###GŽÙ£Gœ‡‡g}ðÕúö”ïj5Ìâ{öìùý÷ßïÝ»÷Ë/¿ìÞ½»»»»,˲,I&CÞ­+'~\½uöû‡–}•zæDEaž`e…D©Þ,jª ’l2šD³É$IFI6Š’DhÅÝœü;退ǻ¹¹]¿~Ýl6³!È”=“¦¡6mÚPJM&cåÒ¥K‹ŠŠÞyç懴¶¶ŽŒŒ”$I§ÓuìØQ=š !ááá_ýµ••Uhh(BH£Ñˆ¢9eÊI’†:sæÌ®]»®X±ÂÍÍõèÑ£hJàoû›­­í7ºtéB)ýðý÷0ÆÆ_~ùeNNN\Šüà8®gÏžgΜÉÌ̬©©!„x{{¯Y³&6¶3S+0wîÜÖ­[6ŒRŠ1.//Ÿ6m¥´{\ddd0Ÿ°££ãwß}ÇqÜñãÇW®Z5éÕW==½!ãŠò²üã-Z´èÞ½;¥T-ÆXnܸ1==½{÷î@€ÜœÜÊâ{2B&“É(S“Ñ`2‹F‰˜ £DŒf³ÉdÔôz½ÁD1Åg­3TWç^»xáçïWÿó‹«W¤ÛWY^&I’$›víÚM›6íçŸNJJ=z´‡‡§b:ÿjà+Ý¡nŸbT²áÎ ½-Z¼÷Þ{;wîܰaÃ{ï¿f †›¿>ðí燖Î;™°²èÖl2ØÛÛÛ:8ò²D% ‚aŒ9 E™©Es„PŒÑ˜1c(¥ééé`ñ(Þ¿???Ÿ-°PJÛ¶m;räHooïN:mÞ¼9>>~ܸqååå¬m‘‘‘v¶¶_ýuuuõ°aÃ=Â^ÁÉÉ©¤¤cÌL“Éäîî>kÖ,öëôéÓwíÞ—šš~ðàAV¦ÂˆˆˆW^yeõêÕ...nnn„¸¸¸o¿ýV«ÕB¡¢¢¢-[¶4iÒDqðtíÚ5##CÅmÛ¶±ÙLxxxbâö^½z±A[PPð÷¿ÿ½_¿~7fRçæÍ›IIIQ;zxx¤¥¥?žçyQ !‚ œ8~<55uØ /‚À,›S§N?~œÁTmY2—””lÙ²¥M›6¶¶¶„R ¸¦²¼4çŽÀ ‰˜ÈaÄQÂÅDIBÖ:­ ¤&?÷ÆGV,ܳpVòÎÍ•ùÙ@kwÄøúø¼òÊ+ßÿ}bbâܹscbb˜Ï’Z¬Š”V=ħ¯üÌxÄàimmݳgÏž={¾4a­[·Î&'Ÿ:uêä/'(Rp;­àvZê©#®|Üš6mëæ`ãàh4‹’ɈˆŒyRš› 'ˆ¢±}ûöaaa!ÏN-Á®ß~ûmTT”½½½(ŠÎÎ΋-ÊËËóõõMNNîÓ§OZZQãQ£FUÕÔ̘1#::ºk×®iiiÀäß‘#G^xá…M?ýÔ½{÷¸=ltºÏ>û,44”i[&&µÍýû÷ÿ1ã………êMäðñÇ———ïÛ·¯sçΕ••:Îl6>¼´´ôÍ·Þ"²Œ:þ|€¿¿‡‡Gvv6 8ÐÍÍ-//–-[f6›'MšÔ¨Q£[·n1ì2ó9%%åÖ­[ƒ^ºt©,Ëf³ùûï¿ÿñÇÛ¶m»k×®wÞyG„^½zýôÓ¦Ú¹ϯ\¹réÒ¥ÉgÛœ={–ã8ƒÁðÑG5nÜ8//¯NËà‡~hÕªUóæÍ/\¸€/‹æ²{><l J© ++d2TÝË¿{íRá­«¥wKór(³D @Ë–-cbc»véÈìWö.ŠáA3Æé‘«FÊ3JÈ<ë¹àààààà!C†äåå]¾|yíÚµIII,H«¦¢¬¦¢,ûæ•ë'»ùxµ lßÉÎË(*‹U•%ws€.]ºèt:P,_VþîÝ»§NúÉ'Ÿ´lÙœÓÒÒÞÿý 6FešÙ2(¨OŸ>3>ýT¯×§¤¤DEE 8ðŸÿü§¢ñ5Mffæ’Å‹—/_ž°aCRRÒåË—===]]]%IÂ33îܹ۶n­ÓI¼xñ¢^¯OMM½}ûvDD»¡mÛ¶Ô²¢\xïâ8w÷ììlŒñÈ‘#EQd^†²²²ùóç'%%¹»»ß¾};??_±C0ÆIIIS¦L±µµ­¨¨€³gÏæååEEEíÚµ+==}ܸq}úôÙ·?°ñPUUuùòåaÆ]¼x‘ ÈÓ§O@||üêÕ«•!‡˜g‹Q5ºpáA”z?+S L9¥ó­Ngc(+É8}¤ðæåœ;™•%ED&È„téÒeܸq:uò÷÷gÝÄÄ [NUï>„ß ×Å*I’(ŠŠÒ­ª¬ºtéÒçŸÞ¾}ûú µsqëÞ·ïë½¶vç„Å?z4i‚F _~ù%+aõêÕ`™**äííݹk׆G´aóDõ=¡5kÖœ8qB£Ñ „&L˜`6›:T'ô™ã8;»‚‚‚+W®¸¹¹q{úôiVoYYÙ´iÓxË$\NðÆoPJwìØÁêêܹsRRÒ;wÖ¬Y£¸mÙŸ2eJž½ÀÓÓ³¼¼œ¼q¬aºl +_×­[wìØ1NW‡`ñáuìØñìÙ³žžÊÅ]»v­\¹R¹M£ÑØØÚ‚eþ8~üø‰/¿Œ9Œ_ÿ—¾]ÿòŠ-/ÿëç)ëvO^µmôç‹;yÑÓ¯‰ uÚØÛû­·Þ:tèPqq±ÚÁ©ôûã»[éóé+ƸڧZYY¹gÏžñãÇ+®Â_夠ñkÖ¢gß~NÎÎ`ñ$$$°†žb$kãÆéÓ§]\\ÀbcÔññ²Ò\\\²³³{õê¥pã7ÞÈÎÎnÒ¤ Ôóû³Çmmm333_zé%e¤ÍžóYjj*óÅ „0ÇÙÙÙ#‹¯?66væÌ™l«Ø;»þlñ” {Ƴ¦ÇÄ7#£uöŽuÆæøøøÞßÿý½{÷”že½\ß­ÿ×"Œ>¸jÄ&Ø Ý¼ysÖ¬YíÚµ³¶¶~àP­ˆa\¾|9+¤¤¤¤]»vð ³[±Õfc­“Ö×7++ë‹/¾‹†0`@ee%¥tÚ´iPÏi>`À†°ß±BöööwîÜ!„\¼xÑÖÖö¡û¶YQã£GŽŸðLš4IaËǬʋ(òéoû¥T —Ž;VVV:ô¡ídW2ïÜYþ¯) =zt^^^X«V šÌ*Õ|ùå—^^^¬AkÕiØØØQÜ=ùË!00ðõ×_?räˆYµ*Ãzöë?EX}‘V­j×®]~ðA‡ŽœœÔ¯Äxúî»ï²ÁA)]²d ÆX-!êc«‡§ç©S§Ö­[§¤ßA 2¤ªªŠræÌ™ú€ðôôÜ´i³ùêËPÅw°+111 ¯eee} àVîg¯0fÌ˜šššøÞ½`ÆŒJ—TUV¾õöÛl#g²²²7n\II !„!ŒUíé陚šºbÅŠ:u)cÌÃÃ#?/ïÔ©SÊ#aaa÷ïßg¾â:ƒœœœöïßV{j—WÖètºààà‰'®ZµŠ½oýýϱñç ¬~ËØÚ»(šÍ{÷îèׯ_ß¾}'Nœ¸~ýú+W®>|¸oß¾j¥ÆúuàÀj›tã¦MPÏrjß¾=µÌ¡ø¨€*–‹••¦L©îÞ½{íÚµ´´46ØëTVVöë×5I™¨;LI©g6›qÎdöÂ… •°z#""ÒÒÒØxÛ²e˸qã:wîðüüü„„„Ë—/ëjkÄÀvý¿E˜Z èõúƒ2»µŽÄR+D„¿¿ÿˆ#öïß_§œ:ù¤¼¼œϱ9æ[o½U§ð¿šžèŽ\zÊq\ffæÌ™3ׯ_O-¡jL*lOOOãЧOIÌb"ê5UÊÉÉÉÉÊÊRÇJ @hFFÆÕ«W[·nÍâ´”GØÞ/xð<"è½÷Þ¿~íÚСCY‚ ½^Ÿ““sðàÁU«V‰¢ˆ9Œ( HÚÉ!.yûF³IÆK’tøðáÇ3ÑË" ©% -"ÉɳQ»çÇò‚Vgë ¯*xAX·n]=¨%-<˜ÍåòåËê÷-//gê^-€•_‹ŠŠ˜Ênß¾ý™3gØO©©©÷ïßwuu%O*ýç“C˜ŸsçÎÉ“'8p@YM£ª AAAíÛ·gNlâÉb\¤tž$I?ÿü3°C„p F¨ô~é¢E‹–-[&«vˆ€‹‹Kddä¾}ûj÷,°g)á­^½zÆ ~~~<ÏWWWçææ²Z8Ì!@‘0Çu<ºUÿ¨lÖ9»^Ù¿½ðvÀÇa„BX|ÂÏa¶Õ„H4 o×aè;ß&’ÉèÙáÖÑ}2¡á]»víß·¯wŸ>,Gi*cNBB‚r…ÅsçääDGG«¢®¨¨èÂ… !6•a%äää”––º¸¸Ð'•gàÉ!Œ±I„¤¤¤°0@&á Y³fÑÑÑ;wnß¾}³fÍ”5J%㢑ÔCüÖ­[!J(¸Ê2å¤#@”ü±[·n£GV?žžž^VV ÌD „x^0›E‚ Ìrâ8æz ήm Œéi4èÈ1ݽ[Ü8¼ëæ©£Õe÷‰%Z–ç8ˆ*YB¯\y‡vï×$ª‹ÖÞ±ºªÊÍZèÑ."ýÜiª¯Æ•——¿ñ曉‰‰ÁÁÁ,/?H’¤ÑhV­Z¥>w‡ñáÊÕ«/¼ðBuIBƘ,Æó|ˆ*ääÞ½{jéøW÷ûÕ’,’ñÚõëJr[;» ãÇwëÖ-$$„më`w²JÅqOéFU› dYþÇ?þQUY‰0¢@ ´[o£ÞP”•&EéõúiӦݻw/**JÅüüü³gÏ&%%efÞÁˆ£H"@ƒ¢ºñíãûe"#"óæ J‰LˆDdx¾y§nÁ±q®-[õ5H–B†Šr³{›¡cÚwοz.çæ SI~uE¹Ñh’ެ<<›D´õkÓÑ®‘Ÿ,šMU•t¨©¹ }ôÑöíÛ!˜Ù«i ï°HŽão?Pz7‹e[q>üðCGGGBÛDª”O €OH«f1=›´í˜~æxѵ ÷+*ˆ\»µF#hlœÝšFvð ‹pk ›ª«%c¶9T2Ô/8û6qö hÑÃ$–—Š&CMe9•e­o¥ÓÚ9X;8‰€ÌÕ•!àx `–I•Î.¤[ïì«çïçß„0Æ—.]êÛ·ïsÏ=×µkW›óçϯ\¹²  @m,²quìØ±üü|gggxð„¹ÔÔÔó)ç8Ž×étŽŽŽLžI’ÄŽ{bôDÆÌüíÚý cI–9ŽÍæiÓ¦ ‚0yòdÆþ»qßTu8 »íÞ½{üñêÕ«Y!2æø°øçGWDI—1¯îùvŽ¡¦†Åɲ\ZZʊ€ãˆ,RJB@x»Æa‘!ÁžAá†Ê²Ê¼ìêû÷F‚•Nç`¯sõÒ9:S¢(Ùˆ¥š†ÚA@eÉ@)Gd!äÞHpây³$ñ"³ÉH)U²ZP!©¦ÊÎ; ê… ‡V,4ÖTSŒ1Š‹‹W¬Xñý÷ß#„X‚ÈÚ·ÆØÇÇ×d40ĘL¦5kÖÌŸ?TIê8ŽÛ´iSvvv\\œÊfiãC’âþ¥ôäò‡1SRúüóÏ;,û‹jjjþþ÷¿'&&²|æ2äÕóv°8 JKKøá‡Ô†b#TFu<* mGÙd0A­û¾ùw߀&˜ãɃæ-Bd‘ãׯî2þ5lë`6è%“Q’D­½{HD@L÷¦1=|ÛF9klíD“Q4@A½_! @ % QJLFj2kª‰ÉhÖëÍz½d2¥jOBUN«Ä›ª+}ÃÛu3ÙÚÞ¡DĘ„˜+NÝf——_šØì×ÝuëÖ?~\ñ ‚°gÏžåË—@lll=T¬Æ'ÖéðäÏ—d¨2 o¾ùæÊ•+™%+ËrãÆ·nÝÚ¾}{&ä ¨v§©}°ÉÉÉK—.Ý·o_m7!Ž8¾Cÿ!­¿h4™Ž£²$QÐh4²¾*3åÔ­G*‹ò%YŽç­t6.¾þm"£8­NM²(¢ÇÈçö[2¥µ]hÉòúëS`9FÄ‚-PÏTÒèlò¯^¸œôSav¦I_cyèÆð‚€1'ŠfªJ˜èêêºhÑ¢¨¨(Y–Ož<ùÑG±=H;vìèÛ·ozzzÛ¶m«ªª˜$KLLìß¿?›«>Kÿ‰"ŒZ2Ô!„ Ô)SÖ­[lÃ÷!CV¯^mooOL)¨2äddd?~|÷îÝ,à“ã8†FB$„¹¨!£ÃÖuý?c CŠL©•ƒ©¬¤ðæå;çÏä¦Þ¬©(­ ±GShh¨Ñh¼}û6+2>>þ§Ÿ~²³³;}úttt4c²ƒƒÃîÝ»;uêôÿað ÈJKKã{÷¾x᳨8Ž[³víˆáÃÙDR–ÑhÌÈȸuëÖ•+W~ùå—‹/–——S” Y&@‰­“KDŸÁ­âšŒ&"ËHq&Y’ÝS,‚ Á,,‹â2©$!–¥‡Ýÿðú«ùT&”ã#kÛG÷ý~±$š(¥Ê6¾‡öS‘Lj4I’wÄÄDSJW­ZõÊ+¯03ß××wçÎaaaIJ ý¯¦'=—D–$®„WW×9³g÷íÛ— *³ÙüˉÞž9ÃÊËËÏ;wüøñK—.effÞ¾}[9`F¶êA$x^Ó¬}tH~-#Ó§µÊÈ¢óƈR*Š,Xr:!Œ1ÿ«Ý –§_ÜŸÏ„8Œ¨$š(¨öèÐøô±¬+)˜ãˆÅ–b° –Ì®JÛØZÏóF£ÑÁÁá›o¾‰ŠêÈFò•+W@ÙGãããììüÐí-5€·©ÎêÖ­[LLì/¿œ`üJLL:t(!dÓ¦M—/_ÎÎÎ.**úµ­<ϱbüÚ:8yµòoíÞk´5=PŠZ«ñÀÂZeîYŸ¯ÊÜBÙÒô¨_)¥ ¨Zsýieá Ä#@#Að̺’B éÙ³§Á ¿zõ[$PžP·“-¼¶nÝzÆŒƒf+(UUUlýŠÝÜ:<ÜÃÃãÉøZk{íÉTóf"­V;gÎì®]»2 Ÿ——7räHI’¯ :w÷¯ÓlŒ€PïæA1c¦Ø{6F/K’¹ªc<Ôú †>ú§Z1¡L;x&X*»Im©%Ù˜RýS ¦€ŒRjÔs¶vœ °ŒŸ0¡G\\qqñÝ»w>|öìÙk×®—––(Z[[·iÓfüøñ}ûömÔ¨‘2¢6oÞ|ýúu°¬ŽDuì(;@îÉôuà La&DEE3†í ’e™ -,uByŽç½<=‹ŠŠÌf3ªµ±èÿ‚K³`CEH €9(úG ©ùu9cA£¥Ɇš‚+çÓr3½ÛÅØyùH²$ ’D© ´vžX¿œÇ¯Z$%sT–Í–œÖÆÝÝÝÝÝ=$$¤gÏž555z½þά¬¬;666<Ïûùùùúú²h(&éB_~ù%XæRAAA‘‘‘jWâ C˜ÂXF3yòä-[¶0»"±€m‹ˆˆhÛ¶í /¼°yóf–ú‚czø¶Š¬))Âfé.AɆÿn×òüW‘E)â8$h9Œ@–+‹òî^NI={²8+ƒÈ’ã‘}þí¢›´íäèí¯ÕéÌ„‚(RI¬Ûs5Ë䙽*Ò¢´æþ}ÐZY99:*ÞTŒ±‡‡Gǎꦬ¡ ‚°xñb–-†QDDD³fÍ@íÉûë©!¦¬¿vêÔiùòåÓ§OÏÎÎfvz£F¢¢¢ Ëâ½ ~ø)J×F>¡=úI’„)Aˆj9XÈRðc6ÀÂeK\¥€'h8€š«*‹²o§>~ûÂY“¾Jyªü~É¥}‰—ö%z· Žíw–mlA’$ÑÌÒòüzðüþ´€*Ê‘%ê¤Àk4Z­&õØ;—S0ÆM›4ñ÷÷W‡Z¨yXç+H’$ÂÅ‹•œ ,'ÙØ±cÙŒ²þž«¿ŽX†)>ÕÑ£GGGGoÚ´éÞ½{žžžƒ báöÀv€½ýöÛi©©!„¹ÈÃíûÕ”•ò\XçµÔ+ÙÙÙ‹/^´x±A¯WŽƒíÞ½ûºuëXÖÅ'*tÃ#LáÔqÌ–Ó™ÙâÒúõëYjà/¿Ø9Þ\S­5üîÌñW†RJÉF+kL©¡¼4õÔÑœ+犲³Ø¬ aÌÖûBBBâãã СC–DH9ñŠÍN€rùòåýû÷oÙ²åܹs€pmð# ^̓ƒb{ºø`•A_CE”° °,6Ô6Q*X[Yíÿî‹ÌKgRO¯FŸÏýìÅ_dȨÿjj‘V\\üóæÍ+W¬¸xñ"ð$“TS¡‡šÒJç)˜`…cAÐj­d}uqêÕÛçNg_½XQ”§ëã9®k\ܘ±c;ÇÆ²$%ð`œ-<$Ãòv¿øâ‹7oÞ\·nÝÞ={‹KŠ€PRr7»änö ÉM[ú¶nØ6J£ÕQŽæKC–#,U\ÀÄl"„PB0Æýû÷ëÚµkAA££ãC7e™L¦ÔÔÔk×®>}úèÑ£©©©¬©`9)¬ÿþ+V¬ðôôl(xÁÓ#Ãêµ÷îÝëÓ§ÏÅ‹9óZ›~oNs 3[œõŸRsP%1ÂX£ÕR„ª‹ 卵̹t®8÷ޱ¦Zýæž^^ýûõ>|xûöí•ó•ó-EÕÝšÁÚÉ®ÆÌÌÌ;v¬Y»6õÖ-uÃ8^ppoÔ´M‡ºØyy@”Q&H’jÍ3¶ò `mçpeõü“‡Bööl£ŠµÎÆÁÞÎÅÅÅÖÖÖÎÞž`XQ^^PXXZZZS]­ãª4Œã¸©S§Îœ9ÓÉÉIѰO^ðt"L9óæÍûÛßþ&h5¢É5dtÄ ‘æêJ‚1B¸ž·ÉòÝ"µ!Ìñœ J ÷‹KsïÝIOO>]qï®%†1öðôŒêر_¿~qqqŠÐR<–ð›®#µ• * º¼¼üàÁƒ»wï>yêtfæmɲƅ²²±ó mÑÖ¥±Ÿ›‡`e#šMD–) ìGÀi­ŒEù;æM¯¸_úǸçêêÚ®]»‰'4ˆAù$ý«õééB˜Òg¡Ë—/GwŠÖõ”PŸð“?t:ÑdÂ?h¶[¸G))Òpxžçyb6—Þ¹•~æ—ÜW+ s©j1ÑÁÁ¡Y³f£F=z4Ûó­4 –/ÿf—<ôÁ²²²={ö¬Y³æÒ¥KìÀT°(Gk;§VÁÍ";{†Dèlí€d6Q”²¶±+͸~lÕ·Ey¹õ+Âgeckm¥«.)6S™éY'GGFãëç?p@ÿÁƒ³ ± « اOÂÀ"?dYîׯß0‡µÖv½ß˜æÜÚTY^kL°;U ÒÌñ á°³–¯@ššÒ⢌[™çOe_:k6‹ÊÜØÑž#FŒèÖ­ÛÝ_Ÿ¬K~£œ .ü¸qã¡C‡nÞ¸Á4šÀaQ& q‹Ð&áí…†Û{4¬uF³Y45Z­±´èæ‘}…i׫++8„‘FckooïáíìãëÐÌÅÁîäšE×®\ÁÆ¿|Ù²˜˜毇z.Ù†íЧajŸÆø›o¾yûí·™«©M¿ç;˜ ¯®¦³~m:¡„ ˜ãy€¬l´ÆJrýìÉ[…©×ïÝÎ @ž% ¬¬¬"##ã{÷~~èPvn(±œ][ÚŸÚê J°„ÜÜ»w/111111ùܹ’âbxžH’ `çâÞ¸yOëö>­"¬mìÌ2¥”h´ZSy©¡¢q¯ÑZÙ;ò‚¼ ™L¼ ܹ|þÀ²ùrM¡tâĉ+V¬`Dõ³ÁáOÂØjÆøÖ­[111,y¸gÓ–½^ûPpp&&ã¯Q_D¢ˆ'’ÈiÎ–ÇØP~?çÆ•Ü«2®œ+î;yŒøùùuêÔé¹çžëÖ­›››Xæ†O ÂS3¶WôzýÉ“'wìØq.ùÜÙ䳬8 2¡«ÈFA­"ÚÚ¸{QNƒÈ¢™Âöƒ „¨$!‰×xkè™ß9°(  £Fj×oÓS„0`!:ÃGŒHܾ`AèñÒ›{U–—i€Fa*ËÀ[YqÖ6æÊŠª¼ìì‹gïÞºZ”}GM< ñqtr 8p`\\\hh(K(¢ÆÖëõ„€ù8X½YYY»wïNJJJ9¾˜E” Äf!.}=šú´jïæë§sóÂo2è ¥Û’`¦ÈEæûÅ?~ýEY^BÈÇÇçø±c>¾¾ðĽö¿MOÂXX”æ¼yó¦}ü1!(mÞ¡Ç”weÄמ%¶²µ•)-ÏJϹz!ëÂÙªÒâêò¶˜FGG8°G\œ—§g£ÆÙÅÁVýw‹;MIÀQRRRPP’’²cÇŽýû÷+[8@cemçäìÜÚ·u{Ï–¡‚ÎV4e“‘)?‘‚ÆÚ:ûäÁ£–‹F# yþù-?ÿܰ¾‰úÔðSëÇK—. 4(77Ø:9üpŽ­§·I_Ãk42ÂA#U—ß½z>'ùDVf¦±â¾zwšÖʺW¯žo¼þz›6m\,‡!²îD¿w"Dƒ¼u†UUU]¹reÍÚµ;wì¸wïžr'¬uŽ^>¡ãÜ›4wòo&Ë‘ej6SŒµ`éüŒ”“!­•Õ–Í›ûöíËΪyJteÃ# Taæo¼ñÆ¢E‹8Ë2é>~J³îý%³™ç0!ÄXV’}19õø’ü\"ËJ£1ÆþþþãÇïׯ_hh¨’ðBq–"•› ž‚‘­ö ({õ£P–å¼¼¼mÛ¶mÙ²åôéÓêݳcG§ˆ6žz95òát¶’ÙÄi´•¹YIÿœ^U^=zöÚ•´“%zJ ²§"¶‚¹cÇŽ9’œø…Eö{û¤±Ò—ßÉ(¼p2í|rUu•º­ŽŽŽmÚL?~РAо~ìTƒ³øq8PPJ>´rÕêC‡«6+ Ìk|‚[¶íàÖ<ÔÑÅÕÊÑåì– §6®AæÏŸÏލ“™¡¡¨!¦ìÁWUU {á…}{÷rge¥ëûÎt«{Î…Ói§¤ßTŸmgccãããÓ½{÷1cÆ(—þ×롬x¨ëÆ›6mÚ³gOjjjee%»ˆ€ÖÙ­kûH—Ž=4ÞM|3÷îµó„ÒÀÀÀ­[·†……5àZdÝwk@b9EÍf3;ÒŒùüýýZwïëêãªèŒqË–-§L™’PXX¨8fŸLRø'Ì“:™…)¥ååå›7oþðÃÛµkÇòt‚å`r­Î¾YÛ¨–Q]xŽc 8p óõ(‰±ðua :äèèÈ"ÐËÉrØ<¸ºº8hÉ’¥êÌû,Ã*y‚yáEêô³……›6m7~|“€5ΰ% Ù‚ ýO#ŒR^^£0æQ`¼kÒ¤É{ï½wäÈåh'vúÁŸrfØkí“¯Ž¨Ž¼0™LÊ )))óçÏïÔ©S­VU1ã8///6 \Œ5 ÂÔzíóÏ?ËiŒ–AÉõêÕkåÊ•j¡Uçž'ß`úÄAöÐ0‘¦$«ÎÍÍùá‡F¥Ìuå@±áÇWWWÿÊ0åµoÞ¼i«:%ÏßßÿÝwß=qâ;—Š‘rm ±X§êì05Йd׫««¯]»6gÎ_å_ŽCíÚµ‹6èÀ  .Ã^ýuprrŠ_¸paVVVýÓYœGJk‹‹‹ïÝ»GŸËO-ÒÔÉ÷óòò–,YòüóÏû@›6mع5 ØàÿܤÞ!ùÕÔ!tEXtSoftwareQuickTime 6.5 (Mac OS X)Éþ…GIEND®B`‚jenkins-json-2.4-jenkins-3/src/site/resources/images/collapsed.gif0000664000175000017500000000006511650253660025716 0ustar jamespagejamespageGIF89a€!ù , DŽ`ºçžcŠ5 ;jenkins-json-2.4-jenkins-3/src/site/resources/images/javatoolbox.png0000664000175000017500000000245111650253660026320 0ustar jamespagejamespage‰PNG  IHDRJ¼x¢tIMEÖ )Dí  pHYsÁÁÃiTSgAMA± üaGPLTEDD?,,.10/ppe¦¦•ŸŸ  ýýáòòØõõÚœœŒççÎèèÎîîÔëë×uujŠŠ{¾¾©ÞÝÆÓÔ½¨¨–­Í͸ááÉÆÆ±ÚÚŸ¸¤˜˜µµ¡ÉÉ´¬¬™——‡ZZR552JJD ~~qððÖAA<$$#;;6llaSSK±±žbcY>>9(('××Àv?8·ˆyµµ­JB££™´pg>30=&$²™‰¤XP·­¤˜?8ÎQHãVMÜÜÔÔÔÈääÑ››”ËÌÄébYàáÒÐÏÅççÜÅźÜÜÎ×ØÐ»¼´É’„ìvmême±bY™‚w¯²§îïæóóèããÙÔª™í~uðrižŽ†ÒÈ´á¼®ñ„|ÏqiæêÑáÆ·ì…ö‹ƒçéÏæ×Äë›÷“Šó£™öœ“ø´«÷ÎÅø¾µûûô겨s4…eIDATxÚ­–ë{Ú6‡mC°la, Câƒ-‚‰Álm [4!–ËJHº5M/Y.Mûÿžl¼íI?ÄëïKGöóž#éÈÇÇ'qœH®Ä”(™’õ“ ã“«©¸Â_Δ¨»šä9^J¡˜’ýùÉa?%ý?ÉêýAÇEɈѩL¬XQ ‡ãù|4 &“Éátvýõë5Žƒ’Ñdö…élÆ4÷÷ßßßßÞ^_ÅŠJë &£ù|ÞŸz{÷ðùáæèJŽ5Á‚ÖÉ¿*V˜ò•ó»»ûÏ—§wÇã»^i·7L·zÛ8^THÖf3‚‘rýÇG¦›‹ÞváÓÓ×J~ØèVÞ¸dúø®w„>ÅÙÁáHc¨é!QÞ^^0]¾ë_©öÊh¾z<ˆPÿžš1NÎæäüâøøøÍÉéo¿‡Éþ7ê%Ô•GHÊBxiÈ3·“é/GÇ''{§¿¾ž,ò?BÉëàù?á0RÍöe1S04s»_‡ÞÁÞÞÞnoT9†+¢VVÑpkDSF e"³,‡RÇ3ˆÁbÛ`7” æö§ôçÝ]FÚéçQv0ÄXYB5ˆ%ðÕ ÊŠšìZ¤”qx5IÖìv5cl$¹vµ&3·Ï»´Ûînõv6Þ+=ó¹¦è[ª¢‚ ÚœÅÃ:¢Ud‰¬´‚ž*ºŽ-@-ËTæöù ÚíRºÓ‚†~Ɇv¼%¥‘ õ’äqm'ZÎØ(²T6­‚GDÇ·ÀêH`3·b•ný(ÐVÛ}VôAÒ”ÚÅp‚¨³¦K[ H ,Pd-P5h¥t§áÁfºäøÌ­îÓ­mÛ±\÷ÜUñ(µ° ’5¸ µ…J (²Ò&ðÙTxÕ¯UÕƒs[ñÁK´]ɇV¦í–U¶; †(  jl‡ò| !“šìô/¬_×1ʸà4rÚ&§^.ó^Þ\p3F³ ÌK©Ág<®UF•²šLÄœ®çY&èzðÖ-¹PÔ £’¹¢³×nÙ‹UŠÑËæA¸(Ie­Pщ¦ç׿yÙ/c,‡× –§/²+ÁHh¤W–Q²Œ¾¥èÖÒ‹î?'4LÑÇJj:ýÔê”ÔG ½(ŠO*ù‹Bÿý>?þ-œ«ÂÕUNyIEND®B`‚jenkins-json-2.4-jenkins-3/src/site/resources/images/expanded.gif0000664000175000017500000000006411650253660025537 0ustar jamespagejamespageGIF89a€!ù , „j œ´Î;jenkins-json-2.4-jenkins-3/src/site/resources/scripts/0000775000175000017500000000000011650253660023502 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/site/resources/scripts/shBrushXml.js0000664000175000017500000000357411650253660026150 0ustar jamespagejamespagedp.sh.Brushes.Xml = function() { this.CssClass = 'dp-xml'; } dp.sh.Brushes.Xml.prototype = new dp.sh.Highlighter(); dp.sh.Brushes.Xml.Aliases = ['xml', 'xhtml', 'xslt', 'html', 'xhtml']; dp.sh.Brushes.Xml.prototype.ProcessRegexList = function() { function push(array, value) { array[array.length] = value; } /* If only there was a way to get index of a group within a match, the whole XML could be matched with the expression looking something like that: () | () | (<)*(\w+)*\s*(\w+)\s*=\s*(".*?"|'.*?'|\w+)(/*>)* | () */ var index = 0; var match = null; var regex = null; // Match CDATA in the following format // <\!\[[\w\s]*?\[(.|\s)*?\]\]> this.GetMatches(new RegExp('<\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\]>', 'gm'), 'cdata'); // Match comments // this.GetMatches(new RegExp('', 'gm'), 'comments'); // Match attributes and their values // (:|\w+)\s*=\s*(".*?"|\'.*?\'|\w+)* regex = new RegExp('([:\\w-\.]+)\\s*=\\s*(".*?"|\'.*?\'|\\w+)*', 'gm'); // Thanks to Tomi Blinnikka of Yahoo! for fixing namespaces in attributes while((match = regex.exec(this.code)) != null) { push(this.matches, new dp.sh.Match(match[1], match.index, 'attribute')); // if xml is invalid and attribute has no property value, ignore it if(match[2] != undefined) { push(this.matches, new dp.sh.Match(match[2], match.index + match[0].indexOf(match[2]), 'attribute-value')); } } // Match opening and closing tag brackets // this.GetMatches(new RegExp('', 'gm'), 'tag'); // Match tag names // About...

    dp.SyntaxHighlighter

    Version: {V}

    http://www.dreamprojections.com/SyntaxHighlighter

    ©2004-2005 Alex Gorbatchev. All right reserved.
    "};dp.SyntaxHighlighter=dp.sh;dp.sh.Toolbar.Commands={ExpandSource:{label:"+ expand source",check:function(_1){return _1.collapse;},func:function(_2,_3){_2.parentNode.removeChild(_2);_3.div.className=_3.div.className.replace("collapsed","");}},ViewSource:{label:"view plain",func:function(_4,_5){var _6=_5.originalCode.replace(/"+_6+"");_7.document.close();}},CopyToClipboard:{label:"copy to clipboard",check:function(){return window.clipboardData!=null;},func:function(_8,_9){window.clipboardData.setData("text",_9.originalCode);alert("The code is in your clipboard now");}},PrintSource:{label:"print",func:function(_a,_b){var _c=document.createElement("IFRAME");var _d=null;_c.style.cssText="position:absolute;width:0px;height:0px;left:-500px;top:-500px;";document.body.appendChild(_c);_d=_c.contentWindow.document;dp.sh.Utils.CopyStyles(_d,window.document);_d.write("
    "+_b.div.innerHTML+"
    ");_d.close();_c.contentWindow.focus();_c.contentWindow.print();alert("Printing...");document.body.removeChild(_c);}},About:{label:"?",func:function(_e){var _f=window.open("","_blank","dialog,width=300,height=150,scrollbars=0");var doc=_f.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write(dp.sh.Strings.AboutDialog.replace("{V}",dp.sh.Version));doc.close();_f.focus();}}};dp.sh.Toolbar.Create=function(_11){var div=document.createElement("DIV");div.className="tools";for(var _13 in dp.sh.Toolbar.Commands){var cmd=dp.sh.Toolbar.Commands[_13];if(cmd.check!=null&&!cmd.check(_11)){continue;}div.innerHTML+=""+cmd.label+"";}return div;};dp.sh.Toolbar.Command=function(_15,_16){var n=_16;while(n!=null&&n.className.indexOf("dp-highlighter")==-1){n=n.parentNode;}if(n!=null){dp.sh.Toolbar.Commands[_15].func(_16,n.highlighter);}};dp.sh.Utils.CopyStyles=function(_18,_19){var _1a=_19.getElementsByTagName("link");for(var i=0;i<_1a.length;i++){if(_1a[i].rel.toLowerCase()=="stylesheet"){_18.write("");}}};dp.sh.RegexLib={MultiLineCComments:new RegExp("/\\*[\\s\\S]*?\\*/","gm"),SingleLineCComments:new RegExp("//.*$","gm"),SingleLinePerlComments:new RegExp("#.*$","gm"),DoubleQuotedString:new RegExp("\"(?:\\.|(\\\\\\\")|[^\\\"\"])*\"","g"),SingleQuotedString:new RegExp("'(?:\\.|(\\\\\\')|[^\\''])*'","g")};dp.sh.Match=function(_1c,_1d,css){this.value=_1c;this.index=_1d;this.length=_1c.length;this.css=css;};dp.sh.Highlighter=function(){this.noGutter=false;this.addControls=true;this.collapse=false;this.tabsToSpaces=true;this.wrapColumn=80;this.showColumns=true;};dp.sh.Highlighter.SortCallback=function(m1,m2){if(m1.indexm2.index){return 1;}else{if(m1.lengthm2.length){return 1;}}}}return 0;};dp.sh.Highlighter.prototype.CreateElement=function(_21){var _22=document.createElement(_21);_22.highlighter=this;return _22;};dp.sh.Highlighter.prototype.GetMatches=function(_23,css){var _25=0;var _26=null;while((_26=_23.exec(this.code))!=null){this.matches[this.matches.length]=new dp.sh.Match(_26[0],_26.index,css);}};dp.sh.Highlighter.prototype.AddBit=function(str,css){if(str==null||str.length==0){return;}var _29=this.CreateElement("SPAN");str=str.replace(/&/g,"&");str=str.replace(/ /g," ");str=str.replace(/");if(css!=null){var _2a=new RegExp("
    ","gi");if(_2a.test(str)){var _2b=str.split(" 
    ");str="";for(var i=0;i<_2b.length;i++){_29=this.CreateElement("SPAN");_29.className=css;_29.innerHTML=_2b[i];this.div.appendChild(_29);if(i+1<_2b.length){this.div.appendChild(this.CreateElement("BR"));}}}else{_29.className=css;_29.innerHTML=str;this.div.appendChild(_29);}}else{_29.innerHTML=str;this.div.appendChild(_29);}};dp.sh.Highlighter.prototype.IsInside=function(_2d){if(_2d==null||_2d.length==0){return false;}for(var i=0;ic.index)&&(_2d.index/gi,"\n");var _43=_42.split("\n");if(this.addControls==true){this.bar.appendChild(dp.sh.Toolbar.Create(this));}if(this.showColumns){var div=this.CreateElement("div");var _45=this.CreateElement("div");var _46=10;var i=1;while(i<=150){if(i%_46==0){div.innerHTML+=i;i+=(i+"").length;}else{div.innerHTML+="·";i++;}}_45.className="columns";_45.appendChild(div);this.bar.appendChild(_45);}for(var i=0,lineIndex=this.firstLine;i<_43.length-1;i++,lineIndex++){var li=this.CreateElement("LI");var _4a=this.CreateElement("SPAN");li.className=(i%2==0)?"alt":"";_4a.innerHTML=_43[i]+" ";li.appendChild(_4a);this.ol.appendChild(li);}this.div.innerHTML="";};dp.sh.Highlighter.prototype.Highlight=function(_4b){function Trim(str){return str.replace(/^\s*(.*?)[\s\n]*$/g,"$1");}function Chop(str){return str.replace(/\n*$/,"").replace(/^\n*/,"");}function Unindent(str){var _4f=str.split("\n");var _50=new Array();var _51=new RegExp("^\\s*","g");var min=1000;for(var i=0;i<_4f.length&&min>0;i++){if(Trim(_4f[i]).length==0){continue;}var _54=_51.exec(_4f[i]);if(_54!=null&&_54.length>0){min=Math.min(_54[0].length,min);}}if(min>0){for(var i=0;i<_4f.length;i++){_4f[i]=_4f[i].substr(min);}}return _4f.join("\n");}function Copy(_56,_57,_58){return _56.substr(_57,_58-_57);}var pos=0;this.originalCode=_4b;this.code=Chop(Unindent(_4b));this.div=this.CreateElement("DIV");this.bar=this.CreateElement("DIV");this.ol=this.CreateElement("OL");this.matches=new Array();this.div.className="dp-highlighter";this.div.highlighter=this;this.bar.className="bar";this.ol.start=this.firstLine;if(this.CssClass!=null){this.ol.className=this.CssClass;}if(this.collapse){this.div.className+=" collapsed";}if(this.noGutter){this.div.className+=" nogutter";}if(this.tabsToSpaces==true){this.code=this.ProcessSmartTabs(this.code);}this.ProcessRegexList();if(this.matches.length==0){this.AddBit(this.code,null);this.SwitchToList();this.div.appendChild(this.ol);return;}this.matches=this.matches.sort(dp.sh.Highlighter.SortCallback);for(var i=0;i Json-lib::Getting Started
    Using the JSONSerializer
    Working with arrays and collections
    Working with objects
    Working with XML

    JSONSerializer can transform any java object to JSON notation and back with a simple and clean interface, leveraging all the builders in JSONObject and JSONArray. To transform a java obect into JSON use JSONSerializer.toJSON(). To transform a valid JSON value (by JSON, I mean an Object implementing that interface), use toJava(). The last method is an instance method because the serializer needs special configuration to transform a JSON value to a bean class, array, List or DynaBean.

    The simplest way to create a JSONArray from a java array or collection is through the static factory methods from JSONArray. JSONArray.fromObject() will inspect its parameter and call the correct factory or constructor.

    Examples:

    The simplest way to create a JSONObject from a bean or Map is through the static factory methods from JSONObject. JSONObject.fromObject() will inspect its parameter and call the correct factory or constructor.

    Examples:

    CAUTION: when parsing, JSONObject and JSONArray will check for cycles in the hierarchy, throwing an exception if one is found. You can change this behavior by registering a CycleDetectionStrategy.

    Json-lib can transform JSONObjects to either a DynaBean or an specific bean class.
    When using DynaBean all arrays are converted to Lists, when using an specific bean class the transformation will use type conversion if necessary on array properties.

    Convert to DynaBean:

    Convert to Bean:

    There are two special cases when converting to an specific bean, if the target bean has a Map property and it must contain other beans, JSONObject.toBean() will transform the nested beans into DynaBeans. If you need those nested beans transformed into an specific class, you can either postprocess the Map attribute or provide hints on JSONObject's attributes for conversion. JSONObject.toBean() may be passed a third argument, a Map, that will provide thos hints. Every key must be either the name of a property or a regular expression matching the object's properties, and the value must be a Class.

    The second case is similar and it happens when the target bean has a Collection (List) as a property and it must contain other beans. In this case there is no way to provide hints for class conversion. The only possible solution is to postprocess the collection transforming each DynaBean into an specific bean.

    To ease the postprocessing scenarios, EZMorph provides a Morpher capable of transforming a DynaBean into an specific bean, BeanMorpher
    Example:

    This yields a MyBean instance that has DynaBeans inside the 'data' attribute', so now comes the part of postprocessing, this can be done with an Iterator
    Example:

    To learn more about Morphers, please visit EZMorph's project site.

    Working with XML has become easier since version 1.1. Transforming JSONObjects and JSONArrays from and to XML is done through the XMLSerializer.

    Writing to JSON to XML is as simple as calling XMLSerializer.write(), but there are a lot of options that you may configure to get better control of the XML output. For example you may change the default names for the root element ('o' if object, 'a' if array), the default name for object (an object inside an array is "anonymous"), the default name for array (for the same reason as object), the default name for element (array items have no name). If you'd like to output namescape information but your JSON does not includes it, no problem, you have 8 methods that will let you register and manage namespaces; namespaces defined this way have precedence on any namespace declaration that may be inside the JSON. By default XMLSerializer will append special attributes to each xml element for easing the transformation back to JSON but you may configure it to skip appending those attributes. Any property on a JSONObject that begins with '@' will be treated as an attribute, any property named '#text' will be treated as a Text node.

    Please review the javadoc for XMLSerializer to know more about the configurable options.

    Code XML output

    XMLSerializer treats each element as a string unless a type parameter is specified.
    JSONFunction needs an additional parameter that specifies that function's params.
    All xml attributes will have the prefix '@' and text nodes will have the property name '#text'. XMLSerializer supports the rules outlined at
    Converting Between XML and JSON

    XML input Code

    CAUTION: when parsing, JSONObject and JSONArray will check for cycles in the hierarchy, throwing an exception if one is found. You can change this behavior by registering a CycleDetectionStrategy.

    jenkins-json-2.4-jenkins-3/src/site/xdoc/package.xml0000664000175000017500000000554111650253660023060 0ustar jamespagejamespage Json-lib::Build instructions
    Building the jdk13 package
    Building the jdk15 package

    1. Download the latest snapshot from cvs .
    2. You must have ant 1.7.0 or newer installed in your system. You can download it from here .
    3. Execute 'ant jar', the distribution jar should be inside the target directory.

    1. Download the latest snapshot from cvs .
    2. You must have ant 1.7.0 or newer installed in your system. You can download it from here .
    3. Execute 'ant jar.jdk5', the distribution jar should be inside the target directory.

    You may additionally generate the source jars and jdk15 javadoc API pages using the provided Ant targets. Type 'ant -p' to get more info on those targets. This site and the documentation for the jdk13 package is still built with Maven .

    jenkins-json-2.4-jenkins-3/src/site/xdoc/advanced.xml0000664000175000017500000001630711650253660023234 0ustar jamespagejamespage Json-lib::Advanced Features
    The JSON spec states that an object key is a String and
    A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
    This means that you may have a valid JSON key but and invalid Java identifier when transforming form JSON to Java. In order to avoid this problem, Json-lib defines a set of helpers of type JavaIdentifierTransformer that will handle the following cases:
    • JavaIdentifierTransformer.NOOP - will perform no transformation.
    • JavaIdentifierTransformer.STRICT - will throw JSONException if a non JavaIdentifier character is found.
    • JavaIdentifierTransformer.CAMEL_CASE - will use non JavaIdentifier and whitespace characters as word boundaries, capitalizing the first char of a new word.
    • JavaIdentifierTransformer.WHITESPACE - will trim all whitespace and non JavaIdentifier characters from the input string.
    • JavaIdentifierTransformer.UNDERSCORE - will transform all whitespace and non JavaIdentifier characters to '_'.
    You may also create and register your own JavaIdentifierTransformers using JsonConfig.setJavaIdentifierTransformer()
    You may recieve events while building an object with the JSONSerializer or the static builder fromObject of JSONObject&JSONArray, all you have to do is enabled event triggering on JsonConfig. The following is a list of events generated by the build process: start/end (object), start/end (array), propertySet( object), elementAdd (array), warning, error. When building a JSONObject with fromObject or with the JSONSerializer you may skip all transient fields of the source bean, provided that the name of the property returned from the PropertyDescriptor matches the name of the field, meaning that this option will not work if you have a BeanInfo that changes the name of a read method or provides a synthetic property.

    When serializing to JSON there may be some times where you would like to exclude some properties from being processed, the current exclusion mechanism matches the property name to a list of Strings, but what if you would like to filter out all properties that match a regex or extend a particular class? PropertyFilter will help you attain that goal with ease, and what's more, it will also work when converting back to Java. Here is an example filter that will exclude all properties that are a Number when serializing to JSON:

    This is another filter example, this time converting back to Java, it will filter out any property named 'bool' or 'integer':

    Please review the net.sf.json.filters package to find out more about default filters and composite filters.

    JsonBeanProcessors are maped to classes but sometimes you'll like that some subclasses may be mapped to the same processor or perhaps you are serializing a recently hydrated instance coming from a database with Hibernate, because the instance's class is not exactly the one you expect (it actually is a cglib proxy class) the default class matching mechanism will not work. In order to solve these problems you may register a JsonBeanProcessorMatcher that will take care of the job of selecting the proper JsonBeanProcessor, just as you need it. When serializing from JSON to Java you have to keep one rule in mind, the target class must follow the JavaBeans convention of a no-args constructor but sometimes it won't be possible, as it is the case of java.sql.Timestamp. Json-lib has an option to overcome this "restriction", just register a NewBeanInstanceStrategy into JsonConfig and you are in business. The JSON spec states that null values can only be assigned to objects, but in Java you can have null assigned to any reference, when Json-lib encounters a null reference it follows these rules
    • value is 0 if the reference is a number (wrapper or primitive)
    • value is '' if the reference is a String, Character or char
    • value is [] if the reference is a Collection or array
    But sometimes it would be useful to change that rule, for example instead of assigning 'null' to a null reference of MyBean you would like to assign '{ "empty": true }' because that's what your client code expects. DefaultValueProcessor will let you change that rules, along with DefaultValueProcessorMatcher which will let you select the most appropriate processor, as it is done with JsonBeanProcessors.
    JSONObject knows how to set values on a Map or bean when transforming JSON to Java. For those rare ocasions wher you would want to handle the set by yourself you can register a PropertySetStrategy through JsonConfig. This feature comes in handy with map backed beans that are neither a Map nor a DynaBean.
    jenkins-json-2.4-jenkins-3/src/site/xdoc/snippets.xml0000664000175000017500000007214611650253660023337 0ustar jamespagejamespage Json-lib::Snippets
    1. Creating a JSONObject from scratch
    2. Creating a JSONObject from a JSON formatted string
    3. Creating a JSONObject from a Map
    4. Creating a JSONObject from a JavaBean
    5. Creating a JSONArray from scratch
    6. Creating a JSONArray from a JSON formatted string
    7. Creating a JSONArray from a Collection
    8. Creating a JSONArray from an array
    9. JavaScript functions
    10. Exclude properties
    11. Exclude properties (with filters)
    1. JSONObject to DynaBean
    2. JSONObject to JavaBean
    3. JSONArray to List
    4. JSONArray to array
    5. JSONArray to array (type conversion)
    6. JSONObject to JavaBean, exclude properties with filters
    1. JSONObject to XML
    2. JSONObject to XML (no type hints)
    3. JSONObject to XML (with json prefix)
    4. JSONObject to XML (change node names)
    5. JSONArray to XML
    6. JSONArray to XML (no type hints)
    7. JSONArray to XML (with json prefix)
    8. Flatten JSONArray into parent
    1. XML to JSONObject
    1. Using the JsonGroovyBuilder
    1. Creating a JSONObject
    2. Append elements to JSONObject with << (array)
    3. Append elements to JSONObject with << (hash)
    [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON] [Index|From Java to JSON]
    [Index|From JSON to Java] [Index|From JSON to Java] [Index|From JSON to Java] [Index|From JSON to Java] [Index|From JSON to Java] [Index|From JSON to Java]
    [Index|From JSON to XML] [Index|From JSON to XML] [Index|From JSON to XML] [Index|From JSON to XML] [Index|From JSON to XML] [Index|From JSON to XML] [Index|From JSON to XML] [Index|From JSON to XML]
    [Index|From XML to JSON]

    The following snippets produce the same JSON output

    [Index|Groovy Support]
    [Index|JRuby Support] [Index|JRuby Support] [Index|JRuby Support]
    jenkins-json-2.4-jenkins-3/src/site/xdoc/index.xml0000664000175000017500000000672711650253660022603 0ustar jamespagejamespage Json-lib::Welcome

    JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.
    It is based on the work by Douglas Crockford in http://www.json.org/java.

    The following tables sumarizes the types conversion between java and javascript:
    JSON Java
    string<=>java.lang.String, java.lang.Character, char
    number<=>java.lang.Number, byte, short, int, long, float, double
    true|false<=>java.lang.Boolean, boolean
    null<=>null
    function<=>net.sf.json.JSONFunction
    array<=>net.sf.json.JSONArray (object, string, number, boolean, function)
    object<=>net.sf.json.JSONObject

    The function type from javascript is not part of the JSON format "officially" (please refer to http://www.json.org) but it is supported as well.

    Json-lib comes in two flavors, depending on the jdk compatibility. json-lib-x.x-jdk13 is compatible with JDK 1.3.1 and upwards. json-lib-x.x-jdk15 is compatible with JDK 1.5, includes support for Enums in JSONArray and JSONObject. Please reffer to the appropriate javadoc links available in the project menu.

    Json-lib requires (at least) the following dependencies in your classpath:

    • jakarta commons-lang 2.5
    • jakarta commons-beanutils 1.8.0
    • jakarta commons-collections 3.2.1
    • jakarta commons-logging 1.1.1
    • ezmorph 1.0.6
    Other dependencies are needed if working with XML andGroovy. Please review the Dependencies report to know more about those extra dependencies.

    JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
    These properties make JSON an ideal data-interchange language.

    jenkins-json-2.4-jenkins-3/src/site/xdoc/users.xml0000664000175000017500000001602711650253660022627 0ustar jamespagejamespage Json-lib::Who is using it

    Project Description
    Mentawai The Mentawai goal is to be a simple, flexible, joyful and productive Java web framework.
    Json-lib is used in the AJAX renderers package. Thanks to Rubem Azenha.
    Spring Modules Spring Modules is a collection of tools, add-ons and modules to extend the Spring Framework. The core goal of Spring Modules is to facilitate integration between Spring and other projects without cluttering or expanding the Spring core.
    Json-lib is used in the XT AJAX Framework. Thanks to Sergio Bossa.
    Nuxeo Nuxeo 5 is a robust, extensible, global Enterprise Content Management (ECM) solution available as Open Source Software.
    Json-lib is used in the NXThemes JSF components module. Thanks to Jean-Marc Orliagueta.
    EJOE EJOE is a lightweight Java client/server framework built to send and receive objects through pluggable (de)serialization mechanisms. It offers a high-performance, simple, and clean object request broker (whereby ORB is meant in its natural manner and not in its relation with CORBA), with server and client components for easy integration in your client/server applications. It's an highly scaleable implementation of the common request-process-response pattern based on the java.nio package.
    Json-lib is used in the JSON adpaters package. Thanks to Michael Manske.
    Apache OFBiz The Open For Business Project is an open source enterprise automation software project licensed under the Apache License Version 2.0. By open source enterprise automation we mean: Open Source ERP, Open Source CRM, Open Source E-Business / E-Commerce, Open Source SCM, Open Source MRP, Open Source CMMS/EAM, and so on.
    Thanks to Si Chen.
    opentaps opentaps Open Source ERP + CRM brings you the advanced features and power of Tier 1 ERP and CRM software with the flexibility and low cost of ownership that only open source can deliver. You can use opentaps as an alternative to expensive and inflexible commercial ERP solutions, as a replacement for in-house solutions that are difficult to maintain or extend, or as a starting point to build your unique business model and processes.
    opentaps is powered by OFBiz. Thanks to Si Chen.
    Apache Tuscany The aim of the Apache Tuscany project is to create, as a community, a robust infrastructure that simplifies the development of SOA-based systems. This project is currently in incubation within the Apache incubator.
    Json-lib is used for testing purpouses in the bindings/jsonrpc module.
    Azuki Framework The Azuki framework is a Java application framework including many features (dependency, AOP, Event-based processing....) and provides a visual tool that describes your software architecture.
    Json-lib is used on the server-side with Azuki beans. Thanks to Mathieu Jucker.
    Pimpas Framework Pimpas Framework its a cool framework that help people to play with Java. We hav security using JAAS, xml reader provide by dom4j, web container provider by tomcat, using jsf to create visual components for web. Our framework its simple and fast.
    Json-lib is used in the javascript transformation module. Thanks to Casmeiron.
    Salto Framework Salto framework is an AJAX based framework which makes possible to build a Web application very quickly. Thanks to AJAX mechanism, datas exchanges between client side an server side are reduced. You are able to refresh only a part of the screen.
    Json-lib is used in Tree-rendering components. Thanks to Jerome Denolf.
    Mule JIRA Transport JIRA Transport is a transport provider that allows your Mule and other integrated services to communicate with one or more JIRA systems easily.
    Json-lib is used to transform JSON objects into XML and Java. Thanks to Yuen Chi Lian.
    Company Description
    TietoEnator The largest IT-services company in Scandinavia is consulting, developing and hosting its customers digital businesses. TietoEnator is among the leading architects in building a more efficient information society. With over 15 000 experts, it is one of the largest IT services providers in Europe.
    Json-lib is used in an undisclosed project. Thanks to Manish Shah.

    If you'd like your project included in this list, please send a message to Json-lib's User list.

    jenkins-json-2.4-jenkins-3/src/site/xdoc/features.xml0000664000175000017500000001237211650253660023303 0ustar jamespagejamespage Json-lib::Feature List

    The following is a list of the most notable features available in Json-lib.

    The following options are configurable with JsonConfig:

    • bidirectional serialization, supports Maps, Collections, arrays (primitives, multidimensional), beans, DynaBeans, Enums & Annotations (jdk15 package only)
    • supports custom serialization with 3 schemes:
      • the bean implements JSONString interface
      • register a JsonBeanProcessor for the whole bean
      • register a JsonValueProcessor for a bean property (key and/or type)
    • register a DefaultValueProcessor for returning a default value when a null reference is encountered
    • plugin your own strategy for selecting a JsonBeanProcessor with JsonBeanProcessorMatcher
    • plugin your own strategy for selecting a DefaultValueProcessor with DefaultValueProcessorMatcher
    • modify the target property name when transforming from JSON to Java if the name is not a valid JavaIdentifier
    • skip modifying map keys when transforming form JSON to Java if the key is not a valid JavaIdentifier
    • register your own JavaIdentifierTransformer strategy
    • plugin your own strategy for setting properties into a bean when transforming from JSON to Java thanks to PropertySetStrategy
    • publish events when building a JSONObject or JSONarray. The available events are:
      • object start/end
      • array start/end
      • propertySet
      • elementAdded
      • warning (recoverable)
      • error (exception)
    • Cycle detection, there are two default strategies (default throws an exception), you can register your own
    • Skip transient fields when serailizing to JSON (default=don't skip)
    • Skip JAP @Transient annotated methods when serailizing to JSON (default=don't skip)
    • Exclude bean properties and/or map keys when serailizing to JSON (default=['class','metaClass','declaringClass'])
    • Filters provide a finer detail for excluding/including properties when serializing to JSON or transforming back to Java
    • plugin your own strategy for instatiating beans if they do now follow the no-args constructor rule
    • default JavaBean instantiton strategy accepts package protected and private no-args constructor (Hibernate friendly)
    • JSONObject implements java.util.Map and java.util.Comparable
    • JSONArray implements java.util.List and java.util.Comparable
    • JSONObject, JSONArray and JSONNull implement a base interface: JSON
    • JSONAssert, a test-friendly class for testing JSON values

    The following options are configurable in XMLSerializer:

    • [read] trim leading and trailing whitespace from element values
    • [read] skip namespace handling
    • [read] trim namespace prefixes
    • [write] skip reading type hints (useful for converting back to JSON)
    • [write] write type hints (useful for converting back to JSON)
    • [write] skip writing type hints (useful for converting back to JSON)
    • [write] change default values for Object, Array and Element tag names
    • [write] change default value for Root element tag name
    • [write] raise error if namespace uri is missing
    • [write] transform an explicit array into an implicit array

    The following options are configurable in WebUtils:

    • do not output quotes for object keys when its safe for JavaScript
    • two default strategies for preventing javascript hijacking, you can register your own

    • support for the leftshift ( << ) operator in JSONObject
    • support for the spaceship ( <=> ) and its cousins
    • type conversion with the as keyword
    • a Groovy JSON builder
    • JSONArray.empty? is an alias for JSONArray.isEmpty()
    • JSONObject.empty? is an alias for JSONObject.isEmpty()
    • support for the leftshift ( << ) operator in JSONObject
    jenkins-json-2.4-jenkins-3/src/site/xdoc/groovy.xml0000664000175000017500000000561511650253660023014 0ustar jamespagejamespage Json-lib::Groovy integration

    Since version 2.0 Json-lib has integrated Groovy support, meaning that POGOs can be transformed into JSON and back, in the same manner as you do now with POJOs. There are other features as well:

    • Type transformations with the as keyword.
      A Groovy List (default type is ArrayList) can be transformed into a JSONArray.
      A Groovy Map (default type is HashMap) can be transformed into a JSONObject.
      A String can be transformed into JSON, JSONObject, JSONArray and JSONFunction.
    • JSONObject supports the leftShift (<<) operator to append values, the following rules apply:
      • If the shifted arg is a Map, it will call putAll() on the object.
      • If the shifted arg is a List and its size == 2, the first element will be the key, and the second will be the value.
      • If the shifted arg is a List and its size > 2, the first element will be the key, the arg will be shifted by 1 and passed as the value (will create a JSONArray because it is a List).
      • Any other type will be discarded, the object will not be affected nor an exception will be thrown.
    • JSONObject and JSONarray implement java.util.Comparable, which enables the use of the comparison operators with them (including the spaceship operator).
    • JSONObject implements java.util.Map and JSONArray implements java.util.List, anything you can do with Maps and List can be done with JSONObject and JSONArray.
    • JsonGroovyBuilder behaves like the JsonBuilder found in Grails but it will create a JSONObject/JSONArray instead of writing the built structure into a String.

    CAUTION: Since version 2.2.1 Json-lib will not automatically enhance class through custom metaclasses, you must call GJson.enhanceClasses() before executing the examples shown on this page.

    jenkins-json-2.4-jenkins-3/src/site/fml/0000775000175000017500000000000011650253660020557 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/site/fml/faq.fml0000664000175000017500000001117011650253660022026 0ustar jamespagejamespage General If I use a LinkedHasMap to create a JSONObject the order is not preserved, why ?

    The answer is in the JSON specification "An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).".
    JSONObject uses a HashMap for its properties representation because the order of its properties is not important.

    Json-lib creates empty JSONObjects from my bean class, help me!

    Json-lib uses the JavaBeans convention to inspect your beans and create JSONObjects. If the properties of your beans do not adhere to the convention, the resulting JSONObject will be empty or half empty. You must provide a read/write method pair for each property.

    How do I configure Json-lib as a dependency with Maven2 ?

    As Json-lib comes in two flavors (for the time being) you'll have to add <classifier> to your dependency declaration, like the following:

    How can I transform a JSON string into a bean with an Enum property ?

    You'll have to register a Morpher that can handle your Enum. Json-lib conveniently includes such a Morpher, so the only thing left to do is configure it and register the Morpher into the MorpherRegistry as follows JSONUtils.getMorpherRegistry().registerMorpher( new EnumMorpher( MyEnum.class ) );
    This step is optional since Json-lib 2.2

    How can I transform a simple value into a complex one when serializing back to Java ?

    Perhaps you've come across a scenario where you'll want a JSON string like "{'id':1}" transformed back to a Java class, but the catch is that the id property is not a simple value but another class (a complex value), say a wrapper around a primitive long. If you try to serialize such a string back to Java you'll get a ClassCastException. The solution to this problem is registering a Morpher that can handle the input and transform it into an instance of the expected type, in this case the class of the id property.

    Json-lib does not find my inner bean, help!

    In order for Json-lib (in fact the PropertyDescriptors) to find and inspect your beans they have to be declared public, and all desired properties must have a public pair of reader/writer. The same applies to beans declared as inner classes (which by the way must also be declared static). Its a good practice to define each bean in its own file, but if you can't please make your inner beans public and static if possible.

    I'd like to use XPath-like expressions with JSON, how do I do it ?

    Use JXPath, which is a simple yet powerful project that enables XPath-like expressions to be used with java beans and maps.

    Where can I get the code for the source code syntax highlighter ?

    The SintaxHighlighter is availabe from Alex Gorbatchev at http://www.dreamprojections.com/SyntaxHighlighter.

    jenkins-json-2.4-jenkins-3/src/site/site.xml0000664000175000017500000000346611650253660021500 0ustar jamespagejamespage Json-lib /images/json-lib.png http://json-lib.sourceforge.net/ ${reports} jenkins-json-2.4-jenkins-3/src/lib/0000775000175000017500000000000011650253660017603 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/0000775000175000017500000000000011650253660020014 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/0000775000175000017500000000000011650253660020735 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/0000775000175000017500000000000011650253660021523 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/0000775000175000017500000000000011650253660022133 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/0000775000175000017500000000000011650253660023104 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayAsJSON.java0000664000175000017500000000354411650253660027343 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * @author Andres Almiray */ public class TestJSONArrayAsJSON extends AbstractJSONTest { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayAsJSON.class ); } public TestJSONArrayAsJSON( String name ) { super( name ); } protected int getIndent() { return 2; } protected int getIndentFactor() { return 2; } protected Object[] getIsArrayExpectations() { return new Object[] { Boolean.TRUE, new JSONArray() }; } protected Object[] getToStringExpectations1() { return new Object[] { "[1,true,\"json\"]", JSONArray.fromObject( "[1,true,'json']" ) }; } protected Object[] getToStringExpectations2() { return new Object[] { "[\n" + " 1,\n" + " true,\n" + " \"json\"\n" + "]", JSONArray.fromObject( "[1,true,'json']" ) }; } protected Object[] getToStringExpectations3() { return new Object[] { " [\n" + " 1,\n" + " true,\n" + " \"json\"\n" + " ]", JSONArray.fromObject( "[1,true,'json']" ) }; } protected Object[] getWriteExpectations() { return new Object[] { "[1,true,\"json\"]", JSONArray.fromObject( "[1,true,'json']" ) }; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_String.java0000664000175000017500000000326411650253660032704 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_String extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_String.class ); } public TestJSONObjectStaticBuilders_String( String name ) { super( name ); } protected Object getSource() { return "{\"parray\":[1,2],\"plong\":9223372036854775807,\"pchar\":\"J\",\"pboolean\":true,\"pfloat\":3.4028234663852886E38,\"pbean\":{\"parray\":null,\"plong\":null,\"pchar\":null,\"pboolean\":null,\"pfloat\":null,\"pbean\":null,\"pshort\":null,\"pdouble\":null,\"pclass\":null,\"pstring\":null,\"pint\":null,\"plist\":null,\"pfunction\":null,\"pmap\":null,\"pbyte\":null},\"pshort\":32767,\"pdouble\":1.7976931348623157E308,\"pclass\":\"java.lang.Object\",\"pstring\":\"json\",\"pint\":2147483647,\"plist\":[\"a\",\"b\"],\"pfunction\":function(){ this; },\"pmap\":null,\"pbyte\":127,\"class\":\"java.lang.Object\",\"pexcluded\":\"\"}"; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/AbstractJSONTest.java0000664000175000017500000000471411650253660027052 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.io.StringWriter; import junit.framework.TestCase; /** * @author Andres Almiray */ public abstract class AbstractJSONTest extends TestCase { public AbstractJSONTest( String name ) { super( name ); } public void testIsArray() { boolean isArray = ((Boolean) getIsArrayExpectations()[0]).booleanValue(); JSON json = (JSON) getIsArrayExpectations()[1]; assertEquals( isArray, json.isArray() ); } public void testToString() { String expected = (String) getToStringExpectations1()[0]; JSON json = (JSON) getToStringExpectations1()[1]; assertEquals( expected, json.toString() ); } public void testToString_indentFactor() { String expected = (String) getToStringExpectations2()[0]; JSON json = (JSON) getToStringExpectations2()[1]; assertEquals( expected, json.toString( getIndentFactor() ) ); } public void testToString_indentFactor_indent() { String expected = (String) getToStringExpectations3()[0]; JSON json = (JSON) getToStringExpectations3()[1]; assertEquals( expected, json.toString( getIndentFactor(), getIndent() ) ); } public void testWrite() throws Exception { StringWriter w = new StringWriter(); String expected = (String) getWriteExpectations()[0]; JSON json = (JSON) getWriteExpectations()[1]; json.write( w ); assertEquals( expected, w.getBuffer() .toString() ); } protected abstract int getIndent(); protected abstract int getIndentFactor(); protected abstract Object[] getIsArrayExpectations(); protected abstract Object[] getToStringExpectations1(); protected abstract Object[] getToStringExpectations2(); protected abstract Object[] getToStringExpectations3(); protected abstract Object[] getWriteExpectations(); }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayAsList.java0000664000175000017500000000764311650253660027511 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.List; import junit.framework.TestCase; import net.sf.json.test.JSONAssert; /** * @author Andres Almiray */ public class TestJSONArrayAsList extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayAsList.class ); } private JSONArray jsonArray; public TestJSONArrayAsList( String name ) { super( name ); } public void testAdd() { assertEquals( 5, jsonArray.size() ); jsonArray.add( "value" ); assertEquals( 6, jsonArray.size() ); } public void testAdd_index_value() { assertEquals( 5, jsonArray.size() ); Object first = jsonArray.get( 0 ); jsonArray.add( 0, "value" ); assertEquals( 6, jsonArray.size() ); assertEquals( "value", jsonArray.get( 0 ) ); assertEquals( first, jsonArray.get( 1 ) ); } public void testAddAll() { JSONArray array = new JSONArray(); array.addAll( jsonArray ); JSONAssert.assertEquals( jsonArray, array ); } public void testAddAll_index_value() { JSONArray array = new JSONArray().element( "value" ); array.addAll( 0, jsonArray ); assertEquals( 6, array.size() ); assertEquals( "value", array.get( 5 ) ); } public void testClear() { assertEquals( 5, jsonArray.size() ); jsonArray.clear(); assertEquals( 0, jsonArray.size() ); } public void testContains() { assertTrue( jsonArray.contains( "1" ) ); assertFalse( jsonArray.contains( "2" ) ); } public void testContainsAll() { assertTrue( jsonArray.containsAll( jsonArray ) ); } public void testIndexOf() { jsonArray.element( "1" ); assertEquals( 0, jsonArray.indexOf( "1" ) ); } public void testIsEmpty() { assertFalse( jsonArray.isEmpty() ); } public void testLastIndexOf() { jsonArray.element( "1" ); assertEquals( 5, jsonArray.lastIndexOf( "1" ) ); } public void testRemove() { assertEquals( 5, jsonArray.size() ); jsonArray.remove( "string" ); assertEquals( 4, jsonArray.size() ); assertTrue( !jsonArray.contains( "string" ) ); } public void testRemove_index() { assertEquals( 5, jsonArray.size() ); jsonArray.remove( 2 ); assertEquals( 4, jsonArray.size() ); assertTrue( !jsonArray.contains( "string" ) ); } public void testRemoveAll() { assertEquals( 5, jsonArray.size() ); jsonArray.removeAll( jsonArray ); assertEquals( 0, jsonArray.size() ); } public void testRetainAll() { assertEquals( 5, jsonArray.size() ); jsonArray.retainAll( jsonArray ); assertEquals( 5, jsonArray.size() ); } public void testSubList() { List actual = jsonArray.subList( 0, 3 ); JSONArray expected = new JSONArray().element( "1" ) .element( "true" ) .element( "string" ); JSONAssert.assertEquals( expected, JSONArray.fromObject( actual ) ); } /* * public void testToArray() { } public void testToArray_array() { } */ protected void setUp() throws Exception { jsonArray = new JSONArray().element( "1" ) .element( "true" ) .element( "string" ) .element( "function(){ return this; }" ) .element( "[1,2,3]" ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/regexp/0000775000175000017500000000000011650253660024376 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/regexp/AbstractRegexpMatcherTestCase.java0000664000175000017500000000274211650253660033124 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; import junit.framework.TestCase; /** * @author Andres Almiray */ public abstract class AbstractRegexpMatcherTestCase extends TestCase { public AbstractRegexpMatcherTestCase( String name ) { super( name ); } public void testGetGroupIfMatches() { RegexpMatcher regexpMatcher = getRegexpMatcher( "[a-z]*([0-9]+)[a-z]*" ); assertEquals( "123", regexpMatcher.getGroupIfMatches( "abc123edf", 1 ) ); assertEquals( "", regexpMatcher.getGroupIfMatches( "abcedf", 1 ) ); } public void testMatches() { assertTrue( getRegexpMatcher( ".*" ).matches( "everything" ) ); assertTrue( getRegexpMatcher( "^json$" ).matches( "json" ) ); assertFalse( getRegexpMatcher( "^json$" ).matches( "json " ) ); } protected abstract RegexpMatcher getRegexpMatcher( String pattern ); }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/regexp/AllTests.java0000664000175000017500000000210111650253660026766 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class AllTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "regexp" ); suite.addTest( new TestSuite( TestJdkRegexpMatcher.class ) ); suite.addTest( new TestSuite( TestPerl5RegexpMatcher.class ) ); return suite; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/regexp/TestPerl5RegexpMatcher.java0000664000175000017500000000212411650253660031546 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; /** * @author Andres Almiray */ public class TestPerl5RegexpMatcher extends AbstractRegexpMatcherTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestPerl5RegexpMatcher.class ); } public TestPerl5RegexpMatcher( String name ) { super( name ); } protected RegexpMatcher getRegexpMatcher( String pattern ) { return new Perl5RegexpMatcher( pattern ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/regexp/TestJdkRegexpMatcher.java0000664000175000017500000000211411650253660031266 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.regexp; /** * @author Andres Almiray */ public class TestJdkRegexpMatcher extends AbstractRegexpMatcherTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJdkRegexpMatcher.class ); } public TestJdkRegexpMatcher( String name ) { super( name ); } protected RegexpMatcher getRegexpMatcher( String pattern ) { return new JdkRegexpMatcher( pattern ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONNullAsJSON.java0000664000175000017500000000320411650253660027170 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * @author Andres Almiray */ public class TestJSONNullAsJSON extends AbstractJSONTest { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONNullAsJSON.class ); } public TestJSONNullAsJSON( String name ) { super( name ); } protected int getIndent() { return 2; } protected int getIndentFactor() { return 2; } protected Object[] getIsArrayExpectations() { return new Object[] { Boolean.FALSE, JSONNull.getInstance() }; } protected Object[] getToStringExpectations1() { return new Object[] { "null", JSONNull.getInstance() }; } protected Object[] getToStringExpectations2() { return new Object[] { "null", JSONNull.getInstance() }; } protected Object[] getToStringExpectations3() { return new Object[] { " null", JSONNull.getInstance() }; } protected Object[] getWriteExpectations() { return new Object[] { "null", JSONNull.getInstance() }; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/PropertyConstants.java0000664000175000017500000000656011650253660027477 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.sample.ObjectBean; /** * @author Andres Almiray */ public final class PropertyConstants { private static final String ARRAY = "parray"; private static final String BEAN = "pbean"; private static final String BOOLEAN = "pboolean"; private static final String BYTE = "pbyte"; private static final String CHAR = "pchar"; private static final String CLASS = "pclass"; private static Map classes = new HashMap(); private static final String DOUBLE = "pdouble"; private static final String FLOAT = "pfloat"; private static final String FUNCTION = "pfunction"; private static final String INT = "pint"; private static final String LIST = "plist"; private static final String LONG = "plong"; private static final String SHORT = "pshort"; private static final String STRING = "pstring"; private static Map values = new HashMap(); static{ values.put( BYTE, new Byte( Byte.MAX_VALUE ) ); values.put( SHORT, new Short( Short.MAX_VALUE ) ); values.put( INT, new Integer( Integer.MAX_VALUE ) ); values.put( LONG, new Long( Long.MAX_VALUE ) ); values.put( FLOAT, new Float( Float.MAX_VALUE ) ); values.put( DOUBLE, new Double( Double.MAX_VALUE ) ); values.put( BOOLEAN, Boolean.TRUE ); values.put( CHAR, new Character( 'J' ) ); values.put( STRING, "json" ); values.put( FUNCTION, new JSONFunction( "this;" ) ); values.put( ARRAY, new int[] { 1, 2 } ); List list = new ArrayList(); list.add( "a" ); list.add( "b" ); values.put( LIST, list ); values.put( CLASS, Object.class ); values.put( BEAN, new ObjectBean() ); classes.put( BYTE, Byte.class ); classes.put( SHORT, Short.class ); classes.put( INT, Integer.class ); classes.put( LONG, Long.class ); classes.put( FLOAT, Float.class ); classes.put( DOUBLE, Double.class ); classes.put( BOOLEAN, Boolean.class ); classes.put( CHAR, Character.class ); classes.put( STRING, String.class ); classes.put( FUNCTION, JSONFunction.class ); classes.put( ARRAY, int[].class ); classes.put( LIST, List.class ); classes.put( CLASS, Class.class ); classes.put( BEAN, ObjectBean.class ); } public static String[] getProperties() { return new String[] { BYTE, SHORT, INT, LONG, FLOAT, DOUBLE, CHAR, BOOLEAN, STRING, FUNCTION, ARRAY, LIST, CLASS, BEAN }; } public static Class getPropertyClass( String key ) { return (Class) classes.get( key ); } public static Object getPropertyValue( String key ) { return values.get( key ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_JSONTokener.java0000664000175000017500000000341611650253660033536 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import net.sf.json.util.JSONTokener; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_JSONTokener extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_JSONTokener.class ); } public TestJSONObjectStaticBuilders_JSONTokener( String name ) { super( name ); } protected Object getSource() { return new JSONTokener( "{\"parray\":[1,2],\"plong\":9223372036854775807,\"pchar\":\"J\",\"pboolean\":true,\"pfloat\":3.4028234663852886E38,\"pbean\":{\"parray\":null,\"plong\":null,\"pchar\":null,\"pboolean\":null,\"pfloat\":null,\"pbean\":null,\"pshort\":null,\"pdouble\":null,\"pclass\":null,\"pstring\":null,\"pint\":null,\"plist\":null,\"pfunction\":null,\"pmap\":null,\"pbyte\":null},\"pshort\":32767,\"pdouble\":1.7976931348623157E308,\"pclass\":\"java.lang.Object\",\"pstring\":\"json\",\"pint\":2147483647,\"plist\":[\"a\",\"b\"],\"pfunction\":function(){ this; },\"pmap\":null,\"pbyte\":127,\"class\":\"java.lang.Object\",\"pexcluded\":\"\"}" ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayEqualsHashCodeCompareTo.java0000664000175000017500000001011611650253660032742 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestJSONArrayEqualsHashCodeCompareTo extends TestCase { private static JSONArray strings; private static Map values = new HashMap(); private static JSONArray values1; private static JSONArray values2; private static JSONArray values3; static{ values.put( "int.1", Integer.valueOf( "1" ) ); values.put( "int.2", Integer.valueOf( "2" ) ); values.put( "long.1", Long.valueOf( "1" ) ); values.put( "long.2", Long.valueOf( "2" ) ); values.put( "string.1", "1" ); values.put( "string.2", "2" ); values.put( "boolean.1", Boolean.TRUE ); values.put( "boolean.2", Boolean.FALSE ); strings = new JSONArray().element( "1" ) .element( "1" ) .element( "true" ) .element( "string" ) .element( "function(){ return this; }" ) .element( "[1,2,3]" ); values.put( "JSONArray.strings", strings ); values1 = new JSONArray().element( Integer.valueOf( "1" ) ) .element( Long.valueOf( "1" ) ) .element( Boolean.TRUE ) .element( "string" ) .element( new JSONFunction( "return this;" ) ) .element( JSONArray.fromObject( new int[] { 1, 2, 3 } ) ); values.put( "JSONArray.values.1", values1 ); values2 = new JSONArray().element( Integer.valueOf( "1" ) ) .element( Long.valueOf( "1" ) ) .element( Boolean.TRUE ) .element( "string" ); values.put( "JSONObject.values.2", values2 ); values3 = new JSONArray().element( Integer.valueOf( "2" ) ) .element( Long.valueOf( "2" ) ) .element( Boolean.FALSE ) .element( "string2" ); values.put( "JSONObject.values.3", values3 ); } public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayEqualsHashCodeCompareTo.class ); } public TestJSONArrayEqualsHashCodeCompareTo( String name ) { super( name ); } public void testCompareTo_different_size() { assertEquals( -1, values2.compareTo( strings ) ); assertEquals( 1, strings.compareTo( values2 ) ); } public void testCompareTo_null() { assertEquals( -1, strings.compareTo( null ) ); } public void testCompareTo_object() { assertEquals( -1, strings.compareTo( new Object() ) ); } public void testCompareTo_same_array() { assertEquals( 0, strings.compareTo( strings ) ); } public void testCompareTo_same_size_different_values() { assertEquals( -1, values2.compareTo( values3 ) ); } public void testCompareTo_same_size_similar_values() { assertEquals( 0, strings.compareTo( values1 ) ); } public void testEquals_different_elements_same_size() { assertFalse( values2.equals( values3 ) ); assertFalse( values3.equals( values2 ) ); } public void testEquals_null() { assertFalse( strings.equals( null ) ); } public void testEquals_object() { assertFalse( strings.equals( new Object() ) ); } public void testEquals_same_object() { assertTrue( strings.equals( strings ) ); } public void testEquals_same_size_similar_values() { assertTrue( strings.equals( values1 ) ); } public void testHashCode_different_elements_same_size() { assertFalse( values2.hashCode() == values3.hashCode() ); } }././@LongLink0000644000000000000000000000015212255646554011656 Lustar rootrootjenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayStaticBuilders_Collection_DynaBean.javajenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayStaticBuilders_Collection_DynaBean0000664000175000017500000000415311650253660034220 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; /** * @author Andres Almiray */ public class TestJSONArrayStaticBuilders_Collection_DynaBean extends AbstractJSONArrayStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayStaticBuilders_Collection_DynaBean.class ); } public TestJSONArrayStaticBuilders_Collection_DynaBean( String name ) { super( name ); } protected Object getSource() { Map map = new HashMap(); String[] props = getProperties(); for( int i = 0; i < props.length; i++ ){ map.put( props[i], PropertyConstants.getPropertyClass( props[i] ) ); } map.put( "class", Class.class ); map.put( "pexcluded", String.class ); MorphDynaClass dynaClass = new MorphDynaClass( map ); MorphDynaBean dynaBean = null; try{ dynaBean = (MorphDynaBean) dynaClass.newInstance(); for( int i = 0; i < props.length; i++ ){ dynaBean.set( props[i], PropertyConstants.getPropertyValue( props[i] ) ); } dynaBean.set( "class", Object.class ); dynaBean.set( "pexcluded", "" ); }catch( Exception e ){ throw new RuntimeException( e ); } List list = new ArrayList(); list.add( dynaBean ); return list; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/AbstractJSONArrayStaticBuildersTestCase.java0000664000175000017500000000563211650253660033507 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import junit.framework.TestCase; /** * @author Andres Almiray */ public abstract class AbstractJSONArrayStaticBuildersTestCase extends TestCase { public AbstractJSONArrayStaticBuildersTestCase( String testName ) { super( testName ); } public void testFromObject() { JSONArray jsonArray = JSONArray.fromObject( getSource() ); assertNotNull( jsonArray ); assertEquals( 1, jsonArray.size() ); JSONObject jsonObject = jsonArray.getJSONObject( 0 ); assertJSONObject( jsonObject, getProperties() ); assertTrue( !jsonObject.has( "class" ) ); } public void testFromObject_excludes() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes( getExclusions() ); JSONArray jsonArray = JSONArray.fromObject( getSource(), jsonConfig ); assertNotNull( jsonArray ); assertEquals( 1, jsonArray.size() ); JSONObject jsonObject = jsonArray.getJSONObject( 0 ); assertJSONObject( jsonObject, getProperties() ); String[] excluded = getExclusions(); for( int i = 0; i < excluded.length; i++ ){ assertTrue( !jsonObject.has( excluded[i] ) ); } assertTrue( !jsonObject.has( "class" ) ); assertTrue( !jsonObject.has( "pexcluded" ) ); } public void testFromObject_excludes_ignoreDefaults() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes( getExclusions() ); jsonConfig.setIgnoreDefaultExcludes( true ); JSONArray jsonArray = JSONArray.fromObject( getSource(), jsonConfig ); assertNotNull( jsonArray ); assertEquals( 1, jsonArray.size() ); JSONObject jsonObject = jsonArray.getJSONObject( 0 ); assertJSONObject( jsonObject, getProperties() ); assertTrue( jsonObject.has( "class" ) ); assertTrue( !jsonObject.has( "pexcluded" ) ); } protected String[] getExclusions() { return new String[] { "pexcluded" }; } protected String[] getProperties() { return PropertyConstants.getProperties(); } protected abstract Object getSource(); private void assertJSONObject( JSONObject json, String[] properties ) { assertNotNull( json ); for( int i = 0; i < properties.length; i++ ){ assertTrue( json.has( properties[i] ) ); } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectEqualsHashCodeCompareTo.java0000664000175000017500000001630011650253660033073 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestJSONObjectEqualsHashCodeCompareTo extends TestCase { private static JSONObject strings; private static Map values = new HashMap(); private static JSONObject values1; private static JSONObject values2; private static JSONObject values3; static{ values.put( "JSONObject.null.1", new JSONObject( true ) ); values.put( "JSONObject.null.2", new JSONObject( true ) ); values.put( "int.1", Integer.valueOf( "1" ) ); values.put( "int.2", Integer.valueOf( "2" ) ); values.put( "long.1", Long.valueOf( "1" ) ); values.put( "long.2", Long.valueOf( "2" ) ); values.put( "string.1", "1" ); values.put( "string.2", "2" ); values.put( "boolean.1", Boolean.TRUE ); values.put( "boolean.2", Boolean.FALSE ); strings = new JSONObject().element( "int", "1" ) .element( "long", "1" ) .element( "boolean", "true" ) .element( "string", "string" ) .element( "func", "function(){ return this; }" ) .element( "array", JSONArray.fromObject("[1,2,3]") ); values.put( "JSONObject.strings", strings ); values1 = new JSONObject().element( "int", Integer.valueOf( "1" ) ) .element( "long", Long.valueOf( "1" ) ) .element( "boolean", Boolean.TRUE ) .element( "string", "string" ) .element( "func", new JSONFunction( "return this;" ) ) .element( "array", JSONArray.fromObject( new int[] { 1, 2, 3 } ) ); values.put( "JSONObject.values.1", values1 ); values2 = new JSONObject().element( "int", Integer.valueOf( "1" ) ) .element( "long", Long.valueOf( "1" ) ) .element( "boolean", Boolean.TRUE ) .element( "string", "string" ); values.put( "JSONObject.values.2", values2 ); values3 = new JSONObject().element( "int", Integer.valueOf( "2" ) ) .element( "long", Long.valueOf( "2" ) ) .element( "boolean", Boolean.FALSE ) .element( "string", "string2" ); values.put( "JSONObject.values.3", values3 ); } public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectEqualsHashCodeCompareTo.class ); } public TestJSONObjectEqualsHashCodeCompareTo( String name ) { super( name ); } public void testCompareTo_different_size() { assertEquals( -1, values2.compareTo( strings ) ); assertEquals( 1, strings.compareTo( values2 ) ); } public void testCompareTo_null() { assertEquals( -1, strings.compareTo( null ) ); } public void testCompareTo_object() { assertEquals( -1, strings.compareTo( new Object() ) ); } public void testCompareTo_same_array() { assertEquals( 0, strings.compareTo( strings ) ); } public void testCompareTo_same_size_different_values() { assertEquals( -1, values2.compareTo( values3 ) ); } public void testCompareTo_same_size_similar_values() { assertEquals( 0, strings.compareTo( values1 ) ); } public void testEquals_different_key_same_size() { JSONObject a = new JSONObject().element( "key1", "string" ); JSONObject b = new JSONObject().element( "key2", "json" ); assertFalse( a.equals( b ) ); assertFalse( b.equals( a ) ); } public void testEquals_different_sizes() { assertFalse( values.get( "JSONObject.values.1" ) .equals( values.get( "JSONObject.values.2" ) ) ); } public void testEquals_nullObject_other() { assertFalse( values.get( "JSONObject.null.1" ) .equals( values.get( "JSONObject.strings" ) ) ); } public void testEquals_nullObjects_different() { assertTrue( values.get( "JSONObject.null.1" ) .equals( values.get( "JSONObject.null.2" ) ) ); } public void testEquals_other_nullObject() { assertFalse( values.get( "JSONObject.strings" ) .equals( values.get( "JSONObject.null.1" ) ) ); } public void testEquals_same() { assertTrue( values.get( "JSONObject.null.1" ) .equals( values.get( "JSONObject.null.1" ) ) ); } public void testEquals_same_key_different_value() { JSONObject a = new JSONObject().element( "key", "string" ); JSONObject b = new JSONObject().element( "key", "json" ); assertFalse( a.equals( b ) ); assertFalse( b.equals( a ) ); } public void testEquals_strings_values() { assertTrue( values.get( "JSONObject.strings" ) .equals( values.get( "JSONObject.values.1" ) ) ); } public void testEquals_to_null() { assertFalse( values.get( "JSONObject.null.1" ) .equals( null ) ); } public void testEquals_to_other() { assertFalse( values.get( "JSONObject.null.1" ) .equals( new Object() ) ); } public void testEquals_values_strings() { assertTrue( values.get( "JSONObject.values.1" ) .equals( values.get( "JSONObject.strings" ) ) ); } public void testHashCode_different_size() { assertFalse( values.get( "JSONObject.values.1" ) .hashCode() == values.get( "JSONObject.values.2" ) .hashCode() ); } public void testHashCode_nullObject_other() { assertFalse( values.get( "JSONObject.null.1" ) .hashCode() == values.get( "JSONObject.strings" ) .hashCode() ); } public void testHashCode_nullObjects_different() { assertTrue( values.get( "JSONObject.null.1" ) .hashCode() == values.get( "JSONObject.null.2" ) .hashCode() ); } public void testHashCode_other_nullObject() { assertFalse( values.get( "JSONObject.strings" ) .hashCode() == values.get( "JSONObject.null.1" ) .hashCode() ); } public void testHashCode_same() { assertTrue( values.get( "JSONObject.null.1" ) .hashCode() == values.get( "JSONObject.null.1" ) .hashCode() ); } public void testHashCode_same_key_different_value() { JSONObject a = new JSONObject().element( "key", "string" ); JSONObject b = new JSONObject().element( "key", "json" ); assertFalse( a.hashCode() == b.hashCode() ); } public void testHashCode_strings_values() { assertTrue( values.get( "JSONObject.strings" ) .hashCode() != values.get( "JSONObject.values.1" ) .hashCode() ); } public void testHashCode_to_other() { assertFalse( values.get( "JSONObject.null.1" ) .hashCode() == new Object().hashCode() ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONFunction.java0000664000175000017500000000673111650253660027075 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import net.sf.json.test.JSONAssert; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestJSONFunction extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONFunction.class ); } public TestJSONFunction( String name ) { super( name ); } public void testEquals() { JSONFunction expected = new JSONFunction( new String[] { "a" }, "return a;" ); assertFalse( expected.equals( null ) ); assertFalse( expected.equals( new Object() ) ); assertFalse( expected.equals( "" ) ); assertFalse( expected.equals( new JSONFunction( "return a;" ) ) ); assertFalse( expected.equals( new JSONFunction( new String[] { "a" }, "return b;" ) ) ); assertTrue( expected.equals( new JSONFunction( new String[] { "a" }, "return a;" ) ) ); } public void testHashCode() { JSONFunction a = new JSONFunction( new String[] { "a,b" }, "return a+b;" ); JSONFunction b = new JSONFunction( new String[] { "a,b" }, "return a+b;" ); assertTrue( a.hashCode() == b.hashCode() ); } public void testParse_String() { assertEquals( "function(){ return a; }", JSONFunction.parse( "function(){ return a; }" ).toString() ); } public void testParse_String_withWhiteSpacechars() { assertEquals( "function(){ return a; }", JSONFunction.parse( "function() { return a; }" ).toString() ); assertEquals( "function(){ return a; }", JSONFunction.parse( "function() { return a; }" ).toString() ); assertEquals( "function(){ return a; }", JSONFunction.parse( "function()\n{ return a; }" ).toString() ); assertEquals( "function(){ return a; }", JSONFunction.parse( "function()\t{ return a; }" ).toString() ); } public void testParse_withSingleArg(){ JSONFunction expected = new JSONFunction(new String[]{"a"},"return this"); JSONFunction actual = JSONFunction.parse( "function(a){ return this}" ); JSONAssert.assertEquals( expected, actual ); } public void testParse_withMultipleArgs(){ JSONFunction expected = new JSONFunction(new String[]{"a","b"},"return this"); JSONAssert.assertEquals( expected, JSONFunction.parse( "function(a,b){ return this }" ) ); JSONAssert.assertEquals( expected, JSONFunction.parse( "function( a,b ){ return this }" ) ); JSONAssert.assertEquals( expected, JSONFunction.parse( "function( a,b){ return this }" ) ); JSONAssert.assertEquals( expected, JSONFunction.parse( "function(a, b ){ return this }" ) ); JSONAssert.assertEquals( expected, JSONFunction.parse( "function( a, b ){ return this }" ) ); JSONAssert.assertEquals( expected, JSONFunction.parse( "function ( a, b ){ return this }" ) ); JSONAssert.assertEquals( expected, JSONFunction.parse( "function ( a, b ) { return this }" ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectAsMap.java0000664000175000017500000000511111650253660027427 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestJSONObjectAsMap extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectAsMap.class ); } private JSONObject jsonObject; public TestJSONObjectAsMap( String name ) { super( name ); } public void testClear() { assertEquals( 6, jsonObject.size() ); jsonObject.clear(); assertEquals( 0, jsonObject.size() ); } public void testContainsKey() { assertTrue( jsonObject.containsKey( "func" ) ); assertFalse( jsonObject.containsKey( "bogus" ) ); } public void testContainsValue() { assertTrue( jsonObject.containsValue( "string" ) ); } public void testIsEmpty() { assertFalse( jsonObject.isEmpty() ); } public void testPut() { String key = "key"; Object value = "value"; jsonObject.put( key, value ); assertEquals( value, jsonObject.get( key ) ); } public void testPutAll() { JSONObject json = new JSONObject(); Map map = new HashMap(); map.put( "key", "value" ); json.putAll( map ); assertEquals( 1, json.size() ); assertEquals( "value", json.get( "key" ) ); map.put( "key", "value2" ); json.putAll( map ); assertEquals( 1, json.size() ); assertEquals( "value2", json.get( "key" ) ); } public void testRemove() { assertTrue( jsonObject.has( "func" ) ); jsonObject.remove( "func" ); assertFalse( jsonObject.has( "func" ) ); } protected void setUp() throws Exception { jsonObject = new JSONObject().element( "int", "1" ) .element( "long", "1" ) .element( "boolean", "true" ) .element( "string", "string" ) .element( "func", "function(){ return this; }" ) .element( "array", "[1,2,3]" ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/AllTests.java0000664000175000017500000000571711650253660025514 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class AllTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "core" ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_ObjectBean.class ) ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_PrimitiveBean.class ) ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_DynaBean.class ) ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_JSONObject.class ) ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_JSONString.class ) ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_JSONTokener.class ) ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_Map.class ) ); suite.addTest( new TestSuite( TestJSONObjectStaticBuilders_String.class ) ); suite.addTest( new TestSuite( TestJSONArrayStaticBuilders_Array_DynaBean.class ) ); suite.addTest( new TestSuite( TestJSONArrayStaticBuilders_Collection_DynaBean.class ) ); suite.addTest( new TestSuite( TestJSONArrayStaticBuilders_JSONString.class ) ); suite.addTest( new TestSuite( TestJSONArrayStaticBuilders_String.class ) ); suite.addTest( new TestSuite( TestJSONFunction.class ) ); suite.addTest( new TestSuite( TestJSONArray.class ) ); suite.addTest( new TestSuite( TestJSONObject.class ) ); suite.addTest( new TestSuite( TestJSONSerializer.class ) ); suite.addTest( new TestSuite( TestJSONArrayAsJSON.class ) ); suite.addTest( new TestSuite( TestJSONNullAsJSON.class ) ); suite.addTest( new TestSuite( TestJSONObjectWithProcessors.class ) ); suite.addTest( new TestSuite( TestJSONObjectEqualsHashCodeCompareTo.class ) ); suite.addTest( new TestSuite( TestJSONArrayEqualsHashCodeCompareTo.class ) ); suite.addTest( new TestSuite( TestJSONObjectEvents.class ) ); suite.addTest( new TestSuite( TestJSONArrayEvents.class ) ); suite.addTest( new TestSuite( TestJSONObjectAsMap.class ) ); suite.addTest( new TestSuite( TestJSONArrayAsList.class ) ); suite.addTest( new TestSuite( TestUserSubmitted.class ) ); suite.addTest( new TestSuite( TestJSONArrayCollections.class ) ); return suite; } } jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_PrimitiveBean.java0000664000175000017500000000304711650253660034173 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import net.sf.json.sample.PrimitiveBean; import org.apache.commons.beanutils.PropertyUtils; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_PrimitiveBean extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_PrimitiveBean.class ); } public TestJSONObjectStaticBuilders_PrimitiveBean( String name ) { super( name ); } protected Object getSource() { PrimitiveBean bean = new PrimitiveBean(); String[] props = getProperties(); try{ for( int i = 0; i < props.length; i++ ){ PropertyUtils.setProperty( bean, props[i], PropertyConstants.getPropertyValue( props[i] ) ); } }catch( Exception e ){ throw new RuntimeException( e ); } return bean; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayStaticBuilders_JSONString.java0000664000175000017500000000351111650253660033241 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * @author Andres Almiray */ public class TestJSONArrayStaticBuilders_JSONString extends AbstractJSONArrayStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayStaticBuilders_JSONString.class ); } public TestJSONArrayStaticBuilders_JSONString( String name ) { super( name ); } protected Object getSource() { return new JsonBean(); } public static class JsonBean implements JSONString { public String toJSONString() { return "[{\"parray\":[1,2],\"plong\":9223372036854775807,\"pchar\":\"J\",\"pboolean\":true,\"pfloat\":3.4028234663852886E38,\"pbean\":{\"parray\":null,\"plong\":null,\"pchar\":null,\"pboolean\":null,\"pfloat\":null,\"pbean\":null,\"pshort\":null,\"pdouble\":null,\"pclass\":null,\"pstring\":null,\"pint\":null,\"plist\":null,\"pfunction\":null,\"pmap\":null,\"pbyte\":null},\"pshort\":32767,\"pdouble\":1.7976931348623157E308,\"pclass\":\"java.lang.Object\",\"pstring\":\"json\",\"pint\":2147483647,\"plist\":[\"a\",\"b\"],\"pfunction\":function(){ this; },\"pmap\":null,\"pbyte\":127,\"class\":\"java.lang.Object\",\"pexcluded\":\"\"}]"; } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectWithProcessors.java0000664000175000017500000001507211650253660031433 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.json.processors.JsDateJsonBeanProcessor; import net.sf.json.processors.JsDateJsonValueProcessor; import net.sf.json.sample.DateBean; import net.sf.json.sample.IdentityJsonValueProcessor; import net.sf.json.test.JSONAssert; /** * @author Andres Almiray */ public class TestJSONObjectWithProcessors extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectWithProcessors.class ); } private Date date; private JsonConfig jsonConfig; public TestJSONObjectWithProcessors( String name ) { super( name ); } public void testBeanWithDateProperty_fromObject_withJsonBeanProcessor() { DateBean bean = new DateBean(); bean.setDate( date ); bean.setValue( 42 ); jsonConfig.registerJsonBeanProcessor( Date.class, new JsDateJsonBeanProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" ) ); JSONObject jsDate = jsonObject.getJSONObject( "date" ); assertJsDate( jsDate ); } public void testBeanWithDateProperty_fromObject_withJsonValueProcessor_1() { DateBean bean = new DateBean(); bean.setDate( date ); bean.setValue( 42 ); jsonConfig.registerJsonValueProcessor( DateBean.class, Date.class, new JsDateJsonValueProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" ) ); JSONObject jsDate = jsonObject.getJSONObject( "date" ); assertJsDate( jsDate ); } public void testBeanWithDateProperty_fromObject_withJsonValueProcessor_2() { DateBean bean = new DateBean(); bean.setDate( date ); bean.setValue( 42 ); jsonConfig.registerJsonValueProcessor( DateBean.class, "date", new JsDateJsonValueProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" ) ); JSONObject jsDate = jsonObject.getJSONObject( "date" ); assertJsDate( jsDate ); } public void testBeanWithDateProperty_fromObject_withJsonValueProcessor_3() { DateBean bean = new DateBean(); bean.setDate( date ); bean.setValue( 42 ); jsonConfig.registerJsonValueProcessor( Date.class, new JsDateJsonValueProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" ) ); JSONObject jsDate = jsonObject.getJSONObject( "date" ); assertJsDate( jsDate ); } public void testBeanWithDateProperty_fromObject_withJsonValueProcessor_4() { DateBean bean = new DateBean(); bean.setDate( date ); bean.setValue( 42 ); jsonConfig.registerJsonValueProcessor( "date", new JsDateJsonValueProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" ) ); JSONObject jsDate = jsonObject.getJSONObject( "date" ); assertJsDate( jsDate ); } public void testBeanWithDateProperty_put() { DateBean bean = new DateBean(); bean.setValue( 42 ); jsonConfig.registerJsonBeanProcessor( Date.class, new JsDateJsonBeanProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" ) ); JSONObject jsDate = jsonObject.getJSONObject( "date" ); JSONAssert.assertNull( jsDate ); jsonObject.element( "date", date, jsonConfig ); jsDate = jsonObject.getJSONObject( "date" ); assertJsDate( jsDate ); } public void testDateAsBean_fromObject() { jsonConfig.registerJsonBeanProcessor( Date.class, new JsDateJsonBeanProcessor() ); JSONObject jsDate = JSONObject.fromObject( date, jsonConfig ); assertJsDate( jsDate ); } public void testNumericValueWithProcessor_Byte(){ Map bean = new HashMap(); bean.put( "value", new Byte(Byte.MAX_VALUE) ); jsonConfig.registerJsonValueProcessor( "value", new IdentityJsonValueProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( new Integer(Byte.MAX_VALUE), jsonObject.get( "value" )); } public void testNumericValueWithProcessor_Short(){ Map bean = new HashMap(); bean.put( "value", new Short(Short.MAX_VALUE) ); jsonConfig.registerJsonValueProcessor( "value", new IdentityJsonValueProcessor() ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( new Integer(Short.MAX_VALUE), jsonObject.get( "value" )); } protected void setUp() throws Exception { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DAY_OF_MONTH, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); date = c.getTime(); jsonConfig = new JsonConfig(); } private void assertJsDate( JSONObject jsDate ) { JSONAssert.assertNotNull( jsDate ); int year = jsDate.getInt( "year" ); // bug ? assertTrue( year == 2007 || year == 107 ); assertEquals( 5, jsDate.getInt( "month" ) ); assertEquals( 17, jsDate.getInt( "day" ) ); assertEquals( 12, jsDate.getInt( "hours" ) ); assertEquals( 13, jsDate.getInt( "minutes" ) ); assertEquals( 14, jsDate.getInt( "seconds" ) ); assertEquals( 150, jsDate.getInt( "milliseconds" ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestUserSubmitted.java0000664000175000017500000011706611650253660027421 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import junit.framework.TestCase; import net.sf.ezmorph.object.MapToDateMorpher; import net.sf.json.sample.ArrayBean; import net.sf.json.sample.BeanA; import net.sf.json.sample.BeanA1763699; import net.sf.json.sample.BeanB1763699; import net.sf.json.sample.BeanC; import net.sf.json.sample.ChildBean; import net.sf.json.sample.DateBean; import net.sf.json.sample.FieldBean; import net.sf.json.sample.IdBean; import net.sf.json.sample.InterfaceBean; import net.sf.json.sample.JSONTestBean; import net.sf.json.sample.ListingBean; import net.sf.json.sample.MappedBean; import net.sf.json.sample.Media; import net.sf.json.sample.MediaBean; import net.sf.json.sample.MediaList; import net.sf.json.sample.MediaListBean; import net.sf.json.sample.NumberArrayBean; import net.sf.json.sample.PackageProtectedBean; import net.sf.json.sample.ParentBean; import net.sf.json.sample.Player; import net.sf.json.sample.PlayerList; import net.sf.json.sample.PrimitiveBean; import net.sf.json.sample.PrivateConstructorBean; import net.sf.json.sample.UnstandardBean; import net.sf.json.sample.UnstandardBeanInstanceStrategy; import net.sf.json.util.JSONUtils; import net.sf.json.util.JavaIdentifierTransformer; import net.sf.json.util.JsonEventListener; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.PropertyUtils; /** * @author Andres Almiray */ public class TestUserSubmitted extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestUserSubmitted.class ); } private JsonConfig jsonConfig; public TestUserSubmitted( String name ) { super( name ); } public void testPatch_2929940() { Map classMap = new HashMap(); classMap.put("attributes", Long.class); ListingBean original = new ListingBean(); original.addAttribute(Long.valueOf(12)); JSONObject jsonObject = JSONObject.fromObject(JSONObject.fromObject(original).toString()); // JSON config JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(ListingBean.class); jsonConfig.setClassMap(classMap); // toBean ListingBean bean = (ListingBean)JSONObject.toBean(jsonObject, jsonConfig); assertTrue(bean.getAttributes().get(0) instanceof Long); } public void testBug_1635890() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // submited by arco.vandenheuvel[at]points[dot].com String TEST_JSON_STRING = "{\"rateType\":\"HOTRATE\",\"rateBreakdown\":{\"rate\":[{\"amount\":\"109.74\",\"date\":{\"month\":\"01\",\"day\":\"15\",\"year\":\"2007\"}},{\"amount\":\"109.74\",\"date\":{\"month\":\"1\",\"day\":\"16\",\"year\":\"2007\"}}]}}"; DynaBean jsonBean = (DynaBean) JSONObject.toBean( JSONObject.fromObject( TEST_JSON_STRING ) ); assertNotNull( jsonBean ); assertEquals( "wrong rate Type", "HOTRATE", jsonBean.get( "rateType" ) ); assertNotNull( "null rate breakdown", jsonBean.get( "rateBreakdown" ) ); DynaBean jsonRateBreakdownBean = (DynaBean) jsonBean.get( "rateBreakdown" ); assertNotNull( "null rate breakdown ", jsonRateBreakdownBean ); Object jsonRateBean = jsonRateBreakdownBean.get( "rate" ); assertNotNull( "null rate ", jsonRateBean ); assertTrue( "list", jsonRateBean instanceof ArrayList ); assertNotNull( "null rate ", jsonRateBreakdownBean.get( "rate", 0 ) ); } public void testBug_1650535_builders() { // submitted by Paul Field String json = "{\"obj\":\"{}\",\"array\":\"[]\"}"; JSONObject object = JSONObject.fromObject( json ); assertNotNull( object ); assertTrue( object.has( "obj" ) ); assertTrue( object.has( "array" ) ); Object obj = object.get( "obj" ); assertTrue( obj instanceof String ); Object array = object.get( "array" ); assertTrue( array instanceof String ); json = "{'obj':'{}','array':'[]'}"; object = JSONObject.fromObject( json ); assertNotNull( object ); assertTrue( object.has( "obj" ) ); assertTrue( object.has( "array" ) ); obj = object.get( "obj" ); assertTrue( obj instanceof String ); array = object.get( "array" ); assertTrue( array instanceof String ); json = "[\"{}\",\"[]\"]"; JSONArray jarray = JSONArray.fromObject( json ); assertNotNull( jarray ); obj = jarray.get( 0 ); assertTrue( obj instanceof String ); array = jarray.get( 1 ); assertTrue( array instanceof String ); json = "['{}','[]']"; jarray = JSONArray.fromObject( json ); assertNotNull( jarray ); obj = jarray.get( 0 ); assertTrue( obj instanceof String ); array = jarray.get( 1 ); assertTrue( array instanceof String ); // submitted by Elizabeth Keogh Map map = new HashMap(); map.put( "address", "1 The flats [Upper floor]" ); map.put( "phoneNumber", "[+44] 582 401923" ); map.put( "info1", "[Likes coffee]" ); map.put( "info2", "[Likes coffee] [Likes tea]" ); map.put( "info3", "[Likes coffee [but not with sugar]]" ); object = JSONObject.fromObject( map ); assertNotNull( object ); assertTrue( object.has( "address" ) ); assertTrue( object.has( "phoneNumber" ) ); assertTrue( object.has( "info1" ) ); assertTrue( object.has( "info2" ) ); assertTrue( object.has( "info3" ) ); assertTrue( object.get( "address" ) instanceof String ); assertTrue( object.get( "phoneNumber" ) instanceof String ); assertTrue( object.get( "info1" ) instanceof String ); assertTrue( object.get( "info2" ) instanceof String ); assertTrue( object.get( "info3" ) instanceof String ); } /* I consider this behavior of "oh I added string but it's not really a string" very evil, as there's no way to add a String that really looks like "{}" public void testBug_1650535_setters() { JSONObject object = new JSONObject(); object.element( "obj", "{}" ); object.element( "notobj", "{string}" ); object.element( "array", "[]" ); object.element( "notarray", "[string]" ); assertTrue( object.get( "obj" ) instanceof JSONObject ); assertTrue( object.get( "array" ) instanceof JSONArray ); assertTrue( object.get( "notobj" ) instanceof String ); assertTrue( object.get( "notarray" ) instanceof String ); object.element( "str", "json,json" ); assertTrue( object.get( "str" ) instanceof String ); } */ public void testBug_1753528_ArrayStringLiteralToString() { // submited bysckimos[at]gmail[dot]com BeanA bean = new BeanA(); bean.setString( "[1234]" ); JSONObject jsonObject = JSONObject.fromObject( bean ); assertEquals( "[1234]", jsonObject.get( "string" ) ); bean.setString( "{'key':'1234'}" ); jsonObject = JSONObject.fromObject( bean ); assertEquals( "{'key':'1234'}", jsonObject.get( "string" ) ); } public void testBug_1763699_toBean() { JSONObject json = JSONObject.fromObject( "{'bbeans':[{'str':'test'}]}" ); BeanA1763699 bean = (BeanA1763699) JSONObject.toBean( json, BeanA1763699.class ); assertNotNull( bean ); BeanB1763699[] bbeans = bean.getBbeans(); assertNotNull( bbeans ); assertEquals( 1, bbeans.length ); assertEquals( "test", bbeans[0].getStr() ); } public void testBug_1764768_toBean() { JSONObject json = JSONObject.fromObject( "{'beanA':''}" ); Map classMap = new HashMap(); classMap.put( "beanA", BeanA.class ); BeanC bean = (BeanC) JSONObject.toBean( json, BeanC.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getBeanA() ); assertEquals( new BeanA(), bean.getBeanA() ); } public void testBug_1769559_array_conversion() { JSONObject jsonObject = new JSONObject().element( "beans", new JSONArray().element( "{}" ) .element( "{'bool':false,'integer':216,'string':'JsOn'}" ) ); ArrayBean bean = (ArrayBean) JSONObject.toBean( jsonObject, ArrayBean.class ); assertNotNull( bean ); // no error should happen here JSONArray jsonArray = jsonObject.getJSONArray( "beans" ); BeanA[] beans = (BeanA[]) JSONArray.toArray( jsonArray, BeanA.class ); assertNotNull( beans ); assertEquals( 2, beans.length ); assertEquals( new BeanA(), beans[0] ); assertEquals( new BeanA( false, 216, "JsOn" ), beans[1] ); } public void testBug_1769578_array_conversion() { JSONObject jsonObject = JSONObject .fromObject( "{'media':[{'title':'Giggles'},{'title':'Dreamland?'}]}" ); Map classMap = new HashMap(); classMap.put( "media", MediaBean.class ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia() ); assertTrue( bean.getMedia().getClass().isArray() ); Object[] media = (Object[]) bean.getMedia(); assertEquals( 2, media.length ); Object mediaItem1 = media[0]; assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testBug_1812682() { int[] numbers = new int[] { 1, 2, 3, 4, 5 }; JSONObject json = new JSONObject().element( "bytes", numbers ).element( "shorts", numbers ) .element( "ints", numbers ).element( "longs", numbers ).element( "floats", numbers ) .element( "doubles", numbers ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( NumberArrayBean.class ); NumberArrayBean bean = (NumberArrayBean) JSONObject.toBean( json, jsonConfig ); assertNotNull( bean ); } public void testBug_1813301() { List list = new ArrayList(); list.add( "1" ); list.add( "2" ); list.add( "3" ); JSONObject jsonObject = new JSONObject().element( "name", "JSON" ).element( "list", list ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( MappedBean.class ); MappedBean bean = (MappedBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( "JSON", bean.getName() ); Assertions.assertEquals( list, bean.getList() ); } public void testBug_1875600_1() { JSONArray jArray = JSONArray.fromObject( "[]" ); int[] iArray = (int[]) JSONArray.toArray( jArray, int.class ); JSONArray actual = JSONArray.fromObject( iArray ); Assertions.assertEquals( new JSONArray(), actual ); } public void testBug_1875600_2() { JSONArray jArray = JSONArray.fromObject( "[ [] ]" ); int[][] iArray = (int[][]) JSONArray.toArray( jArray, int.class ); JSONArray actual = JSONArray.fromObject( iArray ); Assertions.assertEquals( new JSONArray().element( new JSONArray() ), actual ); } public void testConstructor_Object__nullArray() { // submitted by Matt Small String[] strarr = null; JSONObject jsonObject = JSONObject.fromObject( strarr, jsonConfig ); assertTrue( jsonObject.isNullObject() ); } public void testConstructor_Object_EnclosedArray() { // submitted by Matt Small PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( new String[] { "hi", "bye" } ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertFalse( jsonObject.isNullObject() ); assertFalse( jsonObject.getJSONArray( "oarray" ).isEmpty() ); } public void testConstructor_Object_EnclosedNullArray() { // submitted by Matt Small PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( null ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertFalse( jsonObject.isNullObject() ); assertTrue( jsonObject.getJSONArray( "oarray" ).isEmpty() ); } public void testConstructorAndToBean_Object_RoundTrip_EnclosedNullArray() { PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( null ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); PrimitiveBean bean2 = (PrimitiveBean) JSONObject.toBean( jsonObject, PrimitiveBean.class ); assertNotNull( bean2 ); // bean.oarray == null // jsonObject.oarray == [] therefore // bean2.oarray != null assertEquals( 0, bean2.getOarray().length ); } public void testDynaBeanAttributeMap() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // submited by arco.vandenheuvel[at]points[dot].com JSONObject jsonObject = JSONObject.fromObject( new JSONTestBean() ); String jsonString = jsonObject.toString(); DynaBean jsonBean = (DynaBean) JSONObject.toBean( JSONObject.fromObject( jsonString ) ); assertNotNull( jsonBean ); assertEquals( "wrong inventoryID", "", jsonBean.get( "inventoryID" ) ); } public void testFR_1768960_array_conversion() { // 2 items JSONObject jsonObject = JSONObject .fromObject( "{'media2':[{'title':'Giggles'},{'title':'Dreamland?'}]}" ); Map classMap = new HashMap(); classMap.put( "media2", MediaBean.class ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); List media2 = bean.getMedia2(); assertEquals( 2, media2.size() ); Object mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); // 1 // item jsonObject = JSONObject.fromObject( "{'media2':[{'title':'Giggles'}]}" ); bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); media2 = bean.getMedia2(); assertEquals( 1, media2.size() ); mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testFR_1808430_newBeanInstance() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setNewBeanInstanceStrategy( new UnstandardBeanInstanceStrategy() ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "id", 1 ); jsonConfig.setRootClass( UnstandardBean.class ); UnstandardBean bean = (UnstandardBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( UnstandardBean.class, bean.getClass() ); assertEquals( 1, bean.getId() ); } public void testFR_1832047_packageProtectedBean() { JSONObject jsonObject = new JSONObject().element( "value", "42" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( PackageProtectedBean.class ); PackageProtectedBean bean = (PackageProtectedBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( 42, bean.getValue() ); } public void testFR_1832047_privateProtectedBean() { JSONObject jsonObject = new JSONObject().element( "value", "42" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( PrivateConstructorBean.class ); PrivateConstructorBean bean = (PrivateConstructorBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( 42, bean.getValue() ); } public void testFR_1858073_preserveInsertionOrder() { JSONObject jsonObject = new JSONObject().element( "one", "one" ).element( "two", "two" ) .element( "three", "three" ); JSONArray actual = jsonObject.names(); JSONArray expected = new JSONArray().element( "one" ).element( "two" ).element( "three" ); Assertions.assertEquals( expected, actual ); } public void testFromObjectCurliesOnString() { String json = "{'prop':'{value}'}"; JSONObject jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{value}", jsonObject.get( "prop" ) ); json = "{'prop':'{{value}}'}"; jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{{value}}", jsonObject.get( "prop" ) ); json = "{'prop':'{{{value}}}'}"; jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{{{value}}}", jsonObject.get( "prop" ) ); } public void testHandleJettisonEmptyElement() { JSONObject jsonObject = JSONObject.fromObject( "{'beanA':'','beanB':''}" ); jsonConfig.setHandleJettisonEmptyElement( true ); jsonConfig.setRootClass( BeanC.class ); BeanC bean = (BeanC) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNull( bean.getBeanA() ); assertNull( bean.getBeanB() ); } public void testHandleJettisonSingleElementArray() { JSONObject jsonObject = JSONObject.fromObject( "{'media2':{'title':'Giggles'}}" ); Map classMap = new HashMap(); classMap.put( "media2", MediaBean.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( MediaListBean.class ); jsonConfig.setClassMap( classMap ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); List media2 = bean.getMedia2(); assertEquals( 1, media2.size() ); Object mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testHandleJettisonSingleElementArray2() { JSONObject jsonObject = JSONObject.fromObject( "{'mediaList':{'media':{'title':'Giggles'}}}" ); Map classMap = new HashMap(); classMap.put( "media", Media.class ); classMap.put( "mediaList", MediaList.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( Player.class ); jsonConfig.setClassMap( classMap ); Player bean = (Player) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getMediaList() ); MediaList mediaList = bean.getMediaList(); assertNotNull( mediaList.getMedia() ); ArrayList medias = mediaList.getMedia(); assertEquals( "Giggles", ((Media) medias.get( 0 )).getTitle() ); } public void testHandleJettisonSingleElementArray3() { JSONObject jsonObject = JSONObject .fromObject( "{'player':{'mediaList':{'media':{'title':'Giggles'}}}}" ); Map classMap = new HashMap(); classMap.put( "media", Media.class ); classMap.put( "mediaList", MediaList.class ); classMap.put( "player", Player.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( PlayerList.class ); jsonConfig.setClassMap( classMap ); PlayerList bean = (PlayerList) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getPlayer() ); ArrayList players = bean.getPlayer(); assertNotNull( players ); assertNotNull( players.get( 0 ) ); Player player = (Player) players.get( 0 ); assertNotNull( player.getMediaList() ); MediaList mediaList = player.getMediaList(); assertNotNull( mediaList.getMedia() ); ArrayList medias = mediaList.getMedia(); assertEquals( "Giggles", ((Media) medias.get( 0 )).getTitle() ); } public void testJsonWithNamespaceToDynaBean() throws Exception { // submited by Girish Ipadi jsonConfig.setJavaIdentifierTransformer( JavaIdentifierTransformer.NOOP ); String str = "{'version':'1.0'," + "'sid':'AmazonDocStyle', 'svcVersion':'0.1'," + "'oid':'ItemLookup', 'params':[{ 'ns:ItemLookup': {" + "'ns:SubscriptionId':'0525E2PQ81DD7ZTWTK82'," + "'ns:Validate':'False'," + "'ns:Request':{" + "'ns:ItemId':'SDGKJSHDGAJSGL'," + "'ns:IdType':'ASIN'," + "'ns:ResponseGroup':'Large'" + "}," + "'ns:Request':{" + "'ns:ItemId':'XXXXXXXXXX'," + "'ns:IdType':'ASIN'," + "'ns:ResponseGroup':'Large'" + "}" + "}" + "}]" + "} "; JSONObject json = JSONObject.fromObject( str, jsonConfig ); Object bean = JSONObject.toBean( (JSONObject) json ); assertNotNull( bean ); List params = (List) PropertyUtils.getProperty( bean, "params" ); DynaBean param0 = (DynaBean) params.get( 0 ); DynaBean itemLookup = (DynaBean) param0.get( "ns:ItemLookup" ); assertNotNull( itemLookup ); assertEquals( "0525E2PQ81DD7ZTWTK82", itemLookup.get( "ns:SubscriptionId" ) ); } /* No morpher, please - Kohsuke public void testToBeanSimpleToComplexValueTransformation() { // Submitted by Oliver Zyngier JSONObject jsonObject = JSONObject.fromObject( "{'id':null}" ); IdBean idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertEquals( null, idBean.getId() ); jsonObject = JSONObject.fromObject( "{'id':1}" ); idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertNotNull( idBean.getId() ); assertEquals( 0L, idBean.getId().getValue() ); JSONUtils.getMorpherRegistry().registerMorpher( new IdBean.IdMorpher(), true ); jsonObject = JSONObject.fromObject( "{'id':1}" ); idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertEquals( new IdBean.Id( 1L ), idBean.getId() ); } public void testToBeanWithMultipleMorphersForTargetType() { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DATE, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); Date date = c.getTime(); DateBean bean = new DateBean(); bean.setDate( date ); JSONObject jsonObject = JSONObject.fromObject( bean ); JSONUtils.getMorpherRegistry().registerMorpher( new MapToDateMorpher() ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( DateBean.class ); DateBean actual = (DateBean) JSONObject.toBean( jsonObject, jsonConfig ); Calendar d = Calendar.getInstance(); d.setTime( actual.getDate() ); assertEquals( c.get( Calendar.YEAR ), d.get( Calendar.YEAR ) ); assertEquals( c.get( Calendar.MONTH ), d.get( Calendar.MONTH ) ); assertEquals( c.get( Calendar.DATE ), d.get( Calendar.DATE ) ); assertEquals( c.get( Calendar.HOUR_OF_DAY ), d.get( Calendar.HOUR_OF_DAY ) ); assertEquals( c.get( Calendar.MINUTE ), d.get( Calendar.MINUTE ) ); assertEquals( c.get( Calendar.SECOND ), d.get( Calendar.SECOND ) ); assertEquals( c.get( Calendar.MILLISECOND ), d.get( Calendar.MILLISECOND ) ); } public void testToBeanWithInterfaceField() { JSONObject jsonObject = JSONObject.fromObject( "{runnable:{}}" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( InterfaceBean.class ); Map classMap = new HashMap(); classMap.put( "runnable", RunnableImpl.class ); jsonConfig.setClassMap( classMap ); InterfaceBean bean = (InterfaceBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getRunnable() ); assertTrue( bean.getRunnable() instanceof RunnableImpl ); } public void testCycleDetection_withExclusions() { ParentBean parent = new ParentBean(); parent.setChild( new ChildBean() ); // will fail if throws an exception jsonConfig.setExcludes( new String[] { "parent" } ); JSONObject.fromObject( parent, jsonConfig ); } public void testJSONArrayIterator() { JSONArray jsonArray = new JSONArray(); jsonArray.add( "1" ); jsonArray.add( "2" ); jsonArray.add( "3" ); List list = new LinkedList(); list.add( "4" ); list.add( "5" ); list.add( "6" ); jsonArray.add( list ); List newList = new LinkedList(); newList.add( "7" ); newList.add( "8" ); newList.add( "9" ); Assertions.assertEquals( JSONArray.fromObject( "['1','2','3',['4','5','6']]" ), jsonArray ); ListIterator listIterator = jsonArray.listIterator(); listIterator.add( newList ); Assertions.assertEquals( JSONArray.fromObject( "[['7','8','9'],'1','2','3',['4','5','6']]" ), jsonArray ); } public void testJSONArray_badFormattedString() { String badJson = "[{\"a\":\"b\"},"; try { JSONArray.fromObject(badJson); fail("Expecting a syntax error from JSONTokener."); }catch( JSONException jsone ) { assertTrue( jsone.getMessage().startsWith( "Found starting '[' but missing ']' at the end." )); } } public void testJSONObject_badFormattedString() { String badJson = "{\"a\":\"b\"},"; try { JSONObject.fromObject(badJson); fail("Expecting a syntax error from JSONTokener."); }catch( JSONException jsone ) { assertTrue( jsone.getMessage().startsWith( "Found starting '{' but missing '}' at the end." )); } */ public void testQuotedFunctions() { JSONObject json = JSONObject.fromObject( "{'func':\"function(){blah;}\"}" ); assertTrue( json.get( "func" ) instanceof String ); assertEquals( "function(){blah;}", json.get( "func" )); } public void testJsonWithNullKeys() { Map map = new HashMap(); map.put("key", "value"); map.put(null, "value2"); Object[] obj = {map}; try { JSONSerializer.toJSON( obj ); fail( "Should have thrown a ClassCastException" ); } catch( JSONException expected ) { // ok } } public void testJsonWithNullKeys2() { Map map = new HashMap(); map.put("key", "value"); map.put(null, "value2"); try { System.err.println(JSONSerializer.toJSON( map )); fail( "Should have thrown a ClassCastException" ); } catch( JSONException expected ) { // ok } } public void testJSONArray_JavascriptCompliant() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); String json = "[null, undefined]"; JSONArray array = JSONArray.fromObject( json, jsonConfig ); assertNotNull(array); Assertions.assertEquals( JSONNull.getInstance(), array.get(1) ); } public void testJSONArray_JavascriptComplian2t() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); JSONArray array = new JSONArray(); array.element("null", jsonConfig); array.element("undefined", jsonConfig); assertNotNull(array); Assertions.assertEquals( "null", array.get(0) ); Assertions.assertEquals( "undefined", array.get(1) ); } public void testJSONObject_JavascriptCompliant() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); String json = "{key1: null, key2: undefined}"; JSONObject object = JSONObject.fromObject( json, jsonConfig ); assertNotNull(object); Assertions.assertEquals( JSONNull.getInstance(), object.get("key2") ); } public void testJSONObject_JavascriptCompliant2() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); JSONObject object = new JSONObject(); object.element( "key1", "null", jsonConfig ); object.element( "key2", "undefined", jsonConfig ); assertNotNull(object); Assertions.assertEquals( "undefined", object.get("key2") ); } public void testJSONObject_fromObject_FieldBean() { JsonConfig jsonConfig = new JsonConfig(); FieldBean bean = new FieldBean(); bean.setValue( 42 ); bean.string = "stringy"; jsonConfig.setIgnorePublicFields( true ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" )); assertFalse( jsonObject.has( "string" )); jsonConfig.setIgnorePublicFields( false ); jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" )); assertEquals( "stringy", jsonObject.getString( "string" )); } public void testJSONObject_toBean_FieldBean() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( FieldBean.class ); JSONObject jsonObject = new JSONObject(); jsonConfig.setIgnorePublicFields( true ); jsonObject.element( "value", 42 ); jsonObject.element( "string", "stringy" ); FieldBean bean1 = (FieldBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean1 ); assertEquals( 42, bean1.getValue()); assertNull( bean1.string ); jsonConfig.setIgnorePublicFields( false ); FieldBean bean2 = (FieldBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean2 ); assertEquals( 42, bean1.getValue()); assertEquals( "stringy", bean2.string ); } public void testBug_2692698() { String input = "[\"{'selectedOperatorIndex':2,'leftSideValue':'report.field9','rightSideValue':'2009-3-1'}\",\"all\"]"; JSON json = JSONArray.fromObject( input ); String output = json.toString(); assertEquals(input, output); } public void testWithoutAnyTroubleTheyMayBeAlreadyDoneByOtherTest() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener(new JsonErrorDetector()); // String JSONObject jsonObject = JSONObject.fromObject( "{\"string\":\"aString\"}", tConfig ); assertTrue( "L'objet doit contenir une clef \"string\"", jsonObject.containsKey( "string" ) ); assertNotNull( "Le membre \"string\" doit être une String", jsonObject.optString( "string" ) ); assertEquals( "Le membre \"string\" doit être égal a \"aString\"", "aString", jsonObject.get( "string" ) ); // int jsonObject = JSONObject.fromObject( "{\"integer\":10}", tConfig ); assertTrue( "L'objet doit contenir une clef \"integer\"", jsonObject.containsKey( "integer" ) ); assertEquals( "Le membre \"integer\" doit être égal a 10", 10, jsonObject.optInt( "integer" ) ); // boolean jsonObject = JSONObject.fromObject( "{\"double\":2.02}", tConfig ); assertTrue( "L'objet doit contenir une clef \"double\"", jsonObject.containsKey( "double" ) ); assertEquals( "Le membre \"double\" doit être égal a 2.02", 2.02d, jsonObject.optDouble( "double" ), 0.0001 ); // double jsonObject = JSONObject.fromObject( "{\"boolean\":true}", tConfig ); assertTrue( "L'objet doit contenir une clef \"boolean\"", jsonObject.containsKey( "boolean" ) ); assertEquals( "Le membre \"boolean\" doit être égal a true", true, jsonObject.optBoolean( "boolean" ) ); // String array jsonObject = JSONObject.fromObject( "{\"strArray\":[\"a\",\"b\",\"c\"]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"strArray\"", jsonObject.containsKey( "strArray" ) ); assertNotNull( "Le membre \"strArray\" doit être une Array", jsonObject.optJSONArray( "strArray" ) ); assertEquals( "L'element 0 de \"strArray\" doit être égal a \"a\"", "a", jsonObject.optJSONArray( "strArray" ) .optString( 0 ) ); assertEquals( "L'element 1 de \"strArray\" doit être égal a \"b\"", "b", jsonObject.optJSONArray( "strArray" ) .optString( 1 ) ); assertEquals( "L'element 2 de \"strArray\" doit être égal a \"c\"", "c", jsonObject.optJSONArray( "strArray" ) .optString( 2 ) ); // int array jsonObject = JSONObject.fromObject( "{\"intArray\":[1,2,3]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"intArray\"", jsonObject.containsKey( "intArray" ) ); assertNotNull( "Le membre \"intArray\" doit être une Array", jsonObject.optJSONArray( "intArray" ) ); assertEquals( "L'element 0 de \"intArray\" doit être égal a 1", 1, jsonObject.optJSONArray( "intArray" ).optInt( 0 ) ); assertEquals( "L'element 1 de \"intArray\" doit être égal a 2", 2, jsonObject.optJSONArray( "intArray" ).optInt( 1 ) ); assertEquals( "L'element 2 de \"intArray\" doit être égal a 3", 3, jsonObject.optJSONArray( "intArray" ).optInt( 2 ) ); // boolean array jsonObject = JSONObject.fromObject( "{\"booleanArray\":[true, false, true]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"booleanArray\"", jsonObject.containsKey( "booleanArray" ) ); assertNotNull( "Le membre \"strArray\" doit être une booleanArray", jsonObject.optJSONArray( "booleanArray" ) ); assertEquals( "L'element 0 de \"booleanArray\" doit être égal a true", true, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 0 ) ); assertEquals( "L'element 1 de \"booleanArray\" doit être égal a false", false, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 1 ) ); assertEquals( "L'element 2 de \"booleanArray\" doit être égal a true", true, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 2 ) ); // double array jsonObject = JSONObject.fromObject( "{\"doubleArray\":[\"a\",\"b\",\"c\"]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"doubleArray\"", jsonObject.containsKey( "doubleArray" ) ); assertNotNull( "Le membre \"doubleArray\" doit être une Array", jsonObject.optJSONArray( "doubleArray" ) ); assertEquals( "L'element 0 de \"doubleArray\" doit être égal a \"a\"", "a", jsonObject.optJSONArray( "doubleArray" ).optString( 0 ) ); jsonObject = JSONObject.fromObject( "{\"weirdString\":\"[Hello]\"}", tConfig ); assertTrue( "L'objet doit contenir une clef \"weirdString\"", jsonObject.containsKey( "weirdString" ) ); assertNotNull( "Le membre \"weirdString\" doit être une String", jsonObject.optString( "weirdString" ) ); assertEquals( "Le membre \"weirdString\" doit être égal a \"[Hello]\"", "[Hello]", jsonObject.get( "weirdString" ) ); jsonObject = JSONObject.fromObject( "{\"weirdString\":\"{912}\"}" ); assertTrue( "L'objet doit contenir une clef \"weirdString\"", jsonObject.containsKey( "weirdString" ) ); assertNotNull( "Le membre \"weirdString\" doit être une String", jsonObject.optString( "weirdString" ) ); assertEquals( "Le membre \"weirdString\" doit être égal a \"{912}\"", "{912}", jsonObject.get( "weirdString" ) ); } /* public void testDifferenceBetweenStringSerialisationWithJSONObjectAndJSONArray() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener( new JsonErrorDetector() ); // This was Ko JSONObject tJsonSource = new JSONObject(); tJsonSource.element( "weirdString", "[{}][:,;:.[][[]", jsonConfig ); assertEquals( "[{}][:,;:.[][[]", tJsonSource.get( "weirdString" ) ); String tExpected = "{\"weirdString\":\"[{}][:,;:.[][[]\"}"; assertEquals( tExpected, tJsonSource.toString() ); // This was Ko too tJsonSource = new JSONObject(); JSONArray tArraySource = new JSONArray(); tArraySource.element( "{912}", jsonConfig ); tArraySource.element( "[Hello]", jsonConfig ); tArraySource.element( "[]{}[,;.:[[]", jsonConfig ); assertEquals( "[]{}[,;.:[[]", tArraySource.get( 2 ) ); tJsonSource.put( "weirdStringArray", tArraySource ); tExpected = "{\"weirdStringArray\":[\"{912}\",\"[Hello]\",\"[]{}[,;.:[[]\"]}"; assertEquals( tExpected, tJsonSource.toString() ); }*/ /* public void testDifferenceBetweenStringParsingIntoJSONObjectAndJSONArray() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener( new JsonErrorDetector() ); // This part was Ok JSONObject jsonObject = JSONObject.fromObject( "{\"weirdString\":\"[{}][:,;:.[][[]\"}", tConfig ); assertTrue( jsonObject.containsKey( "weirdString" ) ); assertNotNull( jsonObject.optString( "weirdString" ) ); assertEquals( "[{}][:,;:.[][[]", jsonObject.get( "weirdString" ) ); // This part very similar to the previous part was Ko jsonObject = JSONObject.fromObject( "{\"weirdStringArray\":[\"{912}\",\"[Hello]\",\"[]{}[,;.:[[]\"]}", tConfig ); assertTrue( jsonObject.containsKey( "weirdStringArray" ) ); assertNotNull( jsonObject.optJSONArray( "weirdStringArray" ) ); assertEquals( "{912}", jsonObject.getJSONArray( "weirdStringArray" ).optString( 0 ) ); assertEquals( "[Hello]", jsonObject.getJSONArray( "weirdStringArray" ).optString( 1 ) ); assertEquals( "[]{}[,;.:[[]", jsonObject.getJSONArray( "weirdStringArray" ).optString( 2 ) ); } */ public void testBug_2893329() { String jsonStr = "{x:\"\\'hello\\'\"}"; JSONObject json = JSONObject.fromObject(jsonStr); assertEquals("'hello'", json.getString("x")); } public void testBug_3047519() { String jsonStr = "{data:\"[1,2,3]\"}"; JSONObject json = JSONObject.fromObject(jsonStr); Object data = json.get("data"); assertTrue(data instanceof String); assertEquals("[1,2,3]", data); } /* public void testBug_3074732() { String test = "{\"c\":\"{\\\"k\\\":\\\"k\\\", \\\"l\\\":\\\"l\\\"}\"}"; JSONObject jsonObject = JSONObject.fromObject(test); assertTrue(jsonObject.get("c") instanceof String); String test2 = "{\"a\":[{\"c\":\"{\\\"k\\\":\\\"k\\\", \\\"l\\\":\\\"l\\\"}\"}]}"; jsonObject = JSONObject.fromObject(test2); assertTrue(jsonObject.getJSONArray("a").getJSONObject(0).get("c") instanceof String); } */ public static class RunnableImpl implements Runnable { public void run() { } } public static class JsonErrorDetector implements JsonEventListener{ public void onArrayEnd() { } public void onArrayStart() { } public void onElementAdded( int index, Object element ) { } public void onError( JSONException jsone ) { fail("An error occurs during JsonProcessing "+ jsone.getMessage()); } public void onObjectEnd() { } public void onObjectStart() { } public void onPropertySet( String key, Object value, boolean accumulated ) { } public void onWarning( String warning ) { } } protected void setUp() throws Exception { super.setUp(); jsonConfig = new JsonConfig(); } } jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_Map.java0000664000175000017500000000256711650253660032160 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.Map; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_Map extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_Map.class ); } public TestJSONObjectStaticBuilders_Map( String name ) { super( name ); } protected Object getSource() { Map map = new HashMap(); String[] props = getProperties(); for( int i = 0; i < props.length; i++ ){ map.put( props[i], PropertyConstants.getPropertyValue( props[i] ) ); } map.put( "class", "" ); map.put( "pexcluded", "" ); return map; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/xml/0000775000175000017500000000000011650253660023704 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/xml/AllTests.java0000664000175000017500000000220111650253660026275 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.xml; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class AllTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "xml" ); suite.addTest( new TestSuite( TestXMLSerializer_reads.class ) ); suite.addTest( new TestSuite( TestXMLSerializer_writes.class ) ); suite.addTest( new TestSuite( TestUserSubmitted.class ) ); return suite; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/xml/TestUserSubmitted.java0000664000175000017500000002216011650253660030207 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.xml; import junit.framework.TestCase; import net.sf.json.Assertions; import net.sf.json.JSON; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import net.sf.json.test.JSONAssert; /** * @author Andres Almiray */ public class TestUserSubmitted extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestUserSubmitted.class ); } public TestUserSubmitted( String name ) { super( name ); } public void testReadFromXMLToJSON_1735732() throws Exception { // bug 1735732 XMLSerializer xmlSerializer = new XMLSerializer(); JSONObject actual = (JSONObject) xmlSerializer.readFromFile( "net/sf/json/xml/1735732.xml" ); JSONObject expected = new JSONObject().element( "@xmlns:ns2", "http://schemas.foo.com/HelloWorld" ) .element( "item", new JSONObject().element( "age", "2 5" ) .element( "name", "emp1" ) ) .accumulate( "item", new JSONObject().element( "age", "2" ) .element( "name", "emp2" ) ); JSONAssert.assertEquals( expected, actual ); } public void testReadFromXMLToJSON_1739066() throws Exception { // bug 1739066 XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTrimSpaces( true ); JSONObject actual = (JSONObject) xmlSerializer.readFromFile( "net/sf/json/xml/1739066.xml" ); JSONObject expected = new JSONObject().element( "Address", "http://localhost:0/te stToString" ) .element( "@xmlns", "http://www.w3.org/2005/08/addressing" ) .element( "Metadata", new JSONObject().element( "@xmlns:wsa-wsdl", "http://www.w3.org/2006/01/wsdl-instance" ) .element( "@wsa-wsdl:wsdlLocation", "file:///b.wsdl" ) .element( "ns3:InterfaceName", new JSONObject().element( "@xmlns:tns", "http://com.iona.cxf/GreetMe" ) .element( "@xmlns:ns3", "http://www.w3.org/2005/02/addressing/wsdl" ) .element( "#text", "tns:GreetMePortType" ) ) .element( "ns3:ServiceName", new JSONObject().element( "@EndpointName", "GreetMePort" ) .element( "@xmlns:tns", "http://com.iona.cxf/GreetMe" ) .element( "@xmlns:ns3", "http://www.w3.org/2005/02/addressing/wsdl" ) .element( "#text", "tns:GreetMeService" ) ) ); JSONAssert.assertEquals( expected, actual ); } public void testIgnoreWhitespaceWhileReading() { String xml = "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n"; XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setSkipWhitespace( true ); JSON json1 = xmlSerializer.read( xml ); xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; JSON json2 = xmlSerializer.read( xml ); Assertions.assertEquals( json2, json1 ); } public void testXMLRoundtrip() { String json = "{\"entries\": [ { \"credits\": \"p1\", \"id\": 1, \"status\": true, \"text\": \"1\" }, { \"credits\": \"p2\", \"id\": 2, \"status\": true, \"text\": \"2\" } ]}"; JSONObject json1 = JSONObject.fromObject( json ); XMLSerializer xmlSerializer = new XMLSerializer(); String xml = xmlSerializer.write(json1); JSONObject json2 = (JSONObject) xmlSerializer.read( xml ); JSONAssert.assertEquals( json1, json2 ); assertTrue(json1.getJSONArray( "entries" ).getJSONObject( 0 ).get( "id" ) instanceof Integer ); assertTrue(json2.getJSONArray( "entries" ).getJSONObject( 0 ).get( "id" ) instanceof Integer ); } public void testXMLWithArraySingleElement() { String testXML = " " + " \n" + " \n" + " \n" + " 15\n" + " 1\n" + " 2007\n" + " \n" + " 109.74\n" + " \n" + " " + " 219.48\n" + " "; JSON expected = JSONSerializer.toJSON("{\"rate\":{\"rateBreakdown\":[{\"amount\":\"109.74\",\"date\":{\"month\":\"1\",\"day\":\"15\",\"year\":\"2007\"}}],\"totalAmount\":\"219.48\"}}"); // rate.rateBreakdown.rate should be a single entry array. JSONObject actual = convertXML( testXML ); assertNotNull( actual ); Assertions.assertEquals( expected, actual ); } private JSONObject convertXML( String testXML ) { XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setSkipWhitespace( true ); xmlSerializer.setArrayName( "rate" ); xmlSerializer.setForceTopLevelObject( true ); JSON jsonElement = xmlSerializer.read( testXML ); return (JSONObject) jsonElement; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/xml/TestXMLSerializer_writes.java0000664000175000017500000003101711650253660031500 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.xml; import net.sf.json.JSONArray; import net.sf.json.JSONNull; import net.sf.json.JSONObject; import org.custommonkey.xmlunit.XMLTestCase; /** * @author Andres Almiray */ public class TestXMLSerializer_writes extends XMLTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestXMLSerializer_writes.class ); } private XMLSerializer xmlSerializer; public TestXMLSerializer_writes( String testName ) { super( testName ); } public void testWrite_null() throws Exception { String expected = ""; String xml = xmlSerializer.write( null ); assertXMLEqual( expected, xml ); } public void testWriteBooleanArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[true,false]" ); String expected = "truefalse"; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteEmptyObject() throws Exception { JSONObject jsonObject = new JSONObject(); String expected = ""; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteFunctionArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[function(a){ return a; }]" ); String expected = ""; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteFunctionArray_noTypeHintsCompatibility() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[function(a){ return a; }]" ); xmlSerializer.setTypeHintsCompatibility( false ); String expected = ""; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteJSONArray_collapseProperties() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.element( "duplicated", "json1" ); jsonObject.accumulate( "duplicated", "json2" ); jsonObject.getJSONArray( "duplicated" ) .setExpandElements( true ); JSONArray jsonArray = new JSONArray().element( jsonObject ); String expected = "json1json2"; xmlSerializer.setExpandableProperties( new String[] { "duplicated" } ); String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteJSONNull() throws Exception { String expected = ""; String xml = xmlSerializer.write( JSONNull.getInstance() ); assertXMLEqual( expected, xml ); } public void testWriteJSONNull_encoding() throws Exception { String expected = ""; String xml = xmlSerializer.write( JSONNull.getInstance(), "ISO-8859-1" ); assertTrue( xml.startsWith( expected ) ); } public void testWriteJSONObject_collapseProperties() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.element( "duplicated", "json1" ); jsonObject.accumulate( "duplicated", "json2" ); jsonObject.getJSONArray( "duplicated" ) .setExpandElements( true ); String expected = "json1json2"; xmlSerializer.setExpandableProperties( new String[] { "duplicated" } ); String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteMultiBooleanArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[true,false,[true,false]]" ); String expected = "truefalsetruefalse"; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteMultiNumberArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[1.1,2,[3,4.4]]" ); String expected = "1.1234.4"; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteMultiStringArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "['1.1','2',['3','4.4']]" ); String expected = "1.1234.4"; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteNestedNullObject() throws Exception { JSONObject jsonObject = JSONObject.fromObject( "{\"nested\":null}" ); String expected = ""; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteNullObject() throws Exception { JSONObject jsonObject = new JSONObject( true ); String expected = ""; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteNullObject_noTypeHintsCompatibility() throws Exception { JSONObject jsonObject = new JSONObject( true ); String expected = ""; xmlSerializer.setTypeHintsCompatibility( false ); String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteNullObjectArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[null,null]" ); String expected = ""; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteNullObjectArray_noTypeHintsCompatibility() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[null,null]" ); String expected = ""; xmlSerializer.setTypeHintsCompatibility( false ); String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteNumberArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[1.1,2]" ); String expected = "1.12"; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteObject() throws Exception { JSONObject jsonObject = JSONObject.fromObject( "{\"name\":\"json\"}" ); String expected = "json"; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteObject_full_types() throws Exception { JSONObject jsonObject = JSONObject.fromObject( "{\"string\":\"json\",\"int\":1,\"bool\":true,\"array\":[1.1,2],\"nested_null\":null,\"nested\":{\"name\":\"json\"},\"func\":function(a){ return a; }}" ); String expected = "json" + "1" + "true" + "1.12" + "" + "json" + "" + ""; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteObject_withAttributes() throws Exception { JSONObject jsonObject = new JSONObject().element( "@name", "json" ) .element( "string", "json" ); String expected = "json"; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteObject_withNamespacePrefix() throws Exception { JSONObject jsonObject = JSONObject.fromObject( "{\"ns:name\":\"json\"}" ); String expected = "json"; xmlSerializer.setNamespaceLenient( true ); String xml = xmlSerializer.write( jsonObject ); assertTrue( xml.trim() .endsWith( expected ) ); } public void testWriteObject_withNamespaces() throws Exception { JSONObject jsonObject = JSONObject.fromObject( "{\"ns:name\":\"json\"}" ); String expected = "json"; xmlSerializer.setNamespace( null, "http://json.org" ); xmlSerializer.addNamespace( "ns", "http://json.org/ns-schema" ); String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteObject_withNamespaces_element() throws Exception { JSONObject jsonObject = JSONObject.fromObject( "{\"ns:name\":\"json\"}" ); String expected = "json"; xmlSerializer.setNamespace( null, "http://json.org", "ns:name" ); xmlSerializer.addNamespace( "ns", "http://json.org/ns-schema", "ns:name" ); String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteObject_withText() throws Exception { JSONObject jsonObject = new JSONObject().element( "#text", "json" ) .element( "string", "json" ); String expected = "jsonjson"; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteObject_withText_2() throws Exception { JSONObject jsonObject = new JSONObject().element( "#text", JSONArray.fromObject("['json','json']") ) .element( "string", "json" ); String expected = "jsonjsonjson"; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } public void testWriteObjectArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "[{\"name\":\"json\"}]" ); String expected = "json"; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteStringArray() throws Exception { JSONArray jsonArray = JSONArray.fromObject( "['1','2']" ); String expected = "12"; String xml = xmlSerializer.write( jsonArray ); assertXMLEqual( expected, xml ); } public void testWriteWithNamespace() throws Exception { JSONObject jsonObject = new JSONObject().element( "@xmlns", "http://json.org/json/1.0" ) .element( "@xmlns:ns", "http://www.w3.org/2001/XMLSchema-instance" ) .element( "ns:string", "json" ) .element( "ns:number", "1" ); String expected = "" + "1json"; String xml = xmlSerializer.write( jsonObject ); assertXMLEqual( expected, xml ); } protected void setUp() throws Exception { super.setUp(); xmlSerializer = new XMLSerializer(); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/xml/TestXMLSerializer_reads.java0000664000175000017500000005516311650253660031271 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.xml; import junit.framework.TestCase; import net.sf.json.Assertions; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONNull; import net.sf.json.JSONObject; import net.sf.json.test.JSONAssert; /** * @author Andres Almiray */ public class TestXMLSerializer_reads extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestXMLSerializer_reads.class ); } private XMLSerializer xmlSerializer; public TestXMLSerializer_reads( String testName ) { super( testName ); } public void testNullObjectArray() { String xml = ""; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[null,null]" ); Assertions.assertEquals( expected, actual ); } public void testNullObjectArray_noTypeHintsCompatibility() { String xml = ""; xmlSerializer.setTypeHintsCompatibility( false ); JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[null,null]" ); Assertions.assertEquals( expected, actual ); } public void testRead_nullObject() { String xml = ""; JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_2() { String xml = ""; JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_2_noTypeHintsCompatibility() { String xml = ""; xmlSerializer.setTypeHintsCompatibility( false ); JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_3() { String xml = ""; JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_3_noTypeHintsCompatibility() { String xml = ""; xmlSerializer.setTypeHintsCompatibility( false ); JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_4() { String xml = ""; JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_4_noTypeHintsCompatibility() { String xml = ""; xmlSerializer.setTypeHintsCompatibility( false ); JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_5() { String xml = ""; JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testRead_nullObject_5_noTypeHintsCompatibility() { String xml = ""; xmlSerializer.setTypeHintsCompatibility( false ); JSON actual = xmlSerializer.read( xml ); Assertions.assertEquals( JSONNull.getInstance(), actual ); } public void testReadArray_forceTopLevelObject() { String xml = "json"; xmlSerializer.setForceTopLevelObject( true ); JSON actual = xmlSerializer.read( xml ); JSON expected = new JSONObject().element( "a", new JSONArray().element( "json" ) ); Assertions.assertEquals( expected, actual ); } public void testReadArray_withText() { String xml = "json"; JSON actual = xmlSerializer.read( xml ); JSON expected = new JSONArray().element( "json" ); Assertions.assertEquals( expected, actual ); } public void testReadBooleanArray_withDefaultType() { String xml = "truefalse"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,false]" ); Assertions.assertEquals( expected, actual ); } public void testReadBooleanArray_withoutDefaultType() { String xml = "truefalse"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,false]" ); Assertions.assertEquals( expected, actual ); } public void testReadFloatArray_withDefaultType() { String xml = "1.12.23.3"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3.3]" ); Assertions.assertEquals( expected, actual ); } public void testReadFloatArray_withoutDefaultType() { String xml = "1.12.23.3"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3.3]" ); Assertions.assertEquals( expected, actual ); } public void testReadFunctionObject() { String xml = ""; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONObject.fromObject( "{func:function(a){ return a; }}" ); Assertions.assertEquals( expected, actual ); } public void testReadFunctionObject_noTypeHintsCompatibility() { String xml = ""; xmlSerializer.setTypeHintsCompatibility( false ); JSON actual = xmlSerializer.read( xml ); JSON expected = JSONObject.fromObject( "{func:function(a){ return a; }}" ); Assertions.assertEquals( expected, actual ); } public void testReadFunctionObject_withDefaultType() { String xml = ""; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONObject.fromObject( "{func:function(a){ return a; }}" ); Assertions.assertEquals( expected, actual ); } public void testReadFunctionObject_withoutDefaultType() { String xml = ""; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONObject.fromObject( "{func:function(a){ return a; }}" ); Assertions.assertEquals( expected, actual ); } public void testReadIntegerArray_withDefaultType() { String xml = "123"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1,2,3]" ); Assertions.assertEquals( expected, actual ); } public void testReadIntegerArray_withoutDefaultType() { String xml = "123"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1,2,3]" ); Assertions.assertEquals( expected, actual ); } public void testReadMixedArray_withDefaultType() { String xml = "true2.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,2.2,\"3\"]" ); Assertions.assertEquals( expected, actual ); } public void testReadMixedArray_withoutDefaultType() { String xml = "true2.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,2.2,\"3\"]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiBooleanArray_withDefaultType() { String xml = "truefalsefalsetrue"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,false,[false,true]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiBooleanArray_withoutDefaultType() { String xml = "truefalsefalsetrue"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,false,[false,true]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiFloatArray_withDefaultType() { String xml = "1.12.23.31.12.23.3"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3.3,[1.1,2.2,3.3]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiFloatArray_withoutDefaultType() { String xml = "1.12.23.31.12.23.3"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3.3,[1.1,2.2,3.3]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiIntegerArray_withDefaultType() { String xml = "123123"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1,2,3,[1,2,3]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiIntegerArray_withoutDefaultType() { String xml = "123123"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1,2,3,[1,2,3]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiMixedArray_withDefaultType() { String xml = "true2.23true2.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,2.2,\"3\",[true,2.2,\"3\"]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiMixedArray_withoutDefaultType() { String xml = "true2.23true2.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[true,2.2,\"3\",[true,2.2,\"3\"]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiNumberArray_withDefaultType() { String xml = "1.12.231.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3,[1.1,2.2,3]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiNumberArray_withoutDefaultType() { String xml = "1.12.231.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3,[1.1,2.2,3]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiStringArray_withDefaultType() { String xml = "1.12.231.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[\"1.1\",\"2.2\",\"3\",[\"1.1\",\"2.2\",\"3\"]]" ); Assertions.assertEquals( expected, actual ); } public void testReadMultiStringArray_withoutDefaultType() { String xml = "1.12.231.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[\"1.1\",\"2.2\",\"3\",[\"1.1\",\"2.2\",\"3\"]]" ); Assertions.assertEquals( expected, actual ); } public void testReadNestedObject() { String xml = "json1"; JSONObject actual = (JSONObject) xmlSerializer.read( xml ); JSONObject expected = JSONObject.fromObject( "{name:\"json\",nested:{id:1}}" ); Assertions.assertEquals( expected, actual ); } public void testReadNumberArray_withDefaultType() { String xml = "1.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3]" ); Assertions.assertEquals( expected, actual ); } public void testReadNumberArray_withoutDefaultType() { String xml = "1.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[1.1,2.2,3]" ); Assertions.assertEquals( expected, actual ); } public void testReadObject_withAttributes() { String xml = ""; JSON actual = xmlSerializer.read( xml ); JSON expected = new JSONObject().element( "@string", "json" ).element( "@number", "1" ); Assertions.assertEquals( expected, actual ); } public void testReadObject_withAttributes_noTypeHintsEnabled() { String xml = ""; xmlSerializer.setTypeHintsEnabled( false ); JSON actual = xmlSerializer.read( xml ); JSON expected = new JSONObject().element( "@class", "Java.class" ).element( "@type", "object" ).element( "@string", "json" ).element( "@number", "1" ); Assertions.assertEquals( expected, actual ); } public void testReadObject_withAttributes_noTypeHintsEnabled_noTypeHintsCompatibility() { String xml = ""; xmlSerializer.setTypeHintsEnabled( false ); xmlSerializer.setTypeHintsCompatibility( false ); JSON actual = xmlSerializer.read( xml ); JSON expected = new JSONObject().element( "@json_class", "Java.class" ).element( "@json_type", "object" ) .element( "@string", "json" ).element( "@number", "1" ); Assertions.assertEquals( expected, actual ); } public void testReadObject_withText() { String xml = "firstjson\n"; JSON actual = xmlSerializer.read( xml ); JSON expected = new JSONObject().element( "string", "json" ).element( "#text", "first" ); Assertions.assertEquals( expected, actual ); } public void testReadObject_withText_2() { String xml = "firstjsonsecond"; JSON actual = xmlSerializer.read( xml ); JSON expected = new JSONObject().element( "string", "json" ).element( "#text", new JSONArray().element( "first" ).element( "second" ) ); Assertions.assertEquals( expected, actual ); } public void testReadObjectFullTypes() { String xml = "1" + "2.0" + "3.1416" + "true" + "json" + ""; JSONObject actual = (JSONObject) xmlSerializer.read( xml ); JSONObject expected = JSONObject.fromObject( "{func:function(a){ return a; }}" ); expected.element( "int", new Integer( 1 ) ); expected.element( "decimal", new Double( 2.0 ) ); expected.element( "number", new Double( 3.1416 ) ); expected.element( "bool", Boolean.TRUE ); expected.element( "string", "json" ); Assertions.assertEquals( expected, actual ); } public void testReadSimpleObject_withDefaultType() { String xml = "true12.2json4.445"; JSONObject actual = (JSONObject) xmlSerializer.read( xml ); JSONObject expected = JSONObject.fromObject( "{bool:true,int:1,double:2.2,string:'json',numbers:[4.44,5]}" ); Assertions.assertEquals( expected, actual ); } public void testReadStringArray_withDefaultType() { String xml = "1.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[\"1.1\",\"2.2\",\"3\"]" ); Assertions.assertEquals( expected, actual ); } public void testReadStringArray_withoutDefaultType() { String xml = "1.12.23"; JSON actual = xmlSerializer.read( xml ); JSON expected = JSONArray.fromObject( "[\"1.1\",\"2.2\",\"3\"]" ); Assertions.assertEquals( expected, actual ); } public void testReadWithNamespace_array() { String xml = "json1"; JSON actual = xmlSerializer.read( xml ); JSONObject expected = new JSONObject().element( "@xmlns", "http://json.org/json/1.0" ).element( "@xmlns:ns", "http://www.w3.org/2001/XMLSchema-instance" ).element( "ns:string", "json" ).accumulate( "ns:string", "1" ); Assertions.assertEquals( expected, actual ); } public void testReadWithNamespace_object() { String xml = "json1"; JSON actual = xmlSerializer.read( xml ); JSONObject expected = new JSONObject().element( "@xmlns", "http://json.org/json/1.0" ).element( "@xmlns:ns", "http://www.w3.org/2001/XMLSchema-instance" ).element( "ns:string", "json" ).element( "ns:number", "1" ); Assertions.assertEquals( expected, actual ); } public void testRemoveNameSpacePrefixFromElements() throws Exception { xmlSerializer.setRemoveNamespacePrefixFromElements( true ); JSONObject json = (JSONObject) xmlSerializer.readFromFile( "net/sf/json/xml/delicious.xml" ); assertFalse( json.getJSONObject( "item" ).has( "@rdf:about" ) ); assertTrue( json.getJSONObject( "item" ).has( "@about" ) ); } public void testSkipNamespaces() throws Exception { xmlSerializer.setSkipNamespaces( true ); JSONObject json = (JSONObject) xmlSerializer.readFromFile( "net/sf/json/xml/delicious.xml" ); assertFalse( json.getJSONObject( "item" ).has( "@xmlns" ) ); } public void testTrimSpaces() throws Exception { JSONObject json = (JSONObject) xmlSerializer.readFromFile( "net/sf/json/xml/delicious.xml" ); String link = json.getJSONObject( "item" ).getString( "link" ); assertTrue( link.startsWith( " " ) ); assertTrue( link.endsWith( " " ) ); xmlSerializer.setTrimSpaces( true ); json = (JSONObject) xmlSerializer.readFromFile( "net/sf/json/xml/delicious.xml" ); link = json.getJSONObject( "item" ).getString( "link" ); assertFalse( link.startsWith( " " ) ); assertFalse( link.endsWith( " " ) ); } public void testXmlConversionRules() { String xml = "" + "" + "Web 2.0 Conference" + "October 5" + "7" + "Argent Hotel, San Francisco, CA" + "" + ""; xmlSerializer.setTypeHintsCompatibility( false ); xmlSerializer.setForceTopLevelObject( true ); JSONObject actual = (JSONObject) xmlSerializer.read( xml ); assertNotNull( actual ); JSONObject expected = new JSONObject() .element( "span", new JSONObject() .element( "@class", "vevent" ) .element( "a", new JSONObject() .element( "@class", "url" ) .element( "@href", "http://www.web2con.com/" ) .element( "span", JSONObject.fromObject( "{'@class':'summary','#text':'Web 2.0 Conference'}" ) ) .element( "abbr", JSONObject .fromObject( "{'@class':'dtstart','@title': '2005-10-05','#text':'October 5'}" ) ) .accumulate( "abbr", JSONObject .fromObject( "{'@class':'dtend','@title': '2005-10-08','#text':'7'}" ) ) .accumulate( "span", JSONObject .fromObject( "{'@class':'location','#text':'Argent Hotel, San Francisco, CA'}" ) ) ) ); JSONAssert.assertEquals( expected, actual ); } protected void setUp() throws Exception { super.setUp(); xmlSerializer = new XMLSerializer(); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/MaheshDeSilvaTest.java0000664000175000017500000000372011650253660027266 0ustar jamespagejamespagepackage net.sf.json; import junit.framework.TestCase; import java.util.Arrays; /** * This came via e-mail. * *

    * We are using JSON-lib in our application which is used by a lot of customers. * A recent issue came up where user submitted string value 'null' is being stored * into the data base as '"null"'. Basically double quotes are being added at the start and end of the String. * *

    * Investigation revealed that JSON-lib doesn't seem to handle the 'null' string value correctly. * This is exhibited by the following test methods. * *

    * basically when browser sends {@code ["null", "aValue"]} to server, JSON-lib changes it to * {@code ["\"null\"", "aValue"]}. Also from the server side we are unable to construct a JSON * formatted String like {@code ["null", "b"]} using {@link JSONArray}. JSON-lib does not seem to * handle these two basic scenarios properly. * *

    * The test class is attached for your reference. * *

    * Appreciate if you could provide feedback as to how to handle this issue using JSON-lib. * * @author Mahesh De Silva */ public class MaheshDeSilvaTest extends TestCase { public void testShouldHandleNullStringInJsonFormattedString() { String jsonTest = "[\"null\",\"aValue\"]"; assertTrue(jsonTest.contains("\"null\"")); assertFalse(jsonTest.contains("\"\\\"null\\\"\"")); String convertedBack = JSONSerializer.toJSON(jsonTest).toString(); assertFalse(convertedBack.contains("\"\\\"null\\\"\"")); } public void testShouldHandleNullStringLiteral() { JSONArray jsonArray1 = JSONArray.fromObject(Arrays.asList(null, "b")); JSONArray jsonArray2 = JSONArray.fromObject(Arrays.asList(JSONNull.getInstance(), "b")); JSONArray jsonArray3 = JSONArray.fromObject(Arrays.asList("null", "b")); assertEquals("[null,\"b\"]", jsonArray1.toString()); assertEquals("[null,\"b\"]", jsonArray2.toString()); assertEquals("[\"null\",\"b\"]", jsonArray3.toString()); } } jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/PrefixerPropertyNameProcessor.java0000664000175000017500000000064511650253660032006 0ustar jamespagejamespage/** * */ package net.sf.json; import net.sf.json.processors.PropertyNameProcessor; public class PrefixerPropertyNameProcessor implements PropertyNameProcessor { private final String prefix; public PrefixerPropertyNameProcessor( String prefix ) { this.prefix = prefix; } public String processPropertyName( Class beanClass, String name ) { return prefix + name; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/AbstractJSONObjectStaticBuildersTestCase.java0000664000175000017500000000470211650253660033634 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import junit.framework.TestCase; /** * @author Andres Almiray */ public abstract class AbstractJSONObjectStaticBuildersTestCase extends TestCase { public AbstractJSONObjectStaticBuildersTestCase( String testName ) { super( testName ); } public void testFromObject() { JSONObject json = JSONObject.fromObject( getSource() ); assertJSONObject( json, getProperties() ); assertTrue( !json.has( "class" ) ); } public void testFromObject_excludes() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes( getExclusions() ); JSONObject json = JSONObject.fromObject( getSource(), jsonConfig ); assertJSONObject( json, getProperties() ); String[] excluded = getExclusions(); for( int i = 0; i < excluded.length; i++ ){ assertTrue( !json.has( excluded[i] ) ); } assertTrue( !json.has( "class" ) ); assertTrue( !json.has( "pexcluded" ) ); } public void testFromObject_excludes_ignoreDefaults() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes( getExclusions() ); jsonConfig.setIgnoreDefaultExcludes( true ); JSONObject json = JSONObject.fromObject( getSource(), jsonConfig ); assertJSONObject( json, getProperties() ); assertTrue( json.has( "class" ) ); assertTrue( !json.has( "pexcluded" ) ); } protected String[] getExclusions() { return new String[] { "pexcluded" }; } protected String[] getProperties() { return PropertyConstants.getProperties(); } protected abstract Object getSource(); private void assertJSONObject( JSONObject json, String[] properties ) { assertNotNull( json ); for( int i = 0; i < properties.length; i++ ){ assertTrue( json.has( properties[i] ) ); } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayStaticBuilders_String.java0000664000175000017500000000326211650253660032552 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * @author Andres Almiray */ public class TestJSONArrayStaticBuilders_String extends AbstractJSONArrayStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayStaticBuilders_String.class ); } public TestJSONArrayStaticBuilders_String( String name ) { super( name ); } protected Object getSource() { return "[{\"parray\":[1,2],\"plong\":9223372036854775807,\"pchar\":\"J\",\"pboolean\":true,\"pfloat\":3.4028234663852886E38,\"pbean\":{\"parray\":null,\"plong\":null,\"pchar\":null,\"pboolean\":null,\"pfloat\":null,\"pbean\":null,\"pshort\":null,\"pdouble\":null,\"pclass\":null,\"pstring\":null,\"pint\":null,\"plist\":null,\"pfunction\":null,\"pmap\":null,\"pbyte\":null},\"pshort\":32767,\"pdouble\":1.7976931348623157E308,\"pclass\":\"java.lang.Object\",\"pstring\":\"json\",\"pint\":2147483647,\"plist\":[\"a\",\"b\"],\"pfunction\":function(){ this; },\"pmap\":null,\"pbyte\":127,\"class\":\"java.lang.Object\",\"pexcluded\":\"\"}]"; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/0000775000175000017500000000000011650253660024061 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/TestJSONTokener.java0000664000175000017500000000567211650253660027677 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import junit.framework.TestCase; import net.sf.json.JSONException; /** * @author Andres Almiray */ public class TestJSONTokener extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONTokener.class ); } public TestJSONTokener( String name ) { super( name ); } public void testDehexchar() { assertEquals( 0, JSONTokener.dehexchar( '0' ) ); assertEquals( 1, JSONTokener.dehexchar( '1' ) ); assertEquals( 2, JSONTokener.dehexchar( '2' ) ); assertEquals( 3, JSONTokener.dehexchar( '3' ) ); assertEquals( 4, JSONTokener.dehexchar( '4' ) ); assertEquals( 5, JSONTokener.dehexchar( '5' ) ); assertEquals( 6, JSONTokener.dehexchar( '6' ) ); assertEquals( 7, JSONTokener.dehexchar( '7' ) ); assertEquals( 8, JSONTokener.dehexchar( '8' ) ); assertEquals( 9, JSONTokener.dehexchar( '9' ) ); assertEquals( 10, JSONTokener.dehexchar( 'a' ) ); assertEquals( 10, JSONTokener.dehexchar( 'A' ) ); assertEquals( 11, JSONTokener.dehexchar( 'b' ) ); assertEquals( 11, JSONTokener.dehexchar( 'B' ) ); assertEquals( 12, JSONTokener.dehexchar( 'c' ) ); assertEquals( 12, JSONTokener.dehexchar( 'C' ) ); assertEquals( 13, JSONTokener.dehexchar( 'd' ) ); assertEquals( 13, JSONTokener.dehexchar( 'D' ) ); assertEquals( 14, JSONTokener.dehexchar( 'e' ) ); assertEquals( 14, JSONTokener.dehexchar( 'E' ) ); assertEquals( 15, JSONTokener.dehexchar( 'f' ) ); assertEquals( 15, JSONTokener.dehexchar( 'F' ) ); } public void testLength() { assertEquals( 0, new JSONTokener( null ).length() ); assertEquals( 0, new JSONTokener( "" ).length() ); assertEquals( 2, new JSONTokener( "[]" ).length() ); } public void testNextChar() { JSONTokener tok = new JSONTokener( "abc" ); assertEquals( 'a', tok.next( 'a' ) ); try{ assertEquals( 'e', tok.next( 'e' ) ); fail( "Expectd a JSONException" ); }catch( JSONException expected ){ // ok } } public void testReset() { JSONTokener tok = new JSONTokener( "abc" ); tok.next(); tok.next(); assertEquals( 'c', tok.next() ); tok.reset(); assertEquals( 'a', tok.next() ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/TestWebUtils.java0000664000175000017500000001041711650253660027325 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import junit.framework.TestCase; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * @author Andres Almiray */ public class TestWebUtils extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestWebUtils.class ); } public TestWebUtils( String name ) { super( name ); } public void testProtect_comments() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "with:quotes", "json" ); WebUtils.setWebHijackPreventionStrategy( WebHijackPreventionStrategy.COMMENTS ); String str = WebUtils.protect( jsonObject ); assertEquals( 0, str.compareTo( "/*{\"with:quotes\":\"json\"}*/" ) ); } public void testProtect_comments_and_shrink() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "noquotes", "json" ); WebUtils.setWebHijackPreventionStrategy( WebHijackPreventionStrategy.COMMENTS ); String str = WebUtils.protect( jsonObject, true ); assertEquals( 0, str.compareTo( "/*{noquotes:\"json\"}*/" ) ); } public void testProtect_inifiniteLoop() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "with:quotes", "json" ); WebUtils.setWebHijackPreventionStrategy( WebHijackPreventionStrategy.INFINITE_LOOP ); String str = WebUtils.protect( jsonObject ); assertEquals( 0, str.compareTo( "while(1);{\"with:quotes\":\"json\"}" ) ); } public void testProtect_inifiniteLoop_and_shrink() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "noquotes", "json" ); WebUtils.setWebHijackPreventionStrategy( WebHijackPreventionStrategy.INFINITE_LOOP ); String str = WebUtils.protect( jsonObject, true ); assertEquals( 0, str.compareTo( "while(1);{noquotes:\"json\"}" ) ); } public void testToString_array_noquotes() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "noquotes", "json" ); JSONArray jsonArray = new JSONArray().element( jsonObject ); String str = WebUtils.toString( jsonArray ); assertEquals( 0, str.compareTo( "[{noquotes:\"json\"}]" ) ); } public void testToString_array_withquotes1() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "with quotes", "json" ); JSONArray jsonArray = new JSONArray().element( jsonObject ); String str = WebUtils.toString( jsonArray ); assertEquals( 0, str.compareTo( "[{\"with quotes\":\"json\"}]" ) ); } public void testToString_array_withquotes2() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "with:quotes", "json" ); JSONArray jsonArray = new JSONArray().element( jsonObject ); String str = WebUtils.toString( jsonArray ); assertEquals( 0, str.compareTo( "[{\"with:quotes\":\"json\"}]" ) ); } public void testToString_object_noquotes() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "noquotes", "json" ); String str = WebUtils.toString( jsonObject ); assertEquals( 0, str.compareTo( "{noquotes:\"json\"}" ) ); } public void testToString_object_withquotes1() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "with quotes", "json" ); String str = WebUtils.toString( jsonObject ); assertEquals( 0, str.compareTo( "{\"with quotes\":\"json\"}" ) ); } public void testToString_object_withquotes2() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "with:quotes", "json" ); String str = WebUtils.toString( jsonObject ); assertEquals( 0, str.compareTo( "{\"with:quotes\":\"json\"}" ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/TestJavaIdentifierTransformer.java0000664000175000017500000000625011650253660032676 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestJavaIdentifierTransformer extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJavaIdentifierTransformer.class ); } public TestJavaIdentifierTransformer( String testName ) { super( testName ); } public void testCamelCase() { JavaIdentifierTransformer jit = JavaIdentifierTransformer.CAMEL_CASE; assertEquals( "camelCase", jit.transformToJavaIdentifier( "camel case" ) ); assertEquals( "camelCase", jit.transformToJavaIdentifier( "@camel case" ) ); assertEquals( "$camelCase", jit.transformToJavaIdentifier( "$camel case" ) ); assertEquals( "camelCase", jit.transformToJavaIdentifier( "camel@case" ) ); assertEquals( "camelCase", jit.transformToJavaIdentifier( "camel @case" ) ); assertEquals( "camelCase", jit.transformToJavaIdentifier( "camel@@case" ) ); assertEquals( "camelCase", jit.transformToJavaIdentifier( "camel@ @case" ) ); } public void testUnderscore() { JavaIdentifierTransformer jit = JavaIdentifierTransformer.UNDERSCORE; assertEquals( "under_score", jit.transformToJavaIdentifier( "under score" ) ); assertEquals( "under_score", jit.transformToJavaIdentifier( "@under score" ) ); assertEquals( "$under_score", jit.transformToJavaIdentifier( "$under score" ) ); assertEquals( "under_score", jit.transformToJavaIdentifier( "under@score" ) ); assertEquals( "under_score", jit.transformToJavaIdentifier( "under score" ) ); assertEquals( "under_score", jit.transformToJavaIdentifier( "under@@score" ) ); assertEquals( "under_score", jit.transformToJavaIdentifier( "under@ @score" ) ); assertEquals( "under_score", jit.transformToJavaIdentifier( "under score " ) ); } public void testWhitespace() { JavaIdentifierTransformer jit = JavaIdentifierTransformer.WHITESPACE; assertEquals( "whitespace", jit.transformToJavaIdentifier( "white space" ) ); assertEquals( "whitespace", jit.transformToJavaIdentifier( "@white space" ) ); assertEquals( "$whitespace", jit.transformToJavaIdentifier( "$white space" ) ); assertEquals( "whitespace", jit.transformToJavaIdentifier( "white@space" ) ); assertEquals( "whitespace", jit.transformToJavaIdentifier( "white@@space" ) ); assertEquals( "whitespace", jit.transformToJavaIdentifier( "white@ @space" ) ); assertEquals( "whitespace", jit.transformToJavaIdentifier( "white space " ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/AllTests.java0000664000175000017500000000246711650253660026470 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class AllTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "util" ); suite.addTest( new TestSuite( TestJavaIdentifierTransformer.class ) ); suite.addTest( new TestSuite( TestJSONUtils.class ) ); suite.addTest( new TestSuite( TestJSONTokener.class ) ); suite.addTest( new TestSuite( TestJSONBuilder.class ) ); suite.addTest( new TestSuite( TestJSONStringer.class ) ); suite.addTest( new TestSuite( TestWebUtils.class ) ); return suite; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/TestJSONStringer.java0000664000175000017500000000613711650253660030062 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import junit.framework.TestCase; import net.sf.json.JSONFunction; import net.sf.json.JSONObject; /** * @author Andres Almiray */ public class TestJSONStringer extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONStringer.class ); } public TestJSONStringer( String testName ) { super( testName ); } public void testCreateArray() { JSONBuilder b = new JSONStringer().array() .value( true ) .value( 1.1d ) .value( 2L ) .value( "text" ) .endArray(); assertEquals( "[true,1.1,2,\"text\"]", b.toString() ); } public void testCreateEmptyArray() { JSONBuilder b = new JSONStringer().array() .endArray(); assertEquals( "[]", b.toString() ); } public void testCreateEmptyArrayWithNullObjects() { JSONBuilder b = new JSONStringer().array() .value( null ) .value( null ) .endArray(); assertEquals( "[null,null]", b.toString() ); } public void testCreateEmptyObject() { JSONBuilder b = new JSONStringer().object() .endObject(); assertEquals( "{}", b.toString() ); } public void testCreateFunctionArray() { JSONBuilder b = new JSONStringer().array() .value( new JSONFunction( "var a = 1;" ) ) .value( new JSONFunction( "var b = 2;" ) ) .endArray(); assertEquals( "[function(){ var a = 1; },function(){ var b = 2; }]", b.toString() ); } public void testCreateSimpleObject() { JSONBuilder b = new JSONStringer().object() .key( "bool" ) .value( true ) .key( "numDouble" ) .value( 1.1d ) .key( "numInt" ) .value( 2 ) .key( "text" ) .value( "text" ) .key( "func" ) .value( new JSONFunction( "var a = 1;" ) ) .endObject(); JSONObject jsonObj = JSONObject.fromObject( b.toString() ); assertEquals( Boolean.TRUE, jsonObj.get( "bool" ) ); assertEquals( new Double( 1.1d ), jsonObj.get( "numDouble" ) ); assertEquals( new Long( 2 ).longValue(), ((Number) jsonObj.get( "numInt" )).longValue() ); assertEquals( "text", jsonObj.get( "text" ) ); assertTrue( JSONUtils.isFunction( jsonObj.get( "func" ) ) ); assertEquals( "function(){ var a = 1; }", jsonObj.get( "func" ) .toString() ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/TestJSONBuilder.java0000664000175000017500000000645011650253660027651 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.io.StringWriter; import junit.framework.TestCase; import net.sf.json.JSONFunction; import net.sf.json.JSONObject; /** * @author Andres Almiray */ public class TestJSONBuilder extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONBuilder.class ); } public TestJSONBuilder( String testName ) { super( testName ); } public void testCreateArray() { StringWriter w = new StringWriter(); new JSONBuilder( w ).array() .value( true ) .value( 1.1d ) .value( 2L ) .value( "text" ) .endArray(); assertEquals( "[true,1.1,2,\"text\"]", w.toString() ); } public void testCreateEmptyArray() { StringWriter w = new StringWriter(); new JSONBuilder( w ).array() .endArray(); assertEquals( "[]", w.toString() ); } public void testCreateEmptyArrayWithNullObjects() { StringWriter w = new StringWriter(); new JSONBuilder( w ).array() .value( null ) .value( null ) .endArray(); assertEquals( "[null,null]", w.toString() ); } public void testCreateEmptyObject() { StringWriter w = new StringWriter(); new JSONBuilder( w ).object() .endObject(); assertEquals( "{}", w.toString() ); } public void testCreateFunctionArray() { StringWriter w = new StringWriter(); new JSONBuilder( w ).array() .value( new JSONFunction( "var a = 1;" ) ) .value( new JSONFunction( "var b = 2;" ) ) .endArray(); assertEquals( "[function(){ var a = 1; },function(){ var b = 2; }]", w.toString() ); } public void testCreateSimpleObject() { StringWriter w = new StringWriter(); new JSONBuilder( w ).object() .key( "bool" ) .value( true ) .key( "numDouble" ) .value( 1.1d ) .key( "numInt" ) .value( 2 ) .key( "text" ) .value( "text" ) .key( "func" ) .value( new JSONFunction( "var a = 1;" ) ) .endObject(); JSONObject jsonObj = JSONObject.fromObject( w.toString() ); assertEquals( Boolean.TRUE, jsonObj.get( "bool" ) ); assertEquals( new Double( 1.1d ), jsonObj.get( "numDouble" ) ); assertEquals( new Long( 2 ).longValue(), ((Number) jsonObj.get( "numInt" )).longValue() ); assertEquals( "text", jsonObj.get( "text" ) ); assertTrue( JSONUtils.isFunction( jsonObj.get( "func" ) ) ); assertEquals( "function(){ var a = 1; }", jsonObj.get( "func" ) .toString() ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/util/TestJSONUtils.java0000664000175000017500000001320111650253660027353 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.util; import java.util.Collections; import junit.framework.TestCase; import net.sf.json.JSONArray; import net.sf.json.JSONException; /** * @author Andres Almiray */ public class TestJSONUtils extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONUtils.class ); } public TestJSONUtils( String name ) { super( name ); } public void testDoubleToString_infinite() { assertEquals( "null", JSONUtils.doubleToString( Double.POSITIVE_INFINITY ) ); } public void testDoubleToString_nan() { assertEquals( "null", JSONUtils.doubleToString( Double.NaN ) ); } public void testDoubleToString_trailingZeros() { assertEquals( "200", JSONUtils.doubleToString( 200.00000 ) ); } public void testGetFunctionParams() { assertEquals( "", JSONUtils.getFunctionParams( "function()" ) ); assertEquals( "a", JSONUtils.getFunctionParams( "function(a)" ) ); assertEquals( "a,b", JSONUtils.getFunctionParams( "function(a,b)" ) ); assertEquals( "", JSONUtils.getFunctionParams( "notAFunction" ) ); } public void testIsArray() { assertTrue( JSONUtils.isArray( new Object[0] ) ); assertTrue( JSONUtils.isArray( new boolean[0] ) ); assertTrue( JSONUtils.isArray( new byte[0] ) ); assertTrue( JSONUtils.isArray( new char[0] ) ); assertTrue( JSONUtils.isArray( new short[0] ) ); assertTrue( JSONUtils.isArray( new int[0] ) ); assertTrue( JSONUtils.isArray( new long[0] ) ); assertTrue( JSONUtils.isArray( new float[0] ) ); assertTrue( JSONUtils.isArray( new double[0] ) ); // two dimensions assertTrue( JSONUtils.isArray( new Object[0][0] ) ); assertTrue( JSONUtils.isArray( new boolean[0][0] ) ); assertTrue( JSONUtils.isArray( new byte[0][0] ) ); assertTrue( JSONUtils.isArray( new char[0][0] ) ); assertTrue( JSONUtils.isArray( new short[0][0] ) ); assertTrue( JSONUtils.isArray( new int[0][0] ) ); assertTrue( JSONUtils.isArray( new long[0][0] ) ); assertTrue( JSONUtils.isArray( new float[0][0] ) ); assertTrue( JSONUtils.isArray( new double[0][0] ) ); // collections assertTrue( JSONUtils.isArray( Collections.EMPTY_SET ) ); assertTrue( JSONUtils.isArray( Collections.EMPTY_LIST ) ); // jsonArray assertTrue( JSONUtils.isArray( new JSONArray() ) ); } public void testIsFunction() { assertTrue( JSONUtils.isFunction( "function(){ return a; }" ) ); assertTrue( JSONUtils.isFunction( "function (){ return a; }" ) ); assertTrue( JSONUtils.isFunction( "function() { return a; }" ) ); assertTrue( JSONUtils.isFunction( "function () { return a; }" ) ); assertTrue( JSONUtils.isFunction( "function(a){ return a; }" ) ); } public void testNumberToString_null() { try{ JSONUtils.numberToString( null ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // ok } } public void testQuote_emptyString() { assertEquals( "\"\"", JSONUtils.quote( "" ) ); } public void testQuote_escapeChars() { assertEquals( "\"\\b\\t\\n\\r\\f\"", JSONUtils.quote( "\b\t\n\r\f" ) ); } public void testQuote_nullString() { assertEquals( "\"\"", JSONUtils.quote( null ) ); } public void testStripQuotes_singleChar_doubleeQuote() { String quoted = "\""; String actual = JSONUtils.stripQuotes( quoted ); assertEquals( quoted, actual ); } public void testStripQuotes_singleChar_singleQuote() { String quoted = "'"; String actual = JSONUtils.stripQuotes( quoted ); assertEquals( quoted, actual ); } public void testStripQuotes_twoChars_doubleeQuote() { String quoted = "\"\""; String actual = JSONUtils.stripQuotes( quoted ); assertEquals( "", actual ); } public void testStripQuotes_twoChars_singleQuote() { String quoted = "''"; String actual = JSONUtils.stripQuotes( quoted ); assertEquals( "", actual ); } public void testValidity_inifiniteDouble() { try{ JSONUtils.testValidity( new Double( Double.POSITIVE_INFINITY ) ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // ok } } public void testValidity_inifiniteFloat() { try{ JSONUtils.testValidity( new Float( Float.POSITIVE_INFINITY ) ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // ok } } public void testValidity_nanDouble() { try{ JSONUtils.testValidity( new Double( Double.NaN ) ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // ok } } public void testValidity_nanFloat() { try{ JSONUtils.testValidity( new Float( Float.NaN ) ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // ok } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/0000775000175000017500000000000011650253660024365 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/MediaList.java0000664000175000017500000000222511650253660027104 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.ArrayList; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class MediaList { private ArrayList media; public ArrayList getMedia() { return media; } public void setMedia( ArrayList media ) { this.media = media; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ObjectJSONStringBean.java0000664000175000017500000000243511650253660031111 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import net.sf.json.JSONString; /** * @author Andres Almiray */ public class ObjectJSONStringBean implements JSONString { private int id; private String name; public int getId() { return id; } public String getName() { return name; } public void setId( int id ) { this.id = id; } public void setName( String name ) { this.name = name; } public String toJSONString() { return new StringBuffer().append( "{" ) .append( "\"name\":\"" ) .append( (name == null) ? "" : name ) .append( "\"}" ) .toString(); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/Media.java0000664000175000017500000000215311650253660026250 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class Media { private String title; public String getTitle() { return title; } public void setTitle( String title ) { this.title = title; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/PropertyBean.java0000664000175000017500000000225311650253660027644 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class PropertyBean { private String propertyWithNoReadMethod; private final String propertyWithNoWriteMethod = "json"; public String getPropertyWithNoWriteMethod() { return propertyWithNoWriteMethod; } public void setPropertyWithNoReadMethod( String propertyWithNoReadMethod ) { this.propertyWithNoReadMethod = propertyWithNoReadMethod; } public String valueOfPropertyWithNoReadMethod() { return propertyWithNoReadMethod; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/IdentityJsonValueProcessor.java0000664000175000017500000000253511650253660032555 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; import net.sf.json.util.JSONUtils; /** * @author Andres Almiray */ public class IdentityJsonValueProcessor implements JsonValueProcessor { public Object processArrayValue( Object value, JsonConfig jsonConfig ) { return process( value, jsonConfig ); } public Object processObjectValue( String key, Object value, JsonConfig jsonConfig ) { return process( value, jsonConfig ); } private Object process( Object value, JsonConfig jsonConfig ) { if( JSONUtils.isNumber( value )) { value = JSONUtils.transformNumber( (Number)value ); } return value; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/BeanA1763699.java0000664000175000017500000000222111650253660026764 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class BeanA1763699 { private BeanB1763699[] bbeans; public BeanB1763699[] getBbeans() { return bbeans; } public void setBbeans( BeanB1763699[] bbeans ) { this.bbeans = bbeans; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/SetBean.java0000664000175000017500000000343611650253660026557 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class SetBean { private Set attributes = new HashSet(); public void addAttribute( Object value ) { this.attributes.add( value ); } public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null ){ return false; } if( !SetBean.class.isAssignableFrom( obj.getClass() ) ){ return false; } return EqualsBuilder.reflectionEquals( this, obj ); } public Set getAttributes() { return attributes; } public int hashCode() { return HashCodeBuilder.reflectionHashCode( this ); } public void setAttributes( Set attributes ) { this.attributes = attributes; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/EmptyBean.java0000664000175000017500000000446211650253660027122 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.List; /** * @author Andres Almiray */ public class EmptyBean { private Object[] arrayp; private Byte bytep; private Character charp; private Double doublep; private Float floatp; private Integer intp; private List listp; private Long longp; private Short shortp; private String stringp; public Object[] getArrayp() { return arrayp; } public Byte getBytep() { return bytep; } public Character getCharp() { return charp; } public Double getDoublep() { return doublep; } public Float getFloatp() { return floatp; } public Integer getIntp() { return intp; } public List getListp() { return listp; } public Long getLongp() { return longp; } public Short getShortp() { return shortp; } public String getStringp() { return stringp; } public void setArrayp( Object[] arrayp ) { this.arrayp = arrayp; } public void setBytep( Byte bytep ) { this.bytep = bytep; } public void setCharp( Character charp ) { this.charp = charp; } public void setDoublep( Double doublep ) { this.doublep = doublep; } public void setFloatp( Float floatp ) { this.floatp = floatp; } public void setIntp( Integer intp ) { this.intp = intp; } public void setListp( List listp ) { this.listp = listp; } public void setLongp( Long longp ) { this.longp = longp; } public void setShortp( Short shortp ) { this.shortp = shortp; } public void setStringp( String stringp ) { this.stringp = stringp; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/TransientBean.java0000664000175000017500000000173111650253660027767 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class TransientBean extends ValueBean { private transient int transientValue; public int getTransientValue() { return transientValue; } public void setTransientValue( int transientValue ) { this.transientValue = transientValue; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/MappedBean.java0000664000175000017500000000221611650253660027225 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.HashMap; import java.util.List; /** * @author Andres Almiray */ public class MappedBean extends HashMap { private static final long serialVersionUID = -3372716996620968313L; public List getList() { return (List) get( "list" ); } public String getName() { return (String) get( "name" ); } public void setList( List list ) { put( "list", list ); } public void setName( String name ) { put( "name", name ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/BeanFoo.java0000664000175000017500000000161511650253660026544 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class BeanFoo { private String[][] items; public String[][] getItems() { return items; } public void setItems( String[][] items ) { this.items = items; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ListingBean.java0000664000175000017500000000210011650253660027420 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.ArrayList; import java.util.List; /** * @author Andres Almiray */ public class ListingBean { private List attributes = new ArrayList(); public void addAttribute( Object value ) { this.attributes.add( value ); } public List getAttributes() { return attributes; } public void setAttributes( List attributes ) { this.attributes = attributes; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ClassBean.java0000664000175000017500000000160011650253660027060 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class ClassBean { private Class klass; public Class getKlass() { return klass; } public void setKlass( Class klass ) { this.klass = klass; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/UnstandardBeanInstanceStrategy.java0000664000175000017500000000226111650253660033332 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.lang.reflect.InvocationTargetException; import net.sf.json.JSONObject; import net.sf.json.util.NewBeanInstanceStrategy; /** * @author Andres Almiray */ public class UnstandardBeanInstanceStrategy extends NewBeanInstanceStrategy { public Object newInstance( Class target, JSONObject source ) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, InvocationTargetException { return new UnstandardBean( source.getInt( "id" ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/PackageProtectedBean.java0000664000175000017500000000222311650253660031222 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class PackageProtectedBean { private int value; PackageProtectedBean() { } public int getValue() { return value; } public void setValue( int value ) { this.value = value; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/BeanA.java0000664000175000017500000000420711650253660026201 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class BeanA { private boolean bool = true; private int integer = 42; private String string = "json"; public BeanA() { super(); } public BeanA( boolean bool, int integer, String string ) { super(); this.bool = bool; this.integer = integer; this.string = string; } public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null ){ return false; } if( !BeanA.class.isAssignableFrom( obj.getClass() ) ){ return false; } return EqualsBuilder.reflectionEquals( this, obj ); } public int getInteger() { return integer; } public String getString() { return string; } public int hashCode() { return HashCodeBuilder.reflectionHashCode( this ); } public boolean isBool() { return bool; } public void setBool( boolean bool ) { this.bool = bool; } public void setInteger( int integer ) { this.integer = integer; } public void setString( String string ) { this.string = string; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/MediaBean.java0000664000175000017500000000215711650253660027042 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class MediaBean { private String title; public String getTitle() { return title; } public void setTitle( String title ) { this.title = title; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ObjectBean.java0000664000175000017500000000677211650253660027240 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class ObjectBean { private Object parray; private Object pbean; private Object pboolean; private Object pbyte; private Object pchar; private Object pclass; private Object pdouble; private Object pexcluded; private Object pfloat; private Object pfunction; private Object pint; private Object plist; private Object plong; private Object pmap; private Object pshort; private Object pstring; public Object getParray() { return parray; } public Object getPbean() { return pbean; } public Object getPboolean() { return pboolean; } public Object getPbyte() { return pbyte; } public Object getPchar() { return pchar; } public Object getPclass() { return pclass; } public Object getPdouble() { return pdouble; } public Object getPexcluded() { return pexcluded; } public Object getPfloat() { return pfloat; } public Object getPfunction() { return pfunction; } public Object getPint() { return pint; } public Object getPlist() { return plist; } public Object getPlong() { return plong; } public Object getPmap() { return pmap; } public Object getPshort() { return pshort; } public Object getPstring() { return pstring; } public void setParray( Object parray ) { this.parray = parray; } public void setPbean( Object bean ) { this.pbean = bean; } public void setPboolean( Object pboolean ) { this.pboolean = pboolean; } public void setPbyte( Object pbyte ) { this.pbyte = pbyte; } public void setPchar( Object pchar ) { this.pchar = pchar; } public void setPclass( Object pclass ) { this.pclass = pclass; } public void setPdouble( Object pdouble ) { this.pdouble = pdouble; } public void setPexcluded( Object pexcluded ) { this.pexcluded = pexcluded; } public void setPfloat( Object pfloat ) { this.pfloat = pfloat; } public void setPfunction( Object pfunction ) { this.pfunction = pfunction; } public void setPint( Object pint ) { this.pint = pint; } public void setPlist( Object plist ) { this.plist = plist; } public void setPlong( Object plong ) { this.plong = plong; } public void setPmap( Object pmap ) { this.pmap = pmap; } public void setPshort( Object pshort ) { this.pshort = pshort; } public void setPstring( Object pstring ) { this.pstring = pstring; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/InterfaceBean.java0000664000175000017500000000164211650253660027721 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class InterfaceBean { private Runnable runnable; public Runnable getRunnable() { return runnable; } public void setRunnable( Runnable runnable ) { this.runnable = runnable; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/PrivateConstructorBean.java0000664000175000017500000000223711650253660031702 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class PrivateConstructorBean { private int value; private PrivateConstructorBean() { } public int getValue() { return value; } public void setValue( int value ) { this.value = value; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ArrayBean.java0000664000175000017500000000216211650253660027075 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class ArrayBean { private BeanA[] beans; public BeanA[] getBeans() { return beans; } public void setBeans( BeanA[] beans ) { this.beans = beans; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/FieldBean.java0000664000175000017500000000217711650253660027050 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class FieldBean { private int value; public String string; public int getValue() { return value; } public void setValue( int value ) { this.value = value; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/BeanB1763699.java0000664000175000017500000000214411650253660026771 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class BeanB1763699 { private String str; public String getStr() { return str; } public void setStr( String str ) { this.str = str; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/BeanWithFunc.java0000664000175000017500000000221511650253660027545 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import net.sf.json.JSONFunction; /** * @author Andres Almiray */ public class BeanWithFunc { private JSONFunction function; public BeanWithFunc( JSONFunction function ) { this.function = function; } public BeanWithFunc( String function ) { this.function = new JSONFunction( function ); } public JSONFunction getFunction() { return function; } public void setFunction( JSONFunction function ) { this.function = function; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/MediaListBean.java0000664000175000017500000000244711650253660027700 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.List; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class MediaListBean { private Object media; private List media2; public Object getMedia() { return media; } public List getMedia2() { return media2; } public void setMedia( Object media ) { this.media = media; } public void setMedia2( List media2 ) { this.media2 = media2; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/BeanB.java0000664000175000017500000000224311650253660026200 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class BeanB extends BeanA { private int[] intarray = new int[] { 1, 2, 3 }; public int[] getIntarray() { return intarray; } public void setIntarray( int[] intarray ) { this.intarray = intarray; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/UnstandardBean.java0000664000175000017500000000411411650253660030121 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class UnstandardBean { private boolean bool = true; private int id; private int integer = 42; private String string = "json"; public UnstandardBean( int id ) { this.id = id; } public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null ){ return false; } if( !UnstandardBean.class.isAssignableFrom( obj.getClass() ) ){ return false; } return EqualsBuilder.reflectionEquals( this, obj ); } public int getId() { return id; } public int getInteger() { return integer; } public String getString() { return string; } public int hashCode() { return HashCodeBuilder.reflectionHashCode( this ); } public boolean isBool() { return bool; } public void setBool( boolean bool ) { this.bool = bool; } public void setInteger( int integer ) { this.integer = integer; } public void setString( String string ) { this.string = string; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/JSONTestBean.java0000664000175000017500000000171411650253660027432 0ustar jamespagejamespagepackage net.sf.json.sample; import java.util.HashMap; import java.util.Map; public class JSONTestBean { private String email = ""; private String inventoryID = ""; private String notes = ""; private Map options = new HashMap(); private String rateID = ""; public String getEmail() { return email; } public String getInventoryID() { return inventoryID; } public String getNotes() { return notes; } public Map getOptions() { return options; } public String getRateID() { return rateID; } public void setEmail( String email ) { this.email = email; } public void setInventoryID( String inventoryID ) { this.inventoryID = inventoryID; } public void setNotes( String notes ) { this.notes = notes; } public void setOptions( Map options ) { this.options = options; } public void setRateID( String rateID ) { this.rateID = rateID; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/DateBean.java0000664000175000017500000000163711650253660026702 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.Date; /** * @author Andres Almiray */ public class DateBean extends ValueBean { private Date date; public Date getDate() { return date; } public void setDate( Date date ) { this.date = date; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/NumberArrayBean.java0000664000175000017500000000363211650253660030251 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class NumberArrayBean { private byte[] bytes; private double[] doubles; private float[] floats; private int[] ints; private long[] longs; private short[] shorts; public byte[] getBytes() { return bytes; } public double[] getDoubles() { return doubles; } public float[] getFloats() { return floats; } public int[] getInts() { return ints; } public long[] getLongs() { return longs; } public short[] getShorts() { return shorts; } public void setBytes( byte[] bytes ) { this.bytes = bytes; } public void setDoubles( double[] doubles ) { this.doubles = doubles; } public void setFloats( float[] floats ) { this.floats = floats; } public void setInts( int[] ints ) { this.ints = ints; } public void setLongs( long[] longs ) { this.longs = longs; } public void setShorts( short[] shorts ) { this.shorts = shorts; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/JsonEventAdpater.java0000664000175000017500000000446311650253660030453 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import net.sf.json.JSONException; import net.sf.json.util.JsonEventListener; /** * @author Andres Almiray */ public class JsonEventAdpater implements JsonEventListener { private int arrayEnd = 0; private int arrayStart = 0; private int elementAdded = 0; private int error = 0; private int objectEnd = 0; private int objectStart = 0; private int propertySet = 0; private int warning = 0; public int getArrayEnd() { return arrayEnd; } public int getArrayStart() { return arrayStart; } public int getElementAdded() { return elementAdded; } public int getError() { return error; } public int getObjectEnd() { return objectEnd; } public int getObjectStart() { return objectStart; } public int getPropertySet() { return propertySet; } public int getWarning() { return warning; } public void onArrayEnd() { arrayEnd++; } public void onArrayStart() { arrayStart++; } public void onElementAdded( int index, Object element ) { elementAdded++; } public void onError( JSONException jsone ) { error++; } public void onObjectEnd() { objectEnd++; } public void onObjectStart() { objectStart++; } public void onPropertySet( String key, Object value, boolean accumulated ) { propertySet++; } public void onWarning( String warning ) { this.warning++; } public void reset() { objectStart = 0; objectEnd = 0; arrayStart = 0; arrayEnd = 0; error = 0; warning = 0; propertySet = 0; elementAdded = 0; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ArrayJSONStringBean.java0000664000175000017500000000222111650253660030752 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import net.sf.json.JSONString; import org.apache.commons.lang.ArrayUtils; /** * @author Andres Almiray */ public class ArrayJSONStringBean implements JSONString { private String value; public String getValue() { return value; } public void setValue( String value ) { this.value = value; } public String toJSONString() { return ArrayUtils.toString( value.split( "," ) ) .replace( '{', '[' ) .replace( '}', ']' ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/NumberBean.java0000664000175000017500000000577411650253660027263 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.math.BigDecimal; import java.math.BigInteger; /** * @author Andres Almiray */ public class NumberBean { private BigDecimal pbigdec; private BigInteger pbigint; private byte pbyte; private double pdouble; private float pfloat; private int pint; private long plong; private short pshort; private Byte pwbyte; private Double pwdouble; private Float pwfloat; private Integer pwint; private Long pwlong; private Short pwshort; public BigDecimal getPbigdec() { return pbigdec; } public BigInteger getPbigint() { return pbigint; } public byte getPbyte() { return pbyte; } public double getPdouble() { return pdouble; } public float getPfloat() { return pfloat; } public int getPint() { return pint; } public long getPlong() { return plong; } public short getPshort() { return pshort; } public Byte getPwbyte() { return pwbyte; } public Double getPwdouble() { return pwdouble; } public Float getPwfloat() { return pwfloat; } public Integer getPwint() { return pwint; } public Long getPwlong() { return pwlong; } public Short getPwshort() { return pwshort; } public void setPbigdec( BigDecimal pbigdec ) { this.pbigdec = pbigdec; } public void setPbigint( BigInteger pbigint ) { this.pbigint = pbigint; } public void setPbyte( byte pbyte ) { this.pbyte = pbyte; } public void setPdouble( double pdouble ) { this.pdouble = pdouble; } public void setPfloat( float pfloat ) { this.pfloat = pfloat; } public void setPint( int pint ) { this.pint = pint; } public void setPlong( long plong ) { this.plong = plong; } public void setPshort( short pshort ) { this.pshort = pshort; } public void setPwbyte( Byte pwbyte ) { this.pwbyte = pwbyte; } public void setPwdouble( Double pwdouble ) { this.pwdouble = pwdouble; } public void setPwfloat( Float pwfloat ) { this.pwfloat = pwfloat; } public void setPwint( Integer pwint ) { this.pwint = pwint; } public void setPwlong( Long pwlong ) { this.pwlong = pwlong; } public void setPwshort( Short pwshort ) { this.pwshort = pwshort; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ValueBean.java0000664000175000017500000000314611650253660027076 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class ValueBean { private int value; public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null ){ return false; } if( !ValueBean.class.isAssignableFrom( obj.getClass() ) ){ return false; } return EqualsBuilder.reflectionEquals( this, obj ); } public int getValue() { return value; } public int hashCode() { return HashCodeBuilder.reflectionHashCode( this ); } public void setValue( int value ) { this.value = value; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ParentBean.java0000664000175000017500000000167611650253660027261 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class ParentBean extends ValueBean { private ChildBean child; public ChildBean getChild() { return child; } public void setChild( ChildBean child ) { this.child = child; child.setParent( this ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/BeanC.java0000664000175000017500000000243411650253660026203 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class BeanC { private BeanA beanA = new BeanA(); private BeanB beanB = new BeanB(); public BeanA getBeanA() { return beanA; } public BeanB getBeanB() { return beanB; } public void setBeanA( BeanA beanA ) { this.beanA = beanA; } public void setBeanB( BeanB beanB ) { this.beanB = beanB; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/ChildBean.java0000664000175000017500000000165011650253660027043 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class ChildBean extends ValueBean { private ParentBean parent; public ParentBean getParent() { return parent; } public void setParent( ParentBean parent ) { this.parent = parent; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/Player.java0000664000175000017500000000222111650253660026461 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class Player { private MediaList mediaList; public MediaList getMediaList() { return mediaList; } public void setMediaList( MediaList mediaList ) { this.mediaList = mediaList; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/PrimitiveBean.java0000664000175000017500000000734211650253660027774 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.List; import java.util.Map; import net.sf.json.JSONFunction; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class PrimitiveBean { private Object[] oarray; private int[] parray; private ObjectBean pbean; private boolean pboolean; private byte pbyte; private char pchar; private Class pclass; private double pdouble; private String pexcluded; private float pfloat; private JSONFunction pfunction; private int pint; private List plist; private long plong; private Map pmap; private short pshort; private String pstring; public Object[] getOarray() { return oarray; } public int[] getParray() { return parray; } public ObjectBean getPbean() { return pbean; } public byte getPbyte() { return pbyte; } public char getPchar() { return pchar; } public Class getPclass() { return pclass; } public double getPdouble() { return pdouble; } public String getPexcluded() { return pexcluded; } public float getPfloat() { return pfloat; } public JSONFunction getPfunction() { return pfunction; } public int getPint() { return pint; } public List getPlist() { return plist; } public long getPlong() { return plong; } public Map getPmap() { return pmap; } public short getPshort() { return pshort; } public String getPstring() { return pstring; } public boolean isPboolean() { return pboolean; } public void setOarray( Object[] oarray ) { this.oarray = oarray; } public void setParray( int[] parray ) { this.parray = parray; } public void setPbean( ObjectBean pbean ) { this.pbean = pbean; } public void setPboolean( boolean pboolean ) { this.pboolean = pboolean; } public void setPbyte( byte pbyte ) { this.pbyte = pbyte; } public void setPchar( char pchar ) { this.pchar = pchar; } public void setPclass( Class pclass ) { this.pclass = pclass; } public void setPdouble( double pdouble ) { this.pdouble = pdouble; } public void setPexcluded( String pexcluded ) { this.pexcluded = pexcluded; } public void setPfloat( float pfloat ) { this.pfloat = pfloat; } public void setPfunction( JSONFunction pfunction ) { this.pfunction = pfunction; } public void setPint( int pint ) { this.pint = pint; } public void setPlist( List plist ) { this.plist = plist; } public void setPlong( long plong ) { this.plong = plong; } public void setPmap( Map pmap ) { this.pmap = pmap; } public void setPshort( short pshort ) { this.pshort = pshort; } public void setPstring( String pstring ) { this.pstring = pstring; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } } jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/PlayerList.java0000664000175000017500000000223511650253660027322 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.ArrayList; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * @author Andres Almiray */ public class PlayerList { private ArrayList player; public ArrayList getPlayer() { return player; } public void setPlayer( ArrayList player ) { this.player = player; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/MappingBean.java0000664000175000017500000000211211650253660027405 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.HashMap; import java.util.Map; /** * @author Andres Almiray */ public class MappingBean { private Map attributes = new HashMap(); public void addAttribute( Object key, Object value ) { this.attributes.put( key, value ); } public Map getAttributes() { return attributes; } public void setAttributes( Map attributes ) { this.attributes = attributes; } } jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/IdBean.java0000664000175000017500000000421311650253660026352 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import net.sf.ezmorph.object.AbstractObjectMorpher; /** * @author Andres Almiray */ public class IdBean { private Id id; public Id getId() { return id; } public void setId( Id id ) { this.id = id; } public static class Id { private long value; public Id() { value = 0; } public Id( long value ) { super(); this.value = value; } public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null ){ return false; } if( !(obj instanceof Id) ){ return false; } Id other = (Id) obj; return value == other.value; } public long getValue() { return value; } public int hashCode() { return getClass().hashCode() + (int) value; } public void setValue( long value ) { this.value = value; } } public static class IdMorpher extends AbstractObjectMorpher { public Object morph( Object value ) { if( value != null ){ if( value instanceof Number ){ return new IdBean.Id( ((Number) value).longValue() ); }else if( value instanceof String ){ return new IdBean.Id( new Long( (String) value ).longValue() ); } } return null; } public Class morphsTo() { return IdBean.Id.class; } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/sample/JavaIdentifierBean.java0000664000175000017500000000245311650253660030706 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class JavaIdentifierBean { private String camelCase; private String under_score; private String whitespace; public String getCamelCase() { return camelCase; } public String getUnder_score() { return under_score; } public String getWhitespace() { return whitespace; } public void setCamelCase( String camelCase ) { this.camelCase = camelCase; } public void setUnder_score( String under_score ) { this.under_score = under_score; } public void setWhitespace( String whitespace ) { this.whitespace = whitespace; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectEvents.java0000664000175000017500000001176311650253660027704 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; import net.sf.json.sample.BeanA; import net.sf.json.sample.JsonEventAdpater; import net.sf.json.sample.PropertyBean; import org.apache.commons.beanutils.DynaBean; /** * @author Andres Almiray */ public class TestJSONObjectEvents extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectEvents.class ); } private JsonConfig jsonConfig; private JsonEventAdpater jsonEventAdpater; public TestJSONObjectEvents( String name ) { super( name ); } public void testFromObject_bean() { JSONObject.fromObject( new BeanA(), jsonConfig ); assertEvents(); } public void testFromObject_bean2() { JSONObject.fromObject( new PropertyBean(), jsonConfig ); assertEquals( 0, jsonEventAdpater.getError() ); assertEquals( 1, jsonEventAdpater.getWarning() ); assertEquals( 0, jsonEventAdpater.getArrayStart() ); assertEquals( 0, jsonEventAdpater.getArrayEnd() ); assertEquals( 1, jsonEventAdpater.getObjectStart() ); assertEquals( 1, jsonEventAdpater.getObjectEnd() ); assertEquals( 0, jsonEventAdpater.getElementAdded() ); assertEquals( 1, jsonEventAdpater.getPropertySet() ); } public void testFromObject_dynaBean() throws Exception { JSONObject.fromObject( createDynaBean(), jsonConfig ); assertEvents(); } public void testFromObject_error() { try{ JSONObject.fromObject( "[]", jsonConfig ); fail( "A JSONException was expected" ); }catch( JSONException expected ){ assertEquals( 1, jsonEventAdpater.getError() ); assertEquals( 0, jsonEventAdpater.getWarning() ); assertEquals( 0, jsonEventAdpater.getArrayStart() ); assertEquals( 0, jsonEventAdpater.getArrayEnd() ); assertEquals( 0, jsonEventAdpater.getObjectStart() ); assertEquals( 0, jsonEventAdpater.getObjectEnd() ); assertEquals( 0, jsonEventAdpater.getElementAdded() ); assertEquals( 0, jsonEventAdpater.getPropertySet() ); } } public void testFromObject_JSONObject() { JSONObject jsonObject = new JSONObject().element( "name", "json" ) .element( "func", new JSONFunction( "return this;" ) ) .element( "int", new Integer( 1 ) ); JSONObject.fromObject( jsonObject, jsonConfig ); assertEvents(); } public void testFromObject_map() { Map map = new HashMap(); map.put( "name", "json" ); map.put( "func", new JSONFunction( "return this;" ) ); map.put( "int", new Integer( 1 ) ); JSONObject.fromObject( map, jsonConfig ); assertEvents(); } public void testFromObject_string() { JSONObject.fromObject( "{name:'json',int:1,func:function(){ return this; }}", jsonConfig ); assertEvents(); } protected void setUp() throws Exception { jsonEventAdpater = new JsonEventAdpater(); jsonConfig = new JsonConfig(); jsonConfig.addJsonEventListener( jsonEventAdpater ); jsonConfig.enableEventTriggering(); } protected void tearDown() throws Exception { jsonEventAdpater.reset(); } private void assertEvents() { assertEquals( 0, jsonEventAdpater.getError() ); assertEquals( 0, jsonEventAdpater.getWarning() ); assertEquals( 0, jsonEventAdpater.getArrayStart() ); assertEquals( 0, jsonEventAdpater.getArrayEnd() ); assertEquals( 1, jsonEventAdpater.getObjectStart() ); assertEquals( 1, jsonEventAdpater.getObjectEnd() ); assertEquals( 0, jsonEventAdpater.getElementAdded() ); assertEquals( 3, jsonEventAdpater.getPropertySet() ); } private DynaBean createDynaBean() throws Exception { Map properties = new HashMap(); properties.put( "name", String.class ); properties.put( "func", JSONFunction.class ); properties.put( "int", Integer.class ); MorphDynaClass dynaClass = new MorphDynaClass( properties ); MorphDynaBean dynaBean = (MorphDynaBean) dynaClass.newInstance(); dynaBean.setDynaBeanClass( dynaClass ); dynaBean.set( "name", "json" ); dynaBean.set( "func", new JSONFunction( "return this;" ) ); dynaBean.set( "int", new Integer( 1 ) ); return dynaBean; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayStaticBuilders_Array_DynaBean.java0000664000175000017500000000377711650253660034136 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.Map; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; /** * @author Andres Almiray */ public class TestJSONArrayStaticBuilders_Array_DynaBean extends AbstractJSONArrayStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayStaticBuilders_Array_DynaBean.class ); } public TestJSONArrayStaticBuilders_Array_DynaBean( String name ) { super( name ); } protected Object getSource() { Map map = new HashMap(); String[] props = getProperties(); for( int i = 0; i < props.length; i++ ){ map.put( props[i], PropertyConstants.getPropertyClass( props[i] ) ); } map.put( "class", Class.class ); map.put( "pexcluded", String.class ); MorphDynaClass dynaClass = new MorphDynaClass( map ); MorphDynaBean dynaBean = null; try{ dynaBean = (MorphDynaBean) dynaClass.newInstance(); for( int i = 0; i < props.length; i++ ){ dynaBean.set( props[i], PropertyConstants.getPropertyValue( props[i] ) ); } dynaBean.set( "class", Object.class ); dynaBean.set( "pexcluded", "" ); }catch( Exception e ){ throw new RuntimeException( e ); } return new Object[] { dynaBean }; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_DynaBean.java0000664000175000017500000000373211650253660033117 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.Map; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_DynaBean extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_DynaBean.class ); } public TestJSONObjectStaticBuilders_DynaBean( String name ) { super( name ); } protected Object getSource() { Map map = new HashMap(); String[] props = getProperties(); for( int i = 0; i < props.length; i++ ){ map.put( props[i], PropertyConstants.getPropertyClass( props[i] ) ); } map.put( "class", Class.class ); map.put( "pexcluded", String.class ); MorphDynaClass dynaClass = new MorphDynaClass( map ); MorphDynaBean dynaBean = null; try{ dynaBean = (MorphDynaBean) dynaClass.newInstance(); for( int i = 0; i < props.length; i++ ){ dynaBean.set( props[i], PropertyConstants.getPropertyValue( props[i] ) ); } dynaBean.set( "class", Object.class ); dynaBean.set( "pexcluded", "" ); }catch( Exception e ){ throw new RuntimeException( e ); } return dynaBean; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/JSONTestSuite.java0000664000175000017500000000252211650253660026373 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class JSONTestSuite extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "json-lib" ); suite.addTest( net.sf.json.AllTests.suite() ); suite.addTest( net.sf.json.regexp.AllTests.suite() ); suite.addTest( net.sf.json.filters.AllTests.suite() ); suite.addTest( net.sf.json.processors.AllTests.suite() ); suite.addTest( net.sf.json.util.AllTests.suite() ); suite.addTest( net.sf.json.xml.AllTests.suite() ); suite.addTest( net.sf.json.test.AllTests.suite() ); return suite; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONSerializer.java0000664000175000017500000002351411650253660027417 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.sf.json.sample.ArrayJSONStringBean; import net.sf.json.sample.BeanA; import net.sf.json.sample.MappingBean; import net.sf.json.sample.ObjectJSONStringBean; import net.sf.json.sample.ValueBean; import net.sf.json.util.JSONTokener; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.PropertyUtils; /** * @author Andres Almiray */ public class TestJSONSerializer extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONSerializer.class ); } private JsonConfig jsonConfig; public TestJSONSerializer( String name ) { super( name ); } public void testToJava_JSONArray_1() { setName( "JSONArray('[]') -> ToJava[default]" ); JSONArray jsonArray = JSONArray.fromObject( "[]" ); Object java = JSONSerializer.toJava( jsonArray ); assertNotNull( java ); assertTrue( java instanceof List ); List list = (List) java; assertEquals( 0, list.size() ); } public void testToJava_JSONArray_2() { setName( "JSONArray('[]') -> ToJava[arrayMode:OBJECT_ARRAY]" ); JSONArray jsonArray = JSONArray.fromObject( "[]" ); jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY ); Object java = JSONSerializer.toJava( jsonArray, jsonConfig ); assertNotNull( java ); assertTrue( Object[].class.isAssignableFrom( java.getClass() ) ); Object[] array = (Object[]) java; assertEquals( 0, array.length ); } public void testToJava_JSONNull_1() { setName( "JSONNull -> ToJava[default]" ); Object java = JSONSerializer.toJava( JSONNull.getInstance() ); assertNull( java ); } public void testToJava_JSONObject_1() { setName( "JSONObject(null:true) -> ToJava[default]" ); Object java = JSONSerializer.toJava( new JSONObject( true ) ); assertNull( java ); } public void testToJava_JSONObject_2() throws Exception { setName( "JSONObject -> ToJava[default]" ); String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}"; JSONObject jsonObject = JSONObject.fromObject( json ); Object bean = JSONSerializer.toJava( jsonObject ); assertNotNull( bean ); assertTrue( bean instanceof DynaBean ); assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) ); assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) ); assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) ); assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) ); assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) ); List expected = (List) JSONArray.toCollection( jsonObject.getJSONArray( "array" ) ); Assertions.assertEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) ); } public void testToJava_JSONObject_3() throws Exception { setName( "JSONObject -> ToJava[rootClass:BeanA]" ); String json = "{bool:true,integer:1,string:\"json\"}"; JSONObject jsonObject = JSONObject.fromObject( json ); jsonConfig.setRootClass( BeanA.class ); Object java = JSONSerializer.toJava( jsonObject, jsonConfig ); assertNotNull( java ); assertTrue( java instanceof BeanA ); BeanA bean = (BeanA) java; assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) ); assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) ); assertEquals( jsonObject.get( "string" ), bean.getString() ); } public void testToJava_JSONObject_4() { setName( "JSONObject -> ToJava[rootClass:BeanA,classMap]" ); MappingBean mappingBean = new MappingBean(); ValueBean beanA = new ValueBean(); beanA.setValue( 90000 ); ValueBean beanB = new ValueBean(); beanB.setValue( 91000 ); mappingBean.addAttribute( "beanA", beanA ); mappingBean.addAttribute( "beanB", beanB ); Map classMap = new HashMap(); classMap.put( "bean.*", ValueBean.class ); JSONObject jsonObject = JSONObject.fromObject( mappingBean ); jsonConfig.setRootClass( MappingBean.class ); jsonConfig.setClassMap( classMap ); Object java = JSONSerializer.toJava( jsonObject, jsonConfig ); assertNotNull( java ); assertTrue( java instanceof MappingBean ); MappingBean mappingBean2 = (MappingBean) java; Object ba = mappingBean2.getAttributes() .get( "beanA" ); Object bb = mappingBean2.getAttributes() .get( "beanB" ); assertTrue( ba instanceof ValueBean ); assertTrue( bb instanceof ValueBean ); assertEquals( beanA.getValue(), ((ValueBean) ba).getValue() ); assertEquals( beanB.getValue(), ((ValueBean) bb).getValue() ); } public void testToJava_JSONObject_and_reset() throws Exception { String json = "{bool:true,integer:1,string:\"json\"}"; JSONObject jsonObject = JSONObject.fromObject( json ); jsonConfig.setRootClass( BeanA.class ); Object java = JSONSerializer.toJava( jsonObject, jsonConfig ); assertNotNull( java ); assertTrue( java instanceof BeanA ); BeanA bean = (BeanA) java; assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) ); assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) ); assertEquals( jsonObject.get( "string" ), bean.getString() ); jsonConfig.reset(); java = JSONSerializer.toJava( jsonObject, jsonConfig ); assertTrue( java instanceof DynaBean ); assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( java, "bool" ) ); assertEquals( jsonObject.get( "integer" ), PropertyUtils.getProperty( java, "integer" ) ); assertEquals( jsonObject.get( "string" ), PropertyUtils.getProperty( java, "string" ) ); } public void testToJSON_JSONString_array() { ArrayJSONStringBean bean = new ArrayJSONStringBean(); bean.setValue( "'json','json'" ); JSON json = JSONSerializer.toJSON( bean ); assertNotNull( json ); assertTrue( json instanceof JSONArray ); Assertions.assertEquals( JSONArray.fromObject( "['json','json']" ), (JSONArray) json ); } public void testToJSON_JSONString_null() { JSON json = JSONSerializer.toJSON( (JSONString) null ); assertNotNull( json ); assertTrue( JSONNull.getInstance() .equals( json ) ); } public void testToJSON_JSONString_object() { ObjectJSONStringBean bean = new ObjectJSONStringBean(); bean.setName( "json" ); JSON json = JSONSerializer.toJSON( bean ); assertNotNull( json ); assertTrue( json instanceof JSONObject ); Assertions.assertEquals( JSONObject.fromObject( "{\"name\":\"json\"}" ), (JSONObject) json ); } public void testToJSON_Object_array() { JSON json = JSONSerializer.toJSON( new int[] { 1, 2 } ); assertNotNull( json ); assertTrue( json instanceof JSONArray ); Assertions.assertEquals( JSONArray.fromObject( "[1,2]" ), (JSONArray) json ); } public void testToJSON_Object_JSONTokener_array() { JSON json = JSONSerializer.toJSON( new JSONTokener( "[1,2]" ) ); assertNotNull( json ); assertTrue( json instanceof JSONArray ); Assertions.assertEquals( JSONArray.fromObject( "[1,2]" ), (JSONArray) json ); } public void testToJSON_Object_null() { JSON json = JSONSerializer.toJSON( (Object) null ); assertNotNull( json ); assertTrue( JSONNull.getInstance() .equals( json ) ); } public void testToJSON_Object_object() { JSON json = JSONSerializer.toJSON( new BeanA() ); assertNotNull( json ); assertTrue( json instanceof JSONObject ); Assertions.assertEquals( JSONObject.fromObject( new BeanA() ), (JSONObject) json ); } public void testToJSON_String_array() { JSON json = JSONSerializer.toJSON( "['json','json']" ); assertNotNull( json ); assertTrue( json instanceof JSONArray ); Assertions.assertEquals( JSONArray.fromObject( "['json','json']" ), (JSONArray) json ); } public void testToJSON_String_invalid() { try{ JSONSerializer.toJSON( "garbage" ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // ok } } public void testToJSON_String_null() { JSON json = JSONSerializer.toJSON( (String) null ); assertNotNull( json ); assertTrue( JSONNull.getInstance() .equals( json ) ); } public void testToJSON_String_null_literal() { JSON json = JSONSerializer.toJSON( "null" ); assertNotNull( json ); assertTrue( JSONNull.getInstance() .equals( json ) ); } public void testToJSON_String_object() { JSON json = JSONSerializer.toJSON( "{'name':'json'}" ); assertNotNull( json ); assertTrue( json instanceof JSONObject ); Assertions.assertEquals( JSONObject.fromObject( "{\"name\":\"json\"}" ), (JSONObject) json ); } protected void setUp() throws Exception { jsonConfig = new JsonConfig(); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObject.java0000664000175000017500000020277011650253660026517 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.io.Serializable; import java.io.PrintWriter; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import net.sf.ezmorph.MorphUtils; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; import net.sf.ezmorph.test.ArrayAssertions; import net.sf.json.processors.DefaultValueProcessor; import net.sf.json.processors.DefaultValueProcessorMatcher; import net.sf.json.processors.PropertyNameProcessor; import net.sf.json.sample.BeanA; import net.sf.json.sample.BeanB; import net.sf.json.sample.BeanC; import net.sf.json.sample.BeanFoo; import net.sf.json.sample.BeanWithFunc; import net.sf.json.sample.ChildBean; import net.sf.json.sample.ClassBean; import net.sf.json.sample.EmptyBean; import net.sf.json.sample.JavaIdentifierBean; import net.sf.json.sample.ListingBean; import net.sf.json.sample.MappingBean; import net.sf.json.sample.NumberBean; import net.sf.json.sample.ObjectBean; import net.sf.json.sample.ObjectJSONStringBean; import net.sf.json.sample.ParentBean; import net.sf.json.sample.PrimitiveBean; import net.sf.json.sample.PropertyBean; import net.sf.json.sample.SetBean; import net.sf.json.sample.TransientBean; import net.sf.json.sample.ValueBean; import net.sf.json.util.CycleDetectionStrategy; import net.sf.json.util.JSONTokener; import net.sf.json.util.JSONUtils; import net.sf.json.util.JavaIdentifierTransformer; import net.sf.json.util.PropertyExclusionClassMatcher; import net.sf.json.util.PropertyFilter; import net.sf.json.util.PropertySetStrategy; import org.apache.commons.beanutils.PropertyUtils; /** * @author Andres Almiray */ public class TestJSONObject extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObject.class ); } private JsonConfig jsonConfig; public TestJSONObject( String testName ) { super( testName ); } public void testAccumulate() { JSONObject json = new JSONObject(); json.accumulate( "key", "1" ); Assertions.assertEquals( 1, json.getInt( "key" ) ); json.accumulate( "key", "2" ); Assertions.assertEquals( JSONArray.fromObject( "['1','2']" ), json.getJSONArray( "key" ) ); json.accumulate( "key", "3" ); Assertions.assertEquals( JSONArray.fromObject( "['1','2','3']" ), json.getJSONArray( "key" ) ); } public void testAccumulate__nullObject() { try{ new JSONObject( true ).accumulate( "key", "value" ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // ok } } public void testConstructor_Object__nullJSONObject() { JSONObject jsonObject = JSONObject.fromObject( (JSONObject) null ); assertTrue( jsonObject.isNullObject() ); } public void testConstructor_Object_String_Array__nullObject() { jsonConfig.setExcludes( new String[] { "bool", "integer" } ); JSONObject jsonObject = JSONObject.fromObject( (Object) null, jsonConfig ); assertTrue( jsonObject.isNullObject() ); } public void testCycleDetection_beans_noprop() { jsonConfig.setCycleDetectionStrategy( CycleDetectionStrategy.NOPROP ); ParentBean parent = new ParentBean(); parent.setChild( new ChildBean() ); JSONObject actual = JSONObject.fromObject( parent, jsonConfig ); JSONObject expected = new JSONObject().element( "value", 0 ) .element( "child", new JSONObject().element( "value", 0 ) ); Assertions.assertEquals( expected, actual ); } public void testCycleDetection_beans_null() { jsonConfig.setCycleDetectionStrategy( CycleDetectionStrategy.LENIENT ); ParentBean parent = new ParentBean(); parent.setChild( new ChildBean() ); JSONObject actual = JSONObject.fromObject( parent, jsonConfig ); JSONObject expected = new JSONObject().element( "value", 0 ) .element( "child", new JSONObject().element( "value", 0 ) .element( "parent", new JSONObject( true ) ) ); Assertions.assertEquals( expected, actual ); } public void testCycleDetection_beans_strict() { ParentBean parent = new ParentBean(); parent.setChild( new ChildBean() ); try{ JSONObject.fromObject( parent ); fail( "A JSONException was expected" ); }catch( JSONException expected ){ assertTrue( expected.getMessage() .endsWith( "There is a cycle in the hierarchy!" ) ); } } public void testDiscard() { JSONObject jsonObject = new JSONObject().element( "int", "1" ) .element( "long", "1" ) .element( "boolean", "true" ) .element( "string", "string" ) .element( "func", "function(){ return this; }" ) .element( "array", "[1,2,3]" ); assertEquals( 6, jsonObject.size() ); jsonObject.discard( "int" ) .discard( "func" ); assertEquals( 4, jsonObject.size() ); assertFalse( jsonObject.has( "int" ) ); assertFalse( jsonObject.has( "func" ) ); } public void testElement__duplicateProperty() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "duplicated", "json1" ); jsonObject.element( "duplicated", "json2" ); Object o = jsonObject.get( "duplicated" ); assertFalse( o instanceof JSONArray ); assertEquals( "json2", o ); } public void testElement__duplicateProperty_2() { JSONObject jsonObject = JSONObject.fromObject( "{'duplicated':'json1','duplicated':'json2'}" ); Object o = jsonObject.get( "duplicated" ); assertTrue( o instanceof JSONArray ); assertEquals( new JSONArray().element( "json1" ) .element( "json2" ), o ); } public void testElement_Bean() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "bean", new ObjectBean() ); JSONObject actual = jsonObject.getJSONObject( "bean" ); Assertions.assertTrue( !actual.has( "class" ) ); } public void testElement_Bean_exclusions() { JSONObject jsonObject = new JSONObject(); jsonConfig.setExcludes( new String[] { "pexcluded" } ); jsonObject.element( "bean", new ObjectBean(), jsonConfig ); JSONObject actual = jsonObject.getJSONObject( "bean" ); Assertions.assertTrue( !actual.has( "class" ) ); Assertions.assertTrue( !actual.has( "pexcluded" ) ); } public void testElement_Bean_exclusions_ignoreDefault() { JSONObject jsonObject = new JSONObject(); jsonConfig.setExcludes( new String[] { "pexcluded" } ); jsonConfig.setIgnoreDefaultExcludes( true ); jsonObject.element( "bean", new ObjectBean(), jsonConfig ); JSONObject actual = jsonObject.getJSONObject( "bean" ); Assertions.assertTrue( actual.has( "class" ) ); Assertions.assertTrue( !actual.has( "pexcluded" ) ); } public void testElement_boolean() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "bool", true ); assertTrue( jsonObject.getBoolean( "bool" ) ); } public void testElement_Boolean() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "bool", Boolean.TRUE ); Assertions.assertTrue( jsonObject.getBoolean( "bool" ) ); } public void testElement_Class() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "class", Object.class ); assertEquals( "java.lang.Object", jsonObject.get( "class" ) ); } public void testElement_Collection() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "list", Collections.EMPTY_LIST ); Assertions.assertEquals( new JSONArray(), jsonObject.getJSONArray( "list" ) ); } public void testElement_Collection2() { List list = new ArrayList(); list.add( new ObjectBean() ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "list", list ); JSONObject actual = jsonObject.getJSONArray( "list" ) .getJSONObject( 0 ); Assertions.assertTrue( !actual.has( "class" ) ); } public void testElement_Collection2_exclusions() { List list = new ArrayList(); list.add( new ObjectBean() ); JSONObject jsonObject = new JSONObject(); jsonConfig.setExcludes( new String[] { "pexcluded" } ); jsonObject.element( "list", list, jsonConfig ); JSONObject actual = jsonObject.getJSONArray( "list" ) .getJSONObject( 0 ); Assertions.assertTrue( !actual.has( "class" ) ); Assertions.assertTrue( !actual.has( "pexcluded" ) ); } public void testElement_Collection2_exclusions_ignoreDefault() { List list = new ArrayList(); list.add( new ObjectBean() ); jsonConfig.setExcludes( new String[] { "pexcluded" } ); jsonConfig.setIgnoreDefaultExcludes( true ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "list", list, jsonConfig ); JSONObject actual = jsonObject.getJSONArray( "list" ) .getJSONObject( 0 ); Assertions.assertTrue( actual.has( "class" ) ); Assertions.assertTrue( !actual.has( "pexcluded" ) ); } public void testElement_double() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "double", 1d ); assertEquals( 1d, jsonObject.getDouble( "double" ), 0d ); } public void testElement_int() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "int", 1 ); assertEquals( 1, jsonObject.getInt( "int" ) ); } public void testElement_JSON() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "null", JSONNull.getInstance() ); Assertions.assertEquals( JSONNull.getInstance(), jsonObject.get( "null" ) ); } public void testElement_JSONFunction() { JSONObject jsonObject = new JSONObject(); JSONFunction f = new JSONFunction( "return this;" ); jsonObject.element( "func", f ); Assertions.assertEquals( f, (JSONFunction) jsonObject.get( "func" ) ); } public void testElement_JSONString() { JSONObject jsonObject = new JSONObject(); ObjectJSONStringBean bean = new ObjectJSONStringBean(); bean.setName( "json" ); jsonObject.element( "bean", bean ); Assertions.assertEquals( JSONObject.fromObject( bean ), jsonObject.getJSONObject( "bean" ) ); } public void testElement_JSONTokener() { JSONObject jsonObject = new JSONObject(); JSONTokener tok = new JSONTokener( "{'name':'json'}" ); jsonObject.element( "obj", tok ); tok.reset(); Assertions.assertEquals( JSONObject.fromObject( tok ), jsonObject.getJSONObject( "obj" ) ); } public void testElement_long() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "long", 1L ); assertEquals( 1L, jsonObject.getLong( "long" ) ); } public void testElement_Map() { Map map = new HashMap(); map.put( "name", "json" ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "map", map ); Assertions.assertEquals( JSONObject.fromObject( map ), jsonObject.getJSONObject( "map" ) ); } public void testElement_Map2() { Map map = new HashMap(); map.put( "name", "json" ); map.put( "class", "java.lang.Object" ); map.put( "excluded", "excluded" ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "map", map ); JSONObject actual = jsonObject.getJSONObject( "map" ); Assertions.assertTrue( !actual.has( "class" ) ); } public void testElement_Map2_exclusions() { Map map = new HashMap(); map.put( "name", "json" ); map.put( "class", "java.lang.Object" ); map.put( "pexcluded", "excluded" ); jsonConfig.setExcludes( new String[] { "pexcluded" } ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "map", map, jsonConfig ); JSONObject actual = jsonObject.getJSONObject( "map" ); Assertions.assertTrue( !actual.has( "class" ) ); Assertions.assertTrue( !actual.has( "pexcluded" ) ); } public void testElement_Map2_exclusions_ignoreDefault() { Map map = new HashMap(); map.put( "name", "json" ); map.put( "class", "java.lang.Object" ); map.put( "pexcluded", "excluded" ); jsonConfig.setExcludes( new String[] { "pexcluded" } ); jsonConfig.setIgnoreDefaultExcludes( true ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "map", map, jsonConfig ); JSONObject actual = jsonObject.getJSONObject( "map" ); Assertions.assertTrue( actual.has( "class" ) ); Assertions.assertTrue( !actual.has( "pexcluded" ) ); } public void testElement_null_key() { try{ new JSONObject().element( null, "value" ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // ok } } public void testElement_Number() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "num", new Double( 2 ) ); Assertions.assertEquals( new Double( 2 ).doubleValue(), jsonObject.getDouble( "num" ), 0d ); } public void testElement_Object() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "bean", new BeanA() ); Assertions.assertEquals( JSONObject.fromObject( new BeanA() ), jsonObject.getJSONObject( "bean" ) ); } public void testElement_String() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "str", "json" ); Assertions.assertEquals( "json", jsonObject.getString( "str" ) ); } public void testElement_String_JSON() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "str", "[]" ); Assertions.assertEquals( new JSONArray().toString(), jsonObject.getString( "str" ) ); } public void testElement_String_null() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "str", (String) null ); // special case, if value null, there is no value associated to key try{ jsonObject.getString( "str" ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // ok } } public void testFromBean_array() { try{ JSONObject.fromObject( new ArrayList() ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } try{ JSONObject.fromObject( new String[] { "json" } ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testFromBean_ClassBean() { ClassBean classBean = new ClassBean(); classBean.setKlass( Object.class ); JSONObject json = JSONObject.fromObject( classBean ); assertEquals( "java.lang.Object", json.get( "klass" ) ); } public void testFromBean_DynaBean() throws Exception { JSONObject json = JSONObject.fromObject( createDynaBean() ); assertEquals( "json", json.getString( "name" ) ); Assertions.assertEquals( "[1,2]", json.getString( "str" ) ); Assertions.assertEquals( JSONObject.fromObject( "{'id':'1'}" ), json.getJSONObject( "json" ) ); Assertions.assertEquals( JSONObject.fromObject( "{'name':''}" ), json.getJSONObject( "jsonstr" ) ); Assertions.assertEquals( "function(){ return this; }", (JSONFunction) json.get( "func" ) ); } public void testFromBean_JSONObject() { JSONObject json = new JSONObject(); json.element( "name", "json" ); Assertions.assertEquals( json, JSONObject.fromObject( json ) ); } public void testFromBean_JSONString() { ObjectJSONStringBean bean = new ObjectJSONStringBean(); bean.setId( 1 ); bean.setName( "json" ); JSONObject json = JSONObject.fromObject( bean ); assertEquals( "json", json.getString( "name" ) ); assertTrue( !json.has( "id" ) ); } public void testFromBean_JSONTokener() { JSONTokener jsonTokener = new JSONTokener( "{\"string\":\"json\"}" ); JSONObject json = JSONObject.fromObject( jsonTokener ); assertEquals( "json", json.getString( "string" ) ); } public void testFromBean_Map() { Map map = new HashMap(); map.put( "bool", Boolean.TRUE ); map.put( "integer", new Integer( 42 ) ); map.put( "string", "json" ); JSONObject json = JSONObject.fromObject( map ); assertEquals( true, json.getBoolean( "bool" ) ); assertEquals( 42, json.getInt( "integer" ) ); assertEquals( "json", json.getString( "string" ) ); } public void testFromBean_noReadMethod() { JSONObject json = JSONObject.fromObject( new PropertyBean() ); assertTrue( json.has( "propertyWithNoWriteMethod" ) ); assertTrue( !json.has( "propertyWithNoReadMethod" ) ); } public void testFromBean_null() { JSONObject json = JSONObject.fromObject( null ); assertTrue( json.isNullObject() ); assertEquals( JSONNull.getInstance() .toString(), json.toString() ); } public void testFromBean_String() { JSONObject json = JSONObject.fromObject( "{\"string\":\"json\"}" ); assertEquals( "json", json.getString( "string" ) ); } public void testFromBean_use_wrappers() { JSONObject json = JSONObject.fromObject( Boolean.TRUE ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Byte( Byte.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Short( Short.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Integer( Integer.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Long( Long.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Float( Float.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Double( Double.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Character( 'A' ) ); assertTrue( json.isEmpty() ); } public void testFromBeanWithJsonPropertyNameProcessor(){ JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonPropertyNameProcessor( BeanA.class, new PrefixerPropertyNameProcessor("json") ); JSONObject jsonObject = JSONObject.fromObject( new BeanA(), jsonConfig ); assertNotNull( jsonObject ); assertEquals( 3, jsonObject.names().size() ); assertTrue( jsonObject.has( "jsonbool" ) ); assertTrue( jsonObject.has( "jsonstring" ) ); assertTrue( jsonObject.has( "jsoninteger" ) ); } public void testFromDynaBean_full() throws Exception { Map properties = new HashMap(); properties.put( "string", String.class ); properties.put( "number", Integer.class ); properties.put( "array", Object[].class ); properties.put( "list", List.class ); properties.put( "func", JSONFunction.class ); properties.put( "boolean", Boolean.class ); properties.put( "bean", BeanA.class ); MorphDynaClass dynaClass = new MorphDynaClass( "JSON", MorphDynaBean.class, properties ); MorphDynaBean dynaBean = (MorphDynaBean) dynaClass.newInstance(); dynaBean.setDynaBeanClass( dynaClass ); dynaBean.set( "string", "json" ); dynaBean.set( "number", new Double( 2 ) ); dynaBean.set( "array", new Integer[] { new Integer( 1 ), new Integer( 2 ) } ); dynaBean.set( "list", new ArrayList() ); dynaBean.set( "func", new JSONFunction( new String[] { "a" }, "return a;" ) ); dynaBean.set( "boolean", Boolean.TRUE ); dynaBean.set( "bean", new BeanA() ); JSONObject jsonObject = JSONObject.fromObject( dynaBean ); assertEquals( "json", jsonObject.get( "string" ) ); assertEquals( new Double( 2 ), jsonObject.get( "number" ) ); assertEquals( Boolean.TRUE, jsonObject.get( "boolean" ) ); Assertions.assertEquals( "function(a){ return a; }", (JSONFunction) jsonObject.get( "func" ) ); } public void testFromDynaBean_null() { JSONObject jsonObject = JSONObject.fromObject( null ); assertTrue( jsonObject.isNullObject() ); } public void testFromJSONTokener() { JSONTokener jsonTokener = new JSONTokener( "{\"string\":\"json\"}" ); JSONObject json = JSONObject.fromObject( jsonTokener ); assertEquals( "json", json.getString( "string" ) ); } public void testFromMap_nested_null_object() { Map map = new HashMap(); map.put( "nested", null ); map.put( "string", "json" ); JSONObject json = JSONObject.fromObject( map ); assertEquals( "json", json.getString( "string" ) ); Object nested = json.get( "nested" ); assertTrue( JSONUtils.isNull( nested ) ); } public void testFromMap_null_Map() { JSONObject json = JSONObject.fromObject( null ); assertTrue( json.isNullObject() ); assertEquals( JSONNull.getInstance() .toString(), json.toString() ); } public void testFromObject_array() { try{ JSONObject.fromObject( new ArrayList() ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } try{ JSONObject.fromObject( new String[] { "json" } ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testFromObject_Bean() { JSONObject json = JSONObject.fromObject( new BeanA() ); assertEquals( true, json.getBoolean( "bool" ) ); assertEquals( 42, json.getInt( "integer" ) ); assertEquals( "json", json.getString( "string" ) ); } public void testFromObject_BeanWithFunc() { JSONObject json = JSONObject.fromObject( new BeanWithFunc( "return a;" ) ); assertNotNull( json.get( "function" ) ); assertTrue( JSONUtils.isFunction( json.get( "function" ) ) ); assertEquals( "function(){ return a; }", json.get( "function" ) .toString() ); } public void testFromObject_DynaBean() throws Exception { JSONObject json = JSONObject.fromObject( createDynaBean() ); assertEquals( "json", json.getString( "name" ) ); } public void testFromObject_emptyBean() { EmptyBean bean = new EmptyBean(); JSONObject json = JSONObject.fromObject( bean ); JSONObject expected = new JSONObject(); expected.element( "arrayp", new JSONArray() ); expected.element( "listp", new JSONArray() ); expected.element( "bytep", new Integer( 0 ) ); expected.element( "shortp", new Integer( 0 ) ); expected.element( "intp", new Integer( 0 ) ); expected.element( "longp", new Integer( 0 ) ); expected.element( "floatp", new Integer( 0 ) ); expected.element( "doublep", new Double( 0 ) ); expected.element( "charp", "" ); expected.element( "stringp", "" ); Assertions.assertEquals( expected, json ); } public void testFromObject_ExtendedBean() { JSONObject json = JSONObject.fromObject( new BeanB() ); assertEquals( true, json.getBoolean( "bool" ) ); assertEquals( 42, json.getInt( "integer" ) ); assertEquals( "json", json.getString( "string" ) ); assertNotNull( json.get( "intarray" ) ); } public void testFromObject_ignoreTransientFields() { jsonConfig.setIgnoreTransientFields( true ); TransientBean bean = new TransientBean(); bean.setValue( 42 ); bean.setTransientValue( 84 ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertTrue( jsonObject.has( "value" ) ); assertFalse( jsonObject.has( "transientValue" ) ); } public void testFromObject_JSONObject() { JSONObject expected = new JSONObject().element( "id", "1" ) .element( "name", "json" ); JSONObject actual = JSONObject.fromObject( expected ); Assertions.assertEquals( expected, actual ); } public void testFromObject_JSONString() { ObjectJSONStringBean bean = new ObjectJSONStringBean(); bean.setId( 1 ); bean.setName( "json" ); JSONObject json = JSONObject.fromObject( bean ); assertEquals( "json", json.getString( "name" ) ); assertTrue( !json.has( "id" ) ); } public void testFromObject_JSONTokener() { JSONTokener jsonTokener = new JSONTokener( "{\"string\":\"json\"}" ); JSONObject json = JSONObject.fromObject( jsonTokener ); assertEquals( "json", json.getString( "string" ) ); } public void testFromObject_Map() { Map map = new HashMap(); map.put( "bool", Boolean.TRUE ); map.put( "integer", new Integer( 42 ) ); map.put( "string", "json" ); map.put( "array", JSONArray.fromObject( "[1]" ) ); map.put( "object", JSONObject.fromObject( "{\"name\":\"json\"}" ) ); JSONObject json = JSONObject.fromObject( map ); assertEquals( true, json.getBoolean( "bool" ) ); assertEquals( 42, json.getInt( "integer" ) ); assertEquals( "json", json.getString( "string" ) ); Assertions.assertEquals( JSONArray.fromObject( "[1]" ), json.getJSONArray( "array" ) ); Assertions.assertEquals( JSONObject.fromObject( "{\"name\":\"json\"}" ), json.getJSONObject( "object" ) ); } public void testFromObject_nested_bean() { JSONObject json = JSONObject.fromObject( new BeanC() ); assertNotNull( json.get( "beanA" ) ); assertNotNull( json.get( "beanB" ) ); } public void testFromObject_null() { JSONObject json = JSONObject.fromObject( null ); assertTrue( json.isNullObject() ); assertEquals( JSONNull.getInstance() .toString(), json.toString() ); } public void testFromObject_ObjectBean() { // FR 1611204 ObjectBean bean = new ObjectBean(); bean.setPbyte( Byte.valueOf( "1" ) ); bean.setPshort( Short.valueOf( "1" ) ); bean.setPint( Integer.valueOf( "1" ) ); bean.setPlong( Long.valueOf( "1" ) ); bean.setPfloat( Float.valueOf( "1" ) ); bean.setPdouble( Double.valueOf( "1" ) ); bean.setPchar( new Character( '1' ) ); bean.setPboolean( Boolean.TRUE ); bean.setPstring( "json" ); bean.setParray( new String[] { "a", "b" } ); bean.setPbean( new BeanA() ); List list = new ArrayList(); list.add( "1" ); list.add( "2" ); bean.setPlist( list ); Map map = new HashMap(); map.put( "string", "json" ); bean.setPmap( map ); bean.setPfunction( new JSONFunction( "this;" ) ); JSONObject json = JSONObject.fromObject( bean ); assertEquals( 1, json.getInt( "pbyte" ) ); assertEquals( 1, json.getInt( "pshort" ) ); assertEquals( 1, json.getInt( "pint" ) ); assertEquals( 1, json.getInt( "plong" ) ); assertEquals( 1d, json.getDouble( "pfloat" ), 0d ); assertEquals( 1d, json.getDouble( "pdouble" ), 0d ); assertTrue( json.getBoolean( "pboolean" ) ); assertEquals( "json", json.get( "pstring" ) ); Assertions.assertEquals( JSONArray.fromObject( "['a','b']" ), json.getJSONArray( "parray" ) ); Assertions.assertEquals( JSONArray.fromObject( "['1','2']" ), json.getJSONArray( "plist" ) ); assertEquals( "1", json.getString( "pchar" ) ); JSONObject b = new JSONObject().element( "string", "json" ) .element( "integer", "42" ) .element( "bool", "true" ); Assertions.assertEquals( b, json.getJSONObject( "pbean" ) ); b = new JSONObject().element( "string", "json" ); Assertions.assertEquals( b, json.getJSONObject( "pmap" ) ); } public void testFromObject_ObjectBean_empty() { // FR 1611204 ObjectBean bean = new ObjectBean(); JSONObject json = JSONObject.fromObject( bean ); String[] keys = { "pbyte", "pshort", "pint", "plong", "pfloat", "pdouble", "pboolean", "pchar", "pstring", "parray", "plist", "pmap", "pbean" }; for( int i = 0; i < keys.length; i++ ){ assertTrue( JSONNull.getInstance() .equals( json.get( keys[i] ) ) ); } } public void testFromObject_String() { JSONObject json = JSONObject.fromObject( "{\"string\":\"json\"}" ); assertEquals( "json", json.getString( "string" ) ); } public void testFromObject_toBean_DynaBean() { // bug report 1540137 String jsondata = "{\"person\":{\"phone\":[\"111-222-3333\",\"777-888-9999\"]," + "\"address\":{\"street\":\"123 somewhere place\",\"zip\":\"30005\",\"city\":\"Alpharetta\"}," + "\"email\":[\"allen@work.com\",\"allen@home.net\"],\"name\":\"Allen\"}}"; JSONObject jsonobj = JSONObject.fromObject( jsondata ); Object bean = JSONObject.toBean( jsonobj ); // bean is a DynaBean assertTrue( bean instanceof MorphDynaBean ); // convert the DynaBean to a JSONObject again JSONObject jsonobj2 = JSONObject.fromObject( bean ); assertNotNull( jsonobj.getJSONObject( "person" ) ); assertFalse( JSONUtils.isNull( jsonobj.getJSONObject( "person" ) ) ); assertNotNull( jsonobj2.getJSONObject( "person" ) ); assertFalse( JSONUtils.isNull( jsonobj2.getJSONObject( "person" ) ) ); JSONObject person1 = jsonobj.getJSONObject( "person" ); JSONObject person2 = jsonobj2.getJSONObject( "person" ); assertEquals( person1.get( "name" ), person2.get( "name" ) ); assertEquals( person1.get( "phone" ) .toString(), person2.get( "phone" ) .toString() ); assertEquals( person1.get( "email" ) .toString(), person2.get( "email" ) .toString() ); JSONObject address1 = person1.getJSONObject( "address" ); JSONObject address2 = person2.getJSONObject( "address" ); assertEquals( address1.get( "street" ), address2.get( "street" ) ); assertEquals( address1.get( "zip" ), address2.get( "zip" ) ); assertEquals( address1.get( "city" ), address2.get( "city" ) ); } public void testFromObject_use_wrappers() { JSONObject json = JSONObject.fromObject( Boolean.TRUE ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Byte( Byte.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Short( Short.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Integer( Integer.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Long( Long.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Float( Float.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Double( Double.MIN_VALUE ) ); assertTrue( json.isEmpty() ); json = JSONObject.fromObject( new Character( 'A' ) ); assertTrue( json.isEmpty() ); } public void testFromObject_withCustomDefaultValueProcessor() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerDefaultValueProcessor( Integer.class, new NumberDefaultValueProcessor() ); JSONObject jsonObject = JSONObject.fromObject( new NumberBean(), jsonConfig ); assertNotNull( jsonObject ); assertEquals( new Integer( 0 ), jsonObject.get( "pwbyte" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pwshort" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pwint" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pwlong" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pwfloat" ) ); assertEquals( new Double( 0 ), jsonObject.get( "pwdouble" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pbigdec" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pbigint" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pbyte" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pshort" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pint" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "plong" ) ); assertEquals( new Double( 0 ), jsonObject.get( "pfloat" ) ); assertEquals( new Double( 0 ), jsonObject.get( "pdouble" ) ); } public void testFromObject_withCustomDefaultValueProcessor_andMatcher() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerDefaultValueProcessor( Integer.class, new NumberDefaultValueProcessor() ); jsonConfig.setDefaultValueProcessorMatcher( new NumberDefaultValueProcessorMatcher() ); JSONObject jsonObject = JSONObject.fromObject( new NumberBean(), jsonConfig ); assertNotNull( jsonObject ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pbigdec" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pbigint" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pwbyte" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pwshort" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pwint" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pwlong" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pwfloat" ) ); assertEquals( NumberDefaultValueProcessor.NUMBER, jsonObject.get( "pwdouble" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pbyte" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pshort" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "pint" ) ); assertEquals( new Integer( 0 ), jsonObject.get( "plong" ) ); assertEquals( new Double( 0 ), jsonObject.get( "pfloat" ) ); assertEquals( new Double( 0 ), jsonObject.get( "pdouble" ) ); } public void testFromObject_withExcludesPerClass() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerPropertyExclusion( BeanA.class, "bool" ); JSONObject jsonA = JSONObject.fromObject( new BeanA(), jsonConfig ); JSONObject jsonB = JSONObject.fromObject( new BeanB(), jsonConfig ); assertNotNull( jsonA ); assertNotNull( jsonB ); assertFalse( jsonA.has("bool") ); assertTrue( jsonB.has("bool") ); } public void testFromObject_withExcludesPerClassAndMatcher() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerPropertyExclusion( BeanA.class, "bool" ); jsonConfig.setPropertyExclusionClassMatcher( new BeanAPropertyExclusionClassMatcher() ); JSONObject jsonA = JSONObject.fromObject( new BeanA(), jsonConfig ); JSONObject jsonB = JSONObject.fromObject( new BeanB(), jsonConfig ); assertNotNull( jsonA ); assertNotNull( jsonB ); assertFalse( jsonA.has("bool") ); assertFalse( jsonB.has("bool") ); } public void testFromObject_withFilters() { PrimitiveBean bean = new PrimitiveBean(); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter( new NumberPropertyFilter() ); JSONObject json = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( json ); assertTrue( json.has( "pbean" ) ); assertTrue( json.has( "pclass" ) ); assertTrue( json.has( "pexcluded" ) ); assertTrue( json.has( "pfunction" ) ); assertTrue( json.has( "plist" ) ); assertTrue( json.has( "pmap" ) ); assertTrue( json.has( "pstring" ) ); assertTrue( json.has( "parray" ) ); assertTrue( json.has( "pboolean" ) ); assertTrue( !json.has( "pbyte" ) ); assertTrue( !json.has( "pshort" ) ); assertTrue( !json.has( "pint" ) ); assertTrue( !json.has( "plong" ) ); assertTrue( !json.has( "pfloat" ) ); assertTrue( !json.has( "pdouble" ) ); assertTrue( json.has( "pchar" ) ); } public void testFromObject_withFiltersAndExcludes() { PrimitiveBean bean = new PrimitiveBean(); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter( new NumberPropertyFilter() ); jsonConfig.setExcludes( new String[] { "pexcluded" } ); JSONObject json = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( json ); assertTrue( json.has( "pbean" ) ); assertTrue( json.has( "pclass" ) ); assertTrue( !json.has( "pexcluded" ) ); assertTrue( json.has( "pfunction" ) ); assertTrue( json.has( "plist" ) ); assertTrue( json.has( "pmap" ) ); assertTrue( json.has( "pstring" ) ); assertTrue( json.has( "parray" ) ); assertTrue( json.has( "pboolean" ) ); assertTrue( !json.has( "pbyte" ) ); assertTrue( !json.has( "pshort" ) ); assertTrue( !json.has( "pint" ) ); assertTrue( !json.has( "plong" ) ); assertTrue( !json.has( "pfloat" ) ); assertTrue( !json.has( "pdouble" ) ); assertTrue( json.has( "pchar" ) ); } public void testFromString_null_String() { JSONObject json = JSONObject.fromObject( null ); assertTrue( json.isNullObject() ); assertEquals( JSONNull.getInstance() .toString(), json.toString() ); } public void testHas() { assertFalse( new JSONObject().has( "any" ) ); assertTrue( new JSONObject().element( "any", "value" ) .has( "any" ) ); } public void testLength() { assertEquals( 0, new JSONObject().size() ); } public void testLength_nullObject() { /* try{ new JSONObject( true ).size(); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // ok } */ assertEquals( 0, new JSONObject(true).size() ); } public void testOptBoolean() { assertFalse( new JSONObject().optBoolean( "any" ) ); } public void testOptBoolean_defaultValue() { assertTrue( new JSONObject().optBoolean( "any", true ) ); } public void testOptDouble() { assertTrue( Double.isNaN( new JSONObject().optDouble( "any" ) ) ); } public void testOptDouble_defaultValue() { assertEquals( 2d, new JSONObject().optDouble( "any", 2d ), 0d ); } public void testOptInt() { assertEquals( 0, new JSONObject().optInt( "any" ) ); } public void testOptInt_defaultValue() { assertEquals( 1, new JSONObject().optInt( "any", 1 ) ); } public void testOptJSONArray() { JSONObject json = new JSONObject(); assertNull( json.optJSONArray( "a" ) ); json.element( "a", new JSONArray() ); Assertions.assertEquals( new JSONArray(), json.optJSONArray( "a" ) ); } public void testOptJSONObject() { JSONObject json = new JSONObject(); assertNull( json.optJSONObject( "a" ) ); json.element( "a", new JSONObject() ); Assertions.assertEquals( new JSONObject(), json.optJSONObject( "a" ) ); } public void testOptLong() { assertEquals( 0L, new JSONObject().optLong( "any" ) ); } public void testOptLong_defaultValue() { assertEquals( 1L, new JSONObject().optLong( "any", 1L ) ); } public void testOptString() { assertEquals( "", new JSONObject().optString( "any" ) ); } public void testOptString_defaultValue() { assertEquals( "json", new JSONObject().optString( "any", "json" ) ); } public void testToBean() throws Exception { String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}"; JSONObject jsonObject = JSONObject.fromObject( json ); Object bean = JSONObject.toBean( jsonObject ); assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) ); assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) ); assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) ); assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) ); assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) ); List expected = (List) JSONArray.toCollection( jsonObject.getJSONArray( "array" ) ); Assertions.assertEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) ); } public void testToBean_BeanA() { String json = "{bool:true,integer:1,string:\"json\"}"; JSONObject jsonObject = JSONObject.fromObject( json ); BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class ); assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) ); assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) ); assertEquals( jsonObject.get( "string" ), bean.getString() ); } public void testToBean_BeanB() { String json = "{bool:true,integer:1,string:\"json\",intarray:[4,5,6]}"; JSONObject jsonObject = JSONObject.fromObject( json ); BeanB bean = (BeanB) JSONObject.toBean( jsonObject, BeanB.class ); assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) ); assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) ); assertEquals( jsonObject.get( "string" ), bean.getString() ); Assertions.assertEquals( bean.getIntarray(), JSONArray.toArray( jsonObject.getJSONArray( "intarray" ) ) ); } public void testToBean_ClassBean() { JSONObject json = new JSONObject(); json.element( "klass", "java.lang.Object" ); ClassBean bean = (ClassBean) JSONObject.toBean( json, ClassBean.class ); assertEquals( Object.class, bean.getKlass() ); } public void testToBean_DynaBean__BigInteger_BigDecimal() { BigInteger l = new BigDecimal( "1.7976931348623157E308" ).toBigInteger(); BigDecimal m = new BigDecimal( "1.7976931348623157E307" ).add( new BigDecimal( "0.0001" ) ); JSONObject json = new JSONObject().element( "i", BigInteger.ZERO ) .element( "d", MorphUtils.BIGDECIMAL_ONE ) .element( "bi", l ) .element( "bd", m ); Object bean = JSONObject.toBean( json ); Object i = ((MorphDynaBean) bean).get( "i" ); Object d = ((MorphDynaBean) bean).get( "d" ); assertTrue( i instanceof Integer ); assertTrue( d instanceof Integer ); Object bi = ((MorphDynaBean) bean).get( "bi" ); Object bd = ((MorphDynaBean) bean).get( "bd" ); assertTrue( bi instanceof BigInteger ); assertTrue( bd instanceof BigDecimal ); } public void testToBean_emptyBean() { EmptyBean bean = new EmptyBean(); JSONObject json = JSONObject.fromObject( bean ); JSONObject expected = new JSONObject(); expected.element( "arrayp", new JSONArray() ); expected.element( "listp", new JSONArray() ); expected.element( "bytep", new Integer( 0 ) ); expected.element( "shortp", new Integer( 0 ) ); expected.element( "intp", new Integer( 0 ) ); expected.element( "longp", new Integer( 0 ) ); expected.element( "floatp", new Integer( 0 ) ); expected.element( "doublep", new Double( 0 ) ); expected.element( "charp", "" ); expected.element( "stringp", "" ); Assertions.assertEquals( expected, json ); EmptyBean bean2 = (EmptyBean) JSONObject.toBean( json, EmptyBean.class ); ArrayAssertions.assertEquals( new Object[0], bean2.getArrayp() ); Assertions.assertEquals( new ArrayList(), bean2.getListp() ); Assertions.assertEquals( new Byte( (byte) 0 ), bean2.getBytep() ); Assertions.assertEquals( new Short( (short) 0 ), bean2.getShortp() ); Assertions.assertEquals( new Integer( 0 ), bean2.getIntp() ); Assertions.assertEquals( new Long( 0 ), bean2.getLongp() ); Assertions.assertEquals( new Float( 0 ), bean2.getFloatp() ); Assertions.assertEquals( new Double( 0 ), bean2.getDoublep() ); Assertions.assertEquals( new Character( '\0' ), bean2.getCharp() ); Assertions.assertEquals( "", bean2.getStringp() ); } public void testToBean_interface() { // BUG 1542104 try{ JSONObject.toBean( JSONObject.fromObject( "{\"int\":1}" ), Serializable.class ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // ok } } public void testToBean_Map() { // BUG 1542104 Map map = new HashMap(); map.put( "name", "json" ); Object obj = JSONObject.toBean( JSONObject.fromObject( map ), Map.class ); assertTrue( obj instanceof Map ); assertEquals( map.get( "name" ), ((Map) obj).get( "name" ) ); } public void testToBean_nested() throws Exception { String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },nested:{nested:true}}"; JSONObject jsonObject = JSONObject.fromObject( json ); Object bean = JSONObject.toBean( jsonObject ); assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) ); assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) ); assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) ); assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) ); assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) ); JSONObject nestedJson = jsonObject.getJSONObject( "nested" ); Object nestedBean = PropertyUtils.getProperty( bean, "nested" ); assertEquals( nestedJson.get( "nested" ), PropertyUtils.getProperty( nestedBean, "nested" ) ); } public void testToBean_nested_beans__null_object() throws Exception { // BUG 1553617 String json = "{\"beanA\":{bool:true,integer:1,string:\"jsonbean\"},\"beanB\":null}"; JSONObject jsonObject = JSONObject.fromObject( json ); BeanC bean = (BeanC) JSONObject.toBean( jsonObject, BeanC.class ); assertNotNull( bean ); BeanA beanA = bean.getBeanA(); assertNotNull( beanA ); assertEquals( true, beanA.isBool() ); assertEquals( 1, beanA.getInteger() ); assertEquals( "jsonbean", beanA.getString() ); BeanB beanB = bean.getBeanB(); assertNull( beanB ); } public void testToBean_nested_beans_in_list__beans() { // BUG 1592799 ListingBean listingBean = new ListingBean(); ValueBean beanA1 = new ValueBean(); beanA1.setValue( 90000 ); ValueBean beanA2 = new ValueBean(); beanA2.setValue( 91000 ); listingBean.addAttribute( beanA1 ); listingBean.addAttribute( beanA2 ); JSONObject jsonObject = JSONObject.fromObject( listingBean ); Map classMap = new HashMap(); classMap.put( "attributes", ValueBean.class ); ListingBean listingBean2 = (ListingBean) JSONObject.toBean( jsonObject, ListingBean.class, classMap ); List attributes = listingBean2.getAttributes(); Object ba = attributes.get( 0 ); Object bb = attributes.get( 1 ); assertTrue( ba instanceof ValueBean ); assertTrue( bb instanceof ValueBean ); assertEquals( beanA1.getValue(), ((ValueBean) ba).getValue() ); assertEquals( beanA2.getValue(), ((ValueBean) bb).getValue() ); } public void testToBean_nested_beans_in_list__DynaBean() { // BUG 1592799 ListingBean listingBean = new ListingBean(); ValueBean beanA1 = new ValueBean(); beanA1.setValue( 90000 ); ValueBean beanA2 = new ValueBean(); beanA2.setValue( 91000 ); listingBean.addAttribute( beanA1 ); listingBean.addAttribute( beanA2 ); JSONObject jsonObject = JSONObject.fromObject( listingBean ); ListingBean listingBean2 = (ListingBean) JSONObject.toBean( jsonObject, ListingBean.class ); List attributes = listingBean2.getAttributes(); Object ba = attributes.get( 0 ); Object bb = attributes.get( 1 ); assertTrue( ba instanceof MorphDynaBean ); assertTrue( bb instanceof MorphDynaBean ); assertEquals( new Integer( beanA1.getValue() ), ((MorphDynaBean) ba).get( "value" ) ); assertEquals( new Integer( beanA2.getValue() ), ((MorphDynaBean) bb).get( "value" ) ); } public void testToBean_nested_beans_in_map__beans() { // BUG 1542092 MappingBean mappingBean = new MappingBean(); ValueBean beanA = new ValueBean(); beanA.setValue( 90000 ); ValueBean beanB = new ValueBean(); beanB.setValue( 91000 ); mappingBean.addAttribute( "beanA", beanA ); mappingBean.addAttribute( "beanB", beanB ); JSONObject jsonObject = JSONObject.fromObject( mappingBean ); Map classMap = new HashMap(); classMap.put( "bean.*", ValueBean.class ); MappingBean mappingBean2 = (MappingBean) JSONObject.toBean( jsonObject, MappingBean.class, classMap ); Object ba = mappingBean2.getAttributes() .get( "beanA" ); Object bb = mappingBean2.getAttributes() .get( "beanB" ); assertTrue( ba instanceof ValueBean ); assertTrue( bb instanceof ValueBean ); assertEquals( beanA.getValue(), ((ValueBean) ba).getValue() ); assertEquals( beanB.getValue(), ((ValueBean) bb).getValue() ); } public void testToBean_nested_beans_in_map__DynaBean() { // BUG 1542092 MappingBean mappingBean = new MappingBean(); ValueBean beanA = new ValueBean(); beanA.setValue( 90000 ); ValueBean beanB = new ValueBean(); beanB.setValue( 91000 ); mappingBean.addAttribute( "beanA", beanA ); mappingBean.addAttribute( "beanB", beanB ); JSONObject jsonObject = JSONObject.fromObject( mappingBean ); MappingBean mappingBean2 = (MappingBean) JSONObject.toBean( jsonObject, MappingBean.class ); Object ba = mappingBean2.getAttributes() .get( "beanA" ); Object bb = mappingBean2.getAttributes() .get( "beanB" ); assertTrue( ba instanceof MorphDynaBean ); assertTrue( bb instanceof MorphDynaBean ); assertEquals( new Integer( beanA.getValue() ), ((MorphDynaBean) ba).get( "value" ) ); assertEquals( new Integer( beanB.getValue() ), ((MorphDynaBean) bb).get( "value" ) ); } public void testToBean_nested_beans_in_set__beans() { // FR 1847116 SetBean setBean = new SetBean(); ValueBean beanA1 = new ValueBean(); beanA1.setValue( 90000 ); ValueBean beanA2 = new ValueBean(); beanA2.setValue( 91000 ); setBean.addAttribute( beanA1 ); setBean.addAttribute( beanA2 ); JSONObject jsonObject = JSONObject.fromObject( setBean ); Map classMap = new HashMap(); classMap.put( "attributes", ValueBean.class ); SetBean setBean2 = (SetBean) JSONObject.toBean( jsonObject, SetBean.class, classMap ); assertEquals( setBean, setBean2 ); } public void testToBean_nested_beans_in_set__DynaBean() { // FR 1847116 SetBean setBean = new SetBean(); ValueBean beanA1 = new ValueBean(); beanA1.setValue( 90000 ); ValueBean beanA2 = new ValueBean(); beanA2.setValue( 91000 ); setBean.addAttribute( beanA1 ); setBean.addAttribute( beanA2 ); JSONObject jsonObject = JSONObject.fromObject( setBean ); //SetBean setBean2 = (SetBean) JSONObject.toBean( jsonObject, SetBean.class ); //assertEquals( setBean, setBean2 ); } public void testToBean_nested_dynabeans__null_object() throws Exception { // BUG 1553617 String json = "{\"beanA\":{bool:true,integer:1,string:\"jsonbean\"},\"beanB\":null}"; JSONObject jsonObject = JSONObject.fromObject( json ); Object bean = JSONObject.toBean( jsonObject ); assertNotNull( bean ); Object beanA = PropertyUtils.getProperty( bean, "beanA" ); assertNotNull( beanA ); assertEquals( Boolean.TRUE, PropertyUtils.getProperty( beanA, "bool" ) ); assertEquals( new Integer( 1 ), PropertyUtils.getProperty( beanA, "integer" ) ); assertEquals( "jsonbean", PropertyUtils.getProperty( beanA, "string" ) ); Object beanB = PropertyUtils.getProperty( bean, "beanB" ); assertNull( beanB ); } public void testtoBean_noWriteMethod() { JSONObject json = new JSONObject(); json.element( "propertyWithNoReadMethod", "json" ); json.element( "propertyWithNoWriteMethod", "value" ); PropertyBean bean = (PropertyBean) JSONObject.toBean( json, PropertyBean.class ); assertNotNull( bean ); assertEquals( "json", bean.valueOfPropertyWithNoReadMethod() ); assertEquals( "json", bean.getPropertyWithNoWriteMethod() ); } public void testToBean_null() { assertNull( JSONObject.toBean( (JSONObject)null ) ); } public void testToBean_null_2() { assertNull( JSONObject.toBean( null, BeanA.class ) ); } public void testToBean_null_object() { JSONObject jsonObject = new JSONObject( true ); BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class ); assertNull( bean ); } public void testToBean_null_values() { // bug report 1540196 String json = "{\"items\":[[\"000\"],[\"010\", \"011\"],[\"020\"]]}"; JSONObject jsonObject = JSONObject.fromObject( json ); BeanFoo foo = (BeanFoo) JSONObject.toBean( jsonObject, BeanFoo.class ); assertNotNull( foo ); assertNotNull( foo.getItems() ); String[][] items = foo.getItems(); assertEquals( 3, items.length ); assertEquals( "000", items[0][0] ); assertEquals( "010", items[1][0] ); assertEquals( "011", items[1][1] ); assertEquals( "020", items[2][0] ); } public void testToBean_NumberBean() { JSONObject json = new JSONObject(); json.element( "pbyte", new Byte( (byte) 2 ) ); json.element( "pshort", new Short( (short) 2 ) ); json.element( "pint", new Integer( 2 ) ); json.element( "plong", new Long( 2 ) ); json.element( "pfloat", new Float( 2 ) ); json.element( "pdouble", new Double( 2 ) ); json.element( "pbigint", new BigInteger( "2" ) ); json.element( "pbigdec", new BigDecimal( "2" ) ); NumberBean bean = (NumberBean) JSONObject.toBean( json, NumberBean.class ); assertEquals( (byte) 2, bean.getPbyte() ); assertEquals( (short) 2, bean.getPshort() ); assertEquals( 2, bean.getPint() ); assertEquals( 2L, bean.getPlong() ); assertEquals( 2f, bean.getPfloat(), 0f ); assertEquals( 2d, bean.getPdouble(), 0d ); assertEquals( new BigInteger( "2" ), bean.getPbigint() ); assertEquals( new BigDecimal( "2" ), bean.getPbigdec() ); } public void testToBean_NumberBean_2() { JSONObject json = new JSONObject(); json.element( "pbyte", new Integer( 2 ) ); json.element( "pshort", new Integer( 2 ) ); json.element( "pint", new Integer( 2 ) ); json.element( "plong", new Integer( 2 ) ); json.element( "pfloat", new Integer( 2 ) ); json.element( "pdouble", new Integer( 2 ) ); json.element( "pbigint", new Integer( 2 ) ); json.element( "pbigdec", new Integer( 2 ) ); NumberBean bean = (NumberBean) JSONObject.toBean( json, NumberBean.class ); assertEquals( (byte) 2, bean.getPbyte() ); assertEquals( (short) 2, bean.getPshort() ); assertEquals( 2, bean.getPint() ); assertEquals( 2L, bean.getPlong() ); assertEquals( 2f, bean.getPfloat(), 0f ); assertEquals( 2d, bean.getPdouble(), 0d ); assertEquals( new BigInteger( "2" ), bean.getPbigint() ); assertEquals( new BigDecimal( "2" ), bean.getPbigdec() ); } public void testToBean_ObjectBean() { // FR 1611204 ObjectBean bean = new ObjectBean(); bean.setPbyte( Byte.valueOf( "1" ) ); bean.setPshort( Short.valueOf( "1" ) ); bean.setPint( Integer.valueOf( "1" ) ); bean.setPlong( Long.valueOf( "1" ) ); bean.setPfloat( Float.valueOf( "1" ) ); bean.setPdouble( Double.valueOf( "1" ) ); bean.setPchar( new Character( '1' ) ); bean.setPboolean( Boolean.TRUE ); bean.setPstring( "json" ); bean.setParray( new String[] { "a", "b" } ); bean.setPbean( new BeanA() ); List list = new ArrayList(); list.add( "1" ); list.add( "2" ); bean.setPlist( list ); Map map = new HashMap(); map.put( "string", "json" ); bean.setPmap( map ); bean.setPfunction( new JSONFunction( "this;" ) ); JSONObject json = JSONObject.fromObject( bean ); Map classMap = new HashMap(); classMap.put( "pbean", BeanA.class ); ObjectBean obj = (ObjectBean) JSONObject.toBean( json, ObjectBean.class, classMap ); assertEquals( Integer.valueOf( "1" ), obj.getPbyte() ); assertEquals( Integer.valueOf( "1" ), obj.getPshort() ); assertEquals( Integer.valueOf( "1" ), obj.getPint() ); assertEquals( Integer.valueOf( "1" ), obj.getPlong() ); assertEquals( Double.valueOf( "1" ), obj.getPfloat() ); assertEquals( Double.valueOf( "1" ), obj.getPdouble() ); assertEquals( "1", obj.getPchar() ); assertEquals( "json", obj.getPstring() ); List l = new ArrayList(); l.add( "a" ); l.add( "b" ); ArrayAssertions.assertEquals( l.toArray(), (Object[]) obj.getParray() ); l = new ArrayList(); l.add( "1" ); l.add( "2" ); ArrayAssertions.assertEquals( l.toArray(), (Object[]) obj.getPlist() ); assertEquals( new BeanA(), obj.getPbean() ); assertTrue( obj.getPmap() instanceof MorphDynaBean ); } public void testToBean_ObjectBean_empty() throws Exception { // FR 1611204 ObjectBean bean = new ObjectBean(); JSONObject json = JSONObject.fromObject( bean ); Map classMap = new HashMap(); classMap.put( "bean", BeanA.class ); ObjectBean obj = (ObjectBean) JSONObject.toBean( json, ObjectBean.class, classMap ); String[] keys = { "pbyte", "pshort", "pint", "plong", "pfloat", "pdouble", "pboolean", "pchar", "pstring", "parray", "plist", "pmap", "pbean" }; for( int i = 0; i < keys.length; i++ ){ assertNull( PropertyUtils.getProperty( obj, keys[i] ) ); } } public void testToBean_rootObject() { JSONObject json = new JSONObject().element( "bool", "false" ) .element( "integer", 84 ) .element( "string", "bean" ); BeanA expected = new BeanA(); BeanA actual = (BeanA) JSONObject.toBean( json, expected, new JsonConfig() ); assertNotNull( actual ); assertEquals( expected, actual ); assertFalse( actual.isBool() ); assertEquals( 84, actual.getInteger() ); assertEquals( "bean", actual.getString() ); } public void testToBean_withFilters() { BeanA bean = new BeanA(); bean.setBool( false ); bean.setInteger( 84 ); bean.setString( "filter" ); JSONObject json = JSONObject.fromObject( bean ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( BeanA.class ); jsonConfig.setJavaPropertyFilter( new BeanAPropertyFilter() ); BeanA actual = (BeanA) JSONObject.toBean( json, jsonConfig ); assertNotNull( actual ); assertTrue( actual.isBool() ); assertEquals( 42, actual.getInteger() ); assertEquals( "filter", actual.getString() ); } public void testToBean_withNonJavaIdentifier_camelCase_Strategy() { JSONObject json = new JSONObject().element( "camel case", "json" ); jsonConfig.setJavaIdentifierTransformer( JavaIdentifierTransformer.CAMEL_CASE ); jsonConfig.setRootClass( JavaIdentifierBean.class ); JavaIdentifierBean bean = (JavaIdentifierBean) JSONObject.toBean( json, jsonConfig ); assertNotNull( bean ); assertEquals( "json", bean.getCamelCase() ); } public void testToBean_withNonJavaIdentifier_underScore_Strategy() { JSONObject json = new JSONObject().element( "under score", "json" ); jsonConfig.setJavaIdentifierTransformer( JavaIdentifierTransformer.UNDERSCORE ); jsonConfig.setRootClass( JavaIdentifierBean.class ); JavaIdentifierBean bean = (JavaIdentifierBean) JSONObject.toBean( json, jsonConfig ); assertNotNull( bean ); assertEquals( "json", bean.getUnder_score() ); } public void testToBean_withNonJavaIdentifier_whitespace_Strategy() { JSONObject json = new JSONObject().element( " white space ", "json" ); jsonConfig.setJavaIdentifierTransformer( JavaIdentifierTransformer.WHITESPACE ); jsonConfig.setRootClass( JavaIdentifierBean.class ); JavaIdentifierBean bean = (JavaIdentifierBean) JSONObject.toBean( json, jsonConfig ); assertNotNull( bean ); assertEquals( "json", bean.getWhitespace() ); } public void testToBean_withPropertySetStrategy() { JSONObject json = new JSONObject().element( "key", "value" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( MappingBean.class ); jsonConfig.setPropertySetStrategy( new MappingPropertySetStrategy() ); MappingBean bean = (MappingBean) JSONObject.toBean( json, jsonConfig ); assertNotNull( bean ); assertEquals( "value", bean.getAttributes() .get( "key" ) ); } public void testToBeanWithJavaPropertyNameProcessor(){ String json = "{bool:false}"; JSONObject jsonObject = JSONObject.fromObject( json ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJavaPropertyNameProcessor( BeanA.class, new SwapPropertyNameProcessor() ); jsonConfig.setRootClass( BeanA.class ); BeanA bean = (BeanA) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertTrue( bean.isBool() ); assertEquals( "false", bean.getString() ); } public void testToJSONArray() { String json = "{bool:true,integer:1,string:\"json\"}"; JSONArray names = JSONArray.fromObject( "['string','integer','bool']" ); JSONObject jsonObject = JSONObject.fromObject( json ); JSONArray jsonArray = jsonObject.toJSONArray( names ); assertEquals( "json", jsonArray.getString( 0 ) ); assertEquals( 1, jsonArray.getInt( 1 ) ); assertTrue( jsonArray.getBoolean( 2 ) ); } protected void setUp() throws Exception { jsonConfig = new JsonConfig(); } private MorphDynaBean createDynaBean() throws Exception { Map properties = new HashMap(); properties.put( "name", String.class ); properties.put( "func", JSONFunction.class ); properties.put( "jsonstr", JSONString.class ); properties.put( "json", JSON.class ); properties.put( "str", String.class ); MorphDynaClass dynaClass = new MorphDynaClass( properties ); MorphDynaBean dynaBean = (MorphDynaBean) dynaClass.newInstance(); dynaBean.setDynaBeanClass( dynaClass ); dynaBean.set( "name", "json" ); dynaBean.set( "func", new JSONFunction( "return this;" ) ); dynaBean.set( "jsonstr", new ObjectJSONStringBean() ); dynaBean.set( "json", new JSONObject().element( "id", "1" ) ); dynaBean.set( "str", "[1,2]" ); // JSON Strings can not be null, only empty return dynaBean; } public static class BeanAPropertyExclusionClassMatcher extends PropertyExclusionClassMatcher { public Object getMatch( Class target, Set set ) { for( Iterator i = set.iterator(); i.hasNext(); ){ Class c = (Class) i.next(); if( BeanA.class.isAssignableFrom( c ) ){ return c; } } return null; } } public static class BeanAPropertyFilter implements PropertyFilter { public boolean apply( Object source, String name, Object value ) { if( "bool".equals( name ) || "integer".equals( name ) ){ return true; } return false; } } public static class MappingPropertySetStrategy extends PropertySetStrategy { public void setProperty( Object bean, String key, Object value ) throws JSONException { ((MappingBean) bean).addAttribute( key, value ); } } public static class NumberDefaultValueProcessor implements DefaultValueProcessor { public static final Integer NUMBER = new Integer( 42 ); public Object getDefaultValue( Class type ) { return NUMBER; } } public static class NumberDefaultValueProcessorMatcher extends DefaultValueProcessorMatcher { public Object getMatch( Class target, Set set ) { for( Iterator i = set.iterator(); i.hasNext(); ){ Class c = (Class) i.next(); if( Number.class.isAssignableFrom( c ) ){ return c; } } return null; } } public static class NumberPropertyFilter implements PropertyFilter { public boolean apply( Object source, String name, Object value ) { if( value != null && Number.class.isAssignableFrom( value.getClass() ) ){ return true; } return false; } } public static class SwapPropertyNameProcessor implements PropertyNameProcessor { public String processPropertyName( Class beanClass, String name ) { if( name.equals("bool")){ return "string"; } return name; } } public void test_fromJSONObject() { } public void testCanonicalWrite() throws Exception { JSONArray a = new JSONArray(); a.add(true); // a.add(null); a.add(1); a.add(5.3); JSONObject o = new JSONObject(); o.put("key1","1"); o.put("key2","2"); o.put("key3","3"); o.put("string","123\r\n\b\t\f\\\\u65E5\\u672C\\u8A9E"); a.add(o); StringWriter sw = new StringWriter(); a.writeCanonical(sw); System.out.println(sw.toString()); assertEquals(sw.toString(),"[true,1,5.3,{\"key1\":\"1\",\"key2\":\"2\",\"key3\":\"3\",\"string\":\"123\\u000d\\u000a\\u0008\\u0009\\u000c\\\\\\\\u65E5\\\\u672C\\\\u8A9E\"}]"); } public void testMayBeJSON() { assertEquals("[foo]", JSONObject.fromObject("{x=\"[foo]\"}").getString("x")); } } jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_ObjectBean.java0000664000175000017500000000302511650253660033425 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import net.sf.json.sample.ObjectBean; import org.apache.commons.beanutils.PropertyUtils; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_ObjectBean extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_ObjectBean.class ); } public TestJSONObjectStaticBuilders_ObjectBean( String name ) { super( name ); } protected Object getSource() { ObjectBean bean = new ObjectBean(); String[] props = getProperties(); try{ for( int i = 0; i < props.length; i++ ){ PropertyUtils.setProperty( bean, props[i], PropertyConstants.getPropertyValue( props[i] ) ); } }catch( Exception e ){ throw new RuntimeException( e ); } return bean; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/filters/0000775000175000017500000000000011650253660024554 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/filters/TestCompositePropertyFilter.java0000664000175000017500000000264311650253660033141 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestCompositePropertyFilter extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestCompositePropertyFilter.class ); } private CompositePropertyFilter filter; public TestCompositePropertyFilter( String testName ) { super( testName ); } public void testApply_addFilter() { filter.addPropertyFilter( new FalsePropertyFilter() ); assertFalse( filter.apply( null, null, null ) ); filter.addPropertyFilter( new TruePropertyFilter() ); assertTrue( filter.apply( null, null, null ) ); } protected void setUp() throws Exception { filter = new CompositePropertyFilter(); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/filters/TestOrPropertyFilter.java0000664000175000017500000000360211650253660031553 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import junit.framework.TestCase; import net.sf.json.util.PropertyFilter; /** * @author Orres Almiray */ public class TestOrPropertyFilter extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestOrPropertyFilter.class ); } public TestOrPropertyFilter( String testName ) { super( testName ); } public void testApply_false_false() { PropertyFilter filter = new OrPropertyFilter( new FalsePropertyFilter(), new FalsePropertyFilter() ); assertFalse( filter.apply( null, null, null ) ); } public void testApply_false_true() { PropertyFilter filter = new OrPropertyFilter( new FalsePropertyFilter(), new TruePropertyFilter() ); assertTrue( filter.apply( null, null, null ) ); } public void testApply_true_false() { PropertyFilter filter = new OrPropertyFilter( new TruePropertyFilter(), new FalsePropertyFilter() ); assertTrue( filter.apply( null, null, null ) ); } public void testApply_true_true() { PropertyFilter filter = new OrPropertyFilter( new TruePropertyFilter(), new TruePropertyFilter() ); assertTrue( filter.apply( null, null, null ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/filters/AllTests.java0000664000175000017500000000243311650253660027154 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class AllTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "filters" ); suite.addTest( new TestSuite( TestAndPropertyFilter.class ) ); suite.addTest( new TestSuite( TestCompositePropertyFilter.class ) ); suite.addTest( new TestSuite( TestNotPropertyFilter.class ) ); suite.addTest( new TestSuite( TestOrPropertyFilter.class ) ); suite.addTest( new TestSuite( TestMappingPropertyFilter.class ) ); return suite; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/filters/TestNotPropertyFilter.java0000664000175000017500000000252211650253660031733 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestNotPropertyFilter extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestNotPropertyFilter.class ); } public TestNotPropertyFilter( String testName ) { super( testName ); } public void testApply_true() { NotPropertyFilter filter = new NotPropertyFilter(new TruePropertyFilter()); assertFalse( filter.apply( null, null, null ) ); } public void testApply_false() { NotPropertyFilter filter = new NotPropertyFilter(new FalsePropertyFilter()); assertTrue( filter.apply( null, null, null ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/filters/TestMappingPropertyFilter.java0000664000175000017500000000322611650253660032570 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestMappingPropertyFilter extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestMappingPropertyFilter.class ); } public TestMappingPropertyFilter( String testName ) { super( testName ); } public void testApply() { MappingPropertyFilter filter = new SampleMappingPropertyFilter(); filter.addPropertyFilter( String.class, new TruePropertyFilter() ); filter.addPropertyFilter( Long.class, new TruePropertyFilter() ); assertFalse( filter.apply( "String", null, null ) ); assertTrue( filter.apply( new Long( 1L ), null, null ) ); } public static class SampleMappingPropertyFilter extends MappingPropertyFilter { protected boolean keyMatches( Object key, Object source, String name, Object value ) { return ((Class) key).isAssignableFrom( source.getClass() ) && source instanceof Number; } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/filters/TestAndPropertyFilter.java0000664000175000017500000000361411650253660031700 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.filters; import junit.framework.TestCase; import net.sf.json.util.PropertyFilter; /** * @author Andres Almiray */ public class TestAndPropertyFilter extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestAndPropertyFilter.class ); } public TestAndPropertyFilter( String testName ) { super( testName ); } public void testApply_false_false() { PropertyFilter filter = new AndPropertyFilter( new FalsePropertyFilter(), new FalsePropertyFilter() ); assertFalse( filter.apply( null, null, null ) ); } public void testApply_false_true() { PropertyFilter filter = new AndPropertyFilter( new FalsePropertyFilter(), new TruePropertyFilter() ); assertFalse( filter.apply( null, null, null ) ); } public void testApply_true_false() { PropertyFilter filter = new AndPropertyFilter( new TruePropertyFilter(), new FalsePropertyFilter() ); assertFalse( filter.apply( null, null, null ) ); } public void testApply_true_true() { PropertyFilter filter = new AndPropertyFilter( new TruePropertyFilter(), new TruePropertyFilter() ); assertTrue( filter.apply( null, null, null ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/Assertions.java0000664000175000017500000003570711650253660026115 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.List; import net.sf.ezmorph.test.ArrayAssertions; import net.sf.json.test.JSONAssert; /** * @author Andres Almiray */ public class Assertions extends JSONAssert { public static void assertEquals( List expecteds, List actuals ) { assertEquals( null, expecteds, actuals ); } public static void assertEquals( Object expected, Object actual ) { assertEquals( null, expected, actual ); } public static void assertEquals( String message, List expecteds, List actuals ) { String header = message == null ? "" : message + ": "; if( expecteds == null ){ fail( header + "expected list was null" ); } if( actuals == null ){ fail( header + "actual list was null" ); } if( expecteds == actuals || expecteds.equals( actuals ) ){ return; } if( actuals.size() != expecteds.size() ){ fail( header + "list sizes differed, expected.size()=" + expecteds.size() + " actual.size()=" + actuals.size() ); } int max = expecteds.size(); for( int i = 0; i < max; i++ ){ Object o1 = expecteds.get( i ); Object o2 = actuals.get( i ); // handle nulls if( o1 == null ){ if( o2 == null ){ return; }else{ fail( header + "lists first differed at element [" + i + "];" ); } }else{ if( o2 == null ){ fail( header + "lists first differed at element [" + i + "];" ); } } if( o1.getClass() .isArray() && o2.getClass() .isArray() ){ Object[] expected = (Object[]) o1; Object[] actual = (Object[]) o2; assertEquals( header + "lists first differed at element " + i + ";", expected, actual ); }else if( List.class.isAssignableFrom( o1.getClass() ) && List.class.isAssignableFrom( o2.getClass() ) ){ assertEquals( header + "lists first differed at element [" + i + "];", (List) o1, (List) o2 ); }else{ if( o1 instanceof String && o2 instanceof JSONFunction ){ assertEquals( header + "lists first differed at element [" + i + "];", (String) o1, (JSONFunction) o2 ); }else if( o1 instanceof JSONFunction && o2 instanceof String ){ assertEquals( header + "lists first differed at element [" + i + "];", (JSONFunction) o1, (String) o2 ); }else if( o1 instanceof JSONObject && o2 instanceof JSONObject ){ assertEquals( header + "lists first differed at element [" + i + "];", (JSONObject) o1, (JSONObject) o2 ); }else if( o1 instanceof JSONArray && o2 instanceof JSONArray ){ assertEquals( header + "lists first differed at element [" + i + "];", (JSONArray) o1, (JSONArray) o2 ); }else if( o1 instanceof JSONFunction && o2 instanceof JSONFunction ){ assertEquals( header + "lists first differed at element [" + i + "];", (JSONFunction) o1, (JSONFunction) o2 ); }else{ assertEquals( header + "lists first differed at element [" + i + "];", o1, o2 ); } } } } public static void assertEquals( String message, Object expected, Object actual ) { if( expected == null && actual == null ) return; if( expected != null && expected.equals( actual ) ) return; Class expectedClass = expected.getClass(); Class actualClass = actual.getClass(); if( expectedClass.isArray() && actualClass.isArray() ){ Class expectedInnerType = expectedClass.getComponentType(); Class actualInnerType = actualClass.getComponentType(); if( expectedInnerType.isPrimitive() ){ assertExpectedPrimitiveArrays( message, expected, actual, expectedInnerType, actualInnerType ); }else if( actualInnerType.isPrimitive() ){ assertActualPrimitiveArrays( message, expected, actual, expectedInnerType, actualInnerType ); }else{ ArrayAssertions.assertEquals( message, (Object[]) expected, (Object[]) actual ); } }else{ failNotEquals( message, expected, actual ); } } private static void assertActualPrimitiveArrays( String message, Object expected, Object actual, Class expectedInnerType, Class actualInnerType ) { if( Boolean.TYPE.isAssignableFrom( actualInnerType ) ){ if( Boolean.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (boolean[]) expected, (boolean[]) actual ); }else if( Boolean.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Boolean[]) expected, (boolean[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (boolean[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Byte.TYPE.isAssignableFrom( actualInnerType ) ){ if( Byte.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (byte[]) expected, (byte[]) actual ); }else if( Byte.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Byte[]) expected, (byte[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (byte[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Short.TYPE.isAssignableFrom( actualInnerType ) ){ if( Short.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (short[]) expected, (short[]) actual ); }else if( Short.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Short[]) expected, (short[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (short[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Integer.TYPE.isAssignableFrom( actualInnerType ) ){ if( Integer.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (int[]) expected, (int[]) actual ); }else if( Integer.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Integer[]) expected, (int[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (int[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Long.TYPE.isAssignableFrom( actualInnerType ) ){ if( Long.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (long[]) expected, (long[]) actual ); }else if( Long.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Long[]) expected, (long[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (long[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Float.TYPE.isAssignableFrom( actualInnerType ) ){ if( Float.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (float[]) expected, (float[]) actual ); }else if( Float.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Float[]) expected, (float[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (float[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Double.TYPE.isAssignableFrom( actualInnerType ) ){ if( Double.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (double[]) expected, (double[]) actual ); }else if( Double.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Double[]) expected, (double[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (double[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Character.TYPE.isAssignableFrom( actualInnerType ) ){ if( Character.TYPE.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (char[]) expected, (char[]) actual ); }else if( Character.class.isAssignableFrom( expectedInnerType ) ){ ArrayAssertions.assertEquals( message, (Character[]) expected, (char[]) actual ); }else if( !expectedInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (Object[]) expected, (char[]) actual ); }else{ failNotEquals( message, expected, actual ); } } } private static void assertExpectedPrimitiveArrays( String message, Object expected, Object actual, Class expectedInnerType, Class actualInnerType ) { if( Boolean.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Boolean.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (boolean[]) expected, (boolean[]) actual ); }else if( Boolean.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (boolean[]) expected, (Boolean[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (boolean[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Byte.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Byte.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (byte[]) expected, (byte[]) actual ); }else if( Byte.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (byte[]) expected, (Byte[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (byte[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Short.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Short.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (short[]) expected, (short[]) actual ); }else if( Short.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (short[]) expected, (Short[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (short[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Integer.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Integer.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (int[]) expected, (int[]) actual ); }else if( Integer.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (int[]) expected, (Integer[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (int[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Long.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Long.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (long[]) expected, (long[]) actual ); }else if( Long.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (long[]) expected, (Long[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (long[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Float.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Float.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (float[]) expected, (float[]) actual ); }else if( Float.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (float[]) expected, (Float[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (float[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Double.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Double.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (double[]) expected, (double[]) actual ); }else if( Double.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (double[]) expected, (Double[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (double[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } }else if( Character.TYPE.isAssignableFrom( expectedInnerType ) ){ if( Character.TYPE.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (char[]) expected, (char[]) actual ); }else if( Character.class.isAssignableFrom( actualInnerType ) ){ ArrayAssertions.assertEquals( message, (char[]) expected, (Character[]) actual ); }else if( !actualInnerType.isPrimitive() ){ ArrayAssertions.assertEquals( message, (char[]) expected, (Object[]) actual ); }else{ failNotEquals( message, expected, actual ); } } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayCollections.java0000664000175000017500000004143511650253660030565 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import net.sf.ezmorph.MorphUtils; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; import net.sf.json.sample.BeanA; /** * @author Andres Almiray */ public class TestJSONArrayCollections extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayCollections.class ); } public TestJSONArrayCollections( String testName ) { super( testName ); } public void testToList_bean_elements() { List expected = new ArrayList(); expected.add( new BeanA() ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray, BeanA.class ); Assertions.assertEquals( expected, actual ); } public void testToList_BigDecimal() { List expected = new ArrayList(); expected.add( MorphUtils.BIGDECIMAL_ZERO ); expected.add( MorphUtils.BIGDECIMAL_ONE ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_BigInteger() { List expected = new ArrayList(); expected.add( BigInteger.ZERO ); expected.add( BigInteger.ONE ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Boolean() { List expected = new ArrayList(); expected.add( Boolean.TRUE ); expected.add( Boolean.FALSE ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Byte() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); List bytes = new ArrayList(); bytes.add( new Byte( (byte) 1 ) ); bytes.add( new Byte( (byte) 2 ) ); JSONArray jsonArray = JSONArray.fromObject( bytes ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Character() { List expected = new ArrayList(); expected.add( "A" ); expected.add( "B" ); List chars = new ArrayList(); chars.add( new Character( 'A' ) ); chars.add( new Character( 'B' ) ); JSONArray jsonArray = JSONArray.fromObject( chars ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Double() { List expected = new ArrayList(); expected.add( new Double( 1d ) ); expected.add( new Double( 2d ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_dynaBean_elements() throws Exception { List expected = new ArrayList(); expected.add( createDynaBean() ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Float() { List expected = new ArrayList(); expected.add( new Double( 1d ) ); expected.add( new Double( 2d ) ); List floats = new ArrayList(); floats.add( new Float( 1f ) ); floats.add( new Float( 2f ) ); JSONArray jsonArray = JSONArray.fromObject( floats ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Integer() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_JSONFunction_elements() { List expected = new ArrayList(); expected.add( new JSONFunction( new String[] { "a" }, "return a;" ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_JSONFunction_elements_2() { List expected = new ArrayList(); expected.add( "function(a){ return a; }" ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Long() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); List longs = new ArrayList(); longs.add( new Long( 1L ) ); longs.add( new Long( 2L ) ); JSONArray jsonArray = JSONArray.fromObject( longs ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Long2() { List expected = new ArrayList(); expected.add( new Long( Integer.MAX_VALUE + 1L ) ); expected.add( new Long( Integer.MAX_VALUE + 2L ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_null_elements() { List expected = new ArrayList(); expected.add( null ); expected.add( null ); expected.add( null ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Short() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); List shorts = new ArrayList(); shorts.add( new Short( (short) 1 ) ); shorts.add( new Short( (short) 2 ) ); JSONArray jsonArray = JSONArray.fromObject( shorts ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_String() { List expected = new ArrayList(); expected.add( "A" ); expected.add( "B" ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_String_multi() { List a = new ArrayList(); a.add( "a" ); a.add( "b" ); List b = new ArrayList(); b.add( "1" ); b.add( "2" ); List expected = new ArrayList(); expected.add( a ); expected.add( b ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = (List) JSONArray.toCollection( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToSet_bean_elements() { Set expected = new HashSet(); expected.add( new BeanA() ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); jsonConfig.setRootClass( BeanA.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_BigDecimal() { Set expected = new HashSet(); expected.add( MorphUtils.BIGDECIMAL_ZERO ); expected.add( MorphUtils.BIGDECIMAL_ONE ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_BigInteger() { Set expected = new HashSet(); expected.add( BigInteger.ZERO ); expected.add( BigInteger.ONE ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Boolean() { Set expected = new HashSet(); expected.add( Boolean.TRUE ); expected.add( Boolean.FALSE ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Byte() { Set expected = new HashSet(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); Set bytes = new HashSet(); bytes.add( new Byte( (byte) 1 ) ); bytes.add( new Byte( (byte) 2 ) ); JSONArray jsonArray = JSONArray.fromObject( bytes ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Character() { Set expected = new HashSet(); expected.add( "A" ); expected.add( "B" ); Set chars = new HashSet(); chars.add( new Character( 'A' ) ); chars.add( new Character( 'B' ) ); JSONArray jsonArray = JSONArray.fromObject( chars ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Double() { Set expected = new HashSet(); expected.add( new Double( 1d ) ); expected.add( new Double( 2d ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_dynaBean_elements() throws Exception { Set expected = new HashSet(); expected.add( createDynaBean() ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Float() { Set expected = new HashSet(); expected.add( new Double( 1d ) ); expected.add( new Double( 2d ) ); Set floats = new HashSet(); floats.add( new Float( 1f ) ); floats.add( new Float( 2f ) ); JSONArray jsonArray = JSONArray.fromObject( floats ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Integer() { Set expected = new HashSet(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_JSONFunction_elements() { Set expected = new HashSet(); expected.add( new JSONFunction( new String[] { "a" }, "return a;" ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } /* public void testToSet_JSONFunction_elements_2() { Set expected = new HashSet(); expected.add( "function(a){ return a; }" ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } */ public void testToSet_Long() { Set expected = new HashSet(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); Set longs = new HashSet(); longs.add( new Long( 1L ) ); longs.add( new Long( 2L ) ); JSONArray jsonArray = JSONArray.fromObject( longs ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Long2() { Set expected = new HashSet(); expected.add( new Long( Integer.MAX_VALUE + 1L ) ); expected.add( new Long( Integer.MAX_VALUE + 2L ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_null_elements() { Set expected = new HashSet(); expected.add( null ); expected.add( null ); expected.add( null ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_Short() { Set expected = new HashSet(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); Set shorts = new HashSet(); shorts.add( new Short( (short) 1 ) ); shorts.add( new Short( (short) 2 ) ); JSONArray jsonArray = JSONArray.fromObject( shorts ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_String() { Set expected = new HashSet(); expected.add( "A" ); expected.add( "B" ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToSet_String_multi() { Set a = new HashSet(); a.add( "a" ); a.add( "b" ); Set b = new HashSet(); b.add( "1" ); b.add( "2" ); Set expected = new HashSet(); expected.add( a ); expected.add( b ); JSONArray jsonArray = JSONArray.fromObject( expected ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCollectionType( Set.class ); Set actual = (Set) JSONArray.toCollection( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } private MorphDynaBean createDynaBean() throws Exception { Map properties = new HashMap(); properties.put( "name", String.class ); MorphDynaClass dynaClass = new MorphDynaClass( properties ); MorphDynaBean dynaBean = (MorphDynaBean) dynaClass.newInstance(); dynaBean.setDynaBeanClass( dynaClass ); dynaBean.set( "name", "json" ); // JSON Strings can not be null, only empty return dynaBean; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_JSONString.java0000664000175000017500000000352111650253660033372 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_JSONString extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_JSONString.class ); } public TestJSONObjectStaticBuilders_JSONString( String name ) { super( name ); } protected Object getSource() { return new JsonBean(); } public static class JsonBean implements JSONString { public String toJSONString() { return "{\"parray\":[1,2],\"plong\":9223372036854775807,\"pchar\":\"J\",\"pboolean\":true,\"pfloat\":3.4028234663852886E38,\"pbean\":{\"parray\":null,\"plong\":null,\"pchar\":null,\"pboolean\":null,\"pfloat\":null,\"pbean\":null,\"pshort\":null,\"pdouble\":null,\"pclass\":null,\"pstring\":null,\"pint\":null,\"plist\":null,\"pfunction\":null,\"pmap\":null,\"pbyte\":null},\"pshort\":32767,\"pdouble\":1.7976931348623157E308,\"pclass\":\"java.lang.Object\",\"pstring\":\"json\",\"pint\":2147483647,\"plist\":[\"a\",\"b\"],\"pfunction\":function(){ this; },\"pmap\":null,\"pbyte\":127,\"class\":\"java.lang.Object\",\"pexcluded\":\"\"}"; } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArrayEvents.java0000664000175000017500000001045111650253660027545 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import net.sf.json.sample.JsonEventAdpater; /** * @author Andres Almiray */ public class TestJSONArrayEvents extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayEvents.class ); } private JsonConfig jsonConfig; private JsonEventAdpater jsonEventAdpater; public TestJSONArrayEvents( String name ) { super( name ); } public void testFromObject_array() { JSONArray.fromObject( new Object[] { "1", "2", "3" }, jsonConfig ); assertEvents(); } public void testFromObject_error() { try{ JSONArray.fromObject( "{}", jsonConfig ); fail( "A JSONException was expected" ); }catch( JSONException expected ){ assertEquals( 1, jsonEventAdpater.getError() ); assertEquals( 0, jsonEventAdpater.getWarning() ); assertEquals( 0, jsonEventAdpater.getArrayStart() ); assertEquals( 0, jsonEventAdpater.getArrayEnd() ); assertEquals( 0, jsonEventAdpater.getObjectStart() ); assertEquals( 0, jsonEventAdpater.getObjectEnd() ); assertEquals( 0, jsonEventAdpater.getElementAdded() ); assertEquals( 0, jsonEventAdpater.getPropertySet() ); } } public void testFromObject_JSONArray() { JSONArray array = new JSONArray().element( "1" ) .element( "2" ) .element( "3" ); JSONArray.fromObject( array, jsonConfig ); assertEvents(); } public void testFromObject_list() { List list = new ArrayList(); list.add( "1" ); list.add( "2" ); list.add( "3" ); JSONArray.fromObject( list, jsonConfig ); assertEvents(); } public void testFromObject_primitive_boolean() { JSONArray.fromObject( new boolean[] { true, false, true }, jsonConfig ); assertEvents(); } public void testFromObject_primitive_byte() { JSONArray.fromObject( new byte[] { (byte) 1, (byte) 2, (byte) 3 }, jsonConfig ); assertEvents(); } public void testFromObject_primitive_double() { JSONArray.fromObject( new double[] { 1d, 2d, 3d }, jsonConfig ); assertEvents(); } public void testFromObject_primitive_float() { JSONArray.fromObject( new float[] { 1f, 2f, 3f }, jsonConfig ); assertEvents(); } public void testFromObject_primitive_int() { JSONArray.fromObject( new int[] { 1, 2, 3 }, jsonConfig ); assertEvents(); } public void testFromObject_primitive_long() { JSONArray.fromObject( new long[] { 1L, 2L, 3L }, jsonConfig ); assertEvents(); } public void testFromObject_primitive_short() { JSONArray.fromObject( new short[] { (short) 1, (short) 2, (short) 3 }, jsonConfig ); assertEvents(); } public void testFromObject_string() { JSONArray.fromObject( "[1,2,3]", jsonConfig ); assertEvents(); } protected void setUp() throws Exception { jsonEventAdpater = new JsonEventAdpater(); jsonConfig = new JsonConfig(); jsonConfig.addJsonEventListener( jsonEventAdpater ); jsonConfig.enableEventTriggering(); } private void assertEvents() { assertEquals( 0, jsonEventAdpater.getError() ); assertEquals( 0, jsonEventAdpater.getWarning() ); assertEquals( 1, jsonEventAdpater.getArrayStart() ); assertEquals( 1, jsonEventAdpater.getArrayEnd() ); assertEquals( 0, jsonEventAdpater.getObjectStart() ); assertEquals( 0, jsonEventAdpater.getObjectEnd() ); assertEquals( 3, jsonEventAdpater.getElementAdded() ); assertEquals( 0, jsonEventAdpater.getPropertySet() ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONArray.java0000664000175000017500000015162211650253660026366 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.io.StringWriter; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.sf.ezmorph.MorphUtils; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; import net.sf.json.sample.ArrayJSONStringBean; import net.sf.json.sample.BeanA; import net.sf.json.util.JSONTokener; import org.apache.commons.beanutils.DynaBean; /** * @author Andres Almiray */ public class TestJSONArray extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArray.class ); } public TestJSONArray( String testName ) { super( testName ); } public void testDiscard() { JSONArray jsonArray = new JSONArray().element( "1" ) .element( "true" ) .element( "string" ) .element( "function(){ return this; }" ) .element( "[1,2,3]" ); assertEquals( 5, jsonArray.size() ); jsonArray.discard( "string" ) .discard( 0 ); assertEquals( 3, jsonArray.size() ); assertFalse( jsonArray.contains( "string" ) ); assertFalse( jsonArray.contains( "1" ) ); } public void testConstructor_Collection() { List l = new ArrayList(); l.add( Boolean.TRUE ); l.add( new Integer( 1 ) ); l.add( "string" ); l.add( Object.class ); testJSONArray( l, "[true,1,\"string\",\"java.lang.Object\"]" ); } public void testConstructor_Collection_JSONArray() { List l = new ArrayList(); l.add( JSONArray.fromObject( new int[] { 1, 2 } ) ); testJSONArray( l, "[[1,2]]" ); } public void testConstructor_Collection_JSONFunction() { List l = new ArrayList(); l.add( new JSONFunction( new String[] { "a" }, "return a;" ) ); testJSONArray( l, "[function(a){ return a; }]" ); } public void testConstructor_Collection_JSONString() { ArrayJSONStringBean bean = new ArrayJSONStringBean(); bean.setValue( "'json','json'" ); List l = new ArrayList(); l.add( bean ); testJSONArray( l, "[[\"json\",\"json\"]]" ); } public void testConstructor_Collection_nulls() { List l = new ArrayList(); l.add( null ); l.add( null ); testJSONArray( l, "[null,null]" ); } public void testConstructor_func() { JSONArray expected = JSONArray.fromObject( new String[] { "'" + new JSONFunction( new String[] { "a" }, "return a;" ).toString() + "'" } ); JSONArray actual = JSONArray.fromObject( new String[] { "'function(a){ return a; }'" } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_func2() { JSONArray expected = JSONArray.fromObject( new String[] { "\"" + new JSONFunction( new String[] { "a" }, "return a;" ).toString() + "\"" } ); JSONArray actual = JSONArray.fromObject( new String[] { "\"function(a){ return a; }\"" } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_JSONArray() { JSONArray expected = JSONArray.fromObject( "[1,2]" ); JSONArray actual = JSONArray.fromObject( JSONArray.fromObject( "[1,2]" ) ); Assertions.assertEquals( expected, actual ); } public void testConstructor_JSONTokener_functions() { testJSONArray( new JSONTokener( "[function(a){ return a; }]" ), "[function(a){ return a; }]" ); } public void testConstructor_JSONTokener_nulls() { testJSONArray( new JSONTokener( "[,,]" ), "[null,null]" ); } public void testConstructor_JSONTokener_syntax_errors() { try{ JSONArray.fromObject( "" ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // ok } } public void testConstructor_Object_Array() { JSONArray expected = JSONArray.fromObject( "[\"json\",1]" ); JSONArray actual = JSONArray.fromObject( new Object[] { "json", new Integer( 1 ) } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_Array() { JSONArray expected = JSONArray.fromObject( "[[1,2]]" ); JSONArray actual = JSONArray.fromObject( new Object[] { new int[] { 1, 2 } } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_BigDecimal() { // bug 1596168 // an array of BigDecimals Number[] numberArray = new Number[] { BigDecimal.valueOf( 10000000000L, 10 ), new BigDecimal( "-1.0" ), new BigDecimal( "99.99E-1" ) }; assertEquals( "1.0000000000", numberArray[0].toString() ); assertEquals( "-1.0", numberArray[1].toString() ); assertEquals( "9.999", numberArray[2].toString() ); JSONArray jsonNumArray = JSONArray.fromObject( numberArray ); assertEquals( "1.0000000000", jsonNumArray.get( 0 ) .toString() ); assertEquals( "-1.0", jsonNumArray.get( 1 ) .toString() ); assertEquals( "9.999", jsonNumArray.get( 2 ) .toString() ); } public void testConstructor_Object_Array_BigInteger() { // bug 1596168 Number[] numberArray = new Number[] { new BigInteger( "18437736874454810627" ), new BigInteger( "9007199254740990" ) }; assertEquals( "18437736874454810627", numberArray[0].toString() ); assertEquals( "9007199254740990", numberArray[1].toString() ); JSONArray jsonNumArray = JSONArray.fromObject( numberArray ); assertEquals( "18437736874454810627", jsonNumArray.get( 0 ) .toString() ); assertEquals( "9007199254740990", jsonNumArray.get( 1 ) .toString() ); } public void testConstructor_Object_Array_Class() { JSONArray expected = JSONArray.fromObject( "[\"java.lang.Object\"]" ); JSONArray actual = JSONArray.fromObject( new Object[] { Object.class } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_functions() { JSONArray expected = JSONArray.fromObject( "[function(a){ return a; }]" ); JSONArray actual = JSONArray.fromObject( new JSONFunction[] { new JSONFunction( new String[] { "a" }, "return a;" ) } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_functions_2() { JSONArray expected = JSONArray.fromObject( new JSONFunction[] { new JSONFunction( new String[] { "a" }, "return a;" ) } ); JSONArray actual = JSONArray.fromObject( "[function(a){ return a; }]" ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_functions_3() { JSONArray expected = JSONArray.fromObject( new JSONFunction[] { new JSONFunction( new String[] { "a" }, "return a;" ) } ); JSONArray actual = JSONArray.fromObject( new String[] { "function(a){ return a; }" } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_JSONArray() { JSONArray expected = JSONArray.fromObject( "[[1,2]]" ); JSONArray actual = JSONArray.fromObject( new Object[] { JSONArray.fromObject( "[1,2]" ) } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_JSONString() { ArrayJSONStringBean bean = new ArrayJSONStringBean(); bean.setValue( "'json','json'" ); JSONArray expected = JSONArray.fromObject( "[[\"json\",\"json\"]]" ); JSONArray actual = JSONArray.fromObject( new Object[] { bean } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_Object_Array_nulls() { JSONArray expected = JSONArray.fromObject( "[null,null]" ); JSONArray actual = JSONArray.fromObject( new Object[] { null, null } ); Assertions.assertEquals( expected, actual ); } public void testConstructor_primitive_array_boolean() { testJSONArray( new boolean[] { true, false }, "[true,false]" ); } public void testConstructor_primitive_array_byte() { testJSONArray( new byte[] { 1, 2, 3 }, "[1,2,3]" ); } public void testConstructor_primitive_array_char() { testJSONArray( new char[] { 'a', 'b', 'c' }, "[\"a\",\"b\",\"c\"]" ); } public void testConstructor_primitive_array_double() { testJSONArray( new double[] { 1.1, 2.2, 3.3 }, "[1.1,2.2,3.3]" ); } public void testConstructor_primitive_array_double_Infinity() { try{ JSONArray.fromObject( new double[] { Double.NEGATIVE_INFINITY } ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // OK } try{ JSONArray.fromObject( new double[] { Double.POSITIVE_INFINITY } ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // OK } } public void testConstructor_primitive_array_double_NaNs() { try{ JSONArray.fromObject( new double[] { Double.NaN } ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // OK } } public void testConstructor_primitive_array_float() { testJSONArray( new float[] { 1.1f, 2.2f, 3.3f }, "[1.1,2.2,3.3]" ); } public void testConstructor_primitive_array_float_Infinity() { try{ JSONArray.fromObject( new float[] { Float.NEGATIVE_INFINITY } ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // OK } try{ JSONArray.fromObject( new float[] { Float.POSITIVE_INFINITY } ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // OK } } public void testConstructor_primitive_array_float_NaNs() { try{ JSONArray.fromObject( new float[] { Float.NaN } ); fail( "Should have thrown a JSONException" ); }catch( JSONException expected ){ // OK } } public void testConstructor_primitive_array_int() { testJSONArray( new int[] { 1, 2, 3 }, "[1,2,3]" ); } public void testConstructor_primitive_array_long() { testJSONArray( new long[] { 1, 2, 3 }, "[1,2,3]" ); } public void testConstructor_primitive_array_short() { testJSONArray( new short[] { 1, 2, 3 }, "[1,2,3]" ); } public void testConstructor_String_functions() { testJSONArray( "[function(a){ return a; }]", "[function(a){ return a; }]" ); } public void testConstructor_String_functions_multi() { testJSONArray( "[function(a){ return a; },[function(b){ return b; }]]", "[function(a){ return a; },[function(b){ return b; }]]" ); } public void testCycleDetection_arrays() { Object[] array1 = new Object[2]; Object[] array2 = new Object[2]; array1[0] = new Integer( 1 ); array1[1] = array2; array2[0] = new Integer( 2 ); array2[1] = array1; try{ JSONArray.fromObject( array1 ); fail( "A JSONException was expected" ); }catch( JSONException expected ){ assertTrue( expected.getMessage() .endsWith( "There is a cycle in the hierarchy!" ) ); } } public void testElement_Array() { JSONArray array = new JSONArray(); int[] ints = { 1, 2 }; array.element( ints ); Assertions.assertEquals( JSONArray.fromObject( ints ), array.getJSONArray( 0 ) ); } public void testElement_boolean() { JSONArray jsonArray = new JSONArray(); jsonArray.element( true ); assertEquals( 1, jsonArray.size() ); assertTrue( jsonArray.getBoolean( 0 ) ); } public void testElement_Boolean() { JSONArray array = new JSONArray(); array.element( Boolean.TRUE ); Assertions.assertTrue( array.getBoolean( 0 ) ); } public void testElement_Collection() { List l = new ArrayList(); l.add( Boolean.TRUE ); l.add( new Integer( 1 ) ); l.add( "string" ); JSONArray jsonArray = new JSONArray(); jsonArray.element( l ); assertEquals( 1, jsonArray.size() ); Assertions.assertEquals( JSONArray.fromObject( "[true,1,\"string\"]" ), jsonArray.getJSONArray( 0 ) ); } public void testElement_double() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 2.0d ); assertEquals( 1, jsonArray.size() ); assertEquals( 2.0d, jsonArray.getDouble( 0 ), 0d ); } public void testElement_index_0_Array() { JSONArray array = JSONArray.fromObject( "[null,null]" ); ; int[] ints = { 0, 2 }; array.element( 0, ints ); Assertions.assertEquals( JSONArray.fromObject( ints ), array.getJSONArray( 0 ) ); } public void testElement_index_0_Boolean() { JSONArray array = JSONArray.fromObject( "[null,null]" ); ; array.element( 0, Boolean.TRUE ); Assertions.assertTrue( array.getBoolean( 0 ) ); } public void testElement_index_0_Class() { JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, Object.class ); Assertions.assertEquals( "java.lang.Object", array.getString( 0 ) ); } public void testElement_index_0_JSON() { JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, JSONNull.getInstance() ); Assertions.assertEquals( JSONNull.getInstance(), array.get( 0 ) ); } public void testElement_index_0_JSONFunction() { JSONArray array = JSONArray.fromObject( "[null,null]" ); JSONFunction f = new JSONFunction( "return this;" ); array.element( 0, f ); Assertions.assertEquals( f, (JSONFunction) array.get( 0 ) ); } public void testElement_index_0_JSONString() { JSONArray array = JSONArray.fromObject( "[null,null]" ); ArrayJSONStringBean bean = new ArrayJSONStringBean(); bean.setValue( "'json','json'" ); array.element( 0, bean ); Assertions.assertEquals( JSONArray.fromObject( bean ), array.getJSONArray( 0 ) ); } public void testElement_index_0_JSONTokener() { JSONArray array = JSONArray.fromObject( "[null,null]" ); JSONTokener tok = new JSONTokener( "[0,2]" ); array.element( 0, tok ); tok.reset(); Assertions.assertEquals( JSONArray.fromObject( tok ), array.getJSONArray( 0 ) ); } public void testElement_index_0_Number() { JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, new Double( 2 ) ); Assertions.assertEquals( new Double( 2 ).doubleValue(), array.getDouble( 0 ), 0d ); } public void testElement_index_0_Object() { JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, new BeanA() ); Assertions.assertEquals( JSONObject.fromObject( new BeanA() ), array.getJSONObject( 0 ) ); } public void testElement_index_0_String() { JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, "json" ); Assertions.assertEquals( "json", array.getString( 0 ) ); } public void testElement_index_0_String_JSON() { JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, "[]" ); Assertions.assertEquals( new JSONArray().toString(), array.getString( 0 ) ); } public void testElement_index_0_String_null() { JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, (String) null ); Assertions.assertEquals( "", array.getString( 0 ) ); } public void testElement_index_1_Array() { JSONArray array = new JSONArray(); int[] ints = { 1, 2 }; array.element( 1, ints ); Assertions.assertEquals( JSONArray.fromObject( ints ), array.getJSONArray( 1 ) ); } public void testElement_index_1_boolean() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, true ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); assertTrue( jsonArray.getBoolean( 1 ) ); } public void testElement_index_1_Boolean() { JSONArray array = new JSONArray(); array.element( 1, Boolean.TRUE ); Assertions.assertTrue( array.getBoolean( 1 ) ); } public void testElement_index_1_Class() { JSONArray array = new JSONArray(); array.element( 1, Object.class ); Assertions.assertEquals( "java.lang.Object", array.getString( 1 ) ); } public void testElement_index_1_Collection() { List l = new ArrayList(); l.add( Boolean.TRUE ); l.add( new Integer( 1 ) ); l.add( "string" ); JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, l ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); Assertions.assertEquals( JSONArray.fromObject( "[true,1,\"string\"]" ), jsonArray.getJSONArray( 1 ) ); } public void testElement_index_1_double() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, 2.0d ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); assertEquals( 2.0d, jsonArray.getDouble( 1 ), 0d ); } public void testElement_index_1_int() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, 1 ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); assertEquals( 1, jsonArray.getInt( 1 ) ); } public void testElement_index_1_JSON() { JSONArray array = new JSONArray(); array.element( 1, JSONNull.getInstance() ); Assertions.assertEquals( JSONNull.getInstance(), array.get( 1 ) ); } public void testElement_index_1_JSONFunction() { JSONArray array = new JSONArray(); JSONFunction f = new JSONFunction( "return this;" ); array.element( 1, f ); Assertions.assertEquals( f, (JSONFunction) array.get( 1 ) ); } public void testElement_index_1_JSONString() { JSONArray array = new JSONArray(); ArrayJSONStringBean bean = new ArrayJSONStringBean(); bean.setValue( "'json','json'" ); array.element( 1, bean ); Assertions.assertEquals( JSONArray.fromObject( bean ), array.getJSONArray( 1 ) ); } public void testElement_index_1_JSONTokener() { JSONArray array = new JSONArray(); JSONTokener tok = new JSONTokener( "[1,2]" ); array.element( 1, tok ); tok.reset(); Assertions.assertEquals( JSONArray.fromObject( tok ), array.getJSONArray( 1 ) ); } public void testElement_index_1_long() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, 1L ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); assertEquals( 1L, jsonArray.getLong( 1 ) ); } public void testElement_index_1_Map() { Map map = new HashMap(); map.put( "name", "json" ); JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, map ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); Assertions.assertEquals( JSONObject.fromObject( map ), jsonArray.getJSONObject( 1 ) ); } public void testElement_index_1_Number() { JSONArray array = new JSONArray(); array.element( 1, new Double( 2 ) ); Assertions.assertEquals( new Double( 2 ).doubleValue(), array.getDouble( 1 ), 1d ); } public void testElement_index_1_Object() { JSONArray array = new JSONArray(); array.element( 1, new BeanA() ); Assertions.assertEquals( JSONObject.fromObject( new BeanA() ), array.getJSONObject( 1 ) ); } public void testElement_index_1_String() { JSONArray array = new JSONArray(); array.element( 1, "json" ); Assertions.assertEquals( "json", array.getString( 1 ) ); } public void testElement_index_1_String_JSON() { JSONArray array = new JSONArray(); array.element( 1, "[]" ); Assertions.assertEquals( new JSONArray().toString(), array.getString( 1 ) ); } public void testElement_index_1_String_null() { JSONArray array = new JSONArray(); array.element( 1, (String) null ); Assertions.assertEquals( "", array.getString( 1 ) ); } public void testElement_int() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1 ); assertEquals( 1, jsonArray.size() ); assertEquals( 1, jsonArray.getInt( 0 ) ); } public void testElement_JSON() { JSONArray array = new JSONArray(); array.element( JSONNull.getInstance() ); Assertions.assertEquals( JSONNull.getInstance(), array.get( 0 ) ); } public void testElement_JSONFunction() { JSONArray array = new JSONArray(); JSONFunction f = new JSONFunction( "return this;" ); array.element( f ); Assertions.assertEquals( f, (JSONFunction) array.get( 0 ) ); } public void testElement_JSONString() { JSONArray array = new JSONArray(); ArrayJSONStringBean bean = new ArrayJSONStringBean(); bean.setValue( "'json','json'" ); array.element( bean ); Assertions.assertEquals( JSONArray.fromObject( bean ), array.getJSONArray( 0 ) ); } public void testElement_JSONTokener() { JSONArray array = new JSONArray(); JSONTokener tok = new JSONTokener( "[1,2]" ); array.element( tok ); tok.reset(); Assertions.assertEquals( JSONArray.fromObject( tok ), array.getJSONArray( 0 ) ); } public void testElement_long() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1L ); assertEquals( 1, jsonArray.size() ); assertEquals( 1L, jsonArray.getLong( 0 ) ); } public void testElement_Map() { Map map = new HashMap(); map.put( "name", "json" ); JSONArray jsonArray = new JSONArray(); jsonArray.element( map ); assertEquals( 1, jsonArray.size() ); Assertions.assertEquals( JSONObject.fromObject( map ), jsonArray.getJSONObject( 0 ) ); } public void testElement_negativeIndex() { try{ JSONArray jsonArray = new JSONArray(); jsonArray.element( -1, JSONNull.getInstance() ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testElement_Number() { JSONArray array = new JSONArray(); array.element( new Double( 2 ) ); Assertions.assertEquals( new Double( 2 ).doubleValue(), array.getDouble( 0 ), 0d ); } public void testElement_Object() { JSONArray array = new JSONArray(); array.element( new BeanA() ); Assertions.assertEquals( JSONObject.fromObject( new BeanA() ), array.getJSONObject( 0 ) ); } public void testElement_replace() { JSONArray jsonArray = new JSONArray(); jsonArray.element( true ); assertEquals( 1, jsonArray.size() ); assertTrue( jsonArray.getBoolean( 0 ) ); jsonArray.element( 0, false ); assertEquals( 1, jsonArray.size() ); assertFalse( jsonArray.getBoolean( 0 ) ); } public void testElement_String() { JSONArray array = new JSONArray(); array.element( "json" ); Assertions.assertEquals( "json", array.getString( 0 ) ); } public void testElement_String_JSON() { JSONArray array = new JSONArray(); array.element( "[]" ); Assertions.assertEquals( new JSONArray().toString(), array.getString( 0 ) ); } public void testElement_String_null() { JSONArray array = new JSONArray(); array.element( (String) null ); Assertions.assertEquals( "", array.getString( 0 ) ); } public void testFromObject_BigDecimal() { JSONArray actual = JSONArray.fromObject( new BigDecimal( "12345678901234567890.1234567890" ) ); assertTrue( actual.get( 0 ) instanceof BigDecimal ); } public void testFromObject_BigInteger() { JSONArray actual = JSONArray.fromObject( new BigInteger( "123456789012345678901234567890" ) ); assertTrue( actual.get( 0 ) instanceof BigInteger ); } public void testFromObject_Boolean() { JSONArray expected = JSONArray.fromObject( "[true]" ); JSONArray actual = JSONArray.fromObject( Boolean.TRUE ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Byte() { JSONArray expected = JSONArray.fromObject( "[1]" ); JSONArray actual = JSONArray.fromObject( new Byte( (byte) 1 ) ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Double() { JSONArray expected = JSONArray.fromObject( "[1.0]" ); JSONArray actual = JSONArray.fromObject( new Double( 1d ) ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Float() { JSONArray expected = JSONArray.fromObject( "[1.0]" ); JSONArray actual = JSONArray.fromObject( new Float( 1f ) ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Integer() { JSONArray expected = JSONArray.fromObject( "[1]" ); JSONArray actual = JSONArray.fromObject( new Integer( 1 ) ); Assertions.assertEquals( expected, actual ); } public void testFromObject_JSONArray() { JSONArray expected = JSONArray.fromObject( "[1,2]" ); JSONArray actual = JSONArray.fromObject( JSONArray.fromObject( "[1,2]" ) ); Assertions.assertEquals( expected, actual ); } public void testFromObject_JSONFunction() { JSONArray expected = JSONArray.fromObject( "[function(a){ return a; }]" ); JSONArray actual = JSONArray.fromObject( new JSONFunction( new String[] { "a" }, "return a;" ) ); Assertions.assertEquals( expected, actual ); } public void testFromObject_JSONString() { ArrayJSONStringBean bean = new ArrayJSONStringBean(); bean.setValue( "'json','json'" ); JSONArray actual = JSONArray.fromObject( bean ); JSONArray expected = JSONArray.fromObject( "['json','json']" ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Long() { JSONArray expected = JSONArray.fromObject( "[1]" ); JSONArray actual = JSONArray.fromObject( new Long( 1L ) ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Map() { JSONArray expected = JSONArray.fromObject( "[{}]" ); JSONArray actual = JSONArray.fromObject( new HashMap() ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Short() { JSONArray expected = JSONArray.fromObject( "[1]" ); JSONArray actual = JSONArray.fromObject( new Short( (short) 1 ) ); Assertions.assertEquals( expected, actual ); } public void testGet_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[]" ); jsonArray.get( 0 ); fail( "Expected a IndexOutOfBoundsException" ); }catch( IndexOutOfBoundsException expected ){ // OK } } public void testGetBoolean_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[[]]" ); jsonArray.getBoolean( 0 ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testGetBoolean_false() { JSONArray jsonArray = JSONArray.fromObject( "[false]" ); assertFalse( jsonArray.getBoolean( 0 ) ); } public void testGetBoolean_true() { JSONArray jsonArray = JSONArray.fromObject( "[true]" ); assertTrue( jsonArray.getBoolean( 0 ) ); } public void testGetDimensions_empty_array() { int[] dims = JSONArray.getDimensions( new JSONArray() ); assertEquals( 1, dims.length ); assertEquals( 0, dims[0] ); } public void testGetDimensions_null_array() { int[] dims = JSONArray.getDimensions( null ); assertEquals( 1, dims.length ); assertEquals( 0, dims[0] ); } public void testGetDimensions_one_dimension() { int[] dims = JSONArray.getDimensions( JSONArray.fromObject( "[1,2,3]" ) ); assertEquals( 1, dims.length ); assertEquals( 3, dims[0] ); } public void testGetDimensions_pyramid() { int[] dims = JSONArray.getDimensions( JSONArray.fromObject( "[1,[2,[3,[4]]]]" ) ); assertEquals( 4, dims.length ); assertEquals( 2, dims[0] ); assertEquals( 2, dims[1] ); assertEquals( 2, dims[2] ); assertEquals( 1, dims[3] ); dims = JSONArray.getDimensions( JSONArray.fromObject( "[[[[1],2],3],4]" ) ); assertEquals( 4, dims.length ); assertEquals( 2, dims[0] ); assertEquals( 2, dims[1] ); assertEquals( 2, dims[2] ); assertEquals( 1, dims[3] ); } public void testGetDimensions_two_dimension() { int[] dims = JSONArray.getDimensions( JSONArray.fromObject( "[[1,2,3],[4,5,6]]" ) ); assertEquals( 2, dims.length ); assertEquals( 2, dims[0] ); assertEquals( 3, dims[1] ); dims = JSONArray.getDimensions( JSONArray.fromObject( "[[1,2],[4,5,6]]" ) ); assertEquals( 2, dims.length ); assertEquals( 2, dims[0] ); assertEquals( 3, dims[1] ); dims = JSONArray.getDimensions( JSONArray.fromObject( "[[1,2,3],[4,5]]" ) ); assertEquals( 2, dims.length ); assertEquals( 2, dims[0] ); assertEquals( 3, dims[1] ); } public void testGetDouble_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[[]]" ); jsonArray.getDouble( 0 ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testGetDouble_Number() { JSONArray jsonArray = JSONArray.fromObject( "[2.0]" ); assertEquals( 2.0d, jsonArray.getDouble( 0 ), 0d ); } public void testGetDouble_String() { JSONArray jsonArray = JSONArray.fromObject( "[\"2.0\"]" ); assertEquals( 2.0d, jsonArray.getDouble( 0 ), 0d ); } public void testGetInt_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[[]]" ); jsonArray.getInt( 0 ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testGetInt_Number() { JSONArray jsonArray = JSONArray.fromObject( "[2.0]" ); assertEquals( 2, jsonArray.getInt( 0 ) ); } public void testGetInt_String() { JSONArray jsonArray = JSONArray.fromObject( "[\"2.0\"]" ); assertEquals( 2, jsonArray.getInt( 0 ) ); } public void testGetJSONArray() { JSONArray jsonArray = JSONArray.fromObject( "[[1,2]]" ); Assertions.assertEquals( JSONArray.fromObject( "[1,2]" ) .toString(), jsonArray.getJSONArray( 0 ) .toString() ); } public void testGetJSONArray_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[1]" ); jsonArray.getJSONArray( 0 ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testGetJSONObject() { JSONArray jsonArray = JSONArray.fromObject( "[{\"name\":\"json\"}]" ); Assertions.assertEquals( JSONObject.fromObject( "{\"name\":\"json\"}" ), jsonArray.getJSONObject( 0 ) ); } public void testGetJSONObject_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[1]" ); jsonArray.getJSONObject( 0 ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testGetLong_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[[]]" ); jsonArray.getLong( 0 ); fail( "Expected a JSONException" ); }catch( JSONException expected ){ // OK } } public void testGetLong_Number() { JSONArray jsonArray = JSONArray.fromObject( "[2.0]" ); assertEquals( 2, jsonArray.getLong( 0 ) ); } public void testGetLong_String() { JSONArray jsonArray = JSONArray.fromObject( "[\"2.0\"]" ); assertEquals( 2, jsonArray.getLong( 0 ) ); } public void testGetString() { JSONArray jsonArray = JSONArray.fromObject( "[\"2.0\"]" ); assertEquals( "2.0", jsonArray.getString( 0 ) ); } public void testGetString_exception() { try{ JSONArray jsonArray = JSONArray.fromObject( "[]" ); jsonArray.getString( 0 ); fail( "Expected a IndexOutOfBoundsException" ); }catch( IndexOutOfBoundsException expected ){ // OK } } public void testOptionalGet() { Object[] params = new Object[] { new JSONArray(), JSONObject.fromObject( "{\"int\":1}" ) }; JSONArray jsonArray = JSONArray.fromObject( params ); assertFalse( jsonArray.optBoolean( 0 ) ); assertTrue( jsonArray.optBoolean( 0, true ) ); assertTrue( Double.isNaN( jsonArray.optDouble( 0 ) ) ); assertEquals( 0d, jsonArray.optDouble( 0, 0d ), 0d ); assertEquals( 0, jsonArray.optInt( 0 ) ); assertEquals( 1, jsonArray.optInt( 0, 1 ) ); assertEquals( null, jsonArray.optJSONArray( 1 ) ); Assertions.assertEquals( (JSONArray) params[0], jsonArray.optJSONArray( 0 ) ); assertEquals( null, jsonArray.optJSONObject( 0 ) ); Assertions.assertEquals( (JSONObject) params[1], jsonArray.optJSONObject( 1 ) ); assertEquals( 0, jsonArray.optLong( 0 ) ); assertEquals( 1, jsonArray.optLong( 0, 1 ) ); assertEquals( "", jsonArray.optString( 3 ) ); assertEquals( "json", jsonArray.optString( 3, "json" ) ); } public void testToArray_bean_element() { BeanA[] expected = new BeanA[] { new BeanA() }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray, BeanA.class ); Assertions.assertEquals( expected, actual ); } public void testToArray_BigDecimal() { BigDecimal[] expected = new BigDecimal[] { MorphUtils.BIGDECIMAL_ZERO, MorphUtils.BIGDECIMAL_ONE }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_BigInteger() { BigInteger[] expected = new BigInteger[] { BigInteger.ZERO, BigInteger.ONE }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_boolean() { boolean[] expected = new boolean[] { true, false }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Boolean() { Boolean[] expected = new Boolean[] { Boolean.TRUE, Boolean.FALSE }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_boolean_multi() { boolean[][] expected = new boolean[][] { { true, false }, { false, true } }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_byte() { byte[] input = new byte[] { 1, 2, 3, 4, 5, 6 }; int[] expected = new int[] { 1, 2, 3, 4, 5, 6 }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Byte() { Integer[] expected = new Integer[] { new Integer( 1 ), new Integer( 2 ) }; Byte[] bytes = new Byte[] { new Byte( (byte) 1 ), new Byte( (byte) 2 ) }; JSONArray jsonArray = JSONArray.fromObject( bytes ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_byte_multi() { byte[][] input = new byte[][] { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] expected = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_char() { String[] expected = new String[] { "A", "B" }; char[] input = new char[] { 'A', 'B' }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_char_multi() { String[][] expected = new String[][] { { "a", "b" }, { "c", "d" } }; char[][] input = new char[][] { { 'a', 'b' }, { 'c', 'd' } }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Character() { String[] expected = { "A", "B" }; Character[] chars = new Character[] { new Character( 'A' ), new Character( 'B' ) }; JSONArray jsonArray = JSONArray.fromObject( chars ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_double() { double[] expected = new double[] { 1, 2, 3, 4, 5, 6 }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Double() { Double[] expected = new Double[] { new Double( 1d ), new Double( 2d ) }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_double_multi() { double[][] expected = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_dynabean_element() throws Exception { DynaBean[] expected = new DynaBean[] { createDynaBean() }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_float() { double[] expected = new double[] { 1, 2, 3, 4, 5, 6 }; float[] input = new float[] { 1, 2, 3, 4, 5, 6 }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Float() { Double[] expected = new Double[] { new Double( 1d ), new Double( 2d ) }; Float[] floats = new Float[] { new Float( 1f ), new Float( 2f ) }; JSONArray jsonArray = JSONArray.fromObject( floats ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_float_multi() { double[][] expected = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; float[][] input = new float[][] { { 1, 2, 3 }, { 4, 5, 6 } }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_int() { int[] expected = new int[] { 1, 2, 3, 4, 5, 6 }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_int_multi() { int[][] expected = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Integer() { Integer[] expected = new Integer[] { new Integer( 1 ), new Integer( 2 ) }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_long() { long[] input = new long[] { 1, 2, 3, 4, 5, 6 }; int[] expected = new int[] { 1, 2, 3, 4, 5, 6 }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Long() { Integer[] expected = new Integer[] { new Integer( 1 ), new Integer( 2 ) }; Long[] longs = new Long[] { new Long( 1L ), new Long( 2L ) }; JSONArray jsonArray = JSONArray.fromObject( longs ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_long_multi() { long[][] input = new long[][] { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] expected = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Long2() { Long[] expected = new Long[] { new Long( Integer.MAX_VALUE + 1L ), new Long( Integer.MAX_VALUE + 2L ) }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_null_elements() { String[] expected = new String[] { null, null, null }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_short() { short[] input = new short[] { 1, 2, 3, 4, 5, 6 }; int[] expected = new int[] { 1, 2, 3, 4, 5, 6 }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_Short() { Integer[] expected = new Integer[] { new Integer( 1 ), new Integer( 2 ) }; Short[] shorts = new Short[] { new Short( (short) 1 ), new Short( (short) 2 ) }; JSONArray jsonArray = JSONArray.fromObject( shorts ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_short_multi() { short[][] input = new short[][] { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] expected = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }; JSONArray jsonArray = JSONArray.fromObject( input ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_String() { String[] expected = new String[] { "1", "2", "3", "4", "5", "6" }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_String_multi() { String[][] expected = new String[][] { { "1", "2", "3" }, { "4", "5", "6" } }; JSONArray jsonArray = JSONArray.fromObject( expected ); Object actual = JSONArray.toArray( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToArray_StringToInt() { int[] expected = new int[] { 1, 2, 3, 4, 5, 6 }; String[] input = new String[] { "1", "2", "3", "4", "5", "6" }; JSONArray jsonArray = JSONArray.fromObject( input ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( Integer.TYPE ); Object actual = JSONArray.toArray( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToArray_StringToInteger() { int[] expected = new int[] { 1, 2, 3, 4, 5, 6 }; String[] input = new String[] { "1", "2", "3", "4", "5", "6" }; JSONArray jsonArray = JSONArray.fromObject( input ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( Integer.class ); Object actual = JSONArray.toArray( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToArray_StringToInteger_empty() { int[] expected = new int[] {}; String[] input = new String[] {}; JSONArray jsonArray = JSONArray.fromObject( input ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( Integer.class ); Object actual = JSONArray.toArray( jsonArray, jsonConfig ); Assertions.assertEquals( expected, actual ); } public void testToJSONObject() { JSONArray jsonArray = JSONArray.fromObject( "[\"json\",1,true]" ); JSONObject expected = JSONObject.fromObject( "{\"string\":\"json\",\"int\":1,\"bool\":true}" ); JSONArray names = JSONArray.fromObject( "['string','int','bool']" ); Assertions.assertEquals( expected, jsonArray.toJSONObject( names ) ); } public void testToJSONObject_null_object() { JSONArray jsonArray = new JSONArray(); assertNull( jsonArray.toJSONObject( null ) ); assertNull( jsonArray.toJSONObject( new JSONArray() ) ); assertNull( jsonArray.toJSONObject( JSONArray.fromObject( "['json']" ) ) ); } public void testToList_bean_elements() { List expected = new ArrayList(); expected.add( new BeanA() ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray, BeanA.class ); Assertions.assertEquals( expected, actual ); } public void testToList_BigDecimal() { List expected = new ArrayList(); expected.add( MorphUtils.BIGDECIMAL_ZERO ); expected.add( MorphUtils.BIGDECIMAL_ONE ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_BigInteger() { List expected = new ArrayList(); expected.add( BigInteger.ZERO ); expected.add( BigInteger.ONE ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Boolean() { List expected = new ArrayList(); expected.add( Boolean.TRUE ); expected.add( Boolean.FALSE ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Byte() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); List bytes = new ArrayList(); bytes.add( new Byte( (byte) 1 ) ); bytes.add( new Byte( (byte) 2 ) ); JSONArray jsonArray = JSONArray.fromObject( bytes ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Character() { List expected = new ArrayList(); expected.add( "A" ); expected.add( "B" ); List chars = new ArrayList(); chars.add( new Character( 'A' ) ); chars.add( new Character( 'B' ) ); JSONArray jsonArray = JSONArray.fromObject( chars ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Double() { List expected = new ArrayList(); expected.add( new Double( 1d ) ); expected.add( new Double( 2d ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_dynaBean_elements() throws Exception { List expected = new ArrayList(); expected.add( createDynaBean() ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Float() { List expected = new ArrayList(); expected.add( new Double( 1d ) ); expected.add( new Double( 2d ) ); List floats = new ArrayList(); floats.add( new Float( 1f ) ); floats.add( new Float( 2f ) ); JSONArray jsonArray = JSONArray.fromObject( floats ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Integer() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_JSONFunction_elements() { List expected = new ArrayList(); expected.add( new JSONFunction( new String[] { "a" }, "return a;" ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_JSONFunction_elements_2() { List expected = new ArrayList(); expected.add( "function(a){ return a; }" ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Long() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); List longs = new ArrayList(); longs.add( new Long( 1L ) ); longs.add( new Long( 2L ) ); JSONArray jsonArray = JSONArray.fromObject( longs ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Long2() { List expected = new ArrayList(); expected.add( new Long( Integer.MAX_VALUE + 1L ) ); expected.add( new Long( Integer.MAX_VALUE + 2L ) ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_null_elements() { List expected = new ArrayList(); expected.add( null ); expected.add( null ); expected.add( null ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_Short() { List expected = new ArrayList(); expected.add( new Integer( 1 ) ); expected.add( new Integer( 2 ) ); List shorts = new ArrayList(); shorts.add( new Short( (short) 1 ) ); shorts.add( new Short( (short) 2 ) ); JSONArray jsonArray = JSONArray.fromObject( shorts ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_String() { List expected = new ArrayList(); expected.add( "A" ); expected.add( "B" ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testToList_String_multi() { List a = new ArrayList(); a.add( "a" ); a.add( "b" ); List b = new ArrayList(); b.add( "1" ); b.add( "2" ); List expected = new ArrayList(); expected.add( a ); expected.add( b ); JSONArray jsonArray = JSONArray.fromObject( expected ); List actual = JSONArray.toList( jsonArray ); Assertions.assertEquals( expected, actual ); } public void testWrite() throws IOException { JSONArray jsonArray = JSONArray.fromObject( "[[],{},1,true,\"json\"]" ); StringWriter sw = new StringWriter(); jsonArray.write( sw ); assertEquals( "[[],{},1,true,\"json\"]", sw.toString() ); } private MorphDynaBean createDynaBean() throws Exception { Map properties = new HashMap(); properties.put( "name", String.class ); MorphDynaClass dynaClass = new MorphDynaClass( properties ); MorphDynaBean dynaBean = (MorphDynaBean) dynaClass.newInstance(); dynaBean.setDynaBeanClass( dynaClass ); dynaBean.set( "name", "json" ); // JSON Strings can not be null, only empty return dynaBean; } private void testJSONArray( Object array, String expected ) { try{ JSONArray jsonArray = JSONArray.fromObject( array ); assertEquals( expected, jsonArray.toString() ); }catch( JSONException jsone ){ fail( jsone.getMessage() ); } } public void testMayBeJSON() { assertEquals("[foo]", JSONArray.fromObject("[\"[foo]\"]").getString(0)); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/processors/0000775000175000017500000000000011650253660025306 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/processors/TestJsDateJsonBeanProcessor.java0000664000175000017500000000622611650253660033511 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; /** * @author Andres Almiray */ public class TestJsDateJsonBeanProcessor extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJsDateJsonBeanProcessor.class ); } private JsDateJsonBeanProcessor processor; public TestJsDateJsonBeanProcessor( String testName ) { super( testName ); } public void testProcessBean() { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DAY_OF_MONTH, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); Date date = c.getTime(); JSONObject jsonObject = processor.processBean( date, new JsonConfig() ); assertNotNull( jsonObject ); assertEquals( 2007, jsonObject.getInt( "year" ) ); assertEquals( 5, jsonObject.getInt( "month" ) ); assertEquals( 17, jsonObject.getInt( "day" ) ); assertEquals( 12, jsonObject.getInt( "hours" ) ); assertEquals( 13, jsonObject.getInt( "minutes" ) ); assertEquals( 14, jsonObject.getInt( "seconds" ) ); assertEquals( 150, jsonObject.getInt( "milliseconds" ) ); } public void testProcessBean_sqlDate() { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DAY_OF_MONTH, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); Date date = c.getTime(); JSONObject jsonObject = processor.processBean( new java.sql.Date( date.getTime() ), new JsonConfig() ); assertNotNull( jsonObject ); assertEquals( 2007, jsonObject.getInt( "year" ) ); assertEquals( 5, jsonObject.getInt( "month" ) ); assertEquals( 17, jsonObject.getInt( "day" ) ); assertEquals( 12, jsonObject.getInt( "hours" ) ); assertEquals( 13, jsonObject.getInt( "minutes" ) ); assertEquals( 14, jsonObject.getInt( "seconds" ) ); assertEquals( 150, jsonObject.getInt( "milliseconds" ) ); } protected void setUp() throws Exception { processor = new JsDateJsonBeanProcessor(); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/processors/TestJsonBeanProcessorMatcher.java0000664000175000017500000000276411650253660033725 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; /** * @author Andres Almiray */ public class TestJsonBeanProcessorMatcher extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJsonBeanProcessorMatcher.class ); } public void testGetMatchUsingStartsWith() { Set set = new HashSet(); set.add( JsonBeanProcessorMatcher.class ); set.add( JsonBeanProcessorMatcher.DEFAULT.getClass() ); JsonBeanProcessorMatcher matcher = new StartsWithJsonBeanProcessorMatcher( "net.sf.json.processors.JsonBeanProcessorMatcher$" ); assertEquals( JsonBeanProcessorMatcher.DEFAULT.getClass(), matcher.getMatch( JsonBeanProcessorMatcher.DEFAULT.getClass(), set ) ); } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/processors/AllTests.java0000664000175000017500000000230411650253660027703 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class AllTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "processors" ); suite.addTest( new TestSuite( TestJsDateJsonBeanProcessor.class ) ); suite.addTest( new TestSuite( TestJsDateJsonValueProcessor.class ) ); suite.addTest( new TestSuite( TestJsonBeanProcessorMatcher.class ) ); return suite; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/processors/TestJsDateJsonValueProcessor.java0000664000175000017500000000634011650253660033715 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; /** * @author Andres Almiray */ public class TestJsDateJsonValueProcessor extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJsDateJsonValueProcessor.class ); } private JsDateJsonValueProcessor processor; public TestJsDateJsonValueProcessor( String testName ) { super( testName ); } public void testProcessBean() { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DAY_OF_MONTH, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); Date date = c.getTime(); JSONObject jsonObject = (JSONObject) processor.processObjectValue( "date", date, new JsonConfig() ); assertNotNull( jsonObject ); assertEquals( 2007, jsonObject.getInt( "year" ) ); assertEquals( 5, jsonObject.getInt( "month" ) ); assertEquals( 17, jsonObject.getInt( "day" ) ); assertEquals( 12, jsonObject.getInt( "hours" ) ); assertEquals( 13, jsonObject.getInt( "minutes" ) ); assertEquals( 14, jsonObject.getInt( "seconds" ) ); assertEquals( 150, jsonObject.getInt( "milliseconds" ) ); } public void testProcessBean_sqlDate() { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DAY_OF_MONTH, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); Date date = c.getTime(); JSONObject jsonObject = (JSONObject) processor.processObjectValue( "date", new java.sql.Date( date.getTime() ), new JsonConfig() ); assertNotNull( jsonObject ); assertEquals( 2007, jsonObject.getInt( "year" ) ); assertEquals( 5, jsonObject.getInt( "month" ) ); assertEquals( 17, jsonObject.getInt( "day" ) ); assertEquals( 12, jsonObject.getInt( "hours" ) ); assertEquals( 13, jsonObject.getInt( "minutes" ) ); assertEquals( 14, jsonObject.getInt( "seconds" ) ); assertEquals( 150, jsonObject.getInt( "milliseconds" ) ); } protected void setUp() throws Exception { processor = new JsDateJsonValueProcessor(); } }././@LongLink0000644000000000000000000000015012255646554011654 Lustar rootrootjenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/processors/StartsWithJsonBeanProcessorMatcher.javajenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/processors/StartsWithJsonBeanProcessorMatcher.j0000664000175000017500000000263311650253660034425 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.processors; import java.util.Iterator; import java.util.Set; /** * @author Andres Almiray */ public class StartsWithJsonBeanProcessorMatcher extends JsonBeanProcessorMatcher { private String pattern; public StartsWithJsonBeanProcessorMatcher( String pattern ) { this.pattern = pattern; } public Object getMatch( Class target, Set set ) { if( target != null && set != null && target.getName() .startsWith( pattern ) ){ for( Iterator i = set.iterator(); i.hasNext(); ){ Class c = (Class) i.next(); if( c.getName() .startsWith( pattern ) ){ return c; } } } return null; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/test/0000775000175000017500000000000011650253660024063 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/test/AllTests.java0000664000175000017500000000176111650253660026466 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.test; import junit.framework.TestSuite; /** * @author Andres Almiray */ public class AllTests extends TestSuite { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite(); suite.setName( "test" ); suite.addTest( new TestSuite( TestJSONAssert.class ) ); return suite; } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/test/TestJSONAssert.java0000664000175000017500000005146411650253660027533 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.test; import java.util.HashMap; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONFunction; import net.sf.json.JSONNull; import net.sf.json.JSONObject; /** * @author Andres Almiray */ public class TestJSONAssert extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONAssert.class ); } public TestJSONAssert( String testName ) { super( testName ); } public void testArrayWithNullsShouldFail() { JSONArray one = new JSONArray(); one.element( "hello" ); one.element( (Object) null ); one.element( "world" ); JSONArray two = new JSONArray(); two.element( "hello" ); two.element( (Object) null ); two.element( "world!" ); try{ JSONAssert.assertEquals( one, two ); fail( "Did not throw an AssertionFailedError" ); }catch( AssertionFailedError e ){ assertTrue( e.getMessage() .startsWith( "arrays first differed at element [2]" ) ); } } public void testArrayWithNullsShouldPass() { JSONArray one = new JSONArray(); one.element( "hello" ); one.element( (Object) null ); one.element( "world" ); JSONArray two = new JSONArray(); two.element( "hello" ); two.element( (Object) null ); two.element( "world" ); JSONAssert.assertEquals( one, two ); } public void testAssertEquals_JSON_JSON__actual_null() { try{ JSON expected = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( expected, null ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual was null" ); } } public void testAssertEquals_JSON_JSON__expected_null() { try{ JSON actual = JSONObject.fromObject( "{\"str\":\"json\"}" ); JSONAssert.assertEquals( null, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "expected was null" ); } } public void testAssertEquals_JSON_JSON__JSONArray_JSONArray() { try{ JSON expected = JSONArray.fromObject( "[1,2,3]" ); JSON actual = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Arrays should be equal" ); } } public void testAssertEquals_JSON_JSON__JSONArray_JSONObject() { try{ JSON expected = JSONArray.fromObject( "[1,2,3]" ); JSON actual = JSONObject.fromObject( "{\"str\":\"json\"}" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is not a JSONArray" ); } } public void testAssertEquals_JSON_JSON__JSONNull_JSONArray() { try{ JSON expected = JSONNull.getInstance(); JSON actual = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is not a JSONNull" ); } } public void testAssertEquals_JSON_JSON__JSONNull_JSONNull() { try{ JSON expected = JSONNull.getInstance(); JSON actual = JSONNull.getInstance(); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "JSONNull should be equal to itself" ); } } public void testAssertEquals_JSON_JSON__JSONObject_JSONArray() { try{ JSON expected = JSONObject.fromObject( "{\"str\":\"json\"}" ); JSON actual = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is not a JSONObject" ); } } public void testAssertEquals_JSON_JSON__JSONObject_JSONObject() { try{ JSON expected = JSONObject.fromObject( "{\"str\":\"json\"}" ); JSON actual = JSONObject.fromObject( "{\"str\":\"json\"}" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Objects should be equal" ); } } public void testAssertEquals_JSONArray_JSONArray() { Object[] values = new Object[] { Boolean.valueOf( true ), new Integer( Integer.MAX_VALUE ), new Long( Long.MAX_VALUE ), new Float( Float.MAX_VALUE ), new Double( Double.MAX_VALUE ), "json", new JSONArray(), new JSONObject( true ), new JSONObject(), new JSONObject().element( "str", "json" ), "function(){ return this; }", new JSONFunction( "return that;" ), new int[] { 1, 2 } }; JSONArray expected = JSONArray.fromObject( values ); JSONArray actual = JSONArray.fromObject( values ); try{ JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Arrays should be equal" ); } } public void testAssertEquals_JSONArray_JSONArray__actual_null() { try{ JSONArray expected = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( expected, (JSONArray) null ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual array was null" ); } } public void testAssertEquals_JSONArray_JSONArray__different_length() { try{ JSONArray expected = JSONArray.fromObject( "[1]" ); JSONArray actual = new JSONArray(); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "arrays sizes differed, expected.length()=1 actual.length()=0" ); } } public void testAssertEquals_JSONArray_JSONArray__expected_null() { try{ JSONArray actual = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( (JSONArray) null, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "expected array was null" ); } } public void testAssertEquals_JSONArray_JSONArray__nulls() { try{ JSONArray expected = JSONArray.fromObject( "[1]" ); JSONArray actual = new JSONArray().element( JSONNull.getInstance() ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "arrays first differed at element [0];" ); } try{ JSONArray expected = new JSONArray().element( JSONNull.getInstance() ); JSONArray actual = JSONArray.fromObject( "[1]" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "arrays first differed at element [0];" ); } } public void testAssertEquals_JSONArray_String() { try{ JSONArray expected = JSONArray.fromObject( "[1,2,3]" ); String actual = "[1,2,3]"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Arrays should be equal" ); } } public void testAssertEquals_JSONArray_String_fail() { try{ JSONArray expected = JSONArray.fromObject( "[1,2,3]" ); String actual = "{1,2,3}"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is not a JSONArray" ); } } public void testAssertEquals_JSONFunction_String() { try{ JSONFunction expected = new JSONFunction( "return this;" ); String actual = "function(){ return this; }"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Functions should be equal" ); } } public void testAssertEquals_JSONFunction_String__actual_null() { try{ JSONFunction expected = new JSONFunction( ";" ); JSONAssert.assertEquals( expected, (String) null ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual string was null" ); } } public void testAssertEquals_JSONFunction_String__expected_null() { try{ JSONAssert.assertEquals( (JSONFunction) null, ";" ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "expected function was null" ); } } public void testAssertEquals_JSONFunction_String_fail() { try{ JSONFunction expected = new JSONFunction( "return this;" ); String actual = "function(){ return this;"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "'function(){ return this;' is not a function" ); } } public void testAssertEquals_JSONNull_String() { try{ JSONNull expected = JSONNull.getInstance(); String actual = "null"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Should be equal" ); } } public void testAssertEquals_JSONNull_String__actual_null() { try{ JSONNull expected = JSONNull.getInstance(); JSONAssert.assertEquals( expected, (String) null ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual string was null" ); } } public void testAssertEquals_JSONNull_String__expected_null() { try{ JSONAssert.assertEquals( (JSONNull) null, "null" ); }catch( AssertionFailedError e ){ fail( "Should be equal" ); } } public void testAssertEquals_JSONObject_JSONObject_() { try{ String[] names = new String[] { "b", "i", "l", "f", "d", "s", "a1", "o1", "o2", "o3", "u1", "u2" }; Object[] values = new Object[] { Boolean.valueOf( true ), new Integer( Integer.MAX_VALUE ), new Long( Long.MAX_VALUE ), new Float( Float.MAX_VALUE ), new Double( Double.MAX_VALUE ), "json", new JSONArray(), new JSONObject( true ), new JSONObject(), new JSONObject().element( "str", "json" ), "function(){ return this; }", new JSONFunction( "return that;" ) }; Map map = new HashMap(); for( int i = 0; i < names.length; i++ ){ map.put( names[i], values[i] ); } JSONObject expected = JSONObject.fromObject( map ); JSONObject actual = JSONObject.fromObject( map ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Objects should be equal" ); } } public void testAssertEquals_JSONObject_JSONObject__actual_null() { try{ JSONObject expected = JSONObject.fromObject( "{}" ); JSONAssert.assertEquals( expected, (JSONObject) null ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual object was null" ); } } public void testAssertEquals_JSONObject_JSONObject__expected_null() { try{ JSONObject actual = JSONObject.fromObject( "{}" ); JSONAssert.assertEquals( (JSONObject) null, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "expected object was null" ); } } public void testAssertEquals_JSONObject_JSONObject_missingExpectedNamesAreGivenInErrorMessage() { try{ JSONObject expected = new JSONObject().element( "foo", "fooValue" ); JSONObject actual = new JSONObject(); JSONAssert.assertEquals( expected, actual ); fail("Expected AssertionFailedError"); }catch( AssertionFailedError e ){ assertEquals( "missing expected names: [foo]", e.getMessage()); } } public void testAssertEquals_JSONObject_JSONObject_unexpectedNamesAreGivenInErrorMessage() { try{ JSONObject expected = new JSONObject(); JSONObject actual = new JSONObject().element( "foo", "fooValue" ); JSONAssert.assertEquals( expected, actual ); fail("Expected AssertionFailedError"); }catch( AssertionFailedError e ){ assertEquals( "unexpected names: [foo]", e.getMessage()); } } public void testAssertEquals_JSONObject_JSONObject_missingExpectedAnUnexpectedNamesAreBothGivenInErrorMessage() { try{ JSONObject expected = new JSONObject().element( "foo", "fooValue" ).element( "baz", "bazValue" ); JSONObject actual = new JSONObject().element( "bar", "barValue" ); JSONAssert.assertEquals( expected, actual ); fail("Expected AssertionFailedError"); }catch( AssertionFailedError e ){ assertEquals( "missing expected names: [baz, foo], unexpected names: [bar]", e.getMessage()); } } public void testAssertEquals_JSONObject_JSONObject_nullObjects() { try{ JSONObject expected = new JSONObject( true ); JSONObject actual = new JSONObject( true ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Objects should be equal" ); } } public void testAssertEquals_JSONObject_JSONObject_nullObjects_fail1() { try{ JSONObject expected = new JSONObject(); JSONObject actual = new JSONObject( true ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is a null JSONObject" ); } } public void testAssertEquals_JSONObject_JSONObject_nullObjects_fail2() { try{ JSONObject expected = new JSONObject( true ); JSONObject actual = new JSONObject(); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is not a null JSONObject" ); } } public void testAssertEquals_JSONObject_String() { try{ JSONObject expected = JSONObject.fromObject( "{\"str\":\"json\"}" ); String actual = "{\"str\":\"json\"}"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Objects should be equal" ); } } public void testAssertEquals_JSONObject_String_fail() { try{ JSONObject expected = JSONObject.fromObject( "{\"str\":\"json\"}" ); String actual = "[1,2,3]"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is not a JSONObject" ); } } public void testAssertEquals_String_JSONArray() { try{ String expected = "[1,2,3]"; JSONArray actual = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Arrays should be equal" ); } } public void testAssertEquals_String_JSONArray_fail() { try{ String expected = "{1,2,3}"; JSONArray actual = JSONArray.fromObject( "[1,2,3]" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "expected is not a JSONArray" ); } } public void testAssertEquals_String_JSONFunction() { try{ String expected = "function(){ return this; }"; JSONFunction actual = new JSONFunction( "return this;" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Functions should be equal" ); } } public void testAssertEquals_String_JSONFunction_fail() { try{ JSONFunction actual = new JSONFunction( "return this;" ); String expected = "function(){ return this;"; JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "'function(){ return this;' is not a function" ); } } public void testAssertEquals_String_JSONNull() { try{ String expected = "null"; JSONNull actual = JSONNull.getInstance(); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Should be equal" ); } } public void testAssertEquals_String_JSONObject() { try{ String expected = "{\"str\":\"json\"}"; JSONObject actual = JSONObject.fromObject( "{\"str\":\"json\"}" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Objects should be equal" ); } } public void testAssertEquals_String_JSONObject_fail() { try{ String expected = "[1,2,3]"; JSONObject actual = JSONObject.fromObject( "{\"str\":\"json\"}" ); JSONAssert.assertEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "expected is not a JSONObject" ); } } public void testAssertJsonEquals_garbage_json() { try{ String expected = "garbage"; String actual = "null"; JSONAssert.assertJsonEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "expected is not a valid JSON string" ); } } public void testAssertJsonEquals_json_garbage() { try{ String expected = "null"; String actual = "garbage"; JSONAssert.assertJsonEquals( expected, actual ); }catch( AssertionFailedError e ){ assertEquals( e.getMessage(), "actual is not a valid JSON string" ); } } public void testAssertJsonEquals_jsonArray_jsonArray() { try{ String expected = "[1,2,3]"; String actual = "[1,2,3]"; JSONAssert.assertJsonEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Strings should be valid JSON and equal" ); } } public void testAssertJsonEquals_jsonNull_jsonNull() { try{ String expected = "null"; String actual = "null"; JSONAssert.assertJsonEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Strings should be valid JSON and equal" ); } } public void testAssertJsonEquals_jsonObject_jsonObject() { try{ String expected = "{\"str\":\"json\"}"; String actual = "{\"str\":\"json\"}"; JSONAssert.assertJsonEquals( expected, actual ); }catch( AssertionFailedError e ){ fail( "Strings should be valid JSON and equal" ); } } public void testAssertNotNull_JSONNull() { try{ JSONAssert.assertNotNull( JSONNull.getInstance() ); fail( "Parameter is null and assertion did not fail" ); }catch( AssertionFailedError e ){ if( !e.getMessage() .equals( "Object is null" ) ){ fail( "Parameter is null and assertion did not fail" ); } } } public void testAssertNotNull_jsonObject_null() { try{ JSONAssert.assertNotNull( new JSONObject( true ) ); fail( "Parameter is null and assertion did not fail" ); }catch( AssertionFailedError e ){ if( !e.getMessage() .equals( "Object is null" ) ){ fail( "Parameter is null and assertion did not fail" ); } } } public void testAssertNotNull_null() { try{ JSONAssert.assertNotNull( null ); fail( "Parameter is null and assertion did not fail" ); }catch( AssertionFailedError e ){ if( !e.getMessage() .equals( "Object is null" ) ){ fail( "Parameter is null and assertion did not fail" ); } } } public void testAssertNull_JSONNull() { try{ JSONAssert.assertNull( JSONNull.getInstance() ); }catch( AssertionFailedError e ){ fail( "Parameter is null and assertion failed" ); } } public void testAssertNull_jsonObject_null() { try{ JSONAssert.assertNull( new JSONObject( true ) ); }catch( AssertionFailedError e ){ fail( "Parameter is null and assertion failed" ); } } public void testAssertNull_null() { try{ JSONAssert.assertNull( null ); }catch( AssertionFailedError e ){ fail( "Parameter is null and assertion failed" ); } } }jenkins-json-2.4-jenkins-3/src/test/java/net/sf/json/TestJSONObjectStaticBuilders_JSONObject.java0000664000175000017500000000301611650253660033331 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; /** * @author Andres Almiray */ public class TestJSONObjectStaticBuilders_JSONObject extends AbstractJSONObjectStaticBuildersTestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectStaticBuilders_JSONObject.class ); } public TestJSONObjectStaticBuilders_JSONObject( String name ) { super( name ); } protected Object getSource() { String[] props = getProperties(); JSONObject jsonObject = new JSONObject(); try{ for( int i = 0; i < props.length; i++ ){ jsonObject.element( props[i], PropertyConstants.getPropertyValue( props[i] ) ); } jsonObject.element( "class", Object.class ); jsonObject.element( "pexcluded", "" ); }catch( Exception e ){ throw new RuntimeException( e ); } return jsonObject; } }jenkins-json-2.4-jenkins-3/src/test/java/FieldBindingTest.java0000664000175000017500000000157111650253660024762 0ustar jamespagejamespageimport junit.framework.TestCase; import net.sf.json.JSONObject; /** * @author Kohsuke Kawaguchi */ public class FieldBindingTest extends TestCase { public final class Foo { public int x; public String y; } public void test1() throws Exception { Foo f = new Foo(); f.x = 5; f.y = "test"; JSONObject o = JSONObject.fromObject(f); assertEquals(o.getInt("x"),5); assertEquals(o.getString("y"),"test"); assertEquals(o.size(),2); } private final class Bar { public int x; public String y; } public void test2() throws Exception { Bar f = new Bar(); f.x = 5; f.y = "test"; JSONObject o = JSONObject.fromObject(f); assertEquals(o.getInt("x"),5); assertEquals(o.getString("y"),"test"); assertEquals(o.size(),2); } } jenkins-json-2.4-jenkins-3/src/test/resources/0000775000175000017500000000000011650253660022026 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/resources/log4j.properties0000664000175000017500000000050111650253660025157 0ustar jamespagejamespagelog4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%d{yy-MM-dd HH:mm:ss}] %-5p [%-30.30c{1}:%L] %m%n log4j.rootLogger=WARN, console log4j.category.net.sf.json = DEBUG #log4j.category.net.sf.ezmorph = TRACE jenkins-json-2.4-jenkins-3/src/test/resources/runtimebug.xml0000664000175000017500000214717411650253660024751 0ustar jamespagejamespage jenkins-json-2.4-jenkins-3/src/test/resources/net/0000775000175000017500000000000011650253660022614 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/resources/net/sf/0000775000175000017500000000000011650253660023224 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/resources/net/sf/json/0000775000175000017500000000000011650253660024175 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/resources/net/sf/json/groovy/0000775000175000017500000000000011650253660025522 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/resources/net/sf/json/groovy/sample.json0000664000175000017500000000047611650253660027705 0ustar jamespagejamespage{ books: [ { name: 'Groovy in Action', author: 'Dierk Koenig' }, { name: 'The Definitive Guide to Grails', author: 'Graeme Rocher' }, { name: 'Groov Recipes, greasing the wheels of Java', author: 'Scott Davis' } ] }jenkins-json-2.4-jenkins-3/src/test/resources/net/sf/json/xml/0000775000175000017500000000000011650253660024775 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/resources/net/sf/json/xml/1739066.xml0000664000175000017500000000133711650253660026362 0ustar jamespagejamespage

    http://localhost:0/te stToString
    tns:GreetMeService tns:GreetMePortType jenkins-json-2.4-jenkins-3/src/test/resources/net/sf/json/xml/1735732.xml0000664000175000017500000000036311650253660026354 0ustar jamespagejamespage emp1 2 5 emp2 2 jenkins-json-2.4-jenkins-3/src/test/resources/net/sf/json/xml/delicious.xml0000664000175000017500000000266511650253660027510 0ustar jamespagejamespage del.icio.us/aalmiray/javascript http://del.icio.us/aalmiray/javascript Using prototype.js v1.5.0 http://www.sergiopereira.com/articles/prototype.js.html aalmiray 2007-01-03T19:25:20Z guide javascript prototype jenkins-json-2.4-jenkins-3/src/test/groovy/0000775000175000017500000000000011650253660021341 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/groovy/net/0000775000175000017500000000000011650253660022127 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/0000775000175000017500000000000011650253660022537 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/0000775000175000017500000000000011650253660023510 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/0000775000175000017500000000000011650253660025035 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/TestJsonGroovyBuilder.groovy0000664000175000017500000003262611650253660032603 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy import net.sf.json.* import net.sf.json.test.JSONAssert /** * @author Andres Almiray */ public class TestJsonGroovyBuilder extends GroovyTestCase { JsonGroovyBuilder builder void testBuildDefaultRootEmptyObject(){ def actual = builder.json {} JSONAssert.assertEquals( new JSONObject(), actual ) } void testBuildDefaultRootEmptyArray(){ builder.json = [] def actual = builder.json JSONAssert.assertEquals( new JSONArray(), actual ) } void testBuildDefaultRootObjectWithClosure(){ def actual = builder.json { string = "json" integer = 1 bool = true } def expected = new JSONObject() .element("string","json") .element("integer",1) .element("bool",true) JSONAssert.assertEquals( expected, actual ) } void testBuildDefaultRootObjectWithMap(){ def actual = builder.json([ 'string': "json", 'integer': 1, 'bool': true ]) def expected = new JSONObject() .element("string","json") .element("integer",1) .element("bool",true) JSONAssert.assertEquals( expected, actual ) } void testBuildDefaultRootArrayWithList(){ def actual = builder.json(["json", 1, true]) def expected = new JSONArray() .element("json") .element(1) .element(true) JSONAssert.assertEquals( expected, actual ) } void testBuildDefaultRootNestedObjects(){ def actual = builder.json { first = { integer = 42 } second = { integer = 48 } } def expected = new JSONObject() .element( "first", new JSONObject().element("integer",42) ) .element( "second", new JSONObject().element("integer",48) ) JSONAssert.assertEquals( expected, actual ) } void testBuildDefaultRootArrayWithMultipleArgs(){ def actual = builder.json( { key = "first" }, { key = "second" }, [key:'third'], [1,2,3], new Book(title: "Groovy in Action", author: "Dierk Konig"), "json" ) def expected = new JSONArray() .element( new JSONObject().element("key","first") ) .element( new JSONObject().element("key","second") ) .element( new JSONObject().element("key","third") ) .element( JSONArray.fromObject([1,2,3]) ) .element( new JSONObject() .element("title", "Groovy in Action") .element("author", "Dierk Konig") ) .element( "json") JSONAssert.assertEquals( expected, actual ) } void testBuildDefaultRootArrayWithMultipleArgs2(){ def actual = builder.json([key:'first'],[1,2,3]) { key = "third" } def expected = new JSONArray() .element( new JSONObject().element("key","first") ) .element( JSONArray.fromObject([1,2,3]) ) .element( new JSONObject().element("key","third") ) JSONAssert.assertEquals( expected, actual ) } void testBuildObjectWithMaps(){ def actual = builder.books { book = [title: "The Definitive Guide to Grails", author: "Graeme Rocher"] book = [title: "Groovy in Action", author: "Dierk Konig"] } def expected = new JSONObject() .element( "books", new JSONObject() .element( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) .accumulate( "book", new JSONObject() .element("title", "Groovy in Action") .element("author", "Dierk Konig") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObjectWithBeans(){ def actual = builder.books { book = new Book(title: "The Definitive Guide to Grails", author: "Graeme Rocher") book = new Book(title: "Groovy in Action", author: "Dierk Konig") } def expected = new JSONObject() .element( "books", new JSONObject() .element( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) .accumulate( "book", new JSONObject() .element("title", "Groovy in Action") .element("author", "Dierk Konig") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObjectWithClosures(){ def actual = builder.books { book = { title = "The Definitive Guide to Grails" author= "Graeme Rocher" } book = { title = "Groovy in Action" author = "Dierk Konig" } } def expected = new JSONObject() .element( "books", new JSONObject() .element( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) .accumulate( "book", new JSONObject() .element("title", "Groovy in Action") .element("author", "Dierk Konig") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObjectWithClosures2(){ def actual = builder.books { 2.times { book = { title = "The Definitive Guide to Grails" author= "Graeme Rocher" } } } def expected = new JSONObject() .element( "books", new JSONObject() .element( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) .accumulate( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObjectWithClosures3(){ def actual = builder.books { 2.times { book { title = "The Definitive Guide to Grails" author= "Graeme Rocher" } } } def expected = new JSONObject() .element( "books", new JSONObject() .element( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) .accumulate( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObjectWithClosures4(){ def actual = builder.books { book { title = "The Definitive Guide to Grails" author= "Graeme Rocher" } book { title = "The Definitive Guide to Grails" author= "Graeme Rocher" } } def expected = new JSONObject() .element( "books", new JSONObject() .element( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) .accumulate( "book", new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObjectWithMultipleClosures(){ def actual = builder.books( { title = "The Definitive Guide to Grails" author= "Graeme Rocher" }, { title = "Groovy in Action" author = "Dierk Konig" } ) def expected = new JSONObject() .element( "books", new JSONArray() .element( new JSONObject() .element("title", "The Definitive Guide to Grails") .element("author", "Graeme Rocher") ) .element( new JSONObject() .element("title", "Groovy in Action") .element("author", "Dierk Konig") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_Map_with_Closure(){ def actual = builder.json([object:{key = "value"}]) def expected = new JSONObject() .element( "object", new JSONObject() .element( "key", "value" ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_Map_with_Map(){ def actual = builder.json([object:[key:"value"]]) def expected = new JSONObject() .element( "object", new JSONObject() .element( "key", "value" ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_Map_with_List(){ def actual = builder.json([object: [1,2,3]]) def expected = new JSONObject() .element( "object", [1,2,3] ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_List_with_Closure(){ def actual = builder.json([{key = "value"}]) def expected = new JSONArray() .element( new JSONObject() .element( "key", "value" ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_List_with_Map(){ def actual = builder.json([[key:"value"]]) def expected = new JSONArray() .element( new JSONObject() .element( "key", "value" ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_List_with_List(){ def actual = builder.json([[1,2,3]]) def expected = new JSONArray() .element( [1,2,3] ) JSONAssert.assertEquals( expected, actual ) } /* void testBuildObject_GString_with_JSON(){ def actual = builder.json { json = """{ 'object': {'key':'value'}, 'array': [1,2,3] }""" } def expected = new JSONObject() .element( "json", new JSONObject() .element( "object", new JSONObject().element("key","value") ) .element( "array", [1,2,3] ) ) JSONAssert.assertEquals( expected, actual ) } */ void testBuildObject_GString_text(){ def actual = builder.json { func = """function(){ return this; }""" } def expected = new JSONObject() .element( "func", new JSONFunction("return this;") ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_Method_with_Map(){ def actual = builder.json { node( ['key':"value"] ) } def expected = new JSONObject() .element( "node", new JSONObject().element("key","value") ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_Method_with_List(){ def actual = builder.json { node( [1,2,3] ) } def expected = new JSONObject() .element( "node", JSONArray.fromObject([1,2,3]) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_Method_with_Map_multipleArgs(){ def actual = builder.json { node( ['key':"value"], ['key':"value"] ) } def expected = new JSONObject() .element( "node", new JSONArray() .element( new JSONObject().element("key","value") ) .element( new JSONObject().element("key","value") ) ) JSONAssert.assertEquals( expected, actual ) } void testBuildObject_Method_with_List_multipleArgs(){ def actual = builder.json { node( [1,2,3], [4,5,6] ) } def expected = new JSONObject() .element( "node", new JSONArray() .element( JSONArray.fromObject([1,2,3]) ) .element( JSONArray.fromObject([4,5,6]) ) ) JSONAssert.assertEquals( expected, actual ) } /* * This test makes sure that JSON Builder works properly from script. * See bug #302214 for details (https://sourceforge.net/tracker/?func=detail&aid=3022114&group_id=171425&atid=857928). */ void testUseBuilderFromScript() { def scriptClass = new GroovyClassLoader(this.getClass().classLoader).parseClass(''' new net.sf.json.groovy.JsonGroovyBuilder().json { string = 'value' } ''') def expected = new JSONObject().element( 'string', 'value') def actual = scriptClass.newInstance().run() JSONAssert.assertEquals( expected, actual ) } protected void setUp(){ builder = new JsonGroovyBuilder() builder.jsonConfig.setIgnorePublicFields(true) } }jenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/TestJsonSlurper.groovy0000664000175000017500000000703411650253660031436 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy import net.sf.json.* import net.sf.json.test.JSONAssert import org.apache.commons.httpclient.HttpClient import org.apache.commons.httpclient.methods.GetMethod /** * @author Andres Almiray */ class TestJsonSlurper extends GroovyTestCase { private JSONObject expected protected void setUp() throws Exception { GJson.enhanceClasses() expected = new JSONObject().element( 'books', [] ) expected.books << [name:'Groovy in Action', author: 'Dierk Koenig'] expected.books << [name:'The Definitive Guide to Grails', author: 'Graeme Rocher'] expected.books << [name:'Groov Recipes, greasing the wheels of Java', author: 'Scott Davis'] } void testParseFile() { File file = new File(new File(".").absolutePath,"src/test/resources/net/sf/json/groovy/sample.json") JSON actual = new JsonSlurper().parse( file ) JSONAssert.assertEquals( expected, actual ) } void testParseURL() { File file = new File(new File(".").absolutePath,"src/test/resources/net/sf/json/groovy/sample.json") JSON actual = new JsonSlurper().parse( file.toURL() ) JSONAssert.assertEquals( expected, actual ) } void testParseInputStream(){ File file = new File(new File(".").absolutePath,"src/test/resources/net/sf/json/groovy/sample.json") FileInputStream stream = new FileInputStream(file) JSON actual = new JsonSlurper().parse( stream ) JSONAssert.assertEquals( expected, actual ) } void testParseUri() { File file = new File(new File(".").absolutePath,"src/test/resources/net/sf/json/groovy/sample.json") JSON actual = new JsonSlurper().parse( "file://"+file.absolutePath ) JSONAssert.assertEquals( expected, actual ) } void testParseReader() { File file = new File(new File(".").absolutePath,"src/test/resources/net/sf/json/groovy/sample.json") JSON actual = new JsonSlurper().parse( new FileReader(file) ) JSONAssert.assertEquals( expected, actual ) } void testParsetext() { File file = new File(new File(".").absolutePath,"src/test/resources/net/sf/json/groovy/sample.json") JSON actual = new JsonSlurper().parseText( file.text ) JSONAssert.assertEquals( expected, actual ) } void testParseReader_liveUrl() { HttpClient http = new HttpClient() GetMethod get = new GetMethod("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Calvin%20and%20Hobbes") int resultCode = http.executeMethod(get) if( resultCode != 200 ) { fail("Http GET http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Calvin%20and%20Hobbes returned with code $resultCode") } Reader reader = new InputStreamReader( get.responseStream, "utf-8" ) JSON actual = new JsonSlurper().parse( reader ) assertTrue( actual.has("responseData") ) } }jenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/TestJSONArrayGroovy.groovy0000664000175000017500000000306411650253660032125 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy import net.sf.json.* import net.sf.json.test.JSONAssert /** * @author Andres Almiray */ class TestJSONArrayGroovy extends GroovyTestCase { protected void setUp() throws Exception { GJson.enhanceClasses() } public void testEqualsOperator(){ def json = new JSONArray().element(1) assertTrue json == json } public void testLessThanOperator(){ def json1 = new JSONArray().element(1) def json2 = new JSONArray().element(1).element(2) assertTrue json1 < json2 } public void testGreaterThanOperator(){ def json1 = new JSONArray().element(1) def json2 = new JSONArray().element(1).element(2) assertTrue json2 > json1 } public void testSpaceshipOperator(){ def json1 = new JSONArray().element(1) def json2 = new JSONArray().element(1).element(2) assertTrue 0 != (json1 <=> json2) } }jenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/AllTests.groovy0000664000175000017500000000232711650253660030043 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy import junit.framework.TestSuite /** * @author Andres Almiray */ class AllTests extends GroovyTestCase { public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite() suite.setName( "groovy" ) suite.addTest( new TestSuite( TestJsonGroovyBuilder ) ) suite.addTest( new TestSuite( TestJSONObjectGroovy ) ) suite.addTest( new TestSuite( TestJSONArrayGroovy ) ) suite.addTest( new TestSuite( TestMetaClasses ) ) suite.addTest( new TestSuite( TestJsonSlurper ) ) return suite } }jenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/TestJSONObjectGroovy.groovy0000664000175000017500000000513611650253660032257 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy import net.sf.json.* import net.sf.json.test.JSONAssert /** * @author Andres Almiray */ class TestJSONObjectGroovy extends GroovyTestCase { protected void setUp() throws Exception { GJson.enhanceClasses() } public void testLeftShift_with_map(){ def actual = new JSONObject() actual << [key:1] def expected = new JSONObject() .element( "key", 1 ) JSONAssert.assertEquals( expected, actual ) } public void testLeftShift_with_map2(){ def actual = new JSONObject() actual << [key:1,key2:2] def expected = new JSONObject() .element( "key", 1 ) .element( "key2", 2 ) JSONAssert.assertEquals( expected, actual ) } public void testLeftShift_with_list(){ def actual = new JSONObject() actual << ['key',1] def expected = new JSONObject() .element( "key", 1 ) JSONAssert.assertEquals( expected, actual ) } public void testLeftShift_with_list2(){ def actual = new JSONObject() actual << ['key',1,2,3] def expected = new JSONObject() .element( "key", 1 ) .accumulate( "key", 2 ) .accumulate( "key", 3 ) JSONAssert.assertEquals( expected, actual ) } public void testEqualsOperator(){ def json = new JSONObject().element("key",1) assertTrue json == json } public void testLessThanOperator(){ def json1 = new JSONObject().element("key",1) def json2 = new JSONObject().element("key",1).element("key2",2) assertTrue json1 < json2 } public void testGreaterThanOperator(){ def json1 = new JSONObject().element("key",1) def json2 = new JSONObject().element("key",1).element("key2",2) assertTrue json2 > json1 } public void testSpaceshipOperator(){ def json1 = new JSONObject().element("key",1) def json2 = new JSONObject().element("key",1).element("key2",2) assertTrue 0 != (json1 <=> json2) } }jenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/TestMetaClasses.groovy0000664000175000017500000000516311650253660031355 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy; import net.sf.json.* import net.sf.json.test.JSONAssert /** * @author Andres Almiray */ class TestMetaClasses extends GroovyTestCase { protected void setUp() throws Exception { GJson.enhanceClasses() } void testJONObjectGet_withDefaultValue(){ def json = new JSONObject(); assertNull json.opt("key") json.get("key","value") assertNotNull json.get("key") assertEquals "value", json.get("key") } void testTypeConversion_Map_to_JSONObject(){ def map = [key:'value'] def expected = new JSONObject().element("key","value") def actual = map as JSONObject JSONAssert.assertEquals expected, actual } void testTypeConversion_List_to_JSONArray(){ def list = [1,"2",true] def expected = new JSONArray() .element(1) .element("2") .element(true) def actual = list as JSONArray JSONAssert.assertEquals expected, actual } void testTypeConversion_String_to_JSONObject(){ def expected = new JSONObject().element("key","value") def actual = "{'key':'value'}" as JSONObject JSONAssert.assertEquals expected, actual } void testTypeConversion_String_to_JSONArray(){ def expected = new JSONArray() .element(1) .element("2") .element(true) def actual = "[1,'2',true]" as JSONArray JSONAssert.assertEquals expected, actual } void testTypeConversion_String_to_JSONFunction(){ def expected = new JSONFunction("return this;") def actual = "function(){return this;}" as JSONFunction assertEquals expected, actual } void testTypeConversion_String_to_JSON_object(){ def expected = new JSONObject().element("key","value") def actual = "{'key':'value'}" as JSON JSONAssert.assertEquals expected, actual } void testTypeConversion_String_to_JSON_array(){ def expected = new JSONArray() .element(1) .element("2") .element(true) def actual = "[1,'2',true]" as JSON JSONAssert.assertEquals expected, actual } }jenkins-json-2.4-jenkins-3/src/test/groovy/net/sf/json/groovy/Book.groovy0000664000175000017500000000140611650253660027177 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.groovy /** * @author Andres Almiray */ public class Book { String title String author }jenkins-json-2.4-jenkins-3/src/test/jdk15/0000775000175000017500000000000011650253660020732 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/jdk15/net/0000775000175000017500000000000011650253660021520 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/0000775000175000017500000000000011650253660022130 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/0000775000175000017500000000000011650253660023101 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/TestJSONArrayCollection.java0000664000175000017500000001551511650253660030377 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import junit.framework.TestCase; import net.sf.json.sample.GenericsBean; import net.sf.json.sample.GenericsBean.GenericsInternalBean; import org.apache.commons.beanutils.PropertyUtils; /** * @author Matt Small */ public class TestJSONArrayCollection extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayCollection.class ); } public TestJSONArrayCollection( String testName ) { super( testName ); } /* public void testErrorInList() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "stringList" ); JSONArray ja = JSONArray.fromObject( "[12, \"bar\"]" ); JsonConfig jc = new JsonConfig(); try{ jc.setCollectionType( pd.getPropertyType() ); jc.setEnclosedType( JSONArray.getCollectionType( pd, false )[0] ); JSONArray.toCollection( ja, jc ); fail( "didn't get exception" ); }catch( JSONException e ){ // ignore } } public void testGetCollectionType() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "stringSet" ); assertEquals( 1, JSONArray.getCollectionType( pd, false ).length ); assertEquals( String.class, JSONArray.getCollectionType( pd, false )[0] ); assertEquals( 1, JSONArray.getCollectionType( pd, true ).length ); assertEquals( String.class, JSONArray.getCollectionType( pd, true )[0] ); pd = PropertyUtils.getPropertyDescriptor( gb, "stringList" ); assertEquals( 1, JSONArray.getCollectionType( pd, false ).length ); assertEquals( String.class, JSONArray.getCollectionType( pd, false )[0] ); assertEquals( 1, JSONArray.getCollectionType( pd, true ).length ); assertEquals( String.class, JSONArray.getCollectionType( pd, true )[0] ); } public void testToInternalBeanList() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "genericsInternalBeanList" ); JSONArray ja = JSONArray.fromObject( "[{\"string\": \"foo\"}, {\"string\": \"bar\"}]" ); JsonConfig jc = new JsonConfig(); jc.setCollectionType( pd.getPropertyType() ); jc.setEnclosedType( JSONArray.getCollectionType( pd, false )[0] ); Collection c = JSONArray.toCollection( ja, jc); assertEquals( 2, c.size() ); assertTrue( c instanceof ArrayList ); for( Object o : c ){ assertTrue( o instanceof GenericsInternalBean ); GenericsInternalBean gib = (GenericsInternalBean) o; if( gib.getString() .equals( "foo" ) ){ // pass }else if( gib.getString() .equals( "bar" ) ){ // pass }else{ fail( "unknown gib: " + gib.getString() ); } } } public void testToStringArrayList() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "stringArrayList" ); JSONArray ja = JSONArray.fromObject( "[\"foo\", \"bar\"]" ); JsonConfig jc = new JsonConfig(); jc.setCollectionType( pd.getPropertyType() ); jc.setEnclosedType( JSONArray.getCollectionType( pd, false )[0] ); Collection c = JSONArray.toCollection( ja, jc ); assertEquals( 2, c.size() ); assertTrue( c instanceof ArrayList ); assertTrue( c.contains( "foo" ) ); assertTrue( c.contains( "bar" ) ); } public void testToStringHashSet() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "stringHashSet" ); JSONArray ja = JSONArray.fromObject( "[\"foo\", \"bar\"]" ); JsonConfig jc = new JsonConfig(); jc.setCollectionType( pd.getPropertyType() ); jc.setEnclosedType( JSONArray.getCollectionType( pd, false )[0] ); Collection c = JSONArray.toCollection( ja, jc ); assertEquals( 2, c.size() ); assertTrue( c instanceof HashSet ); assertTrue( c.contains( "foo" ) ); assertTrue( c.contains( "bar" ) ); } public void testToStringList() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "stringList" ); JSONArray ja = JSONArray.fromObject( "[\"foo\", \"bar\"]" ); JsonConfig jc = new JsonConfig(); jc.setCollectionType( pd.getPropertyType() ); jc.setEnclosedType( JSONArray.getCollectionType( pd, false )[0] ); Collection c = JSONArray.toCollection( ja, jc ); assertEquals( 2, c.size() ); assertTrue( c instanceof ArrayList ); assertTrue( c.contains( "foo" ) ); assertTrue( c.contains( "bar" ) ); } public void testToStringSet() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "stringSet" ); JSONArray ja = JSONArray.fromObject( "[\"foo\", \"bar\"]" ); JsonConfig jc = new JsonConfig(); jc.setCollectionType( pd.getPropertyType() ); jc.setEnclosedType( JSONArray.getCollectionType( pd, false )[0] ); Collection c = JSONArray.toCollection( ja, jc); assertEquals( 2, c.size() ); assertTrue( c instanceof HashSet ); assertTrue( c.contains( "foo" ) ); assertTrue( c.contains( "bar" ) ); } public void testToUntypedList() throws Exception { GenericsBean gb = new GenericsBean(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( gb, "noTypeList" ); JSONArray ja = JSONArray.fromObject( "[\"foo\", \"bar\", 12]" ); JsonConfig jc = new JsonConfig(); jc.setCollectionType( pd.getPropertyType() ); Collection c = JSONArray.toCollection( ja, jc ); assertEquals( 3, c.size() ); assertTrue( c instanceof ArrayList ); assertTrue( c.contains( "foo" ) ); assertTrue( c.contains( "bar" ) ); assertTrue( c.contains( 12 ) ); } */ public void testNOOP() {} } jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/TestJSONObjectJdk15.java0000664000175000017500000001725411650253660027314 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.ezmorph.Morpher; import net.sf.ezmorph.bean.MorphDynaBean; import net.sf.ezmorph.bean.MorphDynaClass; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.sample.AnnotationBean; import net.sf.json.sample.AnnotatedBean; import net.sf.json.sample.EnumBean; import net.sf.json.sample.JsonEnum; import net.sf.json.sample.JsonAnnotation; import net.sf.json.util.EnumMorpher; import net.sf.json.util.JSONUtils; /** * @author Andres Almiray */ public class TestJSONObjectJdk15 extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONObjectJdk15.class ); } public TestJSONObjectJdk15( String testName ) { super( testName ); } public void testFromBean_AnnotationBean() { AnnotationBean bean = new AnnotationBean(); Annotation[] annotations = bean.getClass() .getAnnotations(); try{ JSONObject.fromObject( annotations[0] ); fail( "Expected a JSONException" ); } catch( JSONException expected ){ // ok } } public void testFromBean_Enum() { try{ JSONObject.fromObject( JsonEnum.OBJECT ); fail( "Expected a JSONException" ); } catch( JSONException expected ){ // ok } } public void testFromBean_EnumBean() { EnumBean bean = new EnumBean(); bean.setJsonEnum( JsonEnum.OBJECT ); bean.setString( "string" ); JSONObject json = JSONObject.fromObject( bean ); assertNotNull( json ); assertEquals( JsonEnum.OBJECT.toString(), json.get( "jsonEnum" ) ); assertEquals( "string", json.get( "string" ) ); } public void testFromObject_AnnotationBean() { AnnotationBean bean = new AnnotationBean(); Annotation[] annotations = bean.getClass() .getAnnotations(); try{ JSONObject.fromObject( annotations[0] ); fail( "Expected a JSONException" ); } catch( JSONException expected ){ // ok } } public void testFromObject_DynaBean__Enum() throws Exception { Map properties = new HashMap(); properties.put( "jsonEnum", JsonEnum.class ); MorphDynaClass dynaClass = new MorphDynaClass( properties ); MorphDynaBean dynaBean = (MorphDynaBean) dynaClass.newInstance(); dynaBean.setDynaBeanClass( dynaClass ); dynaBean.set( "jsonEnum", JsonEnum.OBJECT ); JSONObject json = JSONObject.fromObject( dynaBean ); assertNotNull( json ); assertEquals( JsonEnum.OBJECT.toString(), json.get( "jsonEnum" ) ); } public void testFromObject_Enum() { try{ JSONObject.fromObject( JsonEnum.OBJECT ); fail( "Expected a JSONException" ); } catch( JSONException expected ){ // ok } } public void testFromObject_EnumBean() { EnumBean bean = new EnumBean(); bean.setJsonEnum( JsonEnum.OBJECT ); bean.setString( "string" ); JSONObject json = JSONObject.fromObject( bean ); assertNotNull( json ); assertEquals( JsonEnum.OBJECT.toString(), json.get( "jsonEnum" ) ); assertEquals( "string", json.get( "string" ) ); } public void testFromObject_Map__Enum() { Map properties = new HashMap(); properties.put( "jsonEnum", JsonEnum.OBJECT ); JSONObject json = JSONObject.fromObject( properties ); assertNotNull( json ); assertEquals( JsonEnum.OBJECT.toString(), json.get( "jsonEnum" ) ); } public void testPut_Annotation() { AnnotationBean bean = new AnnotationBean(); Annotation[] annotations = bean.getClass() .getAnnotations(); try{ JSONObject jsonObject = new JSONObject(); jsonObject.element( "annotation", annotations[0] ); fail( "Expected a JSONException" ); } catch( JSONException expected ){ // ok } } public void testPut_Enum() { JSONObject json = new JSONObject(); json.element( "jsonEnum", JsonEnum.OBJECT ); assertEquals( JsonEnum.OBJECT.toString(), json.get( "jsonEnum" ) ); } public void testToBean_EnumBean() { JSONUtils.getMorpherRegistry() .registerMorpher( new EnumMorpher( JsonEnum.class ) ); JSONObject json = new JSONObject(); json.element( "jsonEnum", "OBJECT" ); EnumBean bean = (EnumBean) JSONObject.toBean( json, EnumBean.class ); assertNotNull( bean ); assertEquals( bean.getJsonEnum(), JsonEnum.OBJECT ); } /* public void testToBean_EnumBean2() { JSONUtils.getMorpherRegistry() .registerMorpher( new EnumMorpher( JsonEnum.class ) ); EnumBean bean = new EnumBean(); bean.getEnums().add(JsonEnum.ARRAY); bean.getEnums().add(JsonEnum.OBJECT); JSONObject json = JSONObject.fromObject(bean); System.err.println(json); EnumBean bean2 = (EnumBean) JSONObject.toBean( json, EnumBean.class ); assertNotNull( bean2 ); System.err.println(bean.getEnums().toString()); System.err.println(bean2.getEnums().toString()); Map classMap = new HashMap(); classMap.put("enums", JsonEnum.class); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( EnumBean.class ); jsonConfig.setClassMap(classMap); EnumBean bean3 = (EnumBean) JSONObject.toBean( JSONObject.fromObject(json.toString()), jsonConfig ); assertNotNull( bean3 ); System.err.println(bean3.getEnums().toString()); for(java.util.Iterator i= bean3.getEnums().iterator(); i.hasNext();) System.err.println(i.next().getClass()); } */ public void testToBean_EnumBean_autoRegisterMorpher() { JSONObject json = new JSONObject(); json.element( "jsonEnum", "OBJECT" ); EnumBean bean = (EnumBean) JSONObject.toBean( json, EnumBean.class ); assertNotNull( bean ); assertEquals( bean.getJsonEnum(), JsonEnum.OBJECT ); } public void testFromObject_ignoreAnnotations() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.addIgnoreFieldAnnotation( JsonAnnotation.class ); AnnotatedBean bean = new AnnotatedBean(); bean.setString1("STRING_1"); bean.setString2("STRING_2"); bean.setString3("STRING_3"); JSONObject json = JSONObject.fromObject(bean, jsonConfig); assertNotNull(json); assertEquals("STRING_1", json.get("string1")); assertEquals("STRING_2", json.get("string2")); assertFalse(json.has( "string3" )); jsonConfig.setIgnoreTransientFields( true ); json = JSONObject.fromObject(bean, jsonConfig); assertNotNull(json); assertEquals("STRING_1", json.get("string1")); assertFalse(json.has( "string2" )); assertFalse(json.has( "string3" )); } protected void setUp() throws Exception { Morpher morpher = JSONUtils.getMorpherRegistry().getMorpherFor( JsonEnum.class ); JSONUtils.getMorpherRegistry().deregisterMorpher( morpher ); } }jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/sample/0000775000175000017500000000000011650253660024362 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/sample/AnnotatedBean.java0000664000175000017500000000243711650253660027736 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public class AnnotatedBean { private String string1; @JsonAnnotation private String string2; private String string3; public String getString1() { return string1; } public void setString1( String string ) { this.string1 = string; } public String getString2() { return string2; } public void setString2( String string ) { this.string2 = string; } @JsonAnnotation public String getString3() { return string3; } public void setString3( String string ) { this.string3 = string; } }jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/sample/AnnotationBean.java0000664000175000017500000000165511650253660030134 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ @JsonAnnotation("json") public class AnnotationBean { private String string; public String getString() { return string; } public void setString( String string ) { this.string = string; } }jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/sample/JsonEnum.java0000664000175000017500000000136711650253660026772 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; /** * @author Andres Almiray */ public enum JsonEnum { ARRAY, OBJECT }jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/sample/EnumBean.java0000664000175000017500000000251411650253660026721 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.Set; import java.util.HashSet; /** * @author Andres Almiray */ public class EnumBean { private JsonEnum jsonEnum; private String string; private Set enums = new HashSet(); public JsonEnum getJsonEnum() { return jsonEnum; } public String getString() { return string; } public Set getEnums() { return enums; } public void setJsonEnum( JsonEnum jsonEnum ) { this.jsonEnum = jsonEnum; } public void setString( String string ) { this.string = string; } public void setEnums( Set enums ) { this.enums = enums; } }jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/sample/JsonAnnotation.java0000664000175000017500000000161111650253660030170 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * @author Andres Almiray */ @Retention(RetentionPolicy.RUNTIME) public @interface JsonAnnotation { String value() default ""; }jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/sample/GenericsBean.java0000664000175000017500000000470611650253660027561 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.sample; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Matt Small */ public class GenericsBean { private List genericsInternalBeanList; private List noTypeList; private ArrayList stringArrayList; private HashSet stringHashSet; private List stringList; private Set stringSet; public List getGenericsInternalBeanList() { return genericsInternalBeanList; } public List getNoTypeList() { return noTypeList; } public ArrayList getStringArrayList() { return stringArrayList; } public HashSet getStringHashSet() { return stringHashSet; } public List getStringList() { return stringList; } public Set getStringSet() { return stringSet; } public void setGenericsInternalBeanList( List genericsInternalBeanList ) { this.genericsInternalBeanList = genericsInternalBeanList; } public void setNoTypeList( List noTypeList ) { this.noTypeList = noTypeList; } public void setStringArrayList( ArrayList stringArrayList ) { this.stringArrayList = stringArrayList; } public void setStringHashSet( HashSet stringHashSet ) { this.stringHashSet = stringHashSet; } public void setStringList( List stringList ) { this.stringList = stringList; } public void setStringSet( Set stringSet ) { this.stringSet = stringSet; } public static class GenericsInternalBean { private String string; public String getString() { return string; } public void setString( String string ) { this.string = string; } } }jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/TestGenerics.java0000664000175000017500000001176111650253660026351 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import net.sf.json.sample.GenericsBean; import net.sf.json.sample.GenericsBean.GenericsInternalBean; /** * @author Matt Small */ public class TestGenerics extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestGenerics.class ); } public TestGenerics( String testName ) { super( testName ); } /* public void testBasicList() throws Exception { GenericsBean gb = new GenericsBean(); List stringAL = new ArrayList(); stringAL.add( "foo" ); stringAL.add( "bar" ); gb.setStringList( stringAL ); JSONObject jo = JSONObject.fromObject( gb ); String serializedString = jo.toString(); jo = JSONObject.fromObject( serializedString ); Object o = JSONObject.toBean( jo, GenericsBean.class ); assertTrue( o instanceof GenericsBean ); List resultStringAL = ((GenericsBean) o).getStringList(); assertEquals( stringAL.size(), resultStringAL.size() ); assertEquals( stringAL.get( 0 ), resultStringAL.get( 0 ) ); assertEquals( stringAL.get( 1 ), resultStringAL.get( 1 ) ); } public void testBasicSet() throws Exception { GenericsBean gb = new GenericsBean(); Set stringHS = new HashSet(); stringHS.add( "foo" ); stringHS.add( "bar" ); gb.setStringSet( stringHS ); JSONObject jo = JSONObject.fromObject( gb ); String serializedString = jo.toString(); jo = JSONObject.fromObject( serializedString ); Object o = JSONObject.toBean( jo, GenericsBean.class ); assertTrue( o instanceof GenericsBean ); Set resultStringHS = ((GenericsBean) o).getStringSet(); assertEquals( stringHS.size(), resultStringHS.size() ); for( String s : resultStringHS ){ assertTrue( stringHS.contains( s ) ); } } public void testComplexInList() throws Exception { GenericsBean gb = new GenericsBean(); List ibList = new ArrayList(); GenericsInternalBean gib = new GenericsInternalBean(); gib.setString( "foo" ); ibList.add( gib ); gib = new GenericsInternalBean(); gib.setString( "bar" ); ibList.add( gib ); gb.setGenericsInternalBeanList( ibList ); JSONObject jo = JSONObject.fromObject( gb ); String serializedString = jo.toString(); jo = JSONObject.fromObject( serializedString ); Object o = JSONObject.toBean( jo, GenericsBean.class ); assertTrue( o instanceof GenericsBean ); List resultIBList = ((GenericsBean) o).getGenericsInternalBeanList(); assertEquals( ibList.size(), resultIBList.size() ); assertEquals( ibList.get( 0 ) .getString(), resultIBList.get( 0 ) .getString() ); assertEquals( ibList.get( 1 ) .getString(), resultIBList.get( 1 ) .getString() ); } public void testOnlyList() throws Exception { OnlyListBean gb = new OnlyListBean(); ArrayList stringAL = new ArrayList(); stringAL.add( "foo" ); stringAL.add( "bar" ); gb.setStringList( stringAL ); JSONObject jo = JSONObject.fromObject( gb ); Object slO = jo.get( "stringList" ); assertTrue( slO instanceof JSONArray ); JSONArray sloJA = (JSONArray) slO; assertEquals( 2, sloJA.size() ); assertTrue( sloJA.contains( "foo" ) ); assertTrue( sloJA.contains( "bar" ) ); String serializedString = jo.toString(); jo = JSONObject.fromObject( serializedString ); Object o = JSONObject.toBean( jo, OnlyListBean.class ); assertTrue( o instanceof OnlyListBean ); OnlyListBean olb = (OnlyListBean) o; assertEquals( 2, olb.getStringList() .size() ); assertTrue( olb.getStringList() .contains( "foo" ) ); assertTrue( olb.getStringList() .contains( "bar" ) ); } */ public void testNOOP() {} public static class OnlyListBean { private List stringList; public List getStringList() { return stringList; } public void setStringList( List stringList ) { this.stringList = stringList; } } } jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/bugs/0000775000175000017500000000000011650253660024041 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/bugs/TestBug2843623.java0000664000175000017500000000207611650253660027042 0ustar jamespagejamespagepackage net.sf.json.bugs; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; public class TestBug2843623 extends TestCase { public void testSample() { Container orig = new Container(); List strings = new ArrayList(); strings.add("one"); strings.add("two"); strings.add("three"); orig.setMyList(strings); JSONObject jobj = JSONObject.fromObject(orig); Container root = new Container(); Container res = (Container)JSONObject.toBean(jobj, root, new JsonConfig()); assertTrue(res.getMyList().size() > 0); assertTrue(root.getMyList().size() > 0); } public static class Container { private List myList = new ArrayList(); public List getMyList() { return myList; } public void setMyList(List strings) { this.myList.addAll(strings); } } } jenkins-json-2.4-jenkins-3/src/test/jdk15/net/sf/json/TestJSONArrayJdk15.java0000664000175000017500000001134311650253660027155 0ustar jamespagejamespage/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import net.sf.json.sample.AnnotationBean; import net.sf.json.sample.JsonEnum; /** * @author Andres Almiray */ public class TestJSONArrayJdk15 extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestJSONArrayJdk15.class ); } public TestJSONArrayJdk15( String testName ) { super( testName ); } public void testConstructor_Annotation() { AnnotationBean bean = new AnnotationBean(); Annotation[] annotations = bean.getClass() .getAnnotations(); try{ JSONArray.fromObject( annotations[0] ); fail( "Expected a JSONException" ); } catch( JSONException expected ){ // ok } } public void testConstructor_Collection() { List l = new ArrayList(); l.add( Boolean.TRUE ); l.add( new Integer( 1 ) ); l.add( "string" ); l.add( Object.class ); l.add( JsonEnum.ARRAY ); testJSONArray( l, "[true,1,\"string\",\"java.lang.Object\",\"ARRAY\"]" ); } public void testConstructor_Enum() { testJSONArray( JsonEnum.ARRAY, "[\"ARRAY\"]" ); } public void testConstructor_Object_Array_Enum() { JSONArray expected = JSONArray.fromObject( "[\"ARRAY\",\"OBJECT\"]" ); JSONArray actual = JSONArray.fromObject( new JsonEnum[] { JsonEnum.ARRAY, JsonEnum.OBJECT } ); Assertions.assertEquals( expected, actual ); } public void testFromObject_Enum() { JSONArray actual = JSONArray.fromObject( JsonEnum.ARRAY ); JSONArray expected = new JSONArray().element( "ARRAY" ); Assertions.assertEquals( expected, actual ); } public void testPut_Enum() { JSONArray jsonArray = new JSONArray(); jsonArray.element( JsonEnum.ARRAY ); assertEquals( 1, jsonArray.size() ); assertEquals( "ARRAY", jsonArray.get( 0 ) ); } public void testPut_Enum_2() { JSONArray jsonArray = new JSONArray(); jsonArray.element( (JsonEnum) null ); assertEquals( 1, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); } public void testPut_index_0_Annotation() { AnnotationBean bean = new AnnotationBean(); Annotation[] annotations = bean.getClass() .getAnnotations(); try{ JSONArray array = JSONArray.fromObject( "[null,null]" ); array.element( 0, annotations[0] ); fail( "Expected a JSONException" ); } catch( JSONException expected ){ // ok } } public void testPut_index_0_Enum() { JSONArray jsonArray = JSONArray.fromObject( "[null,null]" ); jsonArray.element( 0, JsonEnum.ARRAY ); assertEquals( "ARRAY", jsonArray.get( 0 ) ); assertEquals( JSONNull.getInstance(), jsonArray.get( 1 ) ); } public void testPut_index_0_Enum_2() { JSONArray jsonArray = JSONArray.fromObject( "[null,null]" ); jsonArray.element( 0, (JsonEnum) null ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); assertEquals( JSONNull.getInstance(), jsonArray.get( 1 ) ); } public void testPut_index_1_Enum() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, JsonEnum.ARRAY ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); assertEquals( "ARRAY", jsonArray.get( 1 ) ); } public void testPut_index_1_Enum_2() { JSONArray jsonArray = new JSONArray(); jsonArray.element( 1, (JsonEnum) null ); assertEquals( 2, jsonArray.size() ); assertEquals( JSONNull.getInstance(), jsonArray.get( 0 ) ); assertEquals( JSONNull.getInstance(), jsonArray.get( 1 ) ); } private void testJSONArray( Object array, String expected ) { try{ JSONArray jsonArray = JSONArray.fromObject( array ); assertEquals( expected, jsonArray.toString() ); } catch( JSONException jsone ){ fail( jsone.getMessage() ); } } }jenkins-json-2.4-jenkins-3/build.properties0000664000175000017500000000005211650253660021460 0ustar jamespagejamespagemaven.repo.local = /usr/dev/m2/repository jenkins-json-2.4-jenkins-3/net.sf.json-lib.sh0000664000175000017500000000030711650253660021513 0ustar jamespagejamespage#!/bin/sh CONTACTS="Andres Almiray " MODE=rsync_ssh FROM=mavensync@shell.sourceforge.net:/home/groups/j/js/json-lib/htdocs/m2/repo/release GROUP_DIR=net/sf/json-lib/jenkins-json-2.4-jenkins-3/extensions/0000775000175000017500000000000011650253660020445 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/0000775000175000017500000000000011650253660021747 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/deploy.sh0000664000175000017500000000266211650253660023605 0ustar jamespagejamespage#!/bin/sh VERSION="1.0.2" GROUPID="net.sf.json-lib" ARTIFACTID="json-lib-ext-spring" REPO_URL="scp://ssh.sf.net/home/groups/j/js/json-lib/htdocs/m2/repo/release" REPOSITORYID="sf_release" mkdir build mvn clean javadoc:jar source:jar package mv target/${ARTIFACTID}-${VERSION}-sources.jar build mv target/${ARTIFACTID}-${VERSION}-javadoc.jar build mv target/${ARTIFACTID}-${VERSION}.jar build mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -DgeneratePom=false \ -Dclassifier=javadoc \ -Dfile=build/${ARTIFACTID}-${VERSION}-javadoc.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -DgeneratePom=false \ -Dclassifier=sources \ -Dfile=build/${ARTIFACTID}-${VERSION}-sources.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=jar \ -Dfile=build/${ARTIFACTID}-${VERSION}.jar mvn deploy:deploy-file -DrepositoryId=${REPOSITORYID} \ -Durl=${REPO_URL} \ -DgroupId=${GROUPID} \ -DartifactId=${ARTIFACTID} \ -Dversion=${VERSION} \ -Dpackaging=pom \ -DgeneratePom=false \ -Dfile=pom.xml jenkins-json-2.4-jenkins-3/extensions/spring/pom.xml0000664000175000017500000001422111650253660023264 0ustar jamespagejamespage 4.0.0 net.sf.json-lib json-lib-ext-spring jar 1.0.2 Json-lib4Spring http://json-lib.sourceforge.net 2006 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo This product includes software developed by Douglas Crockford (http://www.crockford.com). Json-lib http://json-lib.sourceforge.net scm:cvs:pserver:anonymous@json-lib.cvs.sourceforge.net:/cvsroot/json-lib:json-lib http://json-lib.cvs.sourceforge.net/json-lib scm:cvs:ext:${maven.username}@json-lib.cvs.sourceforge.net:/cvsroot/json-lib:json-lib SourceForge https://sourceforge.net/tracker/?group_id=171425 Json-lib User List http://lists.sourceforge.net/lists/listinfo/json-lib-user http://lists.sourceforge.net/lists/listinfo/json-lib-user http://sourceforge.net/mailarchive/forum.php?forum=json-lib-user Andres Almiray aalmiray aalmiray@users.sourceforge.net -5 Java Developer net.sf.json-lib json-lib 2.3 jdk15 org.springframework spring-webmvc 2.5.4 javax.servlet servlet-api 2.4 org.springframework spring-mock 2.0.8 test junit junit 3.8.2 test net.sf.jstester jstester 1.4.1 jdk14 test log4j log4j 1.2.14 runtime 2.0.9 install maven-compiler-plugin 1.5 1.5 org.apache.maven.plugins maven-surefire-plugin **/Abstract*.java **/*TestSuite.java **/*Test.java org.apache.maven.plugins maven-project-info-reports-plugin org.apache.maven.plugins maven-surefire-report-plugin org.apache.maven.plugins maven-jxr-plugin org.apache.maven.plugins maven-javadoc-plugin org.codehaus.mojo cobertura-maven-plugin json-lib http://json-lib.sf.net/m2/repo/release/ jstester http://jstester.sf.net/m2/repo/release/ jenkins-json-2.4-jenkins-3/extensions/spring/.cvsignore0000664000175000017500000000006311650253660023746 0ustar jamespagejamespagetarget .settings .project .classpath build testapp jenkins-json-2.4-jenkins-3/extensions/spring/src/0000775000175000017500000000000011650253660022536 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/0000775000175000017500000000000011650253660023462 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/0000775000175000017500000000000011650253660024403 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/0000775000175000017500000000000011650253660025171 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/0000775000175000017500000000000011650253660025601 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/json/0000775000175000017500000000000011650253660026552 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/json/spring/0000775000175000017500000000000011650253660030054 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/json/spring/web/0000775000175000017500000000000011650253660030631 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/json/spring/web/servlet/0000775000175000017500000000000011650253660032315 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/json/spring/web/servlet/view/0000775000175000017500000000000011650253660033267 5ustar jamespagejamespage././@LongLink0000644000000000000000000000015512255646554011661 Lustar rootrootjenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/json/spring/web/servlet/view/JsonView.javajenkins-json-2.4-jenkins-3/extensions/spring/src/main/java/net/sf/json/spring/web/servlet/view/JsonV0000664000175000017500000001240511650253660034253 0ustar jamespagejamespage/* * Copyright 2006-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.spring.web.servlet.view; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONSerializer; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; import net.sf.json.filters.OrPropertyFilter; import org.springframework.web.servlet.view.AbstractView; /** * A View that renders its model as a JSON object. * * @author Andres Almiray */ public class JsonView extends AbstractView { /** Default content type. Overridable as bean property. */ private static final String DEFAULT_JSON_CONTENT_TYPE = "application/json;charset=UTF-8"; private boolean forceTopLevelArray = false; private boolean skipBindingResult = true; /** Json confiiguration */ private JsonConfig jsonConfig = new JsonConfig(); public JsonView() { super(); setContentType( DEFAULT_JSON_CONTENT_TYPE ); } public JsonConfig getJsonConfig(){ return jsonConfig; } public boolean isForceTopLevelArray() { return forceTopLevelArray; } /** * Returns whether the JSONSerializer will ignore or not its internal property * exclusions. */ public boolean isIgnoreDefaultExcludes() { return jsonConfig.isIgnoreDefaultExcludes(); } /** * Returns whether the JSONSerializer will skip or not any BindingResult related keys on the model.

    * Models in Spring >= 2.5 will cause an exception as they contain a BindingResult that cycles back. */ public boolean isSkipBindingResult() { return skipBindingResult; } /** * Sets the group of properties to be excluded. */ public void setExcludedProperties( String[] excludedProperties ) { jsonConfig.setExcludes( excludedProperties ); } public void setForceTopLevelArray( boolean forceTopLevelArray ) { this.forceTopLevelArray = forceTopLevelArray; } /** * Sets whether the JSONSerializer will ignore or not its internal property * exclusions. */ public void setIgnoreDefaultExcludes( boolean ignoreDefaultExcludes ) { jsonConfig.setIgnoreDefaultExcludes( ignoreDefaultExcludes ); } public void setJsonConfig( JsonConfig jsonConfig ) { this.jsonConfig = jsonConfig != null ? jsonConfig : new JsonConfig(); if( skipBindingResult ){ PropertyFilter jsonPropertyFilter = this.jsonConfig.getJsonPropertyFilter(); if( jsonPropertyFilter == null ) { this.jsonConfig.setJsonPropertyFilter( new BindingResultPropertyFilter() ); }else{ this.jsonConfig.setJsonPropertyFilter( new OrPropertyFilter(new BindingResultPropertyFilter(), jsonPropertyFilter) ); } } } /** * Sets whether the JSONSerializer will skip or not any BindingResult related keys on the model.

    * Models in Spring >= 2.5 will cause an exception as they contain a BindingResult that cycles back. */ public void setSkipBindingResult( boolean skipBindingResult ) { this.skipBindingResult = skipBindingResult; } /** * Creates a JSON [JSONObject,JSONArray,JSONNUll] from the model values. */ protected JSON createJSON( Map model, HttpServletRequest request, HttpServletResponse response ) { return defaultCreateJSON( model ); } /** * Creates a JSON [JSONObject,JSONArray,JSONNUll] from the model values. */ protected final JSON defaultCreateJSON( Map model ) { if( skipBindingResult && jsonConfig.getJsonPropertyFilter() == null ){ this.jsonConfig.setJsonPropertyFilter( new BindingResultPropertyFilter() ); } return JSONSerializer.toJSON( model, jsonConfig ); } /** * Returns the group of properties to be excluded. */ protected String[] getExcludedProperties() { return jsonConfig.getExcludes(); } protected void renderMergedOutputModel( Map model, HttpServletRequest request, HttpServletResponse response ) throws Exception { response.setContentType( getContentType() ); writeJSON( model, request, response ); } protected void writeJSON( Map model, HttpServletRequest request, HttpServletResponse response ) throws Exception { JSON json = createJSON( model, request, response ); if( forceTopLevelArray ){ json = new JSONArray().element(json); } json.write( response.getWriter() ); } private static class BindingResultPropertyFilter implements PropertyFilter { public boolean apply( Object source, String name, Object value ) { return name.startsWith("org.springframework.validation.BindingResult."); } } } jenkins-json-2.4-jenkins-3/extensions/spring/src/test/0000775000175000017500000000000011650253660023515 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/0000775000175000017500000000000011650253660024436 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/0000775000175000017500000000000011650253660025224 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/0000775000175000017500000000000011650253660025634 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/json/0000775000175000017500000000000011650253660026605 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/json/spring/0000775000175000017500000000000011650253660030107 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/json/spring/web/0000775000175000017500000000000011650253660030664 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/json/spring/web/servlet/0000775000175000017500000000000011650253660032350 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/json/spring/web/servlet/view/0000775000175000017500000000000011650253660033322 5ustar jamespagejamespage././@LongLink0000644000000000000000000000016112255646554011656 Lustar rootrootjenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/json/spring/web/servlet/view/JsonViewTest.javajenkins-json-2.4-jenkins-3/extensions/spring/src/test/java/net/sf/json/spring/web/servlet/view/JsonV0000664000175000017500000001436511650253660034315 0ustar jamespagejamespage/* * Copyright 2006-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json.spring.web.servlet.view; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jstester.JsTester; import net.sf.json.JSONSerializer; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.StaticWebApplicationContext; /** * @author Andres Almiray */ public class JsonViewTest extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( JsonViewTest.class ); } private JsTester jsTester; private MockServletContext servletContext; private MockHttpServletRequest servletRequest; private MockHttpServletResponse servletResponse; public JsonViewTest( String testName ) { super( testName ); } public void testRenderObjectGraph() throws Exception { JsonView view = new JsonView(); Map model = new HashMap(); model.put( "bool", Boolean.TRUE ); model.put( "integer", new Integer( 1 ) ); model.put( "str", "string" ); Map bean = new HashMap(); bean.put( "name", "mybean" ); bean.put( "bools", new boolean[] { true, false } ); model.put( "bean", bean ); view.render( model, servletRequest, servletResponse ); jsTester.eval( toJsScript( servletResponse ) ); jsTester.assertNotNull( "json" ); jsTester.assertIsObject( "json" ); jsTester.assertEquals( "json.bool", "true" ); jsTester.assertEquals( "json.integer", "1" ); jsTester.assertEquals( "json.str", "'string'" ); jsTester.assertIsObject( "json.bean" ); jsTester.assertIsArray( "json.bean.bools" ); jsTester.assertEquals( "2", "json.bean.bools.length" ); jsTester.assertEquals( "'mybean'", "json.bean.name" ); } public void testRenderObjectGraphWithPropertyExclusion() throws Exception { JsonView view = new JsonView(); view.setExcludedProperties( new String[] { "bools" } ); Map model = new HashMap(); model.put( "bool", Boolean.TRUE ); model.put( "integer", new Integer( 1 ) ); model.put( "str", "string" ); Map bean = new HashMap(); bean.put( "name", "mybean" ); bean.put( "bools", new boolean[] { true, false } ); model.put( "bean", bean ); view.render( model, servletRequest, servletResponse ); jsTester.eval( toJsScript( servletResponse ) ); jsTester.assertNotNull( "json" ); jsTester.assertIsObject( "json" ); jsTester.assertEquals( "json.bool", "true" ); jsTester.assertEquals( "json.integer", "1" ); jsTester.assertEquals( "json.str", "'string'" ); jsTester.assertIsObject( "json.bean" ); jsTester.assertIsUndefined( "json.bean.bools" ); jsTester.assertEquals( "'mybean'", "json.bean.name" ); } public void testRenderSimpleProperties() throws Exception { JsonView view = new JsonView(); Map model = new HashMap(); model.put( "bool", Boolean.TRUE ); model.put( "integer", new Integer( 1 ) ); model.put( "str", "string" ); view.render( model, servletRequest, servletResponse ); jsTester.eval( toJsScript( servletResponse ) ); jsTester.assertNotNull( "json" ); jsTester.assertIsObject( "json" ); jsTester.assertEquals( "json.bool", "true" ); jsTester.assertEquals( "json.integer", "1" ); jsTester.assertEquals( "json.str", "'string'" ); } public void testForceTopLevelArray() throws Exception { JsonView view = new JsonView(); view.setForceTopLevelArray( true ); Map model = new HashMap(); model.put( "bool", Boolean.TRUE ); model.put( "integer", new Integer( 1 ) ); model.put( "str", "string" ); view.render( model, servletRequest, servletResponse ); jsTester.eval( toJsScript( servletResponse ) ); jsTester.assertNotNull( "json" ); jsTester.assertIsArray( "json" ); jsTester.assertEquals( "json[0].bool", "true" ); jsTester.assertEquals( "json[0].integer", "1" ); jsTester.assertEquals( "json[0].str", "'string'" ); } public void testCharEncoding() throws Exception { JsonView view = new JsonView(); view.setForceTopLevelArray( true ); Map model = new HashMap(); model.put( "unicodestring", "\u5718\u9AD4\u6236\u53E3\u9A57\u8B49\u7A0B\u5E8F" ); view.render( model, servletRequest, servletResponse ); jsTester.eval( toJsScript( servletResponse ) ); jsTester.assertNotNull( "json" ); jsTester.assertIsArray( "json" ); jsTester.assertEquals( "json[0].unicodestring", "'\u5718\u9AD4\u6236\u53E3\u9A57\u8B49\u7A0B\u5E8F'" ); } protected void setUp() throws Exception { servletContext = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext( servletContext ); servletRequest = new MockHttpServletRequest( servletContext ); servletResponse = new MockHttpServletResponse(); servletResponse.setBufferSize(100); jsTester = new JsTester(); jsTester.onSetUp(); } protected void tearDown() throws Exception { jsTester.onTearDown(); } private String toJsScript( MockHttpServletResponse response ) throws Exception { // looks like MockHttpServletResponse is broken String json = response.getContentAsString(); if( json.startsWith("[{") && !json.endsWith("}]") ){ json += "}]"; } if( json.startsWith("{") && !json.endsWith("}") ){ json += "}"; } if( json.startsWith("[") && !json.endsWith("]") ){ json += "]"; } return "var json = eval('(" + json + ")');"; } } jenkins-json-2.4-jenkins-3/extensions/spring/src/test/resources/0000775000175000017500000000000011650253660025527 5ustar jamespagejamespagejenkins-json-2.4-jenkins-3/extensions/spring/src/test/resources/log4j.properties0000664000175000017500000000064211650253660030666 0ustar jamespagejamespagelog4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%d{yy-MM-dd HH:mm:ss}] %-5p [%-30.30c{1}:%L] %m%n log4j.appender.console.Encoding=UTF-8 log4j.rootLogger=WARN, console log4j.category.net.sf.json = DEBUG log4j.category.net.sf.jstester = DEBUG log4j.category.net.sf.json.spring.web.servlet.view = DEBUG jenkins-json-2.4-jenkins-3/LICENSE.txt0000664000175000017500000002613511650253660020100 0ustar jamespagejamespage Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.