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:org.zaizi.alfresco.rating.controller.JsonNodeRefUtil.java

private static JSONArray array(List<String> values) {
    JSONArray array = new JSONArray();
    for (String value : values) {
        array.put(value);
    }//from   w ww  . j  av  a 2 s  .c om
    return array;
}

From source file:org.zaizi.alfresco.rating.controller.JsonNodeRefUtil.java

private static JSONArray array(String... values) {
    JSONArray array = new JSONArray();
    for (String value : values) {
        array.put(value);
    }/*w w w  .  jav  a  2 s. c o m*/
    return array;
}

From source file:org.archive.io.WriterPool.java

public JSONArray jsonStatus() throws JSONException {
    Collection<WriterPoolMember> writers = drainAllWriters();

    JSONArray ja = new JSONArray();
    for (WriterPoolMember w : writers) {
        JSONObject jo = new JSONObject();
        jo.put("file", w.getFile());
        jo.put("position", w.getPosition());
        ja.put(jo);
    }/*  w w w . j  a v a2s.  co  m*/

    availableWriters.addAll(writers);

    return ja;
}

From source file:com.bluepandora.therap.donatelife.jsonbuilder.BloodRequestJson.java

public static JSONObject getBloodRequestJson(ResultSet result) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject;//from   w w  w.java  2  s  .co  m

    try {
        while (result.next()) {
            jsonObject = new JSONObject();
            jsonObject.put(MOBILE_NUMBER, result.getString("mobile_number"));
            jsonObject.put(REQ_TIME, result.getString("req_time"));
            jsonObject.put(GROUP_ID, result.getString("group_id"));
            jsonObject.put(AMOUNT, result.getString("amount"));
            jsonObject.put(HOSP_ID, result.getString("hospital_id"));
            jsonObject.put(EMERGENCY, result.getString("emergency"));

            jsonArray.put(jsonObject);
        }
        jsonObject = new JSONObject();
        jsonObject.put(BLOOD_REQUEST, jsonArray);
        jsonObject.put(DONE, 1);

    } catch (SQLException error) {
        Debug.debugLog("BLOOD_GROUP RESULT SET: ", error);
        jsonObject = new JSONObject();
        jsonObject.put(DONE, 0);
    }
    return jsonObject;
}

From source file:org.ohmage.request.mobility.MobilityReadChunkedRequest.java

/**
 * Responds to the Mobility read chunked request.
 *///from  w  w w  . jav  a 2  s. co  m
@Override
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    LOGGER.info("Responding to the Mobility read chunked request.");

    Map<Long, List<MobilityPoint>> millisToPointMap = new HashMap<Long, List<MobilityPoint>>();

    // Bucket the items preserving order in the bucket.
    for (MobilityPoint mobilityPoint : result) {
        long time = mobilityPoint.getTime();

        // Get this point's bucket.
        time = (time / millisPerChunk) * millisPerChunk;

        List<MobilityPoint> bucket = millisToPointMap.get(time);

        if (bucket == null) {
            bucket = new LinkedList<MobilityPoint>();
            millisToPointMap.put(time, bucket);
        }

        bucket.add(mobilityPoint);
    }

    JSONArray outputArray = new JSONArray();

    // Process the buckets.
    try {
        for (Long time : millisToPointMap.keySet()) {
            Map<String, Integer> modeCountMap = new HashMap<String, Integer>();
            String timestamp = null;
            DateTimeZone timezone = null;
            LocationStatus locationStatus = null;
            Location location = null;

            for (MobilityPoint mobilityPoint : millisToPointMap.get(time)) {
                // The first point sets the information.
                if (timestamp == null) {
                    timestamp = DateTimeUtils.getIso8601DateString(mobilityPoint.getDate(), true);
                    timezone = mobilityPoint.getTimezone();

                    locationStatus = mobilityPoint.getLocationStatus();
                    location = mobilityPoint.getLocation();
                }

                // For all points, get the mode.
                String mode = mobilityPoint.getMode().toString().toLowerCase();
                Integer count = modeCountMap.get(mode);

                if (count == null) {
                    modeCountMap.put(mode, 1);
                } else {
                    modeCountMap.put(mode, count + 1);
                }
            }

            JSONObject currResult = new JSONObject();
            currResult.put(JSON_KEY_MODE_COUNT, modeCountMap);
            currResult.put(JSON_KEY_DURATION, millisPerChunk);
            currResult.put(JSON_KEY_TIMESTAMP, timestamp);
            currResult.put(JSON_KEY_TIMEZONE, timezone.getID());
            currResult.put(JSON_KEY_LOCATION_STATUS, locationStatus.toString().toLowerCase());
            try {
                currResult.put(JSON_KEY_LOCATION,
                        ((location == null) ? null : location.toJson(true, LocationColumnKey.ALL_COLUMNS)));
            } catch (DomainException e) {
                LOGGER.error("Error creating the JSON.", e);
                setFailed();
            }

            outputArray.put(currResult);
        }
    } catch (JSONException e) {
        LOGGER.error("Error building the response.", e);
        setFailed();
    }

    super.respond(httpRequest, httpResponse, JSON_KEY_DATA, outputArray);
}

