Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

In this page you can find the example usage for org.json JSONArray JSONArray.

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:com.jsonstore.util.JSONStoreUtil.java

public static JSONArray convertJSONObjectListToJSONArray(List<JSONObject> objs) {
    JSONArray out = new JSONArray();
    if (objs == null)
        return out;

    for (JSONObject obj : objs) {
        if (obj != null)
            out.put(obj);//  w w  w  . j  a v  a2 s .c o  m
    }

    return out;
}

From source file:org.eclipse.orion.server.logs.jobs.ListRollingFileAppendersJob.java

@Override
protected IStatus performJob() {
    try {/*from  w  w w  .jav a2  s  . c o m*/
        List<RollingFileAppender<ILoggingEvent>> appenders = logService.getRollingFileAppenders();

        JSONObject appendersJSON = new JSONObject();
        appendersJSON.put(ProtocolConstants.KEY_CHILDREN, new JSONArray());
        for (RollingFileAppender<ILoggingEvent> appender : appenders) {

            RollingFileAppenderResource rollingFileAppender = new RollingFileAppenderResource(appender,
                    baseLocation);

            if (rollingFileAppender.getArchivedLogFiles() == null)
                LogUtils.attachArchivedLogFiles(appender, rollingFileAppender, logService);

            appendersJSON.append(ProtocolConstants.KEY_CHILDREN, rollingFileAppender.toJSON());
        }

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, appendersJSON);

    } catch (Exception e) {
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occured when listing rolling file appenders", e);
    }
}

From source file:com.facebook.internal.BundleJSONConverterTest.java

@Test
public void testUnsupportedValues() throws JSONException {
    Bundle b = new Bundle();
    b.putShort("shortValue", (short) 7);

    boolean exceptionCaught = false;
    try {/*from w w w. j ava 2s. com*/
        BundleJSONConverter.convertToJSON(b);
    } catch (IllegalArgumentException a) {
        exceptionCaught = true;
    }
    assertTrue(exceptionCaught);

    JSONArray jsonArray = new JSONArray();
    jsonArray.put(10);
    JSONObject json = new JSONObject();
    json.put("arrayValue", jsonArray);

    exceptionCaught = false;
    try {
        BundleJSONConverter.convertToBundle(json);
    } catch (IllegalArgumentException a) {
        exceptionCaught = true;
    }
    assertTrue(exceptionCaught);
}

From source file:salvatejero.cordova.liferay.LiferayPlugin.java

private void getObjectModel(final CallbackContext callbackContext, String className, String methodName,
        JSONArray values) throws Exception {

    JSONArray jsonArrayInstance = new JSONArray();
    JSONObject jsonObjectInstance = new JSONObject();

    JSONObjectAsyncTaskCallback callBackJSONObject = new JSONObjectAsyncTaskCallback() {

        @Override/* w w  w . j  av a 2  s.  c  om*/
        public void onFailure(Exception arg0) {
            callbackContext.error(arg0.getMessage());
        }

        @Override
        public void onSuccess(JSONObject arg0) {
            // TODO Auto-generated method stub
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, arg0);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }

    };

    JSONArrayAsyncTaskCallback callbackJSONArray = new JSONArrayAsyncTaskCallback() {

        @Override
        public void onFailure(Exception arg0) {
            callbackContext.error(arg0.getMessage());
        }

        @Override
        public void onSuccess(JSONArray arg0) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, arg0);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);

        }
    };

    Method methodToExecute = null;
    Object[] params = null;
    BaseService service = getService(className);

    if (service == null) {
        throw new LiferayPluginException("Service not implemented");
    }
    Method[] methods = service.getClass().getMethods();
    for (Method m : methods) {
        if (m.getName().toLowerCase().equals(methodName.toLowerCase())) {

            if (values.length() != m.getParameterTypes().length) {
                throw new LiferayPluginException("Number of params error for the method " + methodName);
            }
            params = getListOfParam(m, values);
            if (m.getReturnType().isInstance(jsonArrayInstance)) {
                session.setCallback(callbackJSONArray);
            } else if (m.getReturnType().isInstance(jsonObjectInstance)) {
                session.setCallback(callBackJSONObject);
            } else if (m.getReturnType().equals(Void.TYPE)) {
                callbackContext.success();
            }

            methodToExecute = m;
            break;
        }
    }
    if (methodToExecute == null) {
        for (Method m : methods) {
            if (methodName.indexOf(m.getName().toLowerCase()) >= 0) {

                if (values.length() != m.getParameterTypes().length) {
                    throw new LiferayPluginException("Number of params error for the method " + methodName);
                }
                params = getListOfParam(m, values);
                if (m.getReturnType().isInstance(jsonArrayInstance)) {
                    session.setCallback(callbackJSONArray);
                } else if (m.getReturnType().isInstance(jsonObjectInstance)) {
                    session.setCallback(callBackJSONObject);
                } else if (m.getReturnType().equals(Void.TYPE)) {
                    callbackContext.success();
                }

                methodToExecute = m;
                break;
            }
        }
    }
    if (methodToExecute == null) {
        throw new LiferayPluginException("Method " + methodName + "not found");
    }

    try {
        methodToExecute.invoke(service, params);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new LiferayPluginException("Error invoking -- " + e.getMessage());
    }

}

