Example usage for org.json.simple JSONObject size

List of usage examples for org.json.simple JSONObject size

Introduction

In this page you can find the example usage for org.json.simple JSONObject size.

Prototype

int size();

Source Link

Document

Returns the number of key-value mappings in this map.

Usage

From source file:org.jolokia.history.HistoryStore.java

private JSONObject updateHistoryForPatternReadWithMBeanAsPath(JmxReadRequest pJmxReq, long pTimestamp,
        Map<String, Object> pValues) {
    // It the content of the MBean itself. MBean name is the first the single path part
    String beanName = pJmxReq.getPathParts().get(0);
    JSONObject ret = new JSONObject();
    JSONObject beanHistory = addMultipleAttributeValues(pJmxReq, pValues, beanName, pTimestamp);
    if (beanHistory.size() > 0) {
        ret.put(beanName, beanHistory);//from  w  ww .j  a v  a 2 s . c o  m
    }
    return ret;
}

From source file:org.jolokia.history.HistoryStoreTest.java

@Test(groups = "java6")
public void patternAttributeRead() throws Exception {
    JmxReadRequest req = new JmxRequestBuilder(READ, "test:type=*").build();
    store.configure(new HistoryKey("test:type=read", "attr1", null, null), new HistoryLimit(3, 0L));
    store.configure(new HistoryKey("test:type=write", "attr2", null, null), new HistoryLimit(5, 0L));
    /** 5 fresh updates yield 2 history entries returned (and 3 stored) */
    Map mBeanMap = new HashMap();
    Map attr1Map = new HashMap();
    mBeanMap.put("test:type=read", attr1Map);
    attr1Map.put("attr1", "val1");
    Map attr2Map = new HashMap();
    mBeanMap.put("test:type=write", attr2Map);
    attr2Map.put("attr2", "val2");
    JSONObject history = updateNTimesAsMap(req, 4, mBeanMap);
    assertEquals("History has 2 entries", 2, history.size());
    assertEquals("bean1 has 1 entry", 1, ((Map) history.get("test:type=read")).size());
    assertEquals("bean1 has 1 entry", 1, ((Map) history.get("test:type=write")).size());
    assertEquals("attr1 has 3 history entries", 3,
            ((List) ((Map) history.get("test:type=read")).get("attr1")).size());
    assertEquals("attr2 has 3 history entries", 3,
            ((List) ((Map) history.get("test:type=write")).get("attr2")).size());
}

From source file:org.jolokia.jmx.JolokiaMBeanServerTest.java

@Test
public void withConstraint()
        throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException,
        MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException,
        ParseException, InvalidTargetObjectTypeException, NoSuchMethodException, IntrospectionException {
    JolokiaMBeanServer server = new JolokiaMBeanServer();

    ObjectName oName = new ObjectName("test:type=jsonMBean");

    server.registerMBean(new JsonAnnoPlainTest(), oName);

    MBeanServer plattformServer = ManagementFactory.getPlatformMBeanServer();

    String deepDive = (String) plattformServer.getAttribute(oName, "DeepDive");
    JSONObject deepDiveS = (JSONObject) new JSONParser().parse(deepDive);
    assertEquals(deepDiveS.size(), 1);
    // Serialization is truncated because of maxDepth = 1
    assertTrue(deepDiveS.get("map") instanceof String);
    assertTrue(deepDiveS.get("map").toString().matches(".*hot=.*Chili.*"));
    server.unregisterMBean(oName);//  ww  w. j a  va 2  s. c o m
    Assert.assertFalse(plattformServer.isRegistered(oName));
    Assert.assertFalse(server.isRegistered(oName));
}

From source file:org.jppf.example.matrix.MatrixRunner.java

/**
 * Entry point for this class, performs a matrix multiplication a number of times.,<br>
 * The number of times is specified as a configuration property named &quot;matrix.iterations&quot;.<br>
 * The size of the matrices is specified as a configuration property named &quot;matrix.size&quot;.<br>
 * @param args - not used./*from  www  . j  a v  a2  s .  c  o m*/
 */
