Example usage for org.json.simple JSONObject remove

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

Introduction

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

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:mml.handler.json.Dialect.java

/**
 * Is one dialect the same as another?//from  w ww.ja v a 2 s .  co  m
 * @param dialect1 the first dialect file
 * @param dialect2 the second dialect file
 * @return true if they are equal else false
 */
public static boolean compare(JSONObject dialect1, JSONObject dialect2) {
    JSONObject d1 = (JSONObject) dialect1.clone();
    JSONObject d2 = (JSONObject) dialect2.clone();
    // ignore generated ids
    d1.remove("_id");
    d2.remove("_id");
    return compareObjects(d1, d2);
}

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

public static void removeRepository(String id) throws MPTException {
    id = id.toLowerCase();/*from w  ww  .  j a  va2  s  .  co m*/
    JSONObject repos = (JSONObject) Main.repoStore.get("repositories");
    if (repos.containsKey(id)) {
        lockStores();
        repos.remove(id); // remove it from memory
        File store = new File(Main.plugin.getDataFolder(), "repositories.json"); // get the store file
        if (!store.exists()) // avoid dumb errors
            Main.initializeRepoStore(store);
        try {
            writeRepositoryStore();
        } catch (IOException ex) {
            ex.printStackTrace();
            unlockStores();
            throw new MPTException(ERROR_COLOR + "Failed to remove repository from local store!");
        }
        unlockStores();
    } else // repo doesn't exist in local store
        throw new MPTException(ERROR_COLOR + "Cannot find repo with given ID!");
}

From source file:ch.newscron.encryption.Encryption.java

/**
 * Given a String, it is decoded and the result is returned as a String as well.
 * @param encodedUrl is a String that have the full data encrypted
 * @return decoded String/* w ww . j  ava 2 s . c o  m*/
 */
public static String decode(String encodedUrl) {

    try {

        //Decode URL
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));

        String result = new String(cipher.doFinal(Base64.decodeBase64(encodedUrl)));

        //Extract and remove hash from JSONObject
        JSONParser parser = new JSONParser();
        JSONObject receivedData = (JSONObject) parser.parse(result);
        String receivedHash = (String) receivedData.get("hash");
        receivedData.remove("hash");

        //Compare received hash with newly computed hash
        if (checkDataValidity(receivedData)) {
            byte[] hashOfData = createMD5Hash(receivedData);

            if (receivedHash.equals(new String(hashOfData, "UTF-8"))) { //Valid data
                return receivedData.toString();
            }
        }
    } catch (Exception e) {
    } //Invalid data (including encryption algorithm exceptions

    return null;
}

From source file:io.personium.jersey.engine.test.ScriptTestBase.java

/**
 * ????./*  w  w  w  .j a v a  2 s .c  om*/
 */
@SuppressWarnings("unchecked")
static void makeResources() {
    // Account??JSON
    JSONObject accountJson = new JSONObject();
    accountJson.put("Name", accountName);

    // ??JSON
    JSONObject engineAccountJson = new JSONObject();
    engineAccountJson.put("Name", engineAccountName);

    // Box??JSON
    JSONObject boxJson = new JSONObject();
    boxJson.remove("Name");
    boxJson.put("Name", boxName);

    // Cell??JSON
    JSONObject json = new JSONObject();
    json.put("Name", cellName);

    for (int i = 0; i < testCells.length; i++) {
        try {
            testCells[i] = testAs.asCellOwner().unit.cell.create(json);
        } catch (DaoException e) {
            // CONFLICT(409)????????Cell?
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
                fail(e.getMessage());
            }
        }
        // Account?
        try {
            testCells[i].account.create(accountJson, accountPassword);
            // ??
            testCells[i].account.create(engineAccountJson, null);
        } catch (DaoException e) {
            // CONFLICT(409)????????Cell?
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
                fail(e.getMessage());
            }
        }
        // Box?
        try {
            testBoxs[i] = testCells[i].box.create(boxJson);
        } catch (DaoException e) {
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
                fail(e.getMessage());
            }
        }
        json.remove("Name");
        json.put("Name", cellName + (i + 1));
    }
    try {
        if (isServiceTest) {
            // ?? serviceCollectionName
            testBoxs[0].mkService(serviceCollectionName);
            testSvcCol = testBoxs[0].service(serviceCollectionName);
            // ? PROPPATCH
            testSvcCol.configure(serviceName, serviceScriptPath, engineAccountName);
            // ? Dav?put
            putScript("testCommon.js", "testCommon.js");
        }
    } catch (DaoException e) {
        if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
            fail(e.getMessage());
        }
    }
}

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 w w w .j  a  v  a 2  s  . c o m
    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:net.amigocraft.mpt.command.RemoveCommand.java

