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:net.olejon.mdapp.NotificationsFromSlvActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Settings/*w w w . j  a  v  a 2  s .  co  m*/
    PreferenceManager.setDefaultValues(mContext, R.xml.settings, false);

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();

        return;
    }

    // Notification manager
    mNotificationManagerCompat = NotificationManagerCompat.from(mContext);

    // Layout
    setContentView(R.layout.activity_notifications_from_slv);

    // Toolbar
    final Toolbar toolbar = (Toolbar) findViewById(R.id.notifications_from_slv_toolbar);
    toolbar.setTitle(getString(R.string.notifications_from_slv_title));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.notifications_from_slv_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.notifications_from_slv_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            getNotifications(false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.notifications_from_slv_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new NotificationsFromSlvAdapter(mContext, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // Get notifications
    getNotifications(true);
}

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 ww .j  a  v  a  2s  . c  o  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 .j  a  v  a  2  s .c  o  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:com.example.nestedarchetypeactivityexample.InnerArchetypeViewerActivity.java

private JSONArray getTemplateJsonContent() {
    List<WidgetProvider> wps = this.tp.getWidgetProviders();
    JSONArray tmpJson = new JSONArray();
    for (int i = 0; i < wps.size(); i++)
        try {//from www .  j  av a  2s .  c  o  m
            tmpJson.put(i, wps.get(i).toJson());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    return tmpJson;

}

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

/**
 * Responds to the Mobility read chunked request.
 *///ww  w  . ja  v 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. jav  a2 s.c  om*/
            }
        }
    }

    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);
            }/*from   w ww .  j av  a 2 s  .c o m*/
        }
        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");
            }/*w  ww .j  av a2  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   w  ww .  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 av 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;

}