From source file:pt.webdetails.cfr.CfrContentGenerator.java

@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON)
public void listFilesJSON(OutputStream out) throws IOException, JSONException {
    String baseDir = checkRelativePathSanity(getRequestParameters().getStringParameter("dir", ""));
    IFile[] files = service.getRepository().listFiles(baseDir);
    JSONArray arr = new JSONArray();
    if (files != null) {
        for (IFile file : files) {
            if (mr.isCurrentUserAllowed(FilePermissionEnum.READ, relativeFilePath(baseDir, file.getName()))) {
                JSONObject obj = new JSONObject();
                obj.put("fileName", file.getName());
                obj.put("isDirectory", file.isDirectory());
                obj.put("path", baseDir);
                arr.put(obj);
            }//from w w w.j  a va 2  s.c  o m
        }
    }

    writeOut(out, arr.toString(2));
}

From source file:pt.webdetails.cfr.CfrContentGenerator.java

@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON)
public void setPermissions(OutputStream out) throws JSONException, IOException {
    String path = checkRelativePathSanity(getRequestParameters().getStringParameter(pathParameterPath, null));
    String[] userOrGroupId = getRequestParameters().getStringArrayParameter(pathParameterGroupOrUserId,
            new String[] {});
    String[] _permissions = getRequestParameters().getStringArrayParameter(pathParameterPermission,
            new String[] { FilePermissionEnum.READ.getId() });

    JSONObject result = new JSONObject();
    if (path != null && userOrGroupId.length > 0 && _permissions.length > 0) {
        // build valid permissions set
        Set<FilePermissionEnum> validPermissions = new TreeSet<FilePermissionEnum>();
        for (String permission : _permissions) {
            FilePermissionEnum perm = FilePermissionEnum.resolve(permission);
            if (perm != null) {
                validPermissions.add(perm);
            }//  www .j  av a2 s.  com
        }
        JSONArray permissionAddResultArray = new JSONArray();
        for (String id : userOrGroupId) {
            JSONObject individualResult = new JSONObject();
            boolean storeResult = FileStorer
                    .storeFilePermissions(new FilePermissionMetadata(path, id, validPermissions));
            if (storeResult) {
                individualResult.put("status",
                        String.format("Added permission for path %s and user/role %s", path, id));
            } else {
                individualResult.put("status",
                        String.format("Failed to add permission for path %s and user/role %s", path, id));
            }
            permissionAddResultArray.put(individualResult);
        }
        result.put("status", "Operation finished. Check statusArray for details.");
        result.put("statusArray", permissionAddResultArray);
    } else {
        result.put("status", "Path or user group parameters not found");
    }

    writeOut(out, result.toString(2));
}

From source file:pt.webdetails.cfr.CfrContentGenerator.java

@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON)
public void deletePermissions(OutputStream out) throws JSONException, IOException {
    String path = checkRelativePathSanity(getRequestParameters().getStringParameter(pathParameterPath, null));
    String[] userOrGroupId = getRequestParameters().getStringArrayParameter(pathParameterGroupOrUserId,
            new String[] {});

    JSONObject result = new JSONObject();

    if (path != null || (userOrGroupId != null && userOrGroupId.length > 0)) {
        if (userOrGroupId == null || userOrGroupId.length == 0) {
            if (FileStorer.deletePermissions(path, null)) {
                result.put("status", "Permissions deleted");
            } else {
                result.put("status", "Error deleting permissions");
            }//from  w  w w  .ja v a 2 s. c  om
        } else {
            JSONArray permissionDeleteResultArray = new JSONArray();
            for (String id : userOrGroupId) {
                JSONObject individualResult = new JSONObject();
                boolean deleteResult = FileStorer.deletePermissions(path, id);
                if (deleteResult) {
                    individualResult.put("status",
                            String.format("Permission for %s and path %s deleted.", id, path));
                } else {
                    individualResult.put("status",
                            String.format("Failed to delete permission for %s and path %s.", id, path));
                }

                permissionDeleteResultArray.put(individualResult);
            }
            result.put("status", "Multiple permission deletion. Check Status array");
            result.put("statusArray", permissionDeleteResultArray);
        }
    } else {
        result.put("status", "Required arguments user/role and path not found");
    }

    writeOut(out, result.toString(2));

}

