Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

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

Prototype

public JSONArray put(Object value) 

Source Link

Document

Append an object value.

Usage

From source file:com.basho.riak.client.http.mapreduce.filter.UrlDecodeFilter.java

public JSONArray toJson() {
    JSONArray filter = new JSONArray();
    filter.put("urldecode");
    return filter;
}

From source file:com.trk.aboutme.facebook.Request.java

private void serializeToBatch(JSONArray batch, Bundle attachments) throws JSONException, IOException {
    JSONObject batchEntry = new JSONObject();

    if (this.batchEntryName != null) {
        batchEntry.put(BATCH_ENTRY_NAME_PARAM, this.batchEntryName);
        batchEntry.put(BATCH_ENTRY_OMIT_RESPONSE_ON_SUCCESS_PARAM, this.batchEntryOmitResultOnSuccess);
    }/*from www . ja va2  s.co  m*/
    if (this.batchEntryDependsOn != null) {
        batchEntry.put(BATCH_ENTRY_DEPENDS_ON_PARAM, this.batchEntryDependsOn);
    }

    String relativeURL = getUrlForBatchedRequest();
    batchEntry.put(BATCH_RELATIVE_URL_PARAM, relativeURL);
    batchEntry.put(BATCH_METHOD_PARAM, httpMethod);
    if (this.session != null) {
        String accessToken = this.session.getAccessToken();
        Logger.registerAccessToken(accessToken);
    }

    // Find all of our attachments. Remember their names and put them in the attachment map.
    ArrayList<String> attachmentNames = new ArrayList<String>();
    Set<String> keys = this.parameters.keySet();
    for (String key : keys) {
        Object value = this.parameters.get(key);
        if (isSupportedAttachmentType(value)) {
            // Make the name unique across this entire batch.
            String name = String.format("%s%d", ATTACHMENT_FILENAME_PREFIX, attachments.size());
            attachmentNames.add(name);
            Utility.putObjectInBundle(attachments, name, value);
        }
    }

    if (!attachmentNames.isEmpty()) {
        String attachmentNamesString = TextUtils.join(",", attachmentNames);
        batchEntry.put(ATTACHED_FILES_PARAM, attachmentNamesString);
    }

    if (this.graphObject != null) {
        // Serialize the graph object into the "body" parameter.
        final ArrayList<String> keysAndValues = new ArrayList<String>();
        processGraphObject(this.graphObject, relativeURL, new KeyValueSerializer() {
            @Override
            public void writeString(String key, String value) throws IOException {
                keysAndValues.add(String.format("%s=%s", key, URLEncoder.encode(value, "UTF-8")));
            }
        });
        String bodyValue = TextUtils.join("&", keysAndValues);
        batchEntry.put(BATCH_BODY_PARAM, bodyValue);
    }

    batch.put(batchEntry);
}

From source file:tools.xor.AbstractBO.java