public static void removePackage(String id) throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Packages may not be removed from the main thread!");
    id = id.toLowerCase();/* w w w  .  j ava 2 s .com*/
    if (((JSONObject) Main.packageStore.get("packages")).containsKey(id)) {
        JSONObject pack = (JSONObject) ((JSONObject) Main.packageStore.get("packages")).get(id);
        if (pack.containsKey("installed")) {
            lockStores();
            if (pack.containsKey("files")) {
                for (Object e : (JSONArray) pack.get("files")) {
                    File f = new File(Bukkit.getWorldContainer(), e.toString());
                    if (f.exists()) {
                        if (!f.delete()) {
                            if (VERBOSE) {
                                Main.log.warning("Failed to delete file " + f.getName());
                            }
                        } else {
                            checkParent(f);
                        }
                    }
                }
                pack.remove("files");
            } else
                Main.log.warning("No file listing for package " + id + "!");
            File archive = new File(Main.plugin.getDataFolder(), "cache" + File.separator + id + ".zip");
            if (archive.exists()) {
                if (!archive.delete() && VERBOSE) {
                    Main.log.warning("Failed to delete archive from cache");
                }
            }
            pack.remove("installed");
            try {
                writePackageStore();
            } catch (IOException ex) {
                unlockStores();
                throw new MPTException(ERROR_COLOR + "Failed to save changes to disk!");
            }
            unlockStores();
        } else
            throw new MPTException(
                    ERROR_COLOR + "Package " + ID_COLOR + id + ERROR_COLOR + " is not installed!");
    } else
        throw new MPTException(ERROR_COLOR + "Cannot find package with id " + ID_COLOR + id);
    unlockStores();
}

From source file:importer.handler.post.stages.StandoffPair.java

/**
 * Check if any ranges have now finished on the stack and pop them off
 * @param offset the current byte offset in data
 * @param lastWritePos the last position in data written to sb
 * @return the updated lastWritePos value
 *//*from  w  w  w  . j av  a 2s.  c om*/
private int checkStack(int offset, int lastWritePos) {
    while (!stack.isEmpty() && ((Number) stack.peek().get("byteEnd")).intValue() <= offset) {
        JSONObject r = stack.pop();
        int rangeByteEnd = ((Number) r.get("byteEnd")).intValue();
        int rangeCharStart = ((Number) r.get("rangeStart")).intValue();
        r.remove("byteEnd");
        r.remove("rangeStart");
        if (lastWritePos < rangeByteEnd) {
            String chunk = new String(data, lastWritePos, rangeByteEnd - lastWritePos,
                    Charset.forName("UTF-8"));
            sb.append(chunk);
            lastWritePos = rangeByteEnd;
        }
        r.put("len", sb.length() - rangeCharStart);
    }
    return lastWritePos;
}

From source file:com.hmsonline.virgil.CassandraStorage.java

@PooledConnection
public void deleteColumn(String keyspace, String column_family, String key, String column,
        ConsistencyLevel consistency_level, boolean purgeIndex) throws InvalidRequestException,
        UnavailableException, TimedOutException, TException, HttpException, IOException {
    ColumnPath path = new ColumnPath(column_family);
    path.setColumn(ByteBufferUtil.bytes(column));
    getConnection(keyspace).remove(ByteBufferUtil.bytes(key), path, System.currentTimeMillis() * 1000,
            consistency_level);//from  w  ww  .j  av a 2s  .  c o m

    // TODO: Revisit deleting a single field because it requires a fetch
    // first.
    // Evidently it is impossible to remove just a field from a document in
    // SOLR
    // http://stackoverflow.com/questions/4802620/can-you-delete-a-field-from-a-document-in-solr-index
    if (config.isIndexingEnabled() && purgeIndex) {
        indexer.delete(column_family, key);
        JSONObject json = this.getSlice(keyspace, column_family, key, consistency_level);
        json.remove(column);
        indexer.index(column_family, key, json);
    }
}

From source file:com.fujitsu.dc.core.rs.box.BoxResource.java

/**
 * box????????????????????.//from  www.j  a  va 2s .c o  m
 * @return ?JSON
 */
@SuppressWarnings("unchecked")
private JSONObject createResponse(JSONObject values) {
    JSONObject response = new JSONObject();
    response.putAll(values);
    response.remove("cell_id");
    response.remove("box_id");
    response.put("schema", this.getBox().getSchema());
    ProgressInfo.STATUS status = ProgressInfo.STATUS.valueOf((String) values.get("status"));
    if (status == ProgressInfo.STATUS.COMPLETED) {
        response.remove("progress");
        String startedAt = (String) response.remove("started_at");
        response.put("installed_at", startedAt);
    }
    response.put("status", status.value());
    return response;
}

From source file:cc.siara.csv_ml.ParsedObject.java

/**
 * Deletes all attributes with name "parent_ref" in all levels in a
 * JSONObject hierarchy recursively.//from   w  w  w .j  a va 2  s  .co  m
 * 
 * @param obj
 *            Initially pass the root object
 */
private void deleteParentRefsRecursively(JSONObject obj) {
    if (obj.containsKey("parent_ref"))
        obj.remove("parent_ref");
    // Go through each child object or array
    // recursively
    for (Object set : obj.keySet()) {
        String key = (String) set;
        Object child_obj = obj.get(key);
        if (child_obj instanceof JSONArray) {
            JSONArray ja = (JSONArray) child_obj;
            for (Object ele : ja) {
                if (ele instanceof JSONObject)
                    deleteParentRefsRecursively((JSONObject) ele);
            }
        } else if (child_obj instanceof JSONObject) {
            deleteParentRefsRecursively((JSONObject) child_obj);
        }
    }
}