Example usage for org.json.simple JSONObject containsKey

List of usage examples for org.json.simple JSONObject containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:net.amigocraft.mpt.command.UpdateCommand.java

@SuppressWarnings("unchecked")
public static void updateStore() throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Package store may not be updated from the main thread!");
    lockStores();/*from  ww  w.j  ava  2 s .c  om*/
    final File rStoreFile = new File(Main.plugin.getDataFolder(), "repositories.json");
    if (!rStoreFile.exists())
        Main.initializeRepoStore(rStoreFile); // gotta initialize it before using it
    final File pStoreFile = new File(Main.plugin.getDataFolder(), "packages.json");
    if (!pStoreFile.exists())
        Main.initializePackageStore(pStoreFile);
    JSONObject repos = (JSONObject) Main.repoStore.get("repositories");
    Set<Map.Entry> entries = repos.entrySet();
    JSONObject localPackages = (JSONObject) Main.packageStore.get("packages");
    List<Object> remove = new ArrayList<Object>();
    for (Object k : localPackages.keySet()) {
        if (!((JSONObject) localPackages.get(k)).containsKey("installed"))
            remove.add(k);
    }
    for (Object r : remove)
        localPackages.remove(r);
    for (Map.Entry<String, JSONObject> e : entries) {
        final String id = e.getKey().toLowerCase();
        JSONObject repo = e.getValue();
        final String url = repo.get("url").toString();
        if (VERBOSE)
            Main.log.info("Updating repository \"" + id + "\"");
        JSONObject json = MiscUtil.getRemoteIndex(url);
        String repoId = json.get("id").toString();
        JSONObject packages = (JSONObject) json.get("packages");
        Set<Map.Entry> pEntries = packages.entrySet();
        for (Map.Entry en : pEntries) {
            String packId = en.getKey().toString().toLowerCase();
            JSONObject o = (JSONObject) en.getValue();
            if (o.containsKey("name") && o.containsKey("version") && o.containsKey("url")) {
                if (o.containsKey("sha1") || !Config.ENFORCE_CHECKSUM) {
                    String name = o.get("name").toString();
                    String desc = o.containsKey("description") ? o.get("description").toString() : "";
                    String version = o.get("version").toString();
                    String contentUrl = o.get("url").toString();
                    String sha1 = o.containsKey("sha1") ? o.get("sha1").toString() : "";
                    if (VERBOSE)
                        Main.log.info("Fetching package \"" + packId + "\"");
                    String installed = localPackages.containsKey(packId)
                            && ((JSONObject) localPackages.get(packId)).containsKey("installed")
                                    ? (((JSONObject) localPackages.get(packId)).get("installed")).toString()
                                    : "";
                    JSONArray files = localPackages.containsKey(packId)
                            && ((JSONObject) localPackages.get(packId)).containsKey("files")
                                    ? ((JSONArray) ((JSONObject) localPackages.get(packId)).get("files"))
                                    : null;
                    JSONObject pObj = new JSONObject();
                    pObj.put("repo", repoId);
                    pObj.put("name", name);
                    if (!desc.isEmpty())
                        pObj.put("description", desc);
                    pObj.put("version", version);
                    pObj.put("url", contentUrl);
                    if (!sha1.isEmpty())
                        pObj.put("sha1", sha1);
                    if (!installed.isEmpty())
                        pObj.put("installed", installed);
                    if (files != null)
                        pObj.put("files", files);
                    localPackages.put(packId, pObj);
                } else if (VERBOSE)
                    Main.log.warning("Missing checksum for package \"" + packId + ".\" Ignoring package...");
            } else if (VERBOSE)
                Main.log.warning(
                        "Found invalid package definition \"" + packId + "\" in repository \"" + repoId + "\"");
        }
    }
    Main.packageStore.put("packages", localPackages);
    try {
        writePackageStore();
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Failed to save repository store to disk!");
    }
    unlockStores();
}

