Example usage for org.json.simple JSONObject put

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

Introduction

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

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:io.github.casnix.spawnerdropper.SpawnerStack.java

public static boolean PutSpawnerIntoService(String spawnerType) {
    // Read ./SpawnerDropper.SpawnerStack.json into a string

    // get the value of JSON->{spawnerType} and add 1 to it.

    // Write file back to disk
    try {/*from   www  .  j  a va 2s .c o m*/
        // Read entire ./SpawnerDropper.SpawnerStack.json into a string
        String spawnerStack = new String(
                Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json")));

        // get the value of JSON->{spawnerType}
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(spawnerStack);

        JSONObject jsonObj = (JSONObject) obj;

        long numberInService = (Long) jsonObj.get(spawnerType);

        if (numberInService < 0) {
            numberInService = 0;
        }

        //         System.out.println("[SD DBG MSG] PSIS numberInServer("+numberInService+")");
        numberInService += 1;
        jsonObj.put(spawnerType, new Long(numberInService));

        FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json");
        file.write(jsonObj.toJSONString());
        file.flush();
        file.close();

        return true;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in PutSpawnerIntoService(String)");
        e.printStackTrace();

        return false;
    } catch (FileNotFoundException e) {
        Bukkit.getLogger()
                .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json");
        e.printStackTrace();

        return false;
    } catch (IOException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in PutSpawnerIntoService(String)");
        e.printStackTrace();

        return false;
    }
}

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRList(String body)
        throws ParseException, InterruptedException, java.text.ParseException, Exception {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONObject jsonBody = (JSONObject) parser.parse(body);

    Date startDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
            .parse(jsonBody.get("startDateOriginated").toString());
    Date endDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
            .parse(jsonBody.get("endDateOriginated").toString());

    List<String> data = new ArrayList<>();

    class getPSRListForDate implements Runnable {
        private Date dateOriginated;
        private List<String> data;

        public getPSRListForDate(Date dateOriginated, List<String> data) {
            this.dateOriginated = dateOriginated;
            this.data = data;
        }/*  w w w . j ava  2s.com*/

        public getPSRListForDate(List<String> data) {
            this.data = data;
        }

        @Override
        public void run() {
            try {
                String dateOriginatedString = new SimpleDateFormat("MM/dd/yyyy").format(dateOriginated);

                Long startTime = System.currentTimeMillis();

                IQuery query = (IQuery) Agile.session.createObject(IQuery.OBJECT_TYPE,
                        "Product Service Requests");

                String criteria = "[Cover Page.Date Originated] == '" + dateOriginatedString
                        + " 12:00:00 AM GMT' AND "
                        + "[Cover Page.Type] IN ('Customer Complaint', 'Customer Inquiry', 'Partner Complaint', "
                        + "'Reportable Malfunction / Adverse Event', 'Ancillary Devices & Applications', 'Distributors / Partners', "
                        + "'MDR Decision Tree', 'Investigation Report - No RGA', 'Investigation Report - RGA')";
                query.setCriteria(criteria);

                query.setResultAttributes(new Integer[] { 4856 }); // 4856 = Object ID of [Cover Page.PSR Number]

                ITable queryResults = query.execute();
                queryResults.setPageSize(5000);

                ITwoWayIterator tableIterator = queryResults.getTableIterator();
                while (tableIterator.hasNext()) {
                    IRow row = (IRow) tableIterator.next();
                    data.add(row.getCell(4856).toString()); // 4856 = Object ID of [Cover Page.PSR Number]
                }

                Long endTime = System.currentTimeMillis();

                String logMessage = String.format("getPSRList: Query for %s executed in %d milliseconds",
                        new SimpleDateFormat("yyyy-MM-dd").format(dateOriginated), endTime - startTime);
                System.out.println(logMessage);
            } catch (APIException ex) {
                Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    if (startDateOriginated.after(endDateOriginated)) {
        throw new Exception("startDateOriginated is after endDateOriginated. This makes no sense, silly.");
    }

    synchronized (data) {
        Date currentDateOriginated = startDateOriginated;

        ExecutorService executor = Executors.newFixedThreadPool(6);
        do {
            executor.execute(new Thread(new getPSRListForDate(currentDateOriginated, data)));

            Calendar c = Calendar.getInstance();
            c.setTime(currentDateOriginated);
            c.add(Calendar.DATE, 1);

            currentDateOriginated = c.getTime();
        } while (currentDateOriginated.before(endDateOriginated)
                | currentDateOriginated.equals(endDateOriginated));

        executor.shutdown();
        while (!executor.isTerminated()) {
        }
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    return obj;
}

From source file:anotadorderelacoes.model.UtilidadesPacotes.java

public static JSONObject novoToken(Object t, Object l, Object pos, Object sin) {
    JSONObject token = new JSONObject();
    token.put("t", t);
    token.put("l", l);
    token.put("pos", pos);
    token.put("sin", sin);
    return token;
}

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

/**
 * ????.//  w  w  w  .j a  va2 s.c o m
 */
@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:io.github.casnix.spawnerdropper.SpawnerStack.java

public static boolean TakeSpawnerOutOfService(String spawnerType) {
    // Read ./SpawnerDropper.SpawnerStack.json into a string

    // get the value of JSON->{spawnerType} and subtract 1 to it unless it is 0.
    // If it's zero, return false

    // Write file back to disk
    try {// w ww . j av a  2 s  . c o m
        // Read entire ./SpawnerDropper.SpawnerStack.json into a string
        String spawnerStack = new String(
                Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json")));

        // get the value of JSON->{spawnerType}
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(spawnerStack);

        JSONObject jsonObj = (JSONObject) obj;

        long numberInService = (Long) jsonObj.get(spawnerType);

        if (numberInService <= 0) {
            return false;
        } else {
            //            System.out.println("[SD DBG MSG] TSOOS numberInServer("+numberInService+")");

            numberInService -= 1;
            jsonObj.put(spawnerType, new Long(numberInService));

            FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json");
            file.write(jsonObj.toJSONString());
            file.flush();
            file.close();

            return true;
        }
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in TakeSpawnerOutOfService(String)");
        e.printStackTrace();

        return false;
    } catch (FileNotFoundException e) {
        Bukkit.getLogger()
                .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json");
        e.printStackTrace();

        return false;
    } catch (IOException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in TakeSpawnerOutOfService(String)");
        e.printStackTrace();

        return false;
    }
}

From source file:eu.edisonproject.classification.main.BatchMain.java

private static void profile(String csvFile1, String csvFile2, String output) throws IOException, Exception {
    Map<String, Collection<Double>> cv = CSVFileReader.csvCompetanceToMap(csvFile1, ",", Boolean.TRUE);
    Map<String, Collection<Double>> jobVec = CSVFileReader.csvCompetanceToMap(csvFile2, ",", Boolean.TRUE);
    CosineSimilarityMatrix cosineFunction = new CosineSimilarityMatrix();

    String k1 = cv.keySet().iterator().next();
    Map<String, Double> winners = new HashMap<>();
    for (String k : jobVec.keySet()) {
        Collection<Double> j = jobVec.get(k);
        double d = cosineFunction.computeDistance(cv.get(k1), j);
        //      if (!Double.isNaN(d)) {
        winners.put(k, d);/*from w  w w.ja  v a 2s . com*/
        //      }
    }
    StringBuilder lines = new StringBuilder();
    ReaderFile rf = new ReaderFile(csvFile1);
    String fileHeader = rf.readFileWithN().split("\n")[0];
    String[] header = fileHeader.split(",");
    lines.append("rank").append(",");
    lines.append(fileHeader);
    lines.append("\n");

    int rank = 0;

    JSONObject cvJson = new JSONObject();
    Collection<Double> vector = cv.get(k1);
    String val = vector.toString().replaceAll("\\[", "").replaceAll("\\]", "");
    lines.append(rank).append(",").append(k1).append(",").append(val).append("\n");
    Iterator<Double> iter = vector.iterator();
    int i = 0;
    cvJson.put(header[i++], k1);
    while (iter.hasNext()) {
        String key = header[i++];
        Double value = iter.next();
        cvJson.put(key, value);
    }
    cvJson.put("rank", rank);
    JSONArray profileJson = new JSONArray();
    profileJson.add(cvJson);
    ValueComparator bvc = new ValueComparator(winners);
    Map<String, Double> sorted_map = new TreeMap(bvc);
    sorted_map.putAll(winners);

    for (String k : sorted_map.keySet()) {
        JSONObject jobJason = new JSONObject();
        rank++;
        vector = jobVec.get(k);
        val = vector.toString().replaceAll("\\[", "").replaceAll("\\]", "");
        lines.append(rank).append(",").append(k).append(",").append(val).append("\n");

        i = 0;
        jobJason.put(header[i++], k);
        iter = vector.iterator();
        while (iter.hasNext()) {
            String key = header[i++];
            Double value = iter.next();
            jobJason.put(key, value);
        }
        jobJason.put("rank", rank);
        profileJson.add(jobJason);
    }
    WriterFile wf = new WriterFile(output + File.separator + "result.csv");
    wf.writeFile(lines.toString());

    wf = new WriterFile(output + File.separator + "result.json");
    wf.writeFile(profileJson.toJSONString());
}

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method building the {@link MessageType#PROX_BEACONS} message containing data about {@link Entity} of type {@link Type#BLE_BEACON}
 * seen by the sender in last BLE scanning cycles
 *//* w  w w  .  j  a v  a 2 s  .c om*/
public static String buildProxBeaconsMessage(ArrayList<Entity> beacons, Entity e, String logId) {
    JSONObject msg = new JSONObject();
    JSONObject proxMsg = new JSONObject();
    proxMsg.put(JsonStrings.SENDER, e.getEntityID());
    proxMsg.put(JsonStrings.MSG_TYPE, MessageType.PROX_BEACONS.name());
    proxMsg.put(JsonStrings.ENTITY, ((JSONObject) e.getJsonDescriptor().get(JsonStrings.ENTITY)));
    proxMsg.put(JsonStrings.BEACONS, ((JSONArray) buildBeaconsJsonArray(beacons)));
    proxMsg.put(JsonStrings.LOG_ID, logId);
    msg.put(JsonStrings.MESSAGE, proxMsg);
    return msg.toJSONString();
}

From source file:cn.vlabs.umt.ui.servlet.OauthTokenServlet.java

public static String getUserAsJSON(LoginNameInfo info, User user, String passwordType) {
    JSONObject object = new JSONObject();
    object.put("umtId", user.getUmtId());
    putStringToJSON(object, "truename", user.getTrueName());
    putStringToJSON(object, "type", user.getType());
    putStringToJSON(object, "cstnetId", user.getCstnetId());
    putStringToJSON(object, "cstnetIdStatus", info.getStatus());
    putStringToJSON(object, "securityEmail", user.getSecurityEmail());
    putStringToJSON(object, "passwordType", passwordType);
    String[] emails = user.getSecondaryEmails();
    if (emails != null && emails.length > 0) {
        JSONArray ar = new JSONArray();
        for (int i = 0; i < emails.length; i++) {
            ar.add(emails[i]);/*  w ww  .  j  a  v  a  2 s.co m*/
        }
        object.put("secondaryEmails", ar);
    }
    return object.toJSONString();
}

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method that builds a {@link MessageType#CHECK_IN} message relative to the passed {@link Entity}
 *///from ww  w  . ja  va 2 s.c om
public static String buildCheckInMessage(Entity e, String logId) {
    JSONObject mesg = new JSONObject();
    JSONObject checkInMsg = new JSONObject();
    checkInMsg.put(JsonStrings.SENDER, e.getEntityID());
    checkInMsg.put(JsonStrings.MSG_TYPE, MessageType.CHECK_IN.name());
    checkInMsg.put(JsonStrings.ENTITY, ((JSONObject) e.getJsonDescriptor().get(JsonStrings.ENTITY)));
    checkInMsg.put(JsonStrings.LOG_ID, logId);
    mesg.put(JsonStrings.MESSAGE, checkInMsg);

    return mesg.toJSONString();
}

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * //from w ww .  j  a va 2s .com
 * Method that builds the message sent to notify a proximity update between two {@link Entity}, containing
 * the corresponding {@link DistanceRange}
 */
public static String buildProximityMessage(String senderID, MessageType type, Entity e1, Entity e2,
        DistanceRange distance, String logId) {

    JSONObject mesg = new JSONObject();
    JSONObject proxMsg = new JSONObject();
    proxMsg.put(JsonStrings.SENDER, senderID);
    proxMsg.put(JsonStrings.MSG_TYPE, type.name());
    proxMsg.put(JsonStrings.ENTITY_1, (JSONObject) e1.getJsonDescriptor().get(JsonStrings.ENTITY));
    proxMsg.put(JsonStrings.ENTITY_2, (JSONObject) e2.getJsonDescriptor().get(JsonStrings.ENTITY));
    proxMsg.put(JsonStrings.DISTANCE_RANGE, distance.name());
    proxMsg.put(JsonStrings.LOG_ID, logId);
    mesg.put(JsonStrings.MESSAGE, proxMsg);

    return mesg.toJSONString();
}