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.apache.giraph.graph.BspServiceWorker.java

/**
 * Register the health of this worker for a given superstep
 *
 * @param superstep Superstep to register health on
 *///from   w  w  w .ja v  a 2  s .  c om
private void registerHealth(long superstep) {
    JSONArray hostnamePort = new JSONArray();
    hostnamePort.put(getHostname());

    hostnamePort.put(workerInfo.getPort());

    String myHealthPath = null;
    if (isHealthy()) {
        myHealthPath = getWorkerInfoHealthyPath(getApplicationAttempt(), getSuperstep());
    } else {
        myHealthPath = getWorkerInfoUnhealthyPath(getApplicationAttempt(), getSuperstep());
    }
    myHealthPath = myHealthPath + "/" + workerInfo.getHostnameId();
    try {
        myHealthZnode = getZkExt().createExt(myHealthPath, WritableUtils.writeToByteArray(workerInfo),
                Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, true);
    } catch (KeeperException.NodeExistsException e) {
        LOG.warn("registerHealth: myHealthPath already exists (likely " + "from previous failure): "
                + myHealthPath + ".  Waiting for change in attempts " + "to re-join the application");
        getApplicationAttemptChangedEvent().waitForever();
        if (LOG.isInfoEnabled()) {
            LOG.info("registerHealth: Got application " + "attempt changed event, killing self");
        }
        throw new IllegalStateException(
                "registerHealth: Trying " + "to get the new application attempt by killing self", e);
    } catch (KeeperException e) {
        throw new IllegalStateException("Creating " + myHealthPath + " failed with KeeperException", e);
    } catch (InterruptedException e) {
        throw new IllegalStateException("Creating " + myHealthPath + " failed with InterruptedException", e);
    }
    if (LOG.isInfoEnabled()) {
        LOG.info(
                "registerHealth: Created my health node for attempt=" + getApplicationAttempt() + ", superstep="
                        + getSuperstep() + " with " + myHealthZnode + " and workerInfo= " + workerInfo);
    }
}

From source file:com.linkedpipes.plugin.loader.dcatAp11ToCkanBatch.DcatAp11ToCkanBatch.java

