Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:edu.umass.cs.protocoltask.examples.PingPongPacket.java

public PingPongPacket(JSONObject json) throws JSONException {
    super(json, unstringer);
    this.setType(getPacketType(json));
    this.counter = (json.has(COUNTER) ? json.getInt(COUNTER) : 0);
}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an
 * instance of <code>JSONObject.NULL</code>.
 *
 * @param jsonObject The {@link JSONObject} being processed
 * @param field The field to retrieve//from   w w w.j  a v  a  2  s . co  m
 * @param fieldType The data type of the field
 * @return The field value (or null if not found)
 *
 * @param <T> The data type to return
 */
@SuppressWarnings("unchecked")
protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field,
        final Class<T> fieldType) {
    T fieldValue = null;
    if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) {
        try {
            if (fieldType == String.class) {
                fieldValue = (T) jsonObject.getString(field);
            } else if (fieldType == Integer.class) {
                fieldValue = (T) Integer.valueOf(jsonObject.getInt(field));
            } else if (fieldType == Long.class) {
                fieldValue = (T) Long.valueOf(jsonObject.getLong(field));
            } else if (fieldType == Float.class) {
                fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field)));
            } else if (fieldType == JSONArray.class) {
                fieldValue = (T) jsonObject.getJSONArray(field);
            } else if (fieldType == JSONObject.class) {
                fieldValue = (T) jsonObject.getJSONObject(field);
            } else {
                fieldValue = (T) jsonObject.get(field);
            }
        } catch (final JSONException | ClassCastException e) {
            // TODO Log a warning
        }
    }

    return fieldValue;
}

From source file:de.kp.ames.web.function.domain.model.ServiceObject.java

/**
 * Create ServiceObject from JSON representation
 * /*ww w  .j  a  v  a2  s.c o  m*/
 * @param jForm
 * @return
 * @throws Exception
 */
public RegistryObjectImpl create(JSONObject jForm) throws Exception {

    /*
     * Create SpecificationLink instances
     */
    JSONArray jSpecifications = new JSONArray(jForm.getString(RIM_SPEC));

    ArrayList<SpecificationLinkImpl> specificationLinks = new ArrayList<SpecificationLinkImpl>();
    for (int i = 0; i < jSpecifications.length(); i++) {

        JSONObject jSpecification = jSpecifications.getJSONObject(i);

        String uid = jSpecification.getString(RIM_ID);
        String seqNo = jSpecification.getString(RIM_SEQNO);

        RegistryObjectImpl ro = jaxrLCM.getRegistryObjectById(uid);
        if (ro == null)
            throw new Exception("[ServiceObject] RegistryObject with id <" + uid + "> does not exist.");

        /* 
         * Create a new specification link
         */
        SpecificationLinkImpl specificationLink = jaxrLCM.createSpecificationLink();
        if (specificationLink == null)
            throw new Exception("[ServiceObject] Creation of SpecificationLink failed.");

        SlotImpl slot = jaxrLCM.createSlot(JaxrConstants.SLOT_SEQNO, seqNo, JaxrConstants.SLOT_TYPE);
        specificationLink.addSlot(slot);

        specificationLink.setSpecificationObject(ro);
        specificationLinks.add(specificationLink);

    }

    /*
     * Create ServiceBinding instance
     */
    ServiceBindingImpl serviceBinding = null;
    if (specificationLinks.isEmpty() == false) {

        serviceBinding = jaxrLCM.createServiceBinding();
        serviceBinding.addSpecificationLinks(specificationLinks);

    }

    /* 
     * Create Service instance
     */
    ServiceImpl service = jaxrLCM.createService(jForm.getString(RIM_NAME));

    if (jForm.has(RIM_DESC))
        service.setDescription(jaxrLCM.createInternationalString(jForm.getString(RIM_DESC)));
    service.setHome(jaxrHandle.getEndpoint().replace("/saml", ""));

    if (serviceBinding != null)
        service.addServiceBinding(serviceBinding);

    /*
     * Create classifications
     */
    JSONArray jClases = jForm.has(RIM_CLAS) ? new JSONArray(jForm.getString(RIM_CLAS)) : null;
    if (jClases != null) {

        List<ClassificationImpl> classifications = createClassifications(jClases);
        /*
         * Set composed object
         */
        service.addClassifications(classifications);

    }

    /* 
     * Create slots
     */
    JSONObject jSlots = jForm.has(RIM_SLOT) ? new JSONObject(jForm.getString(RIM_SLOT)) : null;
    if (jSlots != null) {

        List<SlotImpl> slots = createSlots(jSlots);
        /*
         * Set composed object
         */
        service.addSlots(slots);

    }

    /*
     * Indicate as created
     */
    this.created = true;

    return service;

}