@Override
public void set(String propertyPath, Map<String, Object> propertyResult, EntityType domainEntityType)
        throws Exception {

    if (domainEntityType.isOpen()) {
        String propertyName = propertyPath.substring(propertyPath.indexOf(OpenType.DELIM) + 1);
        Property property = getType().getProperty(propertyName);
        ((ExtendedProperty) property).setValue(this,
                propertyResult.get(QueryViewProperty.qualifyProperty(propertyPath)));
        return;//  ww w .  ja  v a2 s .co m
    }

    // If we are setting a null value then nothing needs to be done
    if (propertyResult.get(QueryViewProperty.qualifyProperty(propertyPath)) == null)
        return;

    // Since this builds the path for objects already persisted, the identifier value will not be null
    String[] pathSteps = propertyPath.split(Settings.PATH_DELIMITER_REGEX);
    BusinessObject current = this;
    StringBuilder currentPath = new StringBuilder(QueryViewProperty.ROOT_PROPERTY_NAME);
    for (String step : pathSteps) {
        if (currentPath.length() > 0)
            currentPath.append(Settings.PATH_DELIMITER);
        currentPath.append(step);

        Property property = current.getInstanceProperty(step);
        Property domainProperty = domainEntityType
                .getProperty(currentPath.substring(currentPath.indexOf(Settings.PATH_DELIMITER) + 1));
        if (property == null)
            throw new RuntimeException("Unable to resolve property: " + propertyPath);

        //Object propertyDO = current.get(property);
        Object propertyDO = current.getDataObject(property);
        if (!property.isMany()) {
            if (property.getType().isDataType()) {
                // Populate the field and return the data object
                ((ExtendedProperty) property).setValue(current,
                        propertyResult.get(QueryViewProperty.qualifyProperty(propertyPath)));
                return;
            }

            if (((EntityType) property.getType()).isEmbedded()) {
                // Is this true? 
                // TODO: Check if the embedded object gets created
                // What about collection of embedded objects?
                // Maybe we only allow the fast path of object creation, i.e., the result needs to be sorted
                //   and we use this ability to construct the fields as we scan through each row.
                //   This also allows optimization using OpenCL
                continue; // Embedded objects are automatically created as part of its lifecycle owner
            }

            if (propertyDO == null) {
                // Set the natural key if there is one
                Map<String, Object> naturalKeyValues = new HashMap<String, Object>();
                if (((EntityType) property.getType()).getNaturalKey() != null) {
                    Set<String> naturalKey = ((EntityType) property.getType()).getNaturalKey();
                    if (naturalKey != null) {
                        for (String key : naturalKey) {
                            Object keyValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER + key);
                            naturalKeyValues.put(key, keyValue);
                        }
                        propertyDO = getByNaturalKey(naturalKeyValues, domainProperty.getType());
                    }
                }
                // Check if there is a data object with the given key
                // Get the identifier value
                Object idValue = null;
                if (propertyDO == null && ((EntityType) property.getType()).getIdentifierProperty() != null) {
                    idValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER
                            + ((EntityType) property.getType()).getIdentifierProperty().getName());
                    propertyDO = getBySurrogateKey(idValue, domainProperty.getType());
                }

                if (propertyDO == null) { // create and set the instance object
                    // check if we are narrowing
                    String narrowToType = (String) propertyResult.get(
                            currentPath + Settings.PATH_DELIMITER + QueryViewProperty.ENTITYNAME_ATTRIBUTE);
                    EntityType objectType = (EntityType) property.getType();
                    if (narrowToType != null)
                        objectType = (EntityType) getObjectCreator().getDAS().getType(narrowToType);
                    propertyDO = current.createDataObject(idValue, naturalKeyValues, objectType, property);
                }
            }
            if (property.isContainment()) {
                ((BusinessObject) propertyDO).setContainer(current);
                ((BusinessObject) propertyDO).setContainmentProperty(property);
            }

            // Set the instance value in the container
            ((ExtendedProperty) property).setValue(current, ((BusinessObject) propertyDO).getInstance());

            current = (BusinessObject) propertyDO;
        } else {

            //System.out.println("propertyDO class: " + propertyDO.getClass() + ", property: " + property.getName());
            if (propertyDO == null) { // create and set the collection/map object
                propertyDO = current.createDataObject(null, property.getType(), property);
            } else if (!BusinessObject.class.isAssignableFrom(propertyDO.getClass())) {
                propertyDO = objectCreator.createDataObject(propertyDO, property.getType(), current, property);
            }
            current = (BusinessObject) propertyDO;
            Object elementDO = null;

            // Get the identifier value from the collection element
            Type elementType = ((ExtendedProperty) property).getElementType();
            Type domainElementType = ((ExtendedProperty) domainProperty).getElementType();

            // Get by the natural key if there is one
            Map<String, Object> naturalKeyValues = new HashMap<String, Object>();
            if (((EntityType) elementType).getNaturalKey() != null) {
                Set<String> naturalKey = ((EntityType) elementType).getNaturalKey();
                for (String key : naturalKey) {
                    Object keyValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER + key);
                    naturalKeyValues.put(key, keyValue);
                }

                // Get the element
                elementDO = getByNaturalKey(naturalKeyValues, domainElementType);
            }

            Object idValue = null;
            if (elementDO == null && ((EntityType) elementType).getIdentifierProperty() != null) {
                idValue = propertyResult.get(currentPath + Settings.PATH_DELIMITER
                        + ((EntityType) elementType).getIdentifierProperty().getName());
                elementDO = getBySurrogateKey(idValue, domainElementType);
            }

            // check flag to see if the containment should be set
            if (elementDO != null && property.isContainment()) {
                ((BusinessObject) elementDO).setContainer(current); // Containment property is null for a collection element
            }

            if (elementDO == null) { // create and set the instance object

                // Get the property instance if possible
                Object elementInstance = null;

                if (((ExtendedProperty) property).isMap()) {
                    Object keyValue = propertyResult
                            .get(currentPath + Settings.PATH_DELIMITER + QueryViewProperty.MAP_KEY_ATTRIBUTE);
                    Map map = (Map) current.getInstance();
                    elementInstance = map.get(keyValue);
                }

                if (elementInstance == null) {
                    if (idValue != null || naturalKeyValues.size() > 0)
                        elementDO = current.createDataObject(idValue, naturalKeyValues,
                                (EntityType) elementType, null);
                    else
                        return; // Does not have a collection element
                } else
                    // create the data object using the instance
                    elementDO = objectCreator.createDataObject(elementInstance, elementType, current, null);

                // check flag to see if the containment should be set
                if (property.isContainment())
                    ((BusinessObject) elementDO).setContainer(current); // Containment property is null for a collection element
            }

            // Add the element
            Object elementInstance = ((BusinessObject) elementDO).getInstance();
            if (((ExtendedProperty) property).isMap()) {
                // If this is a map, get the key
                Object keyValue = propertyResult
                        .get(currentPath + Settings.PATH_DELIMITER + QueryViewProperty.MAP_KEY_ATTRIBUTE);
                Map map = (Map) current.getInstance();
                map.put(keyValue, elementInstance);
            } else if (((ExtendedProperty) property).isList()) {
                Object indexValue = propertyResult
                        .get(currentPath + Settings.PATH_DELIMITER + QueryViewProperty.LIST_INDEX_ATTRIBUTE);
                List list = (List) current.getInstance();
                int index = Integer.parseInt(indexValue.toString());
                if (index >= list.size() || list.get(index) != elementInstance)
                    list.add(elementInstance);
            } else if (((ExtendedProperty) property).isSet()) {
                // Currently Immutable JSON is treated as a set, so we should check for this
                if (current.getInstance() instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) current.getInstance();
                    jsonArray.put(elementInstance);
                } else {
                    Set set = (Set) current.getInstance();
                    set.add(elementInstance);
                }
            }

            current = (BusinessObject) elementDO;
        }
    }

    return;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static JSONArray makeResponseJSONArray(String data) {

    JSONArray array = null;
    try {//from w  ww  .ja  va 2  s  . c o m
        array = new JSONArray(data);
    } catch (JSONException e) {
        array = new JSONArray();
        array.put(makeResponseJSONObject(data));
    }

    return array;
}