From source file:org.jabsorb.ng.serializer.impl.RawJSONArraySerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    // reprocess the raw json in order to fixup circular references and
    // duplicates
    final JSONArray jsonIn = (JSONArray) o;
    final JSONArray jsonOut = new JSONArray();

    int i = 0;/*w w  w  . ja  v  a  2  s .  c om*/
    try {
        final int j = jsonIn.length();

        for (i = 0; i < j; i++) {
            final Object json = ser.marshall(state, o, jsonIn.get(i), new Integer(i));
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                jsonOut.put(i, json);
            } else {
                // put a slot where the object would go, so it can be fixed
                // up properly in the fix up phase
                jsonOut.put(i, JSONObject.NULL);
            }
        }
    } catch (final MarshallException e) {
        throw new MarshallException("element " + i, e);
    } catch (final JSONException e) {
        throw new MarshallException("element " + i, e);
    }
    return jsonOut;
}

From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java

/**
 * Returns the string that represents the selected attributes in a json
 * understandable way. //from   w  w  w.  j  av  a  2s .c  om
 * First tries to search if the json string is passed by the config. If it is
 * not found then we try to create the json string from original LDAP
 * configuration format.  The original format is individual keys for 
 * each value.
 * @return String json parsable string representation of the selected 
 *         attributes 
 */
static String getJsonStringForSelectedAttributes(Map<String, String> config) {
    String schemaValue = config.get(ConfigName.SCHEMAVALUE.toString());
    if (schemaValue == null || schemaValue.equals("[]")) {
        LOG.info("Trying to recover attributes from individual checkboxes");
        StringBuffer schemaKey = new StringBuffer();
        schemaKey.append(ConfigName.SCHEMA.toString()).append("_").append("\\d");
        Pattern keyPattern = Pattern.compile(schemaKey.toString());
        Set<String> configKeySet = config.keySet();
        JSONArray arr = new JSONArray();
        for (String configKey : configKeySet) {
            Matcher matcher = keyPattern.matcher(configKey);
            if (matcher.find()) {
                String schemaAttribute = config.get(configKey);
                if (schemaAttribute != null && schemaAttribute.trim().length() != 0) {
                    arr.put(config.get(configKey));
                }
            }
        }
        if (arr.length() != 0) {
            schemaValue = arr.toString();
        } else {
            schemaValue = "";
        }
    }
    LOG.info("The appended string for selected attributes is: " + schemaValue);
    return schemaValue;
}

From source file:com.mclinic.json.PatientConverter.java

public JSONArray serialize(final List<Patient> patients) throws JSONException {
    JSONArray array = new JSONArray();
    for (Patient patient : patients)
        array.put(serialize(patient));/* w  ww.j  a  v a  2 s. com*/
    return array;
}