From source file:com.google.testing.testify.risk.frontend.server.task.UploadDataTask.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String user = req.getParameter("user");
    String jsonString = req.getParameter("json");
    try {//from w  ww.jav  a2  s . c  om
        // TODO(jimr): add impersonation of user in string user.
        JSONObject json = new JSONObject(jsonString);
        JSONObject item;
        if (json.has("bug")) {
            item = json.getJSONObject("bug");
            Bug bug = new Bug();
            bug.setParentProjectId(item.getLong("projectId"));
            bug.setExternalId(item.getLong("bugId"));
            bug.setTitle(item.getString("title"));
            bug.setPath(item.getString("path"));
            bug.setSeverity(item.getLong("severity"));
            bug.setPriority(item.getLong("priority"));
            bug.setBugGroups(Sets.newHashSet(StringUtil.csvToList(item.getString("groups"))));
            bug.setBugUrl(item.getString("url"));
            bug.setState(item.getString("status"));
            bug.setStateDate(item.getLong("statusDate"));
            dataService.addBug(bug);
        } else if (json.has("test")) {
            item = json.getJSONObject("test");
            TestCase test = new TestCase();
            test.setParentProjectId(item.getLong("projectId"));
            test.setExternalId(item.getLong("testId"));
            test.setTitle(item.getString("title"));
            test.setTags(Sets.newHashSet(StringUtil.csvToList(item.getString("tags"))));
            test.setTestCaseUrl(item.getString("url"));
            test.setState(item.getString("result"));
            test.setStateDate(item.getLong("resultDate"));
            dataService.addTestCase(test);
        } else if (json.has("checkin")) {
            item = json.getJSONObject("checkin");
            Checkin checkin = new Checkin();
            checkin.setParentProjectId(item.getLong("projectId"));
            checkin.setExternalId(item.getLong("checkinId"));
            checkin.setSummary(item.getString("summary"));
            checkin.setDirectoriesTouched(Sets.newHashSet(StringUtil.csvToList(item.getString("directories"))));
            checkin.setChangeUrl(item.getString("url"));
            checkin.setState(item.getString("state"));
            checkin.setStateDate(item.getLong("stateDate"));
            dataService.addCheckin(checkin);
        } else {
            LOG.severe("No applicable data found for json: " + json.toString());
        }
    } catch (JSONException e) {
        // We don't issue a 500 or similar response code here to prevent retries, which would have
        // no different a result.
        LOG.severe("Couldn't parse input JSON: " + jsonString);
        return;
    }
}

From source file:produvia.com.scanner.DevicesActivity.java

/*********************************************************************
 * The WeaverSdk callback indicating that a task has been completed:
 *********************************************************************/