From source file:com.criticalsoftware.mobics.presentation.util.GeolocationUtil.java

private static String getFormattedAddress(JSONObject jsonObject) {
    String result = null;/*from  w w w .j a  v a  2  s.c o m*/

    if (jsonObject != null && jsonObject.containsKey("address")) {
        result = "";
        JSONObject address = (JSONObject) jsonObject.get("address");
        if (address.containsKey("road")) {
            result += address.get("road").toString();
        }

        if (result.isEmpty() && address.containsKey("path")) {
            result += address.get("path").toString();
        }

        if (result.isEmpty() && address.containsKey("cycleway")) {
            result += address.get("cycleway").toString();
        }

        if (address.containsKey("house_number")) {
            if (result.isEmpty() == false) {
                result += " ";
            }
            result += address.get("house_number").toString();
        }

    }

    return result;
}

From source file:com.conwet.xjsp.session.SessionState.java

private static void hasFields(JSONObject json, String[] keys) throws ConnectionException {
    for (String key : keys) {
        if (!json.containsKey(key)) {
            throw new ConnectionException(ConnError.MessageFieldError, key);
        }/*  w w w.j  av a 2s  .c  o  m*/
    }
}

From source file:net.amigocraft.mpt.command.InstallCommand.java

@SuppressWarnings("unchecked")
public static void downloadPackage(String id) throws MPTException {
    JSONObject packages = (JSONObject) Main.packageStore.get("packages");
    if (packages != null) {
        JSONObject pack = (JSONObject) packages.get(id);
        if (pack != null) {
            if (pack.containsKey("name") && pack.containsKey("version") && pack.containsKey("url")) {
                if (pack.containsKey("sha1") || !Config.ENFORCE_CHECKSUM) {
                    String name = pack.get("name").toString();
                    String version = pack.get("version").toString();
                    String fullName = name + " v" + version;
                    String url = pack.get("url").toString();
                    String sha1 = pack.containsKey("sha1") ? pack.get("sha1").toString() : "";
                    if (pack.containsKey("installed")) { //TODO: compare versions
                        throw new MPTException(ID_COLOR + name + ERROR_COLOR + " is already installed");
                    }/*w ww.  j  a  v  a2 s. co  m*/
                    try {
                        URLConnection conn = new URL(url).openConnection();
                        conn.connect();
                        ReadableByteChannel rbc = Channels.newChannel(conn.getInputStream());
                        File file = new File(Main.plugin.getDataFolder(),
                                "cache" + File.separator + id + ".zip");
                        file.setReadable(true, false);
                        file.setWritable(true, false);
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                        FileOutputStream os = new FileOutputStream(file);
                        os.getChannel().transferFrom(rbc, 0, MiscUtil.getFileSize(new URL(url)));
                        os.close();
                        if (!sha1.isEmpty() && !sha1(file.getAbsolutePath()).equals(sha1)) {
                            file.delete();
                            throw new MPTException(ERROR_COLOR + "Failed to install package " + ID_COLOR
                                    + fullName + ERROR_COLOR + ": checksum mismatch!");
                        }
                    } catch (IOException ex) {
                        throw new MPTException(
                                ERROR_COLOR + "Failed to download package " + ID_COLOR + fullName);
                    }
                } else
                    throw new MPTException(ERROR_COLOR + "Package " + ID_COLOR + id + ERROR_COLOR
                            + " is missing SHA-1 checksum! Aborting...");
            } else
                throw new MPTException(ERROR_COLOR + "Package " + ID_COLOR + id + ERROR_COLOR
                        + " is missing required elements!");
        } else
            throw new MPTException(ERROR_COLOR + "Cannot find package with id " + ID_COLOR + id);
    } else {
        throw new MPTException(ERROR_COLOR + "Package store is malformed!");
    }
}

From source file:kltn.geocoding.Geocoding.java