From source file:ac.blitz.acme.video.VideoCaptureDeviceInfoAndroid.java

private static String getDeviceInfo() {
    try {/*  w  w w.j ava 2  s. co m*/
        JSONArray devices = new JSONArray();
        for (int i = 0; i < Camera.getNumberOfCameras(); ++i) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            String uniqueName = deviceUniqueName(i, info);
            JSONObject cameraDict = new JSONObject();
            devices.put(cameraDict);
            List<Size> supportedSizes;
            List<int[]> supportedFpsRanges;
            try {
                Camera camera = Camera.open(i);
                Parameters parameters = camera.getParameters();
                supportedSizes = parameters.getSupportedPreviewSizes();
                supportedFpsRanges = parameters.getSupportedPreviewFpsRange();
                camera.release();
                Log.d(TAG, uniqueName);
            } catch (RuntimeException e) {
                Log.e(TAG, "Failed to open " + uniqueName + ", skipping");
                continue;
            }
            JSONArray sizes = new JSONArray();
            for (Size supportedSize : supportedSizes) {
                JSONObject size = new JSONObject();
                size.put("width", supportedSize.width);
                size.put("height", supportedSize.height);
                sizes.put(size);
            }
            // Android SDK deals in integral "milliframes per second"
            // (i.e. fps*1000, instead of floating-point frames-per-second) so we
            // preserve that through the Java->C++->Java round-trip.
            int[] mfps = supportedFpsRanges.get(supportedFpsRanges.size() - 1);
            cameraDict.put("name", uniqueName);
            cameraDict.put("front_facing", isFrontFacing(info)).put("orientation", info.orientation)
                    .put("sizes", sizes).put("min_mfps", mfps[Parameters.PREVIEW_FPS_MIN_INDEX])
                    .put("max_mfps", mfps[Parameters.PREVIEW_FPS_MAX_INDEX]);
        }
        String ret = devices.toString(2);
        return ret;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.mist.plot.MainActivity.java

private void dumpSensorData() throws JSONException { //TODO(cjr): do we want JSONException here?
    File dataDir = getOrCreateSessionDir();
    File target = new File(dataDir, String.format("%s.json", mRecordingType));

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("version", "1.0.0");

    boolean isCalibrated = mPullDetector.getCalibrationStatus();
    jsonObject.put("calibrated", isCalibrated);

    // Write system information
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);/* w w  w  .  ja  v a2  s.c  o  m*/
    JSONObject deviceData = new JSONObject();
    deviceData.put("Build.DEVICE", Build.DEVICE);
    deviceData.put("Build.MODEL", Build.MODEL);
    deviceData.put("Build.PRODUCT", Build.PRODUCT);
    deviceData.put("Build.VERSION.SDK_INT", Build.VERSION.SDK_INT);
    deviceData.put("screenResolution.X", size.x);
    deviceData.put("screenResolution.Y", size.y);
    jsonObject.put("systemInfo", deviceData);

    // Write magnetometer data
    JSONArray magnetData = new JSONArray();
    for (int i = 0; i < mSensorData.size(); i++) {
        JSONArray dataPoint = new JSONArray();
        long time = mSensorTime.get(i);
        dataPoint.put(time);
        dataPoint.put(mSensorAccuracy.get(i));
        float[] data = mSensorData.get(i);
        for (float d : data) {
            dataPoint.put(d);
        }
        magnetData.put(dataPoint);
    }
    jsonObject.put("magnetometer", magnetData);

    // Write onAccuracyChanged data
    JSONArray accuracyChangedData = new JSONArray();
    for (int i = 0; i < mAccuracyData.size(); i++) {
        JSONArray dataPoint = new JSONArray();
        long time = mAccuracyTime.get(i);
        dataPoint.put(time);
        dataPoint.put(mAccuracyData.get(i));
        accuracyChangedData.put(dataPoint);
    }
    jsonObject.put("onAccuracyChangedData", accuracyChangedData);

    // Write rotation data
    if (mRecordRotation) {
        JSONArray rotationData = new JSONArray();
        for (int i = 0; i < mSensorData.size(); i++) {
            JSONArray dataPoint = new JSONArray();
            long time = mRotationTime.get(i);
            dataPoint.put(time);
            float[] data = mRotationData.get(i);
            for (float d : data) {
                dataPoint.put(d);
            }
            rotationData.put(dataPoint);
        }
        jsonObject.put("rotation", rotationData);
    }

    // Write event labels
    JSONArray trueLabels = new JSONArray();
    for (int i = 0; i < mPositivesData.size(); i++) {
        JSONArray dataPoint = new JSONArray();
        long time = mPositivesTime.get(i);
        dataPoint.put(time);
        dataPoint.put(mPositivesData.get(i));
        trueLabels.put(dataPoint);
    }
    jsonObject.put("labels", trueLabels);

    try {
        FileWriter fw = new FileWriter(target, true);
        fw.write(jsonObject.toString());
        fw.flush();
        fw.close();
        mDumpPath = target.toString();
    } catch (IOException e) {
        Log.e(TAG, e.toString());
    }
}