@Override
public void execute() throws LpException {

    apiURI = configuration.getApiUri();/* ww w.  j av  a2s.c om*/

    if (apiURI == null || apiURI.isEmpty() || configuration.getApiKey() == null
            || configuration.getApiKey().isEmpty()) {
        throw exceptionFactory.failure("Missing required settings.");
    }

    Map<String, String> organizations = getOrganizations();

    LOG.debug("Querying metadata for datasets");

    LinkedList<String> datasets = new LinkedList<>();
    for (Map<String, Value> map : executeSelectQuery(
            "SELECT ?d WHERE {?d a <" + DcatAp11ToCkanBatchVocabulary.DCAT_DATASET_CLASS + ">}")) {
        datasets.add(map.get("d").stringValue());
    }

    int current = 0;
    int total = datasets.size();

    LOG.info("Found " + total + " datasets");

    progressReport.start(total);

    for (String datasetURI : datasets) {
        current++;

        CloseableHttpResponse queryResponse = null;

        LOG.info("Processing dataset " + current + "/" + total + ": " + datasetURI);

        String datasetID = executeSimpleSelectQuery("SELECT ?did WHERE {<" + datasetURI + "> <"
                + DcatAp11ToCkanBatchVocabulary.LODCZCKAN_DATASET_ID + "> ?did }", "did");
        if (datasetID.isEmpty()) {
            LOG.warn("Dataset " + datasetURI + " has missing CKAN ID");
            continue;
        }

        boolean datasetExists = false;

        Map<String, String> resUrlIdMap = new HashMap<>();
        Map<String, String> resDistroIdMap = new HashMap<>();
        Map<String, JSONObject> resourceList = new HashMap<>();

        LOG.debug("Querying for the dataset " + datasetID + " in CKAN");
        HttpGet httpGet = new HttpGet(apiURI + "/package_show?id=" + datasetID);
        try {
            queryResponse = queryClient.execute(httpGet);
            if (queryResponse.getStatusLine().getStatusCode() == 200) {
                LOG.debug("Dataset found");
                datasetExists = true;

                JSONObject response = new JSONObject(EntityUtils.toString(queryResponse.getEntity()))
                        .getJSONObject("result");
                JSONArray resourcesArray = response.getJSONArray("resources");
                for (int i = 0; i < resourcesArray.length(); i++) {
                    String id = resourcesArray.getJSONObject(i).getString("id");
                    resourceList.put(id, resourcesArray.getJSONObject(i));

                    String url = resourcesArray.getJSONObject(i).getString("url");
                    resUrlIdMap.put(url, id);

                    if (resourcesArray.getJSONObject(i).has("distro_url")) {
                        String distro = resourcesArray.getJSONObject(i).getString("distro_url");
                        resDistroIdMap.put(distro, id);
                    }
                }
            } else {
                String ent = EntityUtils.toString(queryResponse.getEntity());
                LOG.debug("Dataset not found: " + ent);
            }
        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage(), e);
        } finally {
            if (queryResponse != null) {
                try {
                    queryResponse.close();
                } catch (IOException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
            }
        }

        LinkedList<String> keywords = new LinkedList<>();
        for (Map<String, Value> map : executeSelectQuery(
                "SELECT ?keyword WHERE {<" + datasetURI + "> <" + DcatAp11ToCkanBatchVocabulary.DCAT_KEYWORD
                        + "> ?keyword FILTER(LANGMATCHES(LANG(?keyword), \"" + configuration.getLoadLanguage()
                        + "\"))}")) {
            keywords.add(map.get("keyword").stringValue());
        }

        String publisher_uri = executeSimpleSelectQuery("SELECT ?publisher_uri WHERE {<" + datasetURI + "> <"
                + DCTERMS.PUBLISHER + "> ?publisher_uri }", "publisher_uri");
        String publisher_name = executeSimpleSelectQuery(
                "SELECT ?publisher_name WHERE {<" + datasetURI + "> <" + DCTERMS.PUBLISHER + ">/<" + FOAF.NAME
                        + "> ?publisher_name FILTER(LANGMATCHES(LANG(?publisher_name), \""
                        + configuration.getLoadLanguage() + "\"))}",
                "publisher_name");

        if (!organizations.containsKey(publisher_uri)) {
            LOG.debug("Creating organization " + publisher_uri);
            JSONObject root = new JSONObject();

            if (publisher_name == null || publisher_name.isEmpty()) {
                throw exceptionFactory.failure("Organization has no name: " + publisher_uri);
            }

            root.put("title", publisher_name);
            String orgname = Normalizer.normalize(publisher_name, Normalizer.Form.NFD)
                    .replaceAll("\\P{InBasic_Latin}", "").replace(' ', '-').replace('.', '-').toLowerCase();
            root.put("name", orgname);
            JSONArray org_extras = new JSONArray();
            org_extras.put(new JSONObject().put("key", "uri").put("value", publisher_uri));
            root.put("extras", org_extras);

            HttpPost httpPost = new HttpPost(apiURI + "/organization_create");
            httpPost.addHeader(new BasicHeader("Authorization", configuration.getApiKey()));

            String json = root.toString();

            httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));

            CloseableHttpResponse response = null;

            try {
                response = postClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == 200) {
                    LOG.debug("Organization created OK");
                    //LOG.info("Response: " + EntityUtils.toString(response.getEntity()));
                    organizations.put(publisher_uri, orgname);
                } else if (response.getStatusLine().getStatusCode() == 409) {
                    String ent = EntityUtils.toString(response.getEntity());
                    LOG.error("Organization conflict: " + ent);
                    throw exceptionFactory.failure("Organization conflict: " + ent);
                } else {
                    String ent = EntityUtils.toString(response.getEntity());
                    LOG.error("Response:" + ent);
                    throw exceptionFactory.failure("Error creating organization: " + ent);
                }
            } catch (Exception e) {
                LOG.error(e.getLocalizedMessage(), e);
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        LOG.error(e.getLocalizedMessage(), e);
                        throw exceptionFactory.failure("Error creating dataset");
                    }
                }
            }
        }

        LOG.debug("Creating JSON");

        JSONObject root = new JSONObject();

        JSONArray tags = new JSONArray();
        for (String keyword : keywords) {
            String safekeyword = fixKeyword(keyword);
            if (safekeyword.length() >= 2) {
                tags.put(new JSONObject().put("name", safekeyword));
            }
        }
        root.put("tags", tags);

        JSONArray resources = new JSONArray();

        if (!datasetID.isEmpty()) {
            root.put("name", datasetID);
        }

        String title = executeSimpleSelectQuery("SELECT ?title WHERE {<" + datasetURI + "> <" + DCTERMS.TITLE
                + "> ?title FILTER(LANGMATCHES(LANG(?title), \"" + configuration.getLoadLanguage() + "\"))}",
                "title");
        if (!title.isEmpty()) {
            root.put("title", title);
        }
        String description = executeSimpleSelectQuery("SELECT ?description WHERE {<" + datasetURI + "> <"
                + DCTERMS.DESCRIPTION + "> ?description FILTER(LANGMATCHES(LANG(?description), \""
                + configuration.getLoadLanguage() + "\"))}", "description");
        if (!description.isEmpty()) {
            root.put("notes", description);
        }
        String contactPoint = executeSimpleSelectQuery("SELECT ?contact WHERE {<" + datasetURI + "> <"
                + DcatAp11ToCkanBatchVocabulary.DCAT_CONTACT_POINT + ">/<"
                + DcatAp11ToCkanBatchVocabulary.VCARD_HAS_EMAIL + "> ?contact }", "contact");
        if (!contactPoint.isEmpty()) {
            root.put("maintainer_email", contactPoint);
        }
        String curatorName = executeSimpleSelectQuery(
                "SELECT ?name WHERE {<" + datasetURI + "> <" + DcatAp11ToCkanBatchVocabulary.DCAT_CONTACT_POINT
                        + ">/<" + DcatAp11ToCkanBatchVocabulary.VCARD_FN + "> ?name }",
                "name");
        if (!curatorName.isEmpty()) {
            root.put("maintainer", curatorName);
        }
        String issued = executeSimpleSelectQuery(
                "SELECT ?issued WHERE {<" + datasetURI + "> <" + DCTERMS.ISSUED + "> ?issued }", "issued");
        if (!issued.isEmpty()) {
            root.put("metadata_created", issued);
        }
        String modified = executeSimpleSelectQuery(
                "SELECT ?modified WHERE {<" + datasetURI + "> <" + DCTERMS.MODIFIED + "> ?modified }",
                "modified");
        if (!modified.isEmpty()) {
            root.put("metadata_modified", modified);
        }

        if (configuration.getProfile().equals(DcatAp11ToCkanBatchVocabulary.PROFILES_NKOD.stringValue())) {
            if (!publisher_uri.isEmpty()) {
                root.put("publisher_uri", publisher_uri);
            }
            if (!publisher_name.isEmpty()) {
                root.put("publisher_name", publisher_name);
            }

            String periodicity = executeSimpleSelectQuery("SELECT ?periodicity WHERE {<" + datasetURI + "> <"
                    + DCTERMS.ACCRUAL_PERIODICITY + "> ?periodicity }", "periodicity");
            if (!periodicity.isEmpty()) {
                root.put("frequency", periodicity);
            }
            String temporalStart = executeSimpleSelectQuery(
                    "SELECT ?temporalStart WHERE {<" + datasetURI + "> <" + DCTERMS.TEMPORAL + ">/<"
                            + DcatAp11ToCkanBatchVocabulary.SCHEMA_STARTDATE + "> ?temporalStart }",
                    "temporalStart");
            if (!temporalStart.isEmpty()) {
                root.put("temporal_start", temporalStart);
            }
            String temporalEnd = executeSimpleSelectQuery(
                    "SELECT ?temporalEnd WHERE {<" + datasetURI + "> <" + DCTERMS.TEMPORAL + ">/<"
                            + DcatAp11ToCkanBatchVocabulary.SCHEMA_ENDDATE + "> ?temporalEnd }",
                    "temporalEnd");
            if (!temporalEnd.isEmpty()) {
                root.put("temporal_end", temporalEnd);
            }
            String schemaURL = executeSimpleSelectQuery(
                    "SELECT ?schema WHERE {<" + datasetURI + "> <" + FOAF.PAGE + "> ?schema }", "schema");
            if (!schemaURL.isEmpty()) {
                root.put("schema", schemaURL);
            }
            String spatial = executeSimpleSelectQuery(
                    "SELECT ?spatial WHERE {<" + datasetURI + "> <" + DCTERMS.SPATIAL + "> ?spatial }",
                    "spatial");
            if (!spatial.isEmpty()) {
                root.put("spatial_uri", spatial);
            }
            LinkedList<String> themes = new LinkedList<>();
            for (Map<String, Value> map : executeSelectQuery("SELECT ?theme WHERE {<" + datasetURI + "> <"
                    + DcatAp11ToCkanBatchVocabulary.DCAT_THEME + "> ?theme }")) {
                themes.add(map.get("theme").stringValue());
            }
            String concatThemes = "";
            for (String theme : themes) {
                concatThemes += theme + " ";
            }
            if (!concatThemes.isEmpty())
                root.put("theme", concatThemes);

        }

        //Distributions

        LinkedList<String> distributions = new LinkedList<>();
        for (Map<String, Value> map : executeSelectQuery("SELECT ?distribution WHERE {<" + datasetURI + "> <"
                + DcatAp11ToCkanBatchVocabulary.DCAT_DISTRIBUTION + "> ?distribution }")) {
            distributions.add(map.get("distribution").stringValue());
        }

        for (String distribution : distributions) {
            JSONObject distro = new JSONObject();

            String dtitle = executeSimpleSelectQuery("SELECT ?title WHERE {<" + distribution + "> <"
                    + DCTERMS.TITLE + "> ?title FILTER(LANGMATCHES(LANG(?title), \""
                    + configuration.getLoadLanguage() + "\"))}", "title");
            if (!dtitle.isEmpty()) {
                distro.put("name", dtitle);
            }
            String ddescription = executeSimpleSelectQuery("SELECT ?description WHERE {<" + distribution + "> <"
                    + DCTERMS.DESCRIPTION + "> ?description FILTER(LANGMATCHES(LANG(?description), \""
                    + configuration.getLoadLanguage() + "\"))}", "description");
            if (!ddescription.isEmpty()) {
                distro.put("description", ddescription);
            }
            //DCAT-AP v1.1: has to be am IRI from http://publications.europa.eu/mdr/authority/file-type/index.html
            String dformat = executeSimpleSelectQuery(
                    "SELECT ?format WHERE {<" + distribution + "> <" + DCTERMS.FORMAT + "> ?format }",
                    "format");
            if (!dformat.isEmpty() && codelists != null) {
                String formatlabel = executeSimpleCodelistSelectQuery(
                        "SELECT ?formatlabel WHERE {<" + dformat + "> <" + SKOS.PREF_LABEL
                                + "> ?formatlabel FILTER(LANGMATCHES(LANG(?formatlabel), \"en\"))}",
                        "formatlabel");
                if (!formatlabel.isEmpty()) {
                    distro.put("format", formatlabel);
                }
            }

            String dwnld = executeSimpleSelectQuery("SELECT ?dwnld WHERE {<" + distribution + "> <"
                    + DcatAp11ToCkanBatchVocabulary.DCAT_DOWNLOADURL + "> ?dwnld }", "dwnld");
            String access = executeSimpleSelectQuery("SELECT ?acc WHERE {<" + distribution + "> <"
                    + DcatAp11ToCkanBatchVocabulary.DCAT_ACCESSURL + "> ?acc }", "acc");

            //we prefer downloadURL, but only accessURL is mandatory
            if (dwnld == null || dwnld.isEmpty()) {
                dwnld = access;
                if (dwnld == null || dwnld.isEmpty()) {
                    LOG.warn("Empty download and access URLs: " + datasetURI);
                    continue;
                }
            }

            if (!dwnld.isEmpty()) {
                distro.put("url", dwnld);
            }
            if (!distribution.isEmpty()) {
                distro.put("distro_url", distribution);
            }

            distro.put("resource_type", "file");

            if (resDistroIdMap.containsKey(distribution)) {
                String id = resDistroIdMap.get(distribution);
                distro.put("id", id);
                resourceList.remove(id);
            } else if (resUrlIdMap.containsKey(dwnld)) {
                String id = resUrlIdMap.get(dwnld);
                distro.put("id", id);
                resourceList.remove(id);
            }

            String dissued = executeSimpleSelectQuery(
                    "SELECT ?issued WHERE {<" + distribution + "> <" + DCTERMS.ISSUED + "> ?issued }",
                    "issued");
            if (!dissued.isEmpty()) {
                distro.put("created", dissued);
            }
            String dmodified = executeSimpleSelectQuery(
                    "SELECT ?modified WHERE {<" + distribution + "> <" + DCTERMS.MODIFIED + "> ?modified }",
                    "modified");
            if (!dmodified.isEmpty()) {
                distro.put("last_modified", dmodified);
            }

            if (configuration.getProfile().equals(DcatAp11ToCkanBatchVocabulary.PROFILES_NKOD.stringValue())) {
                String dtemporalStart = executeSimpleSelectQuery(
                        "SELECT ?temporalStart WHERE {<" + distribution + "> <" + DCTERMS.TEMPORAL + ">/<"
                                + DcatAp11ToCkanBatchVocabulary.SCHEMA_STARTDATE + "> ?temporalStart }",
                        "temporalStart");
                if (!dtemporalStart.isEmpty()) {
                    distro.put("temporal_start", dtemporalStart);
                }
                String dtemporalEnd = executeSimpleSelectQuery(
                        "SELECT ?temporalEnd WHERE {<" + distribution + "> <" + DCTERMS.TEMPORAL + ">/<"
                                + DcatAp11ToCkanBatchVocabulary.SCHEMA_ENDDATE + "> ?temporalEnd }",
                        "temporalEnd");
                if (!dtemporalEnd.isEmpty()) {
                    distro.put("temporal_end", dtemporalEnd);
                }
                String dspatial = executeSimpleSelectQuery(
                        "SELECT ?spatial WHERE {<" + distribution + "> <" + DCTERMS.SPATIAL + "> ?spatial }",
                        "spatial");
                if (!dspatial.isEmpty()) {
                    root.put("spatial_uri", dspatial);
                }
                String dschemaURL = executeSimpleSelectQuery(
                        "SELECT ?schema WHERE {<" + distribution + "> <" + DCTERMS.CONFORMS_TO + "> ?schema }",
                        "schema");
                if (!dschemaURL.isEmpty()) {
                    distro.put("describedBy", dschemaURL);
                }
                String dlicense = executeSimpleSelectQuery(
                        "SELECT ?license WHERE {<" + distribution + "> <" + DCTERMS.LICENSE + "> ?license }",
                        "license");
                if (!dlicense.isEmpty()) {
                    distro.put("license_link", dlicense);
                }
                String dmimetype = executeSimpleSelectQuery("SELECT ?format WHERE {<" + distribution + "> <"
                        + DcatAp11ToCkanBatchVocabulary.DCAT_MEDIATYPE + "> ?format }", "format");
                if (!dmimetype.isEmpty()) {
                    distro.put("mimetype", dmimetype.replaceAll(".*\\/([^\\/]+\\/[^\\/]+)", "$1"));
                }
            }

            resources.put(distro);
        }

        //Add the remaining distributions that were not updated but existed in the original dataset
        for (Entry<String, JSONObject> resource : resourceList.entrySet()) {
            resources.put(resource.getValue());
        }

        root.put("resources", resources);

        //Create new dataset
        if (!datasetExists) {
            JSONObject createRoot = new JSONObject();
            CloseableHttpResponse response = null;

            createRoot.put("name", datasetID);
            createRoot.put("title", title);
            createRoot.put("owner_org", organizations.get(publisher_uri));

            LOG.debug("Creating dataset in CKAN");
            HttpPost httpPost = new HttpPost(apiURI + "/package_create?id=" + datasetID);
            httpPost.addHeader(new BasicHeader("Authorization", configuration.getApiKey()));

            String json = createRoot.toString();

            LOG.debug("Creating dataset with: " + json);

            httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));

            try {
                response = createClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == 200) {
                    LOG.debug("Dataset created OK");
                    //LOG.info("Response: " + EntityUtils.toString(response.getEntity()));
                } else if (response.getStatusLine().getStatusCode() == 409) {
                    String ent = EntityUtils.toString(response.getEntity());
                    LOG.error("Dataset already exists: " + ent);
                    throw exceptionFactory.failure("Dataset already exists");
                } else {
                    String ent = EntityUtils.toString(response.getEntity());
                    LOG.error("Response:" + ent);
                    throw exceptionFactory.failure("Error creating dataset");
                }
            } catch (Exception e) {
                LOG.error(e.getLocalizedMessage(), e);
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        LOG.error(e.getLocalizedMessage(), e);
                        throw exceptionFactory.failure("Error creating dataset");
                    }
                }
            }
        }

        //Update existing dataset
        String json = root.toString();
        LOG.debug("Posting to CKAN");
        HttpPost httpPost = new HttpPost(apiURI + "/package_update?id=" + datasetID);
        httpPost.addHeader(new BasicHeader("Authorization", configuration.getApiKey()));

        LOG.debug(json);

        httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));
        CloseableHttpResponse response = null;

        try {
            response = postClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                //LOG.info("Response:" + EntityUtils.toString(response.getEntity()));
            } else {
                String ent = EntityUtils.toString(response.getEntity());
                LOG.error("Response:" + ent);
                throw exceptionFactory.failure("Error updating dataset");
            }
        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                    throw exceptionFactory.failure("Error updating dataset");
                }
            }
        }

        progressReport.entryProcessed();
    }

    try {
        queryClient.close();
        createClient.close();
        postClient.close();
    } catch (IOException e) {
        LOG.error(e.getLocalizedMessage(), e);
    }

    progressReport.done();

}