From source file:com.vinexs.tool.XML.java

private static Object getChildJSONObject(org.w3c.dom.Element tag) {
    int i, k;/*from  www  .j a  va 2  s  .com*/

    //get attributes && child nodes
    NamedNodeMap attributes = tag.getAttributes();
    NodeList childNodes = tag.getChildNodes();
    int numAttr = attributes.getLength();
    int numChild = childNodes.getLength();

    //get element nodes
    Boolean hasTagChild = false;
    Map<String, ArrayList<Object>> childMap = new HashMap<>();
    for (i = 0; i < numChild; i++) {
        Node node = childNodes.item(i);
        //not process non-element node
        if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
            continue;
        }
        hasTagChild = true;
        org.w3c.dom.Element childTag = (org.w3c.dom.Element) node;
        String tagName = childTag.getTagName();
        if (!childMap.containsKey(tagName)) {
            childMap.put(tagName, new ArrayList<>());
        }
        childMap.get(tagName).add(getChildJSONObject(childTag));
    }
    if (numAttr == 0 && !hasTagChild) {
        // Return String
        return stringToValue(tag.getTextContent());
    } else {
        // Return JSONObject
        JSONObject data = new JSONObject();
        if (numAttr > 0) {
            for (i = 0; i < numAttr; i++) {
                Node attr = attributes.item(i);
                try {
                    data.put(attr.getNodeName(), stringToValue(attr.getNodeValue()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (hasTagChild) {
            for (Map.Entry<String, ArrayList<Object>> tagMap : childMap.entrySet()) {
                ArrayList<Object> tagList = tagMap.getValue();
                if (tagList.size() == 1) {
                    try {
                        data.put(tagMap.getKey(), tagList.get(0));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    JSONArray array = new JSONArray();
                    for (k = 0; k < tagList.size(); k++) {
                        array.put(tagList.get(k));
                    }
                    try {
                        data.put(tagMap.getKey(), array);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            try {
                data.put("content", stringToValue(tag.getTextContent()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return data;
    }
}

From source file:ub.botiga.data.User.java

public void save(JSONObject root) throws JSONException {
    root.put("name", mName);
    root.put("credit", mCredit);

    JSONArray array = new JSONArray();
    for (Product p : mProducts.values()) {
        array.put(p.getName());/*  w ww .  ja  v a  2 s .co  m*/
    }
    root.put("products", array);
}

From source file:fr.pasteque.client.sync.SendProcess.java

/**
 * Sends new customer to server.//from w w  w  .  j a va  2 s .c  om
 * @return true if customers were send, false otherwise
 */
private boolean sendCustomer() {
    if (Data.Customer.resolvedIds.size() > 0) {
        Log.i(LOG_TAG, "Customer Sync: There are saved local customer ids");
    }
    if (!this.sendCustomer) {
        SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_DONE);
        instance.nextArchive();
        return false;
    }
    JSONArray cstJArray = new JSONArray();
    for (Customer c : Data.Customer.createdCustomers) {
        try {
            // requiered hack to avoid errors. Prepaid is local storage
            // use but the prepaid amount will be calculated from tickets
            // lines by Pastequ-API
            double storedCustomerPrepaid = c.getPrepaid();
            c.setPrepaid(0);
            JSONObject o = c.toJSON();
            cstJArray.put(o);
            c.setPrepaid(storedCustomerPrepaid);
        } catch (JSONException e) {
            Log.d(LOG_TAG, c.toString(), e);
            SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED);
            return false;
        }
    }
    this.subprogress++;
    this.refreshFeedback();
    Map<String, String> postBody = SyncUtils.initParams(this.ctx, "CustomersAPI", "save");
    postBody.put("customers", cstJArray.toString());
    URLTextGetter.getText(SyncUtils.apiUrl(this.ctx), null, postBody, new CustHandler(this, this.listener));
    return true;
}