private static Geometry getBoundary(String s)
        throws MalformedURLException, IOException, org.json.simple.parser.ParseException {
    String link = "https://maps.googleapis.com/maps/api/geocode/json?&key=AIzaSyALCgmmer3Cht-mFQiaJC9yoWdSqvfdAiM";
    link = link + "&address=" + URLEncoder.encode(s);
    URL url = new URL(link);
    HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection();
    InputStream is = httpsCon.getInputStream();
    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer, "UTF-8");

    String jsonString = writer.toString();
    JSONParser parse = new JSONParser();
    Object obj = parse.parse(jsonString);
    JSONObject jsonObject = (JSONObject) obj;
    System.out.println(s);//from w w w. j  a  v  a2 s  .  c o  m
    System.out.println(jsonObject.toJSONString());
    JSONArray resultArr = (JSONArray) jsonObject.get("results");
    Object resultObject = parse.parse(resultArr.get(0).toString());
    JSONObject resultJsonObject = (JSONObject) resultObject;

    Object geoObject = parse.parse(resultJsonObject.get("geometry").toString());
    JSONObject geoJsonObject = (JSONObject) geoObject;

    if (!geoJsonObject.containsKey("bounds")) {
        return null;
    }
    Object boundObject = parse.parse(geoJsonObject.get("bounds").toString());
    JSONObject boundJsonObject = (JSONObject) boundObject;
    //        System.out.println(boundJsonObject.toJSONString());

    Object southwest = parse.parse(boundJsonObject.get("southwest").toString());
    JSONObject southwestJson = (JSONObject) southwest;
    String southwestLat = southwestJson.get("lat").toString();
    String southwestLong = southwestJson.get("lng").toString();

    Object northeast = parse.parse(boundJsonObject.get("northeast").toString());
    JSONObject northeastJson = (JSONObject) northeast;
    String northeastLat = northeastJson.get("lat").toString();
    String northeastLong = northeastJson.get("lng").toString();

    String polygon = "POLYGON((" + southwestLong.trim() + " " + northeastLat.trim() + "," + northeastLong.trim()
            + " " + northeastLat.trim() + "," + northeastLong.trim() + " " + southwestLat.trim() + ","
            + southwestLong.trim() + " " + southwestLat.trim() + "," + southwestLong.trim() + " "
            + northeastLat.trim() + "))";
    Geometry geo = wktToGeometry(polygon);
    return geo;
}

From source file:com.orthancserver.OrthancConnection.java

public static OrthancConnection Unserialize(JSONObject json) {
    OrthancConnection c = new OrthancConnection();
    c.SetName((String) json.get("Name"));
    c.SetBaseUrl((String) json.get("Url"));

    if (json.containsKey("Authentication")) {
        c.authentication_ = (String) json.get("Authentication");
    } else {/*from w w  w.  j a  v  a 2  s  . c  om*/
        c.authentication_ = null;
    }

    return c;
}

From source file:JavaCloud.Utils.java

public static Object request(String address, String function, final JSONObject params) throws CoreException {
    try {/*w  w w  .j a v  a2s  .  c  o  m*/
        GenericUrl url = new GenericUrl(address + "/" + function);
        NetHttpTransport transport = new NetHttpTransport();
        HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new HttpContent() {
            @Override
            public long getLength() throws IOException {
                return params.toString().length();
            }

            @Override
            public String getType() {
                return "text/json";
            }

            @Override
            public boolean retrySupported() {
                return false;
            }

            @Override
            public void writeTo(OutputStream outputStream) throws IOException {
                outputStream.write(params.toString().getBytes());
            }
        });
        HttpResponse response = request.execute();
        JSONParser parser = new JSONParser();
        JSONObject object = (JSONObject) parser.parse(response.parseAsString());

        if (!object.get("status").equals("ok")) {
            throw new CoreException(object.get("status").toString());
        }

        if (object.containsKey("data") && object.get("data") != null)
            return parser.parse(object.get("data").toString());
        else
            return null;
    } catch (ParseException e) {
        System.out.println("Error parsing response: " + e.toString());
        throw new CoreException("json_malformed");
    } catch (IOException e) {
        System.out.println("Error connecting to server: " + e.toString());
        throw new CoreException("connection_failed");
    }
}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Get RSA PublicKey list by JWK JSON input
 * //from   w w  w  .  j a  va  2s  .  c  o  m
 * @param input
 *            JSON Web Key {@link JSONObject}
 * @return List of {@link PublicKey}
 */