From source file:com.tweetlanes.android.core.App.java

public void removeAccount(String accountKey) {
    final Editor edit = mPreferences.edit();
    String accountIndices = mPreferences.getString(SharedPreferencesConstants.ACCOUNT_INDICES, null);
    if (accountIndices != null) {
        try {/*from   w w w  .  j  a  v  a2 s.  c om*/
            JSONArray jsonArray = new JSONArray(accountIndices);
            JSONArray newIndicies = new JSONArray();
            for (int i = 0; i < jsonArray.length(); i++) {
                Long id = jsonArray.getLong(i);

                String key = getAccountDescriptorKey(id);
                String jsonAsString = mPreferences.getString(key, null);
                if (jsonAsString != null) {
                    AccountDescriptor account = new AccountDescriptor(this, jsonAsString);

                    if (!account.getAccountKey().equals(accountKey)) {
                        newIndicies.put(Long.toString(id));
                    } else {
                        ArrayList<LaneDescriptor> lanes = account.getAllLaneDefinitions();
                        for (LaneDescriptor lane : lanes) {
                            String lanekey = lane.getCacheKey(account.getScreenName() + account.getId());
                            edit.remove(lanekey);
                        }

                        edit.remove(key);
                        mAccounts.remove(account);
                    }
                }
            }

            accountIndices = newIndicies.toString();
            edit.putString(SharedPreferencesConstants.ACCOUNT_INDICES, accountIndices);

            edit.commit();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    updateTwitterAccountCount();
}

From source file:com.marpies.ane.firebase.auth.utils.FirebaseAuthHelper.java

private String getJSONFromUser(FirebaseUser newUser) {
    FirebaseUser user = (newUser == null) ? getUser() : newUser;
    if (user != null) {
        JSONObject json = new JSONObject();
        try {//from  ww  w  . j  av  a 2s  .c o m
            json.put("uid", user.getUid());
            json.put("isAnonymous", user.isAnonymous());
            if (user.getDisplayName() != null) {
                json.put("displayName", user.getDisplayName());
            }
            if (user.getEmail() != null) {
                json.put("email", user.getEmail());
            }
            if (user.getPhotoUrl() != null) {
                json.put("email", user.getPhotoUrl().toString());
            }
            JSONArray providerData = new JSONArray();
            for (UserInfo userInfo : user.getProviderData()) {
                String userInfoJSON = getJSONFromUserInfo(userInfo);
                if (userInfoJSON != null) {
                    providerData.put(userInfoJSON);
                }
            }
            if (providerData.length() > 0) {
                json.put("providerData", providerData);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }
    return null;
}

From source file:org.rssin.serialization.JsonSerializer.java

/**
 * Make a JSONArray from a List<? extends Jsonable>
 * @param list the list to serialize//from  w w w  . ja  v  a  2 s. c  o  m
 * @return the JSONArray
 * @throws JSONException if this happens, it should be a problem in the Jsonable's toJson
 */
public static JSONArray listToJson(List<? extends Jsonable> list) throws JSONException {
    JSONArray json = new JSONArray();
    for (Jsonable item : list) {
        json.put(item.toJson());
    }
    return json;
}

From source file:org.rssin.serialization.JsonSerializer.java

public static JSONArray numbersListToJson(List<? extends Number> list) throws JSONException {
    JSONArray json = new JSONArray();
    for (Number item : list) {
        json.put(item);
    }//from   ww w.  ja  v a  2  s . co m
    return json;
}

From source file:org.loklak.api.iot.AbstractPushServlet.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  . jav  a2 s .c o  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;
    }

    JSONObject map;
    String jsonString = "";
    try {
        jsonString = new String(ClientConnection.download(url), StandardCharsets.UTF_8);
        map = new JSONObject(jsonString);
    } catch (Exception e) {
        response.sendError(400, "error reading json file from url");
        return;
    }

    // validation phase
    ProcessingReport report = this.validator.validate(jsonString);
    if (!report.isSuccess()) {
        response.sendError(400,
                "json does not conform to schema : " + this.getValidatorSchema().name() + "\n" + report);
        return;
    }

    // conversion phase
    Object extractResults = extractMessages(map);
    JSONArray messages;
    if (extractResults instanceof JSONArray) {
        messages = (JSONArray) extractResults;
    } else if (extractResults instanceof JSONObject) {
        messages = new JSONArray();
        messages.put((JSONObject) extractResults);
    } else {
        throw new IOException("extractMessages must return either a List or a Map. Get "
                + (extractResults == null ? "null" : extractResults.getClass().getCanonicalName())
                + " instead");
    }
    JSONArray convertedMessages = this.converter.convert(messages);

    PushReport nodePushReport = new PushReport();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    // custom treatment for each message
    for (int i = 0; i < messages.length(); i++) {
        JSONObject message = (JSONObject) convertedMessages.get(i);
        message.put("source_type", this.getSourceType().toString());
        message.put("location_source", LocationSource.USER.name());
        message.put("place_context", PlaceContext.ABOUT.name());
        if (message.get("text") == null) {
            message.put("text", "");
        }

        // append rich-text attachment
        String jsonToText = ow.writeValueAsString(messages.get(i));
        message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText);
        customProcessing(message);

        if (message.get("mtime") == null) {
            String existed = PushServletHelper.checkMessageExistence(message);
            // message known
            if (existed != null) {
                messages.remove(i);
                nodePushReport.incrementKnownCount(existed);
                continue;
            }
            // updated message -> save with new mtime value
            message.put("mtime", Long.toString(System.currentTimeMillis()));
        }

        try {
            message.put("id_str", PushServletHelper.computeMessageId(message, getSourceType()));
        } catch (Exception e) {
            DAO.log("Problem computing id : " + e.getMessage());
        }
    }
    try {
        PushReport savingReport = PushServletHelper.saveMessagesAndImportProfile(convertedMessages,
                jsonString.hashCode(), post, getSourceType(), screen_name);
        nodePushReport.combine(savingReport);
    } catch (IOException e) {
        response.sendError(404, e.getMessage());
        return;
    }
    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), nodePushReport);

    post.setResponse(response, "application/javascript");
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + nodePushReport.getRecordCount() + ", new = "
            + nodePushReport.getNewCount() + ", known = " + nodePushReport.getKnownCount() + ", error = "
            + nodePushReport.getErrorCount() + ", from host hash " + remoteHash);
}

