Test.java

  1. package org.drip.sample.json;

  2. import java.io.*;
  3. import java.util.*;

  4. import org.drip.json.parser.*;
  5. import org.drip.json.simple.*;
  6. import org.drip.service.env.EnvManager;

  7. /*
  8.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  9.  */

  10. /*!
  11.  * Copyright (C) 2019 Lakshmi Krishnamurthy
  12.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  13.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  14.  * Copyright (C) 2016 Lakshmi Krishnamurthy
  15.  * Copyright (C) 2015 Lakshmi Krishnamurthy
  16.  *
  17.  *  This file is part of DROP, an open-source library targeting risk, transaction costs, exposure, margin
  18.  *      calculations, valuation adjustment, and portfolio construction within and across fixed income,
  19.  *      credit, commodity, equity, FX, and structured products.
  20.  *  
  21.  *      https://lakshmidrip.github.io/DROP/
  22.  *  
  23.  *  DROP is composed of three modules:
  24.  *  
  25.  *  - DROP Analytics Core - https://lakshmidrip.github.io/DROP-Analytics-Core/
  26.  *  - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
  27.  *  - DROP Numerical Core - https://lakshmidrip.github.io/DROP-Numerical-Core/
  28.  *
  29.  *  DROP Analytics Core implements libraries for the following:
  30.  *  - Fixed Income Analytics
  31.  *  - Asset Backed Analytics
  32.  *  - XVA Analytics
  33.  *  - Exposure and Margin Analytics
  34.  *
  35.  *  DROP Portfolio Core implements libraries for the following:
  36.  *  - Asset Allocation Analytics
  37.  *  - Transaction Cost Analytics
  38.  *
  39.  *  DROP Numerical Core implements libraries for the following:
  40.  *  - Statistical Learning
  41.  *  - Numerical Optimizer
  42.  *  - Spline Builder
  43.  *  - Algorithm Support
  44.  *
  45.  *  Documentation for DROP is Spread Over:
  46.  *
  47.  *  - Main                     => https://lakshmidrip.github.io/DROP/
  48.  *  - Wiki                     => https://github.com/lakshmiDRIP/DROP/wiki
  49.  *  - GitHub                   => https://github.com/lakshmiDRIP/DROP
  50.  *  - Repo Layout Taxonomy     => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
  51.  *  - Javadoc                  => https://lakshmidrip.github.io/DROP/Javadoc/index.html
  52.  *  - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
  53.  *  - Release Versions         => https://lakshmidrip.github.io/DROP/version.html
  54.  *  - Community Credits        => https://lakshmidrip.github.io/DROP/credits.html
  55.  *  - Issues Catalog           => https://github.com/lakshmiDRIP/DROP/issues
  56.  *  - JUnit                    => https://lakshmidrip.github.io/DROP/junit/index.html
  57.  *  - Jacoco                   => https://lakshmidrip.github.io/DROP/jacoco/index.html
  58.  *
  59.  *  Licensed under the Apache License, Version 2.0 (the "License");
  60.  *      you may not use this file except in compliance with the License.
  61.  *  
  62.  *  You may obtain a copy of the License at
  63.  *      http://www.apache.org/licenses/LICENSE-2.0
  64.  *  
  65.  *  Unless required by applicable law or agreed to in writing, software
  66.  *      distributed under the License is distributed on an "AS IS" BASIS,
  67.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  68.  *  
  69.  *  See the License for the specific language governing permissions and
  70.  *      limitations under the License.
  71.  */

  72. /**
  73.  * <i>Test</i> is an Adaptation of the Test Class from the RFC4627 compliant JSON Simple
  74.  * (https://code.google.com/p/json-simple/).
  75.  *  
  76.  * <br><br>
  77.  *  <ul>
  78.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/NumericalCore.md">Numerical Core Module</a></li>
  79.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/AlgorithmSupportLibrary.md">Algorithm Support Library</a></li>
  80.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/README.md">Sample</a></li>
  81.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/json/README.md">JSON Serialization and De-serialization</a></li>
  82.  *  </ul>
  83.  * <br><br>
  84.  *
  85.  * @author Fang Yidong
  86.  * @author Lakshmi Krishnamurthy
  87.  */

  88. public class Test {

  89.     @SuppressWarnings ("rawtypes") public static final void testDecode() throws Exception{
  90.             System.out.println("=======decode=======");
  91.            
  92.             String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
  93.             Object obj=JSONValue.parse(s);
  94.             JSONArray array=(JSONArray)obj;
  95.             System.out.println("======the 2nd element of array======");
  96.             System.out.println(array.get(1));
  97.             System.out.println();
  98.             System.out.println ("{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}".equalsIgnoreCase(array.get(1).toString()));
  99.            
  100.             JSONObject obj2=(JSONObject)array.get(1);
  101.             System.out.println("======field \"1\"==========");
  102.             System.out.println(obj2.get("1"));      
  103.             System.out.println ("{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}".equalsIgnoreCase(obj2.get("1").toString()));
  104.            
  105.             s="{}";
  106.             obj=JSONValue.parse(s);
  107.             System.out.println ("{}".equalsIgnoreCase(obj.toString()));
  108.            
  109.             s="[5,]";
  110.             obj=JSONValue.parse(s);
  111.             System.out.println ("[5]".equalsIgnoreCase(obj.toString()));
  112.            
  113.             s="[5,,2]";
  114.             obj=JSONValue.parse(s);
  115.             System.out.println ("[5,2]".equalsIgnoreCase(obj.toString()));
  116.            
  117.             s="[\"hello\\bworld\\\"abc\\tdef\\\\ghi\\rjkl\\n123\\u4e2d\"]";
  118.             obj=JSONValue.parse(s);
  119.             System.out.println ("hello\bworld\"abc\tdef\\ghi\rjkl\n123中".equalsIgnoreCase(((List)obj).get(0).toString()));
  120.            
  121.             JSONParser parser = new JSONParser();
  122.             s="{\"name\":";
  123.             try{
  124.                     obj = parser.parse(s);
  125.             }
  126.             catch(ParseException pe){
  127.                 System.out.println (ParseException.ERROR_UNEXPECTED_TOKEN == pe.getErrorType());
  128.                 System.out.println (8 == pe.getPosition());
  129.             }
  130.            
  131.             s="{\"name\":}";
  132.             try{
  133.                     obj = parser.parse(s);
  134.             }
  135.             catch(ParseException pe){
  136.                     System.out.println (ParseException.ERROR_UNEXPECTED_TOKEN == pe.getErrorType());
  137.                     System.out.println (8 == pe.getPosition());
  138.             }
  139.            
  140.            
  141.             s="{\"name";
  142.             try{
  143.                     obj = parser.parse(s);
  144.             }
  145.             catch(ParseException pe){
  146.                     System.out.println (ParseException.ERROR_UNEXPECTED_TOKEN == pe.getErrorType());
  147.                     System.out.println (6 == pe.getPosition());
  148.             }
  149.            
  150.            
  151.             s = "[[null, 123.45, \"a\\\tb c\"}, true]";
  152.             try{
  153.                     parser.parse(s);
  154.             }
  155.             catch(ParseException pe){
  156.                     System.out.println (24 == pe.getPosition());
  157.                     System.out.println("Error at character position: " + pe.getPosition());
  158.                     switch(pe.getErrorType()){
  159.                     case ParseException.ERROR_UNEXPECTED_TOKEN:
  160.                             System.out.println("Unexpected token: " + pe.getUnexpectedObject());
  161.                             break;
  162.                     case ParseException.ERROR_UNEXPECTED_CHAR:
  163.                             System.out.println("Unexpected character: " + pe.getUnexpectedObject());
  164.                             break;
  165.                     case ParseException.ERROR_UNEXPECTED_EXCEPTION:
  166.                             ((Exception)pe.getUnexpectedObject()).printStackTrace();
  167.                             break;
  168.                     }
  169.             }
  170.            
  171.             s = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
  172.             ContainerFactory containerFactory = new ContainerFactory(){
  173.                     public List creatArrayContainer() {
  174.                             return new LinkedList();
  175.                     }

  176.                     public Map createObjectContainer() {
  177.                             return new LinkedHashMap();
  178.                     }
  179.                    
  180.             };
  181.            
  182.             try{
  183.                     Map json = (Map)parser.parse(s, containerFactory);
  184.                     Iterator iter = json.entrySet().iterator();
  185.                     System.out.println("==iterate result==");
  186.                     while(iter.hasNext()){
  187.                             Map.Entry entry = (Map.Entry)iter.next();
  188.                             System.out.println(entry.getKey() + "=>" + entry.getValue());
  189.                     }
  190.                    
  191.                     System.out.println("==toJSONString()==");                      
  192.                     System.out.println(JSONValue.toJSONString(json));
  193.                     System.out.println ("{\"first\":123,\"second\":[4,5,6],\"third\":789}".equalsIgnoreCase(JSONValue.toJSONString(json)));
  194.             }
  195.             catch(ParseException pe){
  196.                     pe.printStackTrace();
  197.             }
  198.            
  199.             s = "{\"first\": 123, \"second\": [{\"s1\":{\"s11\":\"v11\"}}, 4, 5, 6], \"third\": 789}";
  200.             ContentHandler myHandler = new ContentHandler() {

  201.                     public boolean endArray() throws ParseException {
  202.                             System.out.println("endArray()");
  203.                             return true;
  204.                     }

  205.                     public void endJSON() throws ParseException {
  206.                             System.out.println("endJSON()");
  207.                     }

  208.                     public boolean endObject() throws ParseException {
  209.                             System.out.println("endObject()");
  210.                             return true;
  211.                     }

  212.                     public boolean endObjectEntry() throws ParseException {
  213.                             System.out.println("endObjectEntry()");
  214.                             return true;
  215.                     }

  216.                     public boolean primitive(Object value) throws ParseException {
  217.                             System.out.println("primitive(): " + value);
  218.                             return true;
  219.                     }

  220.                     public boolean startArray() throws ParseException {
  221.                             System.out.println("startArray()");
  222.                             return true;
  223.                     }

  224.                     public void startJSON() throws ParseException {
  225.                             System.out.println("startJSON()");
  226.                     }

  227.                     public boolean startObject() throws ParseException {
  228.                             System.out.println("startObject()");
  229.                             return true;
  230.                     }

  231.                     public boolean startObjectEntry(String key) throws ParseException {
  232.                             System.out.println("startObjectEntry(), key:" + key);
  233.                             return true;
  234.                     }
  235.                    
  236.             };
  237.             try{
  238.                     parser.parse(s, myHandler);
  239.             }
  240.             catch(ParseException pe){
  241.                     pe.printStackTrace();
  242.             }
  243.    
  244.     class KeyFinder implements ContentHandler{
  245.         private Object value;
  246.         private boolean found = false;
  247.         private boolean end = false;
  248.         private String key;
  249.         private String matchKey;
  250.        
  251.         public void setMatchKey(String matchKey){
  252.             this.matchKey = matchKey;
  253.         }
  254.        
  255.         public Object getValue(){
  256.             return value;
  257.         }
  258.        
  259.         public boolean isEnd(){
  260.             return end;
  261.         }
  262.        
  263.         public void setFound(boolean found){
  264.             this.found = found;
  265.         }
  266.        
  267.         public boolean isFound(){
  268.             return found;
  269.         }
  270.        
  271.         public void startJSON() throws ParseException, IOException {
  272.             found = false;
  273.             end = false;
  274.         }

  275.         public void endJSON() throws ParseException, IOException {
  276.             end = true;
  277.         }

  278.         public boolean primitive(Object value) throws ParseException, IOException {
  279.             if(key != null){
  280.                 if(key.equals(matchKey)){
  281.                     found = true;
  282.                     this.value = value;
  283.                     key = null;
  284.                     return false;
  285.                 }
  286.             }
  287.             return true;
  288.         }

  289.         public boolean startArray() throws ParseException, IOException {
  290.             return true;
  291.         }

  292.        
  293.         public boolean startObject() throws ParseException, IOException {
  294.             return true;
  295.         }

  296.         public boolean startObjectEntry(String key) throws ParseException, IOException {
  297.             this.key = key;
  298.             return true;
  299.         }
  300.        
  301.         public boolean endArray() throws ParseException, IOException {
  302.             return false;
  303.         }

  304.         public boolean endObject() throws ParseException, IOException {
  305.             return true;
  306.         }

  307.         public boolean endObjectEntry() throws ParseException, IOException {
  308.             return true;
  309.         }
  310.     };
  311.    
  312.     s = "{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}";
  313.     parser.reset();
  314.     KeyFinder keyFinder = new KeyFinder();
  315.     keyFinder.setMatchKey("id");
  316.     int i = 0;
  317.     try{
  318.         while(!keyFinder.isEnd()){
  319.             parser.parse(s, keyFinder, true);
  320.             if(keyFinder.isFound()){
  321.                 i++;
  322.                 keyFinder.setFound(false);
  323.                 System.out.println("found id:");
  324.                 System.out.println(keyFinder.getValue());
  325.                 if(i == 1)
  326.                     System.out.println ("id1".equalsIgnoreCase((String)keyFinder.getValue()));
  327.                 if(i == 2){
  328.                     System.out.println (keyFinder.getValue() instanceof Number);
  329.                     System.out.println ("123".equalsIgnoreCase(String.valueOf(keyFinder.getValue())));
  330.                 }
  331.                 if(i == 3)
  332.                     System.out.println (null == keyFinder.getValue());
  333.             }
  334.         }
  335.     }
  336.     catch(ParseException pe){
  337.         pe.printStackTrace();
  338.     }
  339.     }
  340.    
  341.     @SuppressWarnings ({"rawtypes", "unchecked"}) public static final void testEncode() throws Exception{
  342.             System.out.println("=======encode=======");
  343.            
  344.             JSONArray array1=new JSONArray();
  345.             array1.add("abc\u0010a/");
  346.             array1.add(Integer.toString(123));
  347.             array1.add(Double.toString(222.123));
  348.             array1.add(Boolean.toString(true));
  349.             System.out.println("======array1==========");
  350.             System.out.println(array1);
  351.             System.out.println();
  352.             System.out.println ("[\"abc\\u0010a\\/\",123,222.123,true]".equalsIgnoreCase(array1.toString()));
  353.            
  354.             JSONObject obj1=new JSONObject();
  355.             obj1.put("name","fang");
  356.             obj1.put("age",Integer.toString(27));
  357.             obj1.put("is_developer", Boolean.toString(true));
  358.             obj1.put("weight", Double.toString(60.21));
  359.             obj1.put("array1",array1);
  360.             System.out.println("======obj1 with array1===========");
  361.             System.out.println(obj1);
  362.             System.out.println();
  363.             System.out.println ("{\"array1\":[\"abc\\u0010a\\/\",123,222.123,true],\"weight\":60.21,\"age\":27,\"name\":\"fang\",\"is_developer\":true}".equalsIgnoreCase(obj1.toString()));
  364.            
  365.             obj1.remove("array1");
  366.             array1.add(obj1);
  367.             System.out.println("======array1 with obj1========");
  368.             System.out.println(array1);
  369.             System.out.println();
  370.             System.out.println ("[\"abc\\u0010a\\/\",123,222.123,true,{\"weight\":60.21,\"age\":27,\"name\":\"fang\",\"is_developer\":true}]".equalsIgnoreCase(array1.toString()));
  371.    
  372.             List list = new ArrayList();
  373.             list.add("abc\u0010a/");
  374.             list.add(Integer.toString (123));
  375.             list.add(Double.toString (222.123));
  376.             list.add(Boolean.toString (true));
  377.             list.add(null);
  378.             System.out.println("======list==========");
  379.             System.out.println(JSONArray.toJSONString(list));
  380.             System.out.println();
  381.             System.out.println ("[\"abc\\u0010a\\/\",123,222.123,true,null]".equalsIgnoreCase(JSONArray.toJSONString(list)));
  382.            
  383.             Map map = new HashMap();
  384.             map.put("name","fang");
  385.             map.put("age", Integer.toString (27));
  386.             map.put("is_developer", Boolean.toString (true));
  387.             map.put("weight", Double.toString (60.21));
  388.             map.put("array1",list);
  389.             System.out.println("======map with list===========");
  390.             System.out.println(map);
  391.             System.out.println();
  392.             System.out.println ("{\"array1\":[\"abc\\u0010a\\/\",123,222.123,true,null],\"weight\":60.21,\"age\":27,\"name\":\"fang\",\"is_developer\":true}".equalsIgnoreCase(JSONObject.toJSONString(map)));              
  393.            
  394.     Map m1 = new LinkedHashMap();
  395.     Map m2 = new HashMap();
  396.     List  l1 = new LinkedList();

  397.     m1.put("k11","v11");
  398.     m1.put("k12","v12");
  399.     m1.put("k13", "v13");
  400.     m2.put("k21","v21");
  401.     m2.put("k22","v22");
  402.     m2.put("k23","v23");
  403.     l1.add(m1);
  404.     l1.add(m2);
  405.     String jsonString = JSONValue.toJSONString(l1);
  406.     System.out.println(jsonString);
  407.     System.out.println ("[{\"k11\":\"v11\",\"k12\":\"v12\",\"k13\":\"v13\"},{\"k22\":\"v22\",\"k21\":\"v21\",\"k23\":\"v23\"}]".equalsIgnoreCase(jsonString));

  408.     StringWriter out = new StringWriter();
  409.     JSONValue.writeJSONString(l1, out);
  410.     jsonString = out.toString();
  411.     System.out.println(jsonString);
  412.     System.out.println ("[{\"k11\":\"v11\",\"k12\":\"v12\",\"k13\":\"v13\"},{\"k22\":\"v22\",\"k21\":\"v21\",\"k23\":\"v23\"}]".equalsIgnoreCase(jsonString));
  413.    
  414.     List l2 = new LinkedList();
  415.     Map m3 = new LinkedHashMap();
  416.     m3.put("k31", "v3");
  417.     m3.put("k32", Double.toString (123.45));
  418.     m3.put("k33", Boolean.toString (false));
  419.     m3.put("k34", null);
  420.     l2.add("vvv");
  421.     l2.add("1.23456789123456789");
  422.     l2.add(Boolean.toString (true));
  423.     l2.add(null);
  424.     m3.put("k35", l2);
  425.     m1.put("k14", m3);
  426.     out = new StringWriter();
  427.     JSONValue.writeJSONString(l1, out);
  428.     jsonString = out.toString();
  429.     System.out.println(jsonString);
  430.     System.out.println ("[{\"k11\":\"v11\",\"k12\":\"v12\",\"k13\":\"v13\",\"k14\":{\"k31\":\"v3\",\"k32\":123.45,\"k33\":false,\"k34\":null,\"k35\":[\"vvv\",\"1.23456789123456789\",true,null]}},{\"k22\":\"v22\",\"k21\":\"v21\",\"k23\":\"v23\"}]".equalsIgnoreCase(jsonString));
  431. }

  432.     public static final void main (
  433.         final String[] astrArgs)
  434.         throws Exception
  435.     {
  436.         EnvManager.InitEnv ("");

  437.         testEncode();

  438.         testDecode();

  439.         EnvManager.TerminateEnv();
  440.     }
  441. }