From source file:com.neka.cordova.inappbrowser.InAppBrowser.java

/**
 * Inject an object (script or style) into the InAppBrowser WebView.
 *
 * This is a helper method for the inject{Script|Style}{Code|File} API calls, which
 * provides a consistent method for injecting JavaScript code into the document.
 *
 * If a wrapper string is supplied, then the source string will be JSON-encoded (adding
 * quotes) and wrapped using string formatting. (The wrapper string should have a single
 * '%s' marker)//ww w. ja v  a2  s  .  c  o  m
 *
 * @param source      The source object (filename or script/style text) to inject into
 *                    the document.
 * @param jsWrapper   A JavaScript string to wrap the source string in, so that the object
 *                    is properly injected, or null if the source string is JavaScript text
 *                    which should be executed directly.
 */
private void injectDeferredObject(String source, String jsWrapper) {
    String scriptToInject;
    if (jsWrapper != null) {
        org.json.JSONArray jsonEsc = new org.json.JSONArray();
        jsonEsc.put(source);
        String jsonRepr = jsonEsc.toString();
        String jsonSourceString = jsonRepr.substring(1, jsonRepr.length() - 1);
        scriptToInject = String.format(jsWrapper, jsonSourceString);
    } else {
        scriptToInject = source;
    }
    final String finalScriptToInject = scriptToInject;
    this.cordova.getActivity().runOnUiThread(new Runnable() {
        @SuppressLint("NewApi")
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                // This action will have the side-effect of blurring the currently focused element
                inAppWebView.loadUrl("javascript:" + finalScriptToInject);
            } else {
                inAppWebView.evaluateJavascript(finalScriptToInject, null);
            }
        }
    });
}

