Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

In this page you can find the example usage for org.json JSONObject get.

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:org.wso2.emm.agent.services.ProcessMessage.java

public ProcessMessage(Context context, int mode, String message, String recepient) {
    // TODO Auto-generated constructor stub
    JSONParser jp = new JSONParser();
    params = new HashMap<String, String>();
    try {//from   w  ww.j a v  a 2s  .  c om

        JSONObject jobj = new JSONObject(message);
        params.put("code", (String) jobj.get("message"));
        if (jobj.has("data")) {
            params.put("data", ((JSONObject) jobj.get("data")).toString());
        }

        operation = new Operation(context, mode, params, recepient);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;//from  w  ww.j  ava2  s  .c om
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFolders() {
    //File.deleteAllFolders();

    URL urlO = null;//from   ww w .  j  av a 2  s  .  c o m
    try {
        urlO = new URL(folderUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(folderJson.get("_id").toString());

                if (file == null) {
                    file = new File(folderJson, true);
                } else {
                    file.setName(folderJson.getString("name"));
                    file.setPath(folderJson.getString("path"));
                    file.setCreationDate(folderJson.getString("creationDate"));
                    file.setLastModification(folderJson.getString("lastModification"));
                    file.setTags(folderJson.getString("tags"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing remote folder : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName()));

                file.save();
                createFolder(file.getPath(), file.getName());

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:org.everit.json.schema.ObjectComparator.java

private static boolean deepEqualObjects(final JSONObject jsonObj1, final JSONObject jsonObj2) {
    String[] obj1Names = JSONObject.getNames(jsonObj1);
    if (!Arrays.equals(obj1Names, JSONObject.getNames(jsonObj2))) {
        return false;
    }//from   w  w w  .java  2 s .co m
    if (obj1Names == null) {
        return true;
    }
    for (String name : obj1Names) {
        if (!deepEquals(jsonObj1.get(name), jsonObj2.get(name))) {
            return false;
        }
    }
    return true;
}

From source file:com.mboarder.util.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*from   w  ww .  j  a v a2s.co m*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:gr.cti.android.experimentation.controller.api.AndroidExperimentationWS.java

private Result extractResultFromBody(String body) throws JSONException, IOException {

    body = body.replaceAll("atributeType", "attributeType")
            .replaceAll("org.ambientdynamix.contextplugins.NoiseLevel",
                    OrganicityAttributeTypes.Types.SOUND_PRESSURE_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.sound",
                    OrganicityAttributeTypes.Types.SOUND_PRESSURE_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.10pm",
                    OrganicityAttributeTypes.Types.PARTICLES10.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.25pm",
                    OrganicityAttributeTypes.Types.PARTICLES25.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.co",
                    OrganicityAttributeTypes.Types.CARBON_MONOXIDE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.lpg", OrganicityAttributeTypes.Types.LPG.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.ch4",
                    OrganicityAttributeTypes.Types.METHANE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.temperature",
                    OrganicityAttributeTypes.Types.TEMPERATURE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.battery%",
                    OrganicityAttributeTypes.Types.BATTERY_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.batteryv",
                    OrganicityAttributeTypes.Types.BATTERY_VOLTAGE.getUrn());

    Report result = new ObjectMapper().readValue(body, Report.class);
    LOGGER.info("saving for deviceId:" + result.getDeviceId() + " jobName:" + result.getJobName());
    final Smartphone phone = smartphoneRepository.findById(result.getDeviceId());
    final Experiment experiment = experimentRepository.findById(Integer.parseInt(result.getJobName()));
    LOGGER.info("saving for PhoneId:" + phone.getPhoneId() + " ExperimentName:" + experiment.getName());

    final Result newResult = new Result();
    final JSONObject objTotal = new JSONObject();

    for (final String jobResult : result.getJobResults()) {

        LOGGER.info(jobResult);//from  w w  w  .  j av a2s  .com
        if (jobResult.isEmpty()) {
            continue;
        }

        final Reading readingObj = new ObjectMapper().readValue(jobResult, Reading.class);
        final String value = readingObj.getValue();
        final long readingTime = readingObj.getTimestamp();

        try {
            final Set<Result> res = resultRepository.findByExperimentIdAndDeviceIdAndTimestampAndMessage(
                    experiment.getId(), phone.getId(), readingTime, value);
            if (!res.isEmpty()) {
                continue;
            }
        } catch (Exception e) {
            LOGGER.error(e, e);
        }
        LOGGER.info(jobResult);
        newResult.setDeviceId(phone.getId());
        newResult.setExperimentId(experiment.getId());
        final JSONObject obj = new JSONObject(value);
        for (final String key : JSONObject.getNames(obj)) {
            objTotal.put(key, obj.get(key));
        }
        newResult.setTimestamp(readingTime);
    }

    newResult.setMessage(objTotal.toString());

    LOGGER.info(newResult.toString());
    return newResult;
}

From source file:com.altamiracorp.lumify.twitter.DefaultLumifyTwitterProcessor.java

@Override
public Vertex parseTwitterUser(final String processId, final JSONObject jsonTweet, final Vertex tweetVertex) {
    // TODO set visibility
    Visibility visibility = new Visibility("");
    JSONObject jsonUser = JSON_USER_PROPERTY.getFrom(jsonTweet);
    String screenName = JSON_SCREEN_NAME_PROPERTY.getFrom(jsonUser);
    if (jsonUser == null || screenName == null || screenName.trim().isEmpty()) {
        return null;
    }//w  w w.  j  av a 2s . c o m

    // cache the current Lumify User
    User lumifyUser = getUser();
    Graph graph = getGraph();

    Concept handleConcept = getOntologyRepository().getConceptByName(CONCEPT_TWITTER_HANDLE);

    String id = TWITTER_USER_PREFIX + jsonUser.get("id");
    Vertex userVertex = graph.getVertex(id, lumifyUser.getAuthorizations());
    ElementMutation<Vertex> userVertexMutation;
    if (userVertex == null) {
        userVertexMutation = graph.prepareVertex(id, visibility, lumifyUser.getAuthorizations());
    } else {
        // TODO what happens if userIterator contains multiple users
        userVertexMutation = userVertex.prepareMutation();
    }

    TITLE.setProperty(userVertexMutation, screenName, visibility);
    CONCEPT_TYPE.setProperty(userVertexMutation, handleConcept.getId(), visibility);

    setOptionalProps(userVertexMutation, jsonUser, OPTIONAL_USER_PROPERTY_MAP, visibility);

    if (!(userVertexMutation instanceof ExistingElementMutation)) {
        userVertex = userVertexMutation.save();
        getAuditRepository().auditVertexElementMutation(userVertexMutation, userVertex, processId, lumifyUser,
                visibility);
    } else {
        getAuditRepository().auditVertexElementMutation(userVertexMutation, userVertex, processId, lumifyUser,
                visibility);
        userVertex = userVertexMutation.save();
    }

    // create the relationship between the user and their tweet
    graph.addEdge(tweetVertex, userVertex, TWEETED_RELATIONSHIP, visibility, lumifyUser.getAuthorizations());
    String labelDispName = getOntologyRepository().getDisplayNameForLabel(TWEETED_RELATIONSHIP);
    getAuditRepository().auditRelationship(AuditAction.CREATE, userVertex, tweetVertex, labelDispName,
            processId, "", lumifyUser, visibility);

    return userVertex;
}

From source file:com.altamiracorp.lumify.twitter.DefaultLumifyTwitterProcessor.java

@Override
public void extractEntities(final String processId, final JSONObject jsonTweet, final Vertex tweetVertex,
        final TwitterEntityType entityType) {
    // TODO set visibility
    Visibility visibility = new Visibility("");
    String tweetText = JSON_TEXT_PROPERTY.getFrom(jsonTweet);
    // only process if text is found in the tweet
    if (tweetText != null && !tweetText.trim().isEmpty()) {
        String tweetId = tweetVertex.getId().toString();
        User user = getUser();//w  w w.j  a va  2 s . c o m
        Graph graph = getGraph();
        OntologyRepository ontRepo = getOntologyRepository();
        AuditRepository auditRepo = getAuditRepository();

        Concept concept = ontRepo.getConceptByName(entityType.getConceptName());
        Vertex conceptVertex = concept.getVertex();
        String relDispName = conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0)
                .toString();

        JSONArray entities = jsonTweet.getJSONObject("entities").getJSONArray(entityType.getJsonKey());
        List<TermMentionModel> mentions = new ArrayList<TermMentionModel>();

        for (int i = 0; i < entities.length(); i++) {
            JSONObject entity = entities.getJSONObject(i);
            String id;
            String sign = entity.getString(entityType.getSignKey());
            if (entityType.getConceptName().equals(CONCEPT_TWITTER_MENTION)) {
                id = TWITTER_USER_PREFIX + entity.get("id");
            } else if (entityType.getConceptName().equals(CONCEPT_TWITTER_HASHTAG)) {
                sign = sign.toLowerCase();
                id = TWITTER_HASHTAG_PREFIX + sign;
            } else {
                try {
                    id = URLEncoder.encode(TWITTER_URL_PREFIX + sign, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("URL id could not be UTF-8 encoded");
                }
            }
            checkNotNull(sign, "Term sign cannot be null");
            JSONArray indices = entity.getJSONArray("indices");
            TermMentionRowKey termMentionRowKey = new TermMentionRowKey(tweetId, indices.getLong(0),
                    indices.getLong(1));
            TermMentionModel termMention = new TermMentionModel(termMentionRowKey);
            termMention.getMetadata().setSign(sign)
                    .setOntologyClassUri(
                            (String) conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0))
                    .setConceptGraphVertexId(concept.getId()).setVertexId(id);
            mentions.add(termMention);
        }

        for (TermMentionModel mention : mentions) {
            String sign = mention.getMetadata().getSign().toLowerCase();
            String rowKey = mention.getRowKey().toString();
            String id = mention.getMetadata().getGraphVertexId();

            ElementMutation<Vertex> termVertexMutation;
            Vertex termVertex = graph.getVertex(id, user.getAuthorizations());
            if (termVertex == null) {
                termVertexMutation = graph.prepareVertex(id, visibility, user.getAuthorizations());
            } else {
                termVertexMutation = termVertex.prepareMutation();
            }

            TITLE.setProperty(termVertexMutation, sign, visibility);
            ROW_KEY.setProperty(termVertexMutation, rowKey, visibility);
            CONCEPT_TYPE.setProperty(termVertexMutation, concept.getId(), visibility);

            if (!(termVertexMutation instanceof ExistingElementMutation)) {
                termVertex = termVertexMutation.save();
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
            } else {
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
                termVertex = termVertexMutation.save();
            }

            String termId = termVertex.getId().toString();

            mention.getMetadata().setVertexId(termId);
            getTermMentionRepository().save(mention);

            graph.addEdge(tweetVertex, termVertex, entityType.getRelationshipLabel(), visibility,
                    user.getAuthorizations());

            auditRepo.auditRelationship(AuditAction.CREATE, tweetVertex, termVertex, relDispName, processId, "",
                    user, visibility);
            graph.flush();
        }
    }
}

From source file:com.facebook.config.StringExtractor.java

@Override
public String extract(String key, JSONObject jsonObject) throws JSONException {
    Object obj = jsonObject.get(key);

    if (obj instanceof String) {
        return (String) obj;
    } else {/*from w  w  w .  j a  v  a2s. c  o m*/
        return String.valueOf(obj);
    }
}

From source file:com.voidsearch.data.provider.facebook.objects.FacebookUser.java

public FacebookUser(JSONObject data) throws Exception {
    super(data);// w w  w . j ava 2  s  . co  m
    this.name = (String) data.get("name");
}