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:nl.spellenclubeindhoven.dominionshuffle.Application.java

public void saveResult() {
    if (result == null)
        return;//from w  w  w .  j a  v a 2 s. c  o m

    JSONObject jsonResult = new JSONObject();

    JSONArray jsonCards = new JSONArray();
    for (Card card : result.getCards()) {
        jsonCards.put(card.getName());
    }

    try {
        jsonResult.put("cards", jsonCards);
        if (result.getBaneCard() != null) {
            jsonResult.put("baneCard", result.getBaneCard().getName());
        }
        if (result.getObeliskCard() != null) {
            jsonResult.put("obeliskCard", result.getObeliskCard().getName());
        }
        DataReader.writeStringToFile(this, "result.json", jsonResult.toString());
    } catch (JSONException ignore) {
        ignore.printStackTrace();
    }
}

From source file:github.popeen.dsub.util.SongDBHandler.java

public JSONArray exportData() {
    SQLiteDatabase db = this.getReadableDatabase();
    String[] columns = { SONGS_ID, SONGS_SERVER_KEY, SONGS_SERVER_ID, SONGS_COMPLETE_PATH, SONGS_LAST_PLAYED,
            SONGS_LAST_COMPLETED };/*from w  w w .  j  ava 2  s.  co m*/
    Cursor cursor = db.query(TABLE_SONGS, columns, SONGS_LAST_PLAYED + " != ''", null, null, null, null, null);
    try {
        JSONArray jsonSongDb = new JSONArray();
        while (cursor.moveToNext()) {
            JSONObject tempJson = new JSONObject();
            tempJson.put("SONGS_ID", cursor.getInt(0));
            tempJson.put("SONGS_SERVER_KEY", cursor.getInt(1));
            tempJson.put("SONGS_SERVER_ID", cursor.getString(2));
            tempJson.put("SONGS_COMPLETE_PATH", cursor.getString(3));
            tempJson.put("SONGS_LAST_PLAYED", cursor.getInt(4));
            tempJson.put("SONGS_LAST_COMPLETED", cursor.getInt(5));
            jsonSongDb.put(tempJson);
        }
        cursor.close();
        return jsonSongDb;
    } catch (Exception e) {
    }
    return new JSONArray();
}

From source file:org.schedulesdirect.grabber.ProgramTask.java

/**
 * Constructor//from  w ww.  j a  v a2 s.  c o m
 * @param req The array of program ids to be downloaded
 * @param vfs The name of the vfs being written to
 * @param clnt The EpgClient to be used to download the request
 * @param factory The JsonRequestFactory implementation to use
 * @param seriesIds The master collection of series info object ids that needs to be collected
 * @param targetDir The directory where collected programs should be stored
 * @param retrySet A set of ids that were not available on the server side; should be retried again later 
 */
public ProgramTask(Collection<String> progIds, FileSystem vfs, NetworkEpgClient clnt,
        IJsonRequestFactory factory, Set<String> seriesIds, String targetDir, Set<String> retrySet,
        boolean logMissingAtDebug) throws JSONException {
    this.req = new JSONArray();
    for (String id : progIds)
        req.put(id);
    this.vfs = vfs;
    this.clnt = clnt;
    this.factory = factory;
    this.seriesIds = seriesIds;
    this.targetDir = targetDir;
    this.retrySet = retrySet;
    this.logMissingAtDebug = logMissingAtDebug;
}