From source file:org.charvolant.argushiigi.server.TypeQueryResource.java

/**
 * Get a list of matching resources as a JSON document.
 *
 * @see org.restlet.resource.ServerResource#get()
 *///  w  w  w .  j  a  v a  2 s . co  m
@Get
public Representation get() {
    String type = Reference.decode(this.getQueryValue(this.PARAM_TYPE));

    try {
        JSONObject wrap = new JSONObject();
        JSONArray result = new JSONArray();
        StmtIterator si = this.model.listStatements(null, RDF.type, this.model.createResource(type));
        Comparator<Resource> classComparator = this.sorter.getClassComparator();

        while (si.hasNext()) {
            Statement s = si.next();
            Resource res = s.getSubject();

            if (res.isURIResource()) {
                JSONObject obj = new JSONObject();
                Reference ref = this.application.getLocalRef(new Reference(res.getURI()));
                StmtIterator ci = this.model.listStatements(res, RDF.type, (Resource) null);
                Resource cls = null;

                obj.put("name", this.sorter.getName(s.getSubject(), Locale.ENGLISH));
                obj.put("uri", s.getSubject().getURI());
                obj.put("href", ref);
                while (ci.hasNext()) {
                    Resource c = ci.next().getResource();

                    if (c.isAnon())
                        continue;
                    if (cls == null || classComparator.compare(cls, c) > 0)
                        cls = c;
                }
                if (cls == null)
                    cls = OWL.Thing;
                ref = this.application.getLocalRef(new Reference(cls.getURI()));
                obj.put("cls", this.sorter.getName(cls, Locale.ENGLISH));
                obj.put("clsUri", cls.getURI());
                obj.put("clsHref", ref);
                result.put(obj);
            }
        }
        wrap.put("aaData", result);
        return new JsonRepresentation(wrap);
    } catch (Exception ex) {
        this.application.getLogger().log(Level.SEVERE, "Unable to get resources of type " + type, ex);
        this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, ex);
        return new StringRepresentation(ex.getMessage());
    }
}

From source file:com.basho.riak.client.mapreduce.filter.ToLowerFilter.java

public JSONArray toJson() {
    JSONArray filter = new JSONArray();
    filter.put("to_lower");
    return filter;
}

From source file:org.seadpdt.impl.ROServicesImpl.java

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)/*from   w  ww  . j  av a  2s  . co  m*/
public Response getROsList(@QueryParam("Purpose") final String purpose) {
    FindIterable<Document> iter;
    if (purpose != null && purpose.equals("Production")) {
        iter = publicationsCollection.find(Filters.ne("Preferences.Purpose", "Testing-Only"));
    } else if (purpose != null && purpose.equals("Testing-Only")) {
        iter = publicationsCollection.find(Filters.eq("Preferences.Purpose", purpose));
    } else if (purpose != null) {
        return Response.status(ClientResponse.Status.BAD_REQUEST)
                .entity(new JSONObject()
                        .put("Error", "'" + purpose + "' is not an acceptable value for 'Purpose'").toString())
                .build();
    } else {
        iter = publicationsCollection.find();
    }
    iter.projection(new Document("Status", 1).append("Repository", 1).append("Aggregation.Identifier", 1)
            .append("Aggregation.Title", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        array.put(JSON.parse(cursor.next().toJson()));
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}