public String[] go(String[] input) {
    try {
        //if ((args != null) && (args.length > 0)) jppfClient = new JPPFClient(args[0]);
        jppfClient = new JPPFClient();
        JSONArray array;
        JSONArray array2;
        //String input1 = "[{\"0\":44, \"1\":22}, {\"0\":1, \"1\":3}]";
        //String input2 = "[{\"0\":10, \"1\":44}, {\"0\":2, \"1\":6}]";
        if (input[1] != null & input[2] != null) {

            output("Heeello");
            //here is the JSON with the matrix values
            Object obj = JSONValue.parse(input[1]);
            array = (JSONArray) obj;
            Object obj2 = JSONValue.parse(input[2]);
            array2 = (JSONArray) obj2;

            //Get the single elements of the JSON and thus be able to find out number of rows and columns
            //
            //
            double[][] values1; //values of first matrix
            double[][] values2; //values of second matrix
            int rows1 = array.size();
            int rows2 = array2.size();
            output("rows1: " + rows1 + "rows2: " + rows2);
            JSONObject j1 = (JSONObject) array.get(0);
            JSONObject j2 = (JSONObject) array2.get(0);
            output("j1: " + j1 + "j2: " + j2);
            int cols1 = j1.size();
            int cols2 = j2.size();
            output("cols1: " + cols1 + "cols2: " + cols2);
            values1 = new double[rows1][cols1];
            values2 = new double[rows2][cols2];
            for (int i = 0; i < rows1; i++) {
                for (int j = 0; j < cols1; j++) {
                    JSONObject thisRow = (JSONObject) array.get(i);
                    output("row: " + thisRow);
                    String js = String.valueOf(j);
                    String bla = thisRow.get(js).toString();
                    //output(bla);
                    double valueOf = Double.parseDouble(bla);
                    //output(String.valueOf(valueOf));
                    //long thisValuef = (long)thisRow.get(js);
                    //double thisValue = thisValuef.doubleValue();
                    //output("value: " + thisValue);
                    values1[i][j] = valueOf;

                }
            }
            for (int i = 0; i < rows2; i++) {
                for (int j = 0; j < cols2; j++) {
                    JSONObject thisRow = (JSONObject) array.get(i);
                    output("row: " + thisRow);
                    String js = String.valueOf(j);
                    String bla = thisRow.get(js).toString();
                    //output(bla);
                    double valueOf = Double.parseDouble(bla);
                    values2[i][j] = valueOf;
                }
            }

            TypedProperties props = JPPFConfiguration.getProperties();
            //how big is the matrix
            int size = props.getInt("matrix.size", 300);
            //how many times to calculate
            int iterations = props.getInt("matrix.iterations", 10);
            //number of rows of matrix a per task
            int nbRows = props.getInt("task.nbRows", 1);
            output("Running Matrix demo with matrix size = " + size + "*" + size + " for " + iterations
                    + " iterations");
            Matrix c = perform(values1, values2, iterations, nbRows);
            String[] result = new String[2];
            output("Array created");
            result[0] = input[0];
            result[1] = c.printConsole();
            if (jppfClient != null)
                jppfClient.close();
            return result;
        } else {
            output("No input");
            String[] result = new String[2];
            result[0] = input[0];
            result[1] = "Nothing";
            if (jppfClient != null)
                jppfClient.close();
            return result;
        }
    } catch (Exception e) {
        e.printStackTrace();
        output("catch");
        if (jppfClient != null)
            jppfClient.close();
        return null;
    }
}

From source file:org.pentaho.osgi.i18n.webservice.ResourceBundleMessageBodyWriterTest.java

@Test
public void testJsonWrite() throws IOException {
    Map<String, String> props = new HashMap<String, String>();
    props.put("key1", "value1");
    props.put("key2", "value2");
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    new ResourceBundleMessageBodyWriter().writeTo(makeResourceBundle(props), ResourceBundle.class, null, null,
            MediaType.APPLICATION_JSON_TYPE, null, byteArrayOutputStream);
    JSONObject result = (JSONObject) JSONValue.parse(byteArrayOutputStream.toString());
    assertEquals(2, result.size());
    assertEquals("value1", result.get("key1"));
    assertEquals("value2", result.get("key2"));
}

From source file:org.pentaho.osgi.platform.plugin.deployer.impl.handlers.pluginxml.PluginXmlExternalResourcesHandlerTest.java