public static List<PublicKey> getRsaPublicKeysByJwk(final Object input) {
    List<PublicKey> keys = new ArrayList<>();

    if (!(input instanceof JSONObject))
        return keys;

    JSONObject inputJsonObject = (JSONObject) input;

    // Multiple keys existent
    if (inputJsonObject.containsKey("keys")) {
        loggerInstance.log(Converter.class, "Key array found...", Logger.LogLevel.DEBUG);

        for (final Object value : (JSONArray) inputJsonObject.get("keys")) {
            JSONObject keyJson = (JSONObject) value;

            PublicKey key = getRsaPublicKeyByJwk(keyJson);

            if (key != null)
                keys.add(key);
        }
    } else {
        PublicKey key = getRsaPublicKeyByJwk(inputJsonObject);

        if (key != null)
            keys.add(key);
    }

    return keys;
}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Get RSA PublicKey list by JWK JSON input with an identifying string
 * /*from  w  w w.  j a  va2  s  . co  m*/
 * @param input
 *            JSON Web Key {@link JSONObject}
 * @return HashMap of {@link PublicKey} with identifying string as key
 */
public static HashMap<String, PublicKey> getRsaPublicKeysByJwkWithId(final Object input) {
    HashMap<String, PublicKey> keys = new HashMap<>();

    if (!(input instanceof JSONObject))
        return keys;

    JSONObject inputJsonObject = (JSONObject) input;

    // Multiple keys existent
    if (inputJsonObject.containsKey("keys")) {
        loggerInstance.log(Converter.class, "Key array found...", Logger.LogLevel.DEBUG);

        int counter = 1;
        for (final Object value : (JSONArray) inputJsonObject.get("keys")) {
            JSONObject keyJson = (JSONObject) value;

            PublicKey key = getRsaPublicKeyByJwk(keyJson);

            String id = "#" + counter;

            if (keyJson.containsKey("kty"))
                id += "_" + keyJson.get("kty");
            if (keyJson.containsKey("alg"))
                id += "_" + keyJson.get("alg");
            if (keyJson.containsKey("use"))
                id += "_" + keyJson.get("use");
            if (keyJson.containsKey("kid"))
                id += "_" + keyJson.get("kid");

            if (key != null)
                keys.put(id, key);
            counter++;
        }
    } else {
        PublicKey key = getRsaPublicKeyByJwk(inputJsonObject);

        if (key != null)
            keys.put("#1", key);
    }

    return keys;
}

From source file:com.walmartlabs.mupd8.application.Config.java

@SuppressWarnings("unchecked")
private static void apply(JSONObject destination, JSONObject source) {
    for (Object k : source.keySet()) {
        String key = (String) k;
        if (destination.containsKey(key) && (destination.get(key) != null)
                && (destination.get(key) instanceof JSONObject) && (source.get(key) instanceof JSONObject)) {
            try {
                JSONObject subDestination = (JSONObject) destination.get(key);
                JSONObject subSource = (JSONObject) source.get(key);
                apply(subDestination, subSource);
            } catch (ClassCastException e) {
                throw new ClassCastException("Config: cannot override key " + key
                        + " with new value because it is not a JSON object");
            }/*from w  ww .  j  av  a  2 s  .c  o m*/
        } else {
            destination.put(key, source.get(key));
        }
    }
}