@Override/*w  w w .  j  a  v a2  s  . com*/
public void onTaskCompleted(final int flag, final JSONObject response) {
    if (response == null || mActivityPaused)
        return;
    try {

        if (response.has("responseCode") && response.getInt("responseCode") == 401) {
            //unauthorized:
            runWelcomeActivity();
        }

        switch (flag) {
        case WeaverSdk.ACTION_USER_LOGOUT:
            runWelcomeActivity();
            break;

        case WeaverSdk.ACTION_SERVICES_GET:
            if (response.getBoolean("success")) {
                handleReceivedServices(response.getJSONObject("data"));
            }
            break;

        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:produvia.com.scanner.DevicesActivity.java

private void updateServiceDeviceDatabase(JSONObject data) {
    try {//w ww  . j  ava 2  s. c  om
        //first add the services to the devices:
        JSONArray services = data.getJSONArray("services");
        for (int i = 0; i < services.length(); i++) {
            JSONObject service = services.getJSONObject(i);
            String device_id = service.getString("device_id");
            JSONObject device = data.getJSONObject("devices_info").getJSONObject(device_id);
            if (!device.has("services"))
                device.put("services", new JSONObject());
            device.getJSONObject("services").put(service.getString("id"), service);
        }

        JSONObject devices = data.getJSONObject("devices_info");
        //loop over the devices and merge them into the device display:
        for (Iterator<String> iter = devices.keys(); iter.hasNext();) {
            String device_id = iter.next();
            JSONObject device = devices.getJSONObject(device_id);
            //if a device card is already present - just merge the data:
            boolean found = false;
            int network_card_idx = -1;
            for (int i = 0; i < mDevices.size(); i++) {
                CustomListItem cli = mDevices.get(i);
                if (cli instanceof DeviceCard && ((DeviceCard) cli).getId().equals(device_id)) {
                    ((DeviceCard) cli).updateInfo(device);
                    found = true;
                    break;
                } else if (cli.getDescription().equals(device.getString("network_id"))) {
                    network_card_idx = i;
                }
            }

            if (!found) {
                if (network_card_idx < 0) {
                    JSONObject network = data.getJSONObject("networks_info")
                            .getJSONObject(device.getString("network_id"));
                    String name = "";
                    if (network.has("name") && network.getString("name") != null)
                        name = network.getString("name");
                    network_card_idx = addNetworkCard(name, device.getString("network_id"),
                            network.getBoolean("user_inside_network"));
                }
                network_card_idx += 1;
                //find the correct index for the card sorted by last seen:
                for (; network_card_idx < mDevices.size(); network_card_idx++) {
                    CustomListItem cli = mDevices.get(network_card_idx);
                    if (!(cli instanceof DeviceCard))
                        break;
                    if (((DeviceCard) cli).getLastSeen()
                            .compareTo(DeviceCard.getLastSeenFromString(device.getString("last_seen"))) < 0)
                        break;
                }

                DeviceCard dc = new DeviceCard(device);
                mDevices.add(network_card_idx, dc);
            }
        }
        notifyDataSetChanged();

    } catch (JSONException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:produvia.com.scanner.DevicesActivity.java

public void promptLogin(final JSONObject loginService, final JSONObject responseData) {

    runOnUiThread(new Runnable() {
        public void run() {
            try {
                String type = loginService.getString("type");
                //there was a login error. login again
                if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_NORMAL)) {
                    //prompt for username and password and retry:
                    promptUsernamePassword(loginService, responseData, false, null);

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_KEY)) {

                    promptUsernamePassword(loginService, responseData, true,
                            loginService.getString("description"));

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_PRESS2LOGIN)) {
                    //prompt for username and password and retry:
                    int countdown = loginService.has("login_timeout") ? loginService.getInt("login_timeout")
                            : 15;// w  w  w  .ja va2  s .  c  om
                    final AlertDialog alertDialog = new AlertDialog.Builder(DevicesActivity.this).create();
                    alertDialog.setTitle(loginService.getString("description"));
                    alertDialog.setCancelable(false);
                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.setMessage(loginService.getString("description") + "\n"
                            + "Attempting to login again in " + countdown + " seconds...");
                    alertDialog.show(); //

                    new CountDownTimer(countdown * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            try {
                                alertDialog.setMessage(loginService.getString("description") + "\n"
                                        + "Attempting to login again in " + millisUntilFinished / 1000
                                        + " seconds...");
                            } catch (JSONException e) {

                            }
                        }

                        @Override
                        public void onFinish() {
                            alertDialog.dismiss();
                            new Thread(new Runnable() {
                                public void run() {

                                    try {
                                        JSONArray services = new JSONArray();
                                        services.put(loginService);
                                        responseData.put("services", services);
                                        WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
                                    } catch (JSONException e) {

                                    }
                                }
                            }).start();

                        }
                    }.start();

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    });

}

From source file:com.vk.sdkweb.api.model.VKList.java

/**
 * Fills list according with data in {@code from}.
 * @param from an object that represents a list adopted in accordance with VK API format. You can use null.
 * @param clazz class represents a model that has a public constructor with {@link org.json.JSONObject} argument.
 *///from w w w. ja  v a 2  s.c  om
public void fill(JSONObject from, Class<? extends T> clazz) {
    if (from.has("response")) {
        JSONArray array = from.optJSONArray("response");
        if (array != null) {
            fill(array, clazz);
        } else {
            fill(from.optJSONObject("response"), clazz);
        }
    } else {
        fill(from, new ReflectParser<T>(clazz));
    }
}

From source file:networkedassets.Bamboo.java

public boolean fetchNextBuild() throws IOException {
    try {//from w ww  .ja v  a2 s  . c  o m
        if (nextBuildNumber > 0) {
            JSONObject resp = Useful.readJsonFromUrl(String.format(
                    "%sbamboo/rest/api/latest/result/status/%s.json?expand=results.result&os_authType=basic",
                    bambooUrl, bambooKey + "-" + String.valueOf(nextBuildNumber)), bambooUser, bambooPass);
            return resp.has("progress");
        }
    } catch (java.io.FileNotFoundException ex) {
        return false;
    }

    return false;
}

From source file:org.loklak.api.iot.GeoJsonPushServlet.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  w ww  .  j a v  a2  s  .  c o m
    }

    String url = post.get("url", "");
    String map_type = post.get("map_type", "");
    String source_type_str = post.get("source_type", "");
    if ("".equals(source_type_str) || !SourceType.isValid(source_type_str)) {
        DAO.log("invalid or missing source_type value : " + source_type_str);
        source_type_str = SourceType.GEOJSON.toString();
    }
    SourceType sourceType = SourceType.GEOJSON;

    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;
    }
    // parse json retrieved from url
    final JSONArray features;
    byte[] jsonText;
    try {
        jsonText = ClientConnection.download(url);
        JSONObject map = new JSONObject(new String(jsonText, StandardCharsets.UTF_8));
        features = map.getJSONArray("features");
    } catch (Exception e) {
        response.sendError(400, "error reading json file from url");
        return;
    }
    if (features == null) {
        response.sendError(400, "geojson format error : member 'features' missing.");
        return;
    }

    // parse maptype
    Map<String, List<String>> mapRules = new HashMap<>();
    if (!"".equals(map_type)) {
        try {
            String[] mapRulesArray = map_type.split(",");
            for (String rule : mapRulesArray) {
                String[] splitted = rule.split(":", 2);
                if (splitted.length != 2) {
                    throw new Exception("Invalid format");
                }
                List<String> valuesList = mapRules.get(splitted[0]);
                if (valuesList == null) {
                    valuesList = new ArrayList<>();
                    mapRules.put(splitted[0], valuesList);
                }
                valuesList.add(splitted[1]);
            }
        } catch (Exception e) {
            response.sendError(400, "error parsing map_type : " + map_type + ". Please check its format");
            return;
        }
    }

    JSONArray rawMessages = new JSONArray();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    PushReport nodePushReport = new PushReport();
    for (Object feature_obj : features) {
        JSONObject feature = (JSONObject) feature_obj;
        JSONObject properties = feature.has("properties") ? (JSONObject) feature.get("properties")
                : new JSONObject();
        JSONObject geometry = feature.has("geometry") ? (JSONObject) feature.get("geometry") : new JSONObject();
        JSONObject message = new JSONObject(true);

        // add mapped properties
        JSONObject mappedProperties = convertMapRulesProperties(mapRules, properties);
        message.putAll(mappedProperties);

        if (!"".equals(sourceType)) {
            message.put("source_type", sourceType);
        } else {
            message.put("source_type", SourceType.GEOJSON);
        }
        message.put("provider_type", ProviderType.IMPORT.name());
        message.put("provider_hash", remoteHash);
        message.put("location_point", geometry.get("coordinates"));
        message.put("location_mark", geometry.get("coordinates"));
        message.put("location_source", LocationSource.USER.name());
        message.put("place_context", PlaceContext.FROM.name());

        if (message.get("text") == null) {
            message.put("text", "");
        }
        // append rich-text attachment
        String jsonToText = ow.writeValueAsString(properties);
        message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText);

        if (properties.get("mtime") == null) {
            String existed = PushServletHelper.checkMessageExistence(message);
            // message known
            if (existed != null) {
                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, sourceType));
        } catch (Exception e) {
            DAO.log("Problem computing id : " + e.getMessage());
            nodePushReport.incrementErrorCount();
        }

        rawMessages.put(message);
    }

    PushReport report = PushServletHelper.saveMessagesAndImportProfile(rawMessages, Arrays.hashCode(jsonText),
            post, sourceType, screen_name);

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