@Test
public void testHandleTwoNodes() throws PluginHandlingException, IOException {
    Map<String, String> node1Props = new HashMap<String, String>();
    node1Props.put("context", "requirejs");
    Map<String, String> node2Props = new HashMap<String, String>();
    node2Props.put("context", "requirejs");
    Node node1 = PluginXmlStaticPathsHandlerTest.makeMockNode(node1Props);
    when(node1.getTextContent()).thenReturn("/test/content/1");
    Node node2 = PluginXmlStaticPathsHandlerTest.makeMockNode(node2Props);
    when(node2.getTextContent()).thenReturn("/test/content/2");
    PluginXmlExternalResourcesHandler pluginXmlExternalResourcesHandler = new PluginXmlExternalResourcesHandler();
    pluginXmlExternalResourcesHandler.setJsonUtil(new JSONUtil());
    PluginMetadata pluginMetadata = mock(PluginMetadata.class);
    FileWriter fileWriter = mock(FileWriter.class);
    final StringBuilder sb = new StringBuilder();
    doAnswer(new Answer<Object>() {
        @Override/*from   w  w  w  .j a  v  a  2s  .  c  o m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            sb.append(invocation.getArguments()[0]);
            return null;
        }
    }).when(fileWriter).write(anyString());
    when(pluginMetadata.getFileWriter(PluginXmlExternalResourcesHandler.EXTERNAL_RESOURCES_FILE))
            .thenReturn(fileWriter);

    // Setup Blueprint
    Document blueprint = null;
    try {
        blueprint = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        blueprint.appendChild(
                blueprint.createElementNS(PluginXmlStaticPathsHandler.BLUEPRINT_BEAN_NS, "blueprint"));
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        fail();
    }
    when(pluginMetadata.getBlueprint()).thenReturn(blueprint);

    List<Node> nodes = new ArrayList<Node>(Arrays.asList(node1, node2));
    pluginXmlExternalResourcesHandler.handle("plugin.xml", nodes, pluginMetadata);
    String result = sb.toString();
    JSONObject jsonObject = (JSONObject) JSONValue.parse(result);
    assertEquals(1, jsonObject.size());
    List<String> configs = (List<String>) jsonObject.get("requirejs");
    assertNotNull(configs);
    assertEquals(2, configs.size());
    assertEquals("/test/content/1", configs.get(0));
    assertEquals("/test/content/2", configs.get(1));

    NodeList childNodes = blueprint.getDocumentElement().getChildNodes();
    assertEquals(2, childNodes.getLength());
    for (int i = 0; i < childNodes.getLength(); i++) {
        assertEquals("service", childNodes.item(i).getNodeName());
        assertEquals("org.pentaho.platform.pdi.PlatformWebResource",
                childNodes.item(i).getFirstChild().getAttributes().getNamedItem("class").getNodeValue());
    }
}

From source file:org.powertac.hamweather.Parser.java

public void processFiles() {
    try {/*w w w  .j av a 2  s  .  c  om*/
        BufferedReader in = new BufferedReader(new FileReader(inputFile));
        Pattern observation = Pattern.compile("^-- observation: ([SMTWF][a-z]+ [A-Za-z]+ \\d+ [-0-9: ]+)");
        Pattern loc = Pattern.compile("^-- location: " + location);
        String line;
        State state = State.OBS;
        Matcher m;
        JSONParser jparser = new JSONParser();
        DateTimeFormatter dtf = DateTimeFormat.forPattern("E MMM d HH:mm:ss Z YYYY");
        iso = ISODateTimeFormat.dateTimeNoMillis();
        DateTime lastObs = null;
        DateTime obsHour = null;
        while (true) {
            line = in.readLine();
            if (null == line || 0 == line.length())
                break;
            switch (state) {
            case OBS:
                m = observation.matcher(line);
                if (m.matches()) {
                    DateTime obsTime = dtf.parseDateTime(m.group(1));
                    if (null == lastObs) {
                        lastObs = obsTime;
                    } else if (obsTime.isAfter(lastObs.plus(MAX_INTERVAL))) {
                        System.out.println("Missed obs - last = " + iso.print(lastObs) + ", current = "
                                + iso.print(obsTime));
                    }
                    lastObs = obsTime;
                    obsHour = obsTime.plus(HOUR / 2).withMillisOfSecond(0).withSecondOfMinute(0)
                            .withMinuteOfHour(0);
                    state = State.LOC;
                }
                break;
            case LOC:
                m = loc.matcher(line);
                if (m.matches()) {
                    //System.out.println("Location: " + location);
                    state = State.JSON_OB;
                }
                break;
            case JSON_OB:
                // process new observation
                JSONObject obs = (JSONObject) jparser.parse(line);
                // check for errors
                Boolean success = (Boolean) obs.get("success");
                if (!success) {
                    System.out.println("Observation retrieval failed at " + iso.print(obsHour));
                    state = State.OBS;
                } else {
                    JSONObject err = (JSONObject) obs.get("error");
                    if (null != err) {
                        // error at server end
                        String msg = (String) err.get("description");
                        System.out.println("Observation error: " + msg + " at " + iso.print(obsHour));
                        state = State.OBS;
                    } else {
                        try {
                            JSONObject response = (JSONObject) obs.get("response");
                            JSONObject ob = (JSONObject) response.get("ob");
                            extractObservation(ob);
                            state = State.JSON_FCST;
                        } catch (ClassCastException cce) {
                            System.out.println("Faulty observation " + obs.toString());
                            state = State.OBS;
                        }
                    }
                }
                break;
            case JSON_FCST:
                // process new forecast
                JSONObject fcst = (JSONObject) jparser.parse(line);
                // check for errors
                Boolean success1 = (Boolean) fcst.get("success");
                if (!success1) {
                    // could not retrieve forecast
                    System.out.println("Forecast retrieval failed at " + iso.print(obsHour));
                    output.forecastMissing();
                } else {
                    JSONObject err = (JSONObject) fcst.get("error");
                    if (null != err) {
                        // error at server end
                        String msg = (String) err.get("description");
                        System.out.println("Forecast error: " + msg + " at " + iso.print(obsHour));
                        output.forecastMissing();
                    } else {
                        JSONArray response = (JSONArray) fcst.get("response");
                        if (response.size() == 0) {
                            // should never get here
                            System.out.println("Empty forecast at " + iso.print(obsHour));
                        }
                        JSONObject periods = (JSONObject) response.get(0);
                        JSONArray fcsts = (JSONArray) periods.get("periods");
                        if (fcsts.size() != FORECAST_HORIZON) {
                            System.out.println(
                                    "Missing forecasts (" + fcsts.size() + ") at " + iso.print(lastObs));
                        }
                        for (int i = 0; i < fcsts.size(); i++) {
                            JSONObject forecast = (JSONObject) fcsts.get(i);
                            extractForecast(forecast, i + 1, obsHour);
                        }
                    }
                }
                state = State.OBS;
                break;
            }
        }
        output.write();
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    }
}

From source file:org.talend.components.splunk.objects.SplunkJSONEventTest.java

@Test
public void testSplunkJSONEventFieldsSetting() {
    SplunkJSONEvent splunkEvent = new SplunkJSONEvent();

    // Test setting some metadata fields
    splunkEvent.put(SplunkJSONEventField.INDEX, "index");
    splunkEvent.put(SplunkJSONEventField.SOURCE, "localhost");

    // Assert set fields
    assertTrue("Index should be equal to index",
            "index".equals(splunkEvent.get(SplunkJSONEventField.INDEX.getName())));
    assertTrue("Source should be equal to localhost",
            "localhost".equals(splunkEvent.get(SplunkJSONEventField.SOURCE.getName())));

    // Try to set null values. It shouldn't be set.
    splunkEvent.put(SplunkJSONEventField.HOST, null);
    assertFalse("Host value was set to null. It shouldn't be set.",
            splunkEvent.containsKey(SplunkJSONEventField.HOST.getName()));

    // Try to add event field
    splunkEvent.addEventObject("Field1", "Value1");
    splunkEvent.addEventObject("FieldInt", 123);

    // Check event fields
    JSONObject eventObject = (JSONObject) splunkEvent.get(SplunkJSONEventField.EVENT.getName());
    assertFalse("Event Field should not be null", eventObject == null);

    assertTrue("Field1 value should be equal to Value1", "Value1".equals(eventObject.remove("Field1")));
    assertTrue("FieldInt value should be int value and be equal to 123",
            (int) eventObject.remove("FieldInt") == 123);

    // Nothing else should be in the event object
    assertTrue("Nothing should be left in the event object", eventObject.size() == 0);
}

From source file:org.wso2.developerstudio.datamapper.diagram.tree.generator.SchemaTransformer.java

/**
 * generate the schema recursively//w  ww . java 2 s .co  m
 * 
 * @param treeNodeModel
 * @param parent
 * @param root
 */
@SuppressWarnings("unchecked")
private void recursiveSchemaGenerator(TreeNodeImpl treeNodeModel, JSONObject parent, JSONObject root) {
    if (treeNodeModel != null) {
        EList<Element> elemList = treeNodeModel.getElement();
        EList<TreeNode> nodeList = treeNodeModel.getNode();
        for (TreeNode node : nodeList) {
            String name = node.getName();
            String schemaType = getPropertyKeyValuePairforTreeNode(node, JSON_SCHEMA_TYPE);
            String schemaArrayItemsID = getPropertyKeyValuePairforTreeNode(node, JSON_SCHEMA_ARRAY_ITEMS_ID);
            String schemaArrayItemsType = getPropertyKeyValuePairforTreeNode(node,
                    JSON_SCHEMA_ARRAY_ITEMS_TYPE);
            String schemaID = getPropertyKeyValuePairforTreeNode(node, JSON_SCHEMA_ID);
            String attributeID = getPropertyKeyValuePairforTreeNode(node, JSON_SCHEMA_ATTRIBUTE_ID);
            String attributeType = getPropertyKeyValuePairforTreeNode(node, JSON_SCHEMA_ATTRIBUTE_TYPE);
            String propertiesId = getPropertyKeyValuePairforTreeNode(node, JSON_SCHEMA_PROPERTIES_ID);
            String objectValueBlockType = getPropertyKeyValuePairforTreeNode(node,
                    JSON_SCHEMA_OBJECT_VALUE_TYPE);
            String objectElementIdentifier = getPropertyKeyValuePairforTreeNode(node,
                    JSON_SCHEMA_OBJECT_ELEMENT_IDENTIFIERS_URL);
            String objectAddedAttributeID = getPropertyKeyValuePairforTreeNode(node,
                    JSON_SCHEMA_ADDED_ATTRIBUTE_ID);
            String objectAddedAttributeType = getPropertyKeyValuePairforTreeNode(node,
                    JSON_SCHEMA_ADDED_ATTRIBUTE_TYPE);
            String arrayValueBlockType = getPropertyKeyValuePairforTreeNode(node,
                    JSON_SCHEMA_ARRAY_ITEMS_VALUE_TYPE);
            if (schemaType != null && schemaType.equals(JSON_SCHEMA_OBJECT)) {
                JSONObject nodeObject = new JSONObject();
                JSONObject propertiesObject = new JSONObject();
                JSONObject attributeObject = new JSONObject();
                JSONObject valueObject = new JSONObject();
                // Check if there are attributes in the child nodes of an
                // object when creating the tree by hand
                addedObjectHasAttributes = checkForAttributes(node);
                // Check if there are properties in the child nodes of an
                // object when creating the tree by hand
                addedObjectHasProperties = checkForProperties(node);
                // Check if there are namespaces in the object when creating
                // the tree by hand
                addedObjectNamespaces = checkValueFromPropertyKeyValuePair(node, JSON_SCHEMA_OBJECT_NAMESPACES);
                // Check if there are element identifiers in the object when creating
                // the tree by hand
                addedObjectElementIdentifiers = checkValueFromPropertyKeyValuePair(node,
                        JSON_SCHEMA_OBJECT_ELEMENT_IDENTIFIERS);
                // If the iteration happens not because of attributes (
                // properties), then
                // handle the other elements the object
                if (!hasAttributes) {
                    insetIDAndTypeForJsonObject(node, nodeObject);
                    // If object contains a value block then handle it (
                    // when generating and creating tree)
                    if (objectValueBlockType != null) {
                        valueObject.put(JSON_SCHEMA_TYPE, objectValueBlockType);
                        nodeObject.put(JSON_SCHEMA_VALUE, valueObject);
                    }
                    //If an object doesn't contain properties, then avoid serializing the properties field
                    EList<TreeNode> childList = node.getNode();
                    if (childList.size() > 0) {
                        nodeObject.put(JSON_SCHEMA_PROPERTIES, propertiesObject);
                    }
                    parent.put(node.getName(), nodeObject);
                    insertRequiredArray(nodeObject, node, false);
                    // Handles attributes
                    if (attributeID != null && attributeType != null) {
                        hasAttributes = true;
                        nodeObject.put(JSON_SCHEMA_ATTRIBUTES, attributeObject);
                        parent.put(node.getName(), nodeObject);
                        recursiveSchemaGenerator((TreeNodeImpl) node, nodeObject, root);
                        hasAttributes = false;
                    }
                    // Handle properties when creating tree by hand
                    if (addedObjectHasProperties) {
                        // Fixing DEVTOOLESB-154
                        if (((TreeNodeImpl) node).getNode().size() > 0) {
                            nodeObject.put(JSON_SCHEMA_PROPERTIES, propertiesObject);
                        }
                    }
                    if (StringUtils.isNotEmpty(addedObjectNamespaces)) {
                        // If namespaces are available when creating the
                        // tree by hand then add those to the root elements
                        if (!namespaceList.contains(addedObjectNamespaces)) {
                            namespaceList.add(addedObjectNamespaces);
                        }
                    }

                    if (StringUtils.isNotEmpty(objectElementIdentifier)) {
                        // If element identifiers are available when creating the
                        // tree by hand then add those to the root elements
                        if (!namespaceList.contains(objectElementIdentifier)) {
                            namespaceList.add(objectElementIdentifier);
                        }
                    }

                    if (StringUtils.isNotEmpty(addedObjectElementIdentifiers)) {
                        // If element identifiers are available when creating the
                        // tree by hand then add those to the root elements
                        if (!elementIdentifierList.contains(addedObjectElementIdentifiers)) {
                            elementIdentifierList.add(addedObjectElementIdentifiers);
                        }
                    }
                    // Handle attributes when creating tree by hand
                    if (addedObjectHasAttributes) {
                        // Fixing DEVTOOLESB-154
                        if (((TreeNodeImpl) node).getNode().size() > 0) {
                            hasAttributes = true;
                            nodeObject.put(JSON_SCHEMA_ATTRIBUTES, attributeObject);
                            parent.put(node.getName(), nodeObject);
                            recursiveSchemaGenerator((TreeNodeImpl) node, nodeObject, root);
                            hasAttributes = false;
                        }
                    }

                    recursiveSchemaGenerator((TreeNodeImpl) node, propertiesObject, root);
                }

            } else if (schemaType != null && schemaType.equals(JSON_SCHEMA_ARRAY)) {
                JSONObject arrayObject = new JSONObject();
                JSONObject itemsObject = new JSONObject();
                JSONArray arrayItemsObject = new JSONArray();
                JSONObject attributeObject = new JSONObject();
                JSONObject itemProperties = new JSONObject();
                JSONObject valueObject = new JSONObject();
                // Check if there are attributes in the child nodes of the
                // array when creating the tree by hand
                addedObjectHasAttributes = checkForAttributes(node);
                // Check if there are properties in the child nodes of the
                // array when creating the tree by hand
                addedObjectHasProperties = checkForProperties(node);
                // Check if there are namespaces in the array when creating
                // the tree by hand
                addedObjectNamespaces = checkValueFromPropertyKeyValuePair(node, JSON_SCHEMA_ARRAY_NAMESPACES);
                // Check if there are element identifiers in the array when creating
                // the tree by hand
                addedObjectElementIdentifiers = checkValueFromPropertyKeyValuePair(node,
                        JSON_SCHEMA_ARRAY_ELEMENT_IDENTIFIERS);
                String arrayElementIdentifier = getPropertyKeyValuePairforTreeNode(node,
                        JSON_SCHEMA_ARRAY_ELEMENT_IDENTIFIERS_URL);
                // If the iteration happens not because of attributes (
                // properties), then
                // handle the other elements in the array
                if (!hasAttributes) {
                    insetIDAndTypeForJsonObject(node, arrayObject);
                    if (schemaArrayItemsID != null) {
                        itemProperties.put(JSON_SCHEMA_ID, schemaArrayItemsID.replace("\\", ""));
                    }
                    if (schemaArrayItemsType != null) {
                        itemProperties.put(JSON_SCHEMA_TYPE, schemaArrayItemsType);
                    }
                    insertRequiredArray(arrayObject, node, false);
                    insertRequiredArray(itemProperties, node, true);
                    parent.put(node.getName(), arrayObject);
                    if (itemProperties.size() > 0) {
                        arrayItemsObject.add(itemProperties);
                    }
                    arrayObject.put(JSON_SCHEMA_ITEMS, arrayItemsObject);
                    if (((TreeNodeImpl) node).getNode().size() > 0) {
                        // Handle properties in array
                        //if (propertiesId != null) {
                        itemProperties.put(JSON_SCHEMA_PROPERTIES, itemsObject);
                        recursiveSchemaGenerator((TreeNodeImpl) node, itemsObject, root);
                        //}
                        // Handle attributes in array
                        if (attributeID != null && attributeType != null) {
                            hasAttributes = true;
                            itemProperties.put(JSON_SCHEMA_ATTRIBUTES, attributeObject);
                            recursiveSchemaGenerator((TreeNodeImpl) node, attributeObject, root);
                            hasAttributes = false;
                        }
                        // handle value block ( when generating and creating
                        // tree)
                        if (arrayValueBlockType != null) {
                            valueObject.put(JSON_SCHEMA_TYPE, arrayValueBlockType);
                            itemProperties.put(JSON_SCHEMA_VALUE, valueObject);
                        }

                        /*
                         * Handle type in items block based on the value
                         * block when creating tree by hand "items": [{
                         * "id": "http://wso2jsonschema.org/phone/0",
                         * "type": "object", "value":{ "type": "number" },
                         * "properties": { "ext": { "id":
                         * "http://wso2jsonschema.org/phone/0/ext", "type":
                         * "number" } }]}
                         */
                        if (addedObjectHasAttributes || addedObjectHasProperties) {
                            itemProperties.put(JSON_SCHEMA_TYPE, JSON_SCHEMA_OBJECT);
                        }

                        if (StringUtils.isNotEmpty(addedObjectNamespaces)) {
                            // If namespaces are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!namespaceList.contains(addedObjectNamespaces)) {
                                namespaceList.add(addedObjectNamespaces);
                            }
                        }
                        if (StringUtils.isNotEmpty(arrayElementIdentifier)) {
                            // If identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!namespaceList.contains(arrayElementIdentifier)) {
                                namespaceList.add(arrayElementIdentifier);
                            }
                        }

                        if (StringUtils.isNotEmpty(addedObjectElementIdentifiers)) {
                            // If element identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!elementIdentifierList.contains(addedObjectElementIdentifiers)) {
                                elementIdentifierList.add(addedObjectElementIdentifiers);
                            }

                        }
                        // Handle properties when creating tree by hand
                        if (addedObjectHasProperties) {
                            itemProperties.put(JSON_SCHEMA_PROPERTIES, itemsObject);
                            recursiveSchemaGenerator((TreeNodeImpl) node, itemsObject, root);
                        }

                        // Handle attributes when creating tree by hand
                        if (addedObjectHasAttributes) {
                            hasAttributes = true;
                            itemProperties.put(JSON_SCHEMA_ATTRIBUTES, attributeObject);
                            recursiveSchemaGenerator((TreeNodeImpl) node, attributeObject, root);
                            hasAttributes = false;
                        }

                    } else {
                        /*
                         * If array item doesn't contain attributes or
                         * properties then set the user entered type as the
                         * item's type "items": [{ "id":
                         * "http://wso2jsonschema.org/phone/phone", "type"
                         * :"number" }]
                         */
                        if (!itemProperties.containsKey(JSON_SCHEMA_TYPE)) {
                            itemProperties.put(JSON_SCHEMA_TYPE, arrayValueBlockType);
                        }

                        if (StringUtils.isNotEmpty(addedObjectNamespaces)) {
                            // If namespaces are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!namespaceList.contains(addedObjectNamespaces)) {
                                namespaceList.add(addedObjectNamespaces);
                            }
                        }

                        if (StringUtils.isNotEmpty(addedObjectElementIdentifiers)) {
                            // If element identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!elementIdentifierList.contains(addedObjectElementIdentifiers)) {
                                elementIdentifierList.add(addedObjectElementIdentifiers);
                            }
                        }
                        if (StringUtils.isNotEmpty(arrayElementIdentifier)) {
                            // If identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!namespaceList.contains(arrayElementIdentifier)) {
                                namespaceList.add(arrayElementIdentifier);
                            }
                        }
                    }
                }
            } else if (schemaType != null) {
                String fieldElementIdentifier = getPropertyKeyValuePairforTreeNode(node,
                        JSON_SCHEMA_FIELD_ELEMENT_IDENTIFIERS_URL);
                // Adds attributes
                if (hasAttributes) {
                    JSONObject elemObject = null;
                    //If the attribute is an element identifier then set the id and type
                    if (objectAddedAttributeID != null && objectAddedAttributeType != null) {
                        elemObject = new JSONObject();
                        elemObject.put(JSON_SCHEMA_ID, objectAddedAttributeID);
                        elemObject.put(JSON_SCHEMA_TYPE, objectAddedAttributeType);
                    } else {
                        elemObject = createElementObject(schemaID);
                        elemObject.put(JSON_SCHEMA_TYPE, schemaType);
                    }

                    // ignore other elements comes from attribute iteration
                    if (name.startsWith(PREFIX)) {
                        // Check if there are namespaces in the attributes
                        // when creating the tree by hand
                        addedObjectNamespaces = checkValueFromPropertyKeyValuePair(node,
                                JSON_SCHEMA_ATTRIBUTE_NAMESPACES);
                        if (StringUtils.isNotEmpty(addedObjectNamespaces)) {
                            // If namespaces are available add those to the
                            // root elements
                            if (!namespaceList.contains(addedObjectNamespaces)) {
                                namespaceList.add(addedObjectNamespaces);
                            }
                        }
                        if (StringUtils.isNotEmpty(fieldElementIdentifier)) {
                            // If identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!namespaceList.contains(fieldElementIdentifier)) {
                                namespaceList.add(fieldElementIdentifier);
                            }
                        }
                        addedObjectElementIdentifiers = checkValueFromPropertyKeyValuePair(node,
                                JSON_SCHEMA_FIELD_ELEMENT_IDENTIFIERS);
                        if (StringUtils.isNotEmpty(addedObjectElementIdentifiers)) {
                            // If element identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!elementIdentifierList.contains(addedObjectElementIdentifiers)) {
                                elementIdentifierList.add(addedObjectElementIdentifiers);
                            }
                        }
                        // Removes the @prefix
                        String nodeName = node.getName().substring(1);
                        if (((JSONObject) parent.get(JSON_SCHEMA_ATTRIBUTES)) != null) {
                            ((JSONObject) parent.get(JSON_SCHEMA_ATTRIBUTES)).put(nodeName, elemObject);
                        } else {
                            parent.put(nodeName, elemObject);
                        }
                    }
                } else {
                    JSONObject elemObject = createElementObject(schemaID);
                    elemObject.put(JSON_SCHEMA_TYPE, schemaType);
                    // ignore attributes comes with property iteration
                    if (!name.startsWith(PREFIX)) {
                        // Check if there are namespaces in the fields when
                        // creating the tree by hand
                        addedObjectNamespaces = checkValueFromPropertyKeyValuePair(node,
                                JSON_SCHEMA_FIELD_NAMESPACES);
                        if (StringUtils.isNotEmpty(addedObjectNamespaces)) {
                            // If namespaces are available add those to the
                            // root elements
                            if (!namespaceList.contains(addedObjectNamespaces)) {
                                namespaceList.add(addedObjectNamespaces);
                            }
                        }
                        addedObjectElementIdentifiers = checkValueFromPropertyKeyValuePair(node,
                                JSON_SCHEMA_FIELD_ELEMENT_IDENTIFIERS);
                        if (StringUtils.isNotEmpty(addedObjectElementIdentifiers)) {
                            // If element identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!elementIdentifierList.contains(addedObjectElementIdentifiers)) {
                                elementIdentifierList.add(addedObjectElementIdentifiers);
                            }
                        }
                        if (StringUtils.isNotEmpty(fieldElementIdentifier)) {
                            // If identifiers are available when creating the
                            // tree by hand then add those to the root
                            // elements
                            if (!namespaceList.contains(fieldElementIdentifier)) {
                                namespaceList.add(fieldElementIdentifier);
                            }
                        }
                        parent.put(name, elemObject);
                        if (node.getNode() != null) {
                            // check if it contains attributes object
                            if (((TreeNodeImpl) node).getNode().size() > 0) {
                                JSONObject attributesObject = new JSONObject();
                                hasAttributes = true;
                                elemObject.put(JSON_SCHEMA_ATTRIBUTES, attributesObject);
                                recursiveSchemaGenerator((TreeNodeImpl) node, elemObject, root);
                                hasAttributes = false;
                            }
                        }
                    }
                }

            }
        }
        for (Element elem : elemList) {

            String schemaType = getPropertyKeyValuePairforElements(elem, JSON_SCHEMA_TYPE);
            String schemaID = getPropertyKeyValuePairforElements(elem, JSON_SCHEMA_ID);
            if (schemaType != null) {
                JSONObject elemObject = createElementObject(schemaID);
                elemObject.put(JSON_SCHEMA_TYPE, schemaType);
                parent.put(elem.getName(), elemObject);
            }
        }
    }
}