From source file:org.loklak.api.iot.NetmonPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Query post = RemoteAccess.evaluate(request);
    String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode()));

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*from   ww  w . j  a va  2  s  .  co m*/
    }

    String url = post.get("url", "");
    if (url == null || url.length() == 0) {
        response.sendError(400, "your request does not contain an url to your data object");
        return;
    }
    String screen_name = post.get("screen_name", "");
    if (screen_name == null || screen_name.length() == 0) {
        response.sendError(400, "your request does not contain required screen_name parameter");
        return;
    }

    JSONArray nodesList = new JSONArray();
    byte[] xmlText;
    try {
        xmlText = ClientConnection.download(url);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(new String(xmlText))));
        NodeList routerList = document.getElementsByTagName("router");
        for (int i = 0; i < routerList.getLength(); i++) {
            JSONObject node = convertDOMNodeToMap(routerList.item(i));
            if (node != null)
                nodesList.put(node);
        }
    } catch (Exception e) {
        Log.getLog().warn(e);
        response.sendError(400, "error reading json file from url");
        return;
    }

    JsonFieldConverter converter = new JsonFieldConverter(
            JsonFieldConverter.JsonConversionSchemaEnum.NETMON_NODE);
    JSONArray nodes = converter.convert(nodesList);

    for (Object node_obj : nodes) {
        JSONObject node = (JSONObject) node_obj;
        if (!node.has("text")) {
            node.put("text", "");
        }
        node.put("source_type", SourceType.NETMON.toString());
        if (!node.has("user")) {
            node.put("user", new JSONObject());
        }

        List<Object> location_point = new ArrayList<>();
        location_point.add(0, Double.parseDouble((String) node.get("latitude")));
        location_point.add(1, Double.parseDouble((String) node.get("longitude")));
        node.put("location_point", location_point);
        node.put("location_mark", location_point);
        node.put("location_source", LocationSource.USER.name());
        try {
            node.put("id_str", PushServletHelper.computeMessageId(node, SourceType.NETMON));
        } catch (Exception e) {
            DAO.log("Problem computing id" + e.getMessage());
            continue;
        }
        try {
            JSONObject user = (JSONObject) node.get("user");
            user.put("screen_name", computeUserId(user.get("update_date"), user.get("id"), SourceType.NETMON));
        } catch (Exception e) {
            DAO.log("Problem computing user id : " + e.getMessage());
        }
    }

    PushReport pushReport = PushServletHelper.saveMessagesAndImportProfile(nodes, Arrays.hashCode(xmlText),
            post, SourceType.NETMON, screen_name);

    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), pushReport);
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + pushReport.getRecordCount() + ", new = "
            + pushReport.getNewCount() + ", known = " + pushReport.getKnownCount() + ", from host hash "
            + remoteHash);

}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject getPerm(Storage storage, Record recordForPermResource, String resourceName, String permLevel)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject permitem = new JSONObject();

    if (permLevel.equals("none")) {
        return permitem;
    }/* ww  w .j a v a  2 s .  c  om*/

    JSONArray actions = new JSONArray();
    JSONObject permR = permJSON("READ");
    JSONObject permC = permJSON("CREATE");
    JSONObject permU = permJSON("UPDATE");
    JSONObject permD = permJSON("DELETE");
    JSONObject permL = permJSON("SEARCH");

    ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL
    String queryString = "CRUDL";

    if (permLevel.equals(Generic.READ_PERMISSION)) {
        queryString = "RL";
        actions.put(permR);
        actions.put(permL);
    } else if (permLevel.equals(Generic.WRITE_PERMISSION)) {
        queryString = "CRUL";
        actions.put(permC);
        actions.put(permR);
        actions.put(permU);
        actions.put(permL);
    } else if (permLevel.equals(Generic.DELETE_PERMISSION) || permLevel.equals(Generic.LOCK_PERMISSION)) {
        actions.put(permC);
        actions.put(permR);
        actions.put(permU);
        if (recordForPermResource != null && recordForPermResource.hasSoftDeleteMethod()) {
            // Delete is handled in the workflow perms
            queryString = "CRUL";
        } else {
            queryString = "CRUDL";
            actions.put(permD);
        }
        actions.put(permL); // Keep this here to preserve CRUDL order of actions
    } else {
        log.warn("RecordCreateDelete.getPerm passed unknown permLevel: " + permLevel);
    }

    String permbase = spec.getRecordByWebUrl("permission").getID();

    permitem = getPermID(storage, Generic.ResourceNameServices(spec, resourceName), queryString, permbase,
            actions);
    return permitem;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject getWorkflowPerm(Storage storage, Record recordForPermResource, String resourceName,
        String permLevel, String workflowTransition)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject permitem = new JSONObject();

    if (permLevel.equals("none")) {
        return permitem;
    }//from w  w  w  .j  a  v  a2 s  .c o  m

    JSONArray actions = new JSONArray();
    JSONObject permC = permJSON("CREATE");
    JSONObject permR = permJSON("READ");
    JSONObject permU = permJSON("UPDATE");
    JSONObject permD = permJSON("DELETE");
    JSONObject permL = permJSON("SEARCH");
    actions.put(permR);
    actions.put(permL);

    ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL
    String queryString = "RL";
    String permbase = spec.getRecordByWebUrl("permission").getID();
    boolean hasRights = false;

    if (workflowTransition.equals(DELETE_WORKFLOW_TRANSITION)) {
        // permLevel delete or lock includes this
        hasRights = permLevel.equals(Generic.DELETE_PERMISSION) || permLevel.equals(Generic.LOCK_PERMISSION);
    } else if (workflowTransition.equals(LOCK_WORKFLOW_TRANSITION)) {
        // permLevel lock includes this
        // UI does not yet support admin of the lock perm, so 
        //hasRights = permLevel.equals(Generic.LOCK_PERMISSION);
        // Assumes this is only called for records that actually support locking...
        hasRights = permLevel.equals(Generic.DELETE_PERMISSION) || permLevel.equals(Generic.UPDATE_PERMISSION)
                || permLevel.equals(Generic.LOCK_PERMISSION);
    } else {
        log.warn("RecordCreateUpdate.getWorkflowPerm passed unknown workflowTransition: " + workflowTransition);
    }
    if (hasRights) {
        actions.put(permC);
        actions.put(permU);
        actions.put(permD);
        // They do not really get DELETE rights on a workflow, but that is what the services models by
        // default, so let's stick with that 
        queryString = "CRUDL";
    }
    // Workflow resources all have leading slashes.
    String resource = Generic.ResourceNameServices(spec, resourceName) + WORKFLOW_SUB_RESOURCE
            + workflowTransition;
    if (!resource.startsWith("/"))
        resource = "/" + resource;
    permitem = getPermID(storage, resource, queryString, permbase, actions);
    return permitem;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private void assignPermissions(Storage storage, String path, JSONObject data)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject fields = data.optJSONObject("fields");

    JSONArray permdata = new JSONArray();
    JSONObject permcheck = new JSONObject();
    if (fields.has("permissions")) {
        JSONArray permissions = fields.getJSONArray("permissions");
        for (int i = 0; i < permissions.length(); i++) {
            JSONObject perm = permissions.getJSONObject(i);

            Record recordForPermResource = Generic.RecordNameServices(spec, perm.getString("resourceName"));
            if (recordForPermResource != null) {
                if (recordForPermResource.hasSoftDeleteMethod()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            DELETE_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(//from   w w  w .j  a v a2  s .c  o  m
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/delete permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
                if (recordForPermResource.supportsLocking()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            LOCK_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/lock permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
            }
            JSONObject permitem = getPerm(storage, recordForPermResource, perm.getString("resourceName"),
                    perm.getString("permission"));
            if (permitem.has("permissionId")) {
                if (permcheck.has(permitem.getString("resourceName"))) {
                    //ignore as we have duplicate name - eek
                    log.warn("RecordCreateUpdate.assignPermissions got duplicate permission for: "
                            + permitem.getString("resourceName"));
                } else {
                    permcheck.put(permitem.getString("resourceName"), permitem);
                    permdata.put(permitem);
                }
            }
        }
    }

    //log.info("permdata"+permdata.toString());
    JSONObject roledata = new JSONObject();
    roledata.put("roleName", fields.getString("roleName"));

    String[] ids = path.split("/");
    roledata.put("roleId", ids[ids.length - 1]);

    JSONObject accountrole = new JSONObject();
    JSONObject arfields = new JSONObject();
    arfields.put("role", roledata);
    arfields.put("permission", permdata);
    accountrole.put("fields", arfields);
    //log.info("WAAA"+arfields.toString());
    if (fields != null)
        path = storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(), arfields, null);
}

From source file:net.straylightlabs.archivo.net.MindCommandRecordingFolderItemSearch.java

private static JSONArray buildTemplate() {
    JSONArray templates = new JSONArray();
    JSONObject template;/*ww  w  . j  a  va  2 s . c o m*/

    // Only get the recording ID
    template = new JSONObject();
    template.put(TYPE, "responseTemplate");
    template.put(FIELD_NAME, Collections.singletonList("childRecordingId"));
    template.put(TYPE_NAME, "recordingFolderItem");
    templates.put(template);

    return templates;
}

From source file:com.googlecode.CallerLookup.Main.java

public void saveUserLookupEntries() {
    try {//from  w  ww.  jav a  2 s .  c  o  m
        FileOutputStream file = getApplicationContext().openFileOutput(SAVED_FILE, MODE_PRIVATE);
        JSONArray userLookupEntries = new JSONArray();
        for (String lookupEntryName : mUserLookupEntries.keySet()) {
            try {
                userLookupEntries.put(mUserLookupEntries.get(lookupEntryName).toJSONObject());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        OutputStreamWriter content = new OutputStreamWriter(file);
        content.write(userLookupEntries.toString());
        content.flush();
        content.close();
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.dattasmoon.pebble.plugin.FireReceiver.java

public void sendAlertToPebble(final Context context, int bundleVersionCode, String title, String body) {
    // Create json object to be sent to Pebble
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put("title", title);
    data.put("body", body);
    final JSONObject jsonData = new JSONObject(data);
    final String notificationData = new JSONArray().put(jsonData).toString();

    // Create the intent to house the Pebble notification
    final Intent i = new Intent(Constants.INTENT_SEND_PEBBLE_NOTIFICATION);
    i.putExtra("messageType", Constants.PEBBLE_MESSAGE_TYPE_ALERT);
    i.putExtra("sender", context.getString(R.string.app_name));
    i.putExtra("notificationData", notificationData);

    // Send the alert to Pebble
    if (Constants.IS_LOGGABLE) {
        Log.d(Constants.LOG_TAG, "About to send a modal alert to Pebble: " + notificationData);
    }//from w  w  w.j a va2 s  .c o m
    context.sendBroadcast(i);
}