From source file:com.kakao.internal.Action.java

public JSONObject createJSONObject() throws JSONException {
    JSONObject json = new JSONObject();
    json.put(KakaoTalkLinkProtocol.ACTION_TYPE, type.value);
    if (url != null) {
        json.put(KakaoTalkLinkProtocol.ACTION_URL, url);
    }/*from   w  w  w . j  ava  2 s .  c  o  m*/
    if (appActionInfos != null) {
        JSONArray jsonObjs = new JSONArray();
        for (AppActionInfo obj : appActionInfos) {
            jsonObjs.put(obj.createJSONObject());
        }
        json.put(KakaoTalkLinkProtocol.ACTION_ACTIONINFO, jsonObjs);
    }
    return json;
}

From source file:org.uiautomation.ios.server.servlet.IOSServlet.java

private JSONArray serializeStackTrace(StackTraceElement[] els) throws JSONException {
    JSONArray stacktace = new JSONArray();
    for (StackTraceElement el : els) {
        JSONObject stckEl = new JSONObject();
        stckEl.put("fileName", el.getFileName());
        stckEl.put("className", el.getClassName());
        stckEl.put("methodName", el.getMethodName());
        stckEl.put("lineNumber", el.getLineNumber());
        stacktace.put(stckEl);
    }//from   ww  w  . jav a  2  s  . co m
    return stacktace;
}

From source file:fr.simon.marquis.secretcodes.util.Utils.java

public static void saveSecretCodes(Context ctx, ArrayList<SecretCode> secretCodes) {
    Editor ed = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
    JSONArray array = new JSONArray();
    for (SecretCode code : secretCodes) {
        array.put(code.toJSON());
    }/*from ww  w .  ja v  a  2 s . co  m*/
    ed.putString(KEY_SECRET_CODES, array.toString());
    ed.commit();
}