From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java

@Override
public void toRaw(ByteBuffer _bb) throws MalformedPacketException {
    super.toRaw(_bb);
    _bb.put(gatewayEui);//from  ww  w .j a v  a 2 s.co  m

    JSONObject json = new JSONObject();
    if (!stats.isEmpty()) {
        JSONArray stat = new JSONArray();
        for (Stat s : stats) {
            stat.put(s.toJson());
        }
        json.put("stat", stats);
    }
    if (!rxpks.isEmpty()) {
        JSONArray rxpk = new JSONArray();
        for (Rxpk s : rxpks) {
            rxpk.put(s.toJson());
        }
        json.put("rxpk", rxpks);
    }

    _bb.put(json.toString().getBytes());
}

From source file:org.zaizi.alfresco.redlink.webscript.DocumentEntities.java

@SuppressWarnings("unchecked")
@Override/*from  w w  w. j a v a 2  s  . co m*/
public Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    Map<String, Object> model = new HashMap<String, Object>(1);

    if (logger.isDebugEnabled()) {
        logger.debug("Retrieving and checking the parameters...");
    }

    try {
        String noderefString = req.getParameter(PARAM_NODEREF);
        NodeRef nodeRef = new NodeRef(noderefString);
        String lang = req.getParameter(PARAM_LANG);
        if (lang == null) {
            lang = DEFAULT_LANG;
        }

        if (nodeService.exists(nodeRef) && nodeService.hasAspect(nodeRef, SensefyModel.ASPECT_ENHANCED)) {
            List<NodeRef> categories = (List<NodeRef>) nodeService.getProperty(nodeRef,
                    ContentModel.PROP_CATEGORIES);

            Map<String, List<JSONObject>> mapTypeEntities = new HashMap<String, List<JSONObject>>();

            if (categories != null && !categories.isEmpty()) {
                for (NodeRef cat : categories) {
                    if (isEntity(cat)) {
                        JSONObject json = new JSONObject();
                        json.put(ENTITY_PARAM, nodeService.getProperty(cat, SensefyModel.PROP_URI));
                        json.put(LABEL_PARAM, nodeService.getProperty(cat, SensefyModel.PROP_LABEL));
                        json.put(THUMBNAIL_PARAM,
                                nodeService.getProperty(cat, SensefyModel.PROP_THUMBNAIL) != null
                                        ? nodeService.getProperty(cat, SensefyModel.PROP_THUMBNAIL)
                                        : "");
                        json.put(ABSTRACT_PARAM, nodeService.getProperty(cat, SensefyModel.PROP_ABSTRACT));

                        // Related documents
                        String query = "NOT ID:\"" + QueryParser.escape(nodeRef.toString()) + "\" AND "
                                + AT_SIGN
                                + QueryParser
                                        .escape(ContentModel.PROP_CATEGORIES.toPrefixString(namespaceService))
                                + ":\"" + QueryParser.escape(cat.toString()) + "\"";

                        SearchParameters sp = new SearchParameters();
                        sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
                        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
                        sp.setQuery(query);
                        ResultSet rs = null;
                        List<NodeRef> relatedDocs = new ArrayList<NodeRef>();
                        try {
                            relatedDocs = searchService.query(sp).getNodeRefs();
                        } finally {
                            if (rs != null) {
                                rs.close();
                            }
                        }
                        JSONArray relatedDocsArray = new JSONArray();
                        for (NodeRef node : relatedDocs) {
                            JSONObject jsonRelated = new JSONObject();
                            jsonRelated.put(NODEREF2_PARAM, node);
                            String name = (String) nodeService.getProperty(node, ContentModel.PROP_NAME);
                            jsonRelated.put(NAME_PARAM, name);
                            relatedDocsArray.put(jsonRelated);
                        }

                        json.put(RELATED_PARAM, relatedDocsArray);

                        String typeEntity = entityTypeExtractor.getType(new LinkedHashSet<String>(
                                (List<String>) nodeService.getProperty(cat, SensefyModel.PROP_TYPES)));

                        if (typeEntity != null) {
                            List<JSONObject> prevValues = mapTypeEntities.get(typeEntity);
                            if (prevValues == null) {
                                prevValues = new ArrayList<JSONObject>();
                            }
                            prevValues.add(json);
                            mapTypeEntities.put(typeEntity, prevValues);
                        }
                    }
                }

                model.put("data", mapTypeEntities);
            }
        }
    } catch (Exception e) {
        logger.error("Error when trying to query stanbolClient for entities: " + e.getMessage(), e);
        status.setCode(Status.STATUS_INTERNAL_SERVER_ERROR);
    }
    return model;

}