From source file:qhindex.controller.ServerDataCacheController.java

public boolean cacheAuthorWorksFromServer(String authorUrl, Author author, ArrayList<AuthorWork> authorWorks)
        throws AppException {
    // Set results to null
    authorWorks.clear();//from   www . j  a va 2s  .c om

    JSONObject data = new JSONObject();
    data.put("authorUrl", authorUrl);
    data.put("username", "client_app_user");
    data.put("password", "xPK81Kan1ejtN71Z4mKw");

    JSONObject results = serverDataCache.sendRequest(data, cacheAuthorWorksFromServerUrl, false);
    resultsMsg += serverDataCache.getResultsMsg();

    if (results.size() > 0 && results.containsKey("result")
            && results.get("result").toString().contains("ok")) {
        try {
            // Ensure it is a valid array of author works
            if (results.containsKey("authorWorks")) {
                // Extract author data
                if (results.containsKey("authorSelected")) {
                    String authorStr = (String) results.get("authorSelected");
                    JSONObject authorJsonObj = null;
                    try {
                        authorJsonObj = (JSONObject) new JSONParser().parse(authorStr);
                    } catch (ParseException pEx) {
                        throw new AppException("Could not parse response.", pEx);
                    }
                    if (authorJsonObj != null) {
                        AuthorJsonConverter authorJsonConverter = new AuthorJsonConverter();
                        Author authorFromJson = authorJsonConverter.jsonToAuthor(authorJsonObj);
                        author.setName(authorFromJson.getName());
                        author.setAffiliation(authorFromJson.getAffiliation());
                        author.setUrl(authorFromJson.getUrl());
                    }
                }

                // Extract author works and citing works
                String authorWorksStr = (String) results.get("authorWorks");

                JSONArray authorWorksJsonArray = null;
                try {
                    authorWorksJsonArray = (JSONArray) new JSONParser().parse(authorWorksStr);
                } catch (ParseException pEx) {
                    throw new AppException("Could not parse response.", pEx);
                }
                if (authorWorksJsonArray != null && authorWorksJsonArray.size() > 0) {
                    for (int i = 0; i < authorWorksJsonArray.size(); i++) {
                        JSONObject authorWorkJsonObj = (JSONObject) authorWorksJsonArray.get(i);
                        AuthorWork authorWork = authorWorkJsonConverter.jsonToAuthorWork(authorWorkJsonObj);
                        authorWorks.add(authorWork);
                    }
                }
            } else {
                return false;
            }
        } catch (ClassCastException ccEx) {
            throw new AppException("Wrong formatted data recived.", ccEx);
        }
    } else {
        return false;
    }

    return true;
}