Example usage for org.json.simple JSONObject get

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.conwet.silbops.model.Subscription.java

/**
 * Deserializes a Subscription from its JSON representation.
 *
 * @param json JSON representation of a subscription
 * @return A new subscription//from www.j a v a  2  s.c o  m
 */
@SuppressWarnings("unchecked")
public static Subscription fromJSON(JSONObject json) {

    Subscription subscription = new Subscription();
    subscription.setId((String) json.get("id"));
    subscription.setContextFunction(ContextFunction.fromJSON((JSONObject) json.get("contextFunction")));

    JSONObject constr = (JSONObject) json.get("constraints");

    for (Entry<String, JSONArray> entry : (Set<Entry<String, JSONArray>>) constr.entrySet()) {

        for (JSONObject jsonConstr : (List<JSONObject>) entry.getValue()) {

            subscription.addConstraint(Attribute.fromJSON(entry.getKey()), Constraint.fromJSON(jsonConstr));
        }
    }

    return subscription;
}

From source file:at.ac.tuwien.dsg.rSybl.planningEngine.celar.staticData.ActionEffectsCELAR.java

public static HashMap<String, List<ActionEffect>> getActionEffects() {
    HashMap<String, List<ActionEffect>> actionEffects = new HashMap<String, List<ActionEffect>>();

    JSONParser parser = new JSONParser();

    try {/*from w w  w .  j a v a 2 s .  co  m*/
        InputStream inputStream = Configuration.class.getClassLoader()
                .getResourceAsStream(Configuration.getEffectsPath());
        Object obj = parser.parse(new InputStreamReader(inputStream));

        JSONObject jsonObject = (JSONObject) obj;

        for (Object actionName : jsonObject.keySet()) {
            ActionEffect actionEffect = new ActionEffect();
            String myaction = (String) actionName;
            actionEffect.setActionType((String) actionName);
            actionEffect.setActionName(myaction);
            JSONObject object = (JSONObject) jsonObject.get(myaction);
            for (Object actions : object.keySet()) {

                JSONObject scaleinDescription = (JSONObject) object.get(actions);
                String targetUnit = (String) scaleinDescription.get("targetUnit");
                actionEffect.setTargetedEntityID(targetUnit);

                JSONObject effects = (JSONObject) scaleinDescription.get("effects");

                for (Object effectPerUnit : effects.keySet()) {
                    //System.out.println(effects.toString());
                    String affectedUnit = (String) effectPerUnit;
                    JSONObject metriceffects = (JSONObject) effects.get(affectedUnit);
                    for (Object metric : metriceffects.keySet()) {
                        String metricName = (String) metric;
                        try {
                            actionEffect.setActionEffectForMetric(metricName,
                                    (Double) metriceffects.get(metricName), affectedUnit);

                            //System.out.println("metricName="+metricName+" metric effect="+metriceffects.get(metricName)+"Affected unit="+affectedUnit);

                        } catch (Exception e) {

                            actionEffect.setActionEffectForMetric(metricName,
                                    ((Long) metriceffects.get(metricName) + 0.0), affectedUnit);

                            //   System.out.println("metricName="+metricName+" metric effect="+metriceffects.get(metricName)+"Affected unit="+affectedUnit);

                        }
                    }
                }
            }
            List<ActionEffect> l = new ArrayList<ActionEffect>();
            l.add(actionEffect);
            actionEffects.put(actionEffect.getTargetedEntityID(), l);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return actionEffects;
}

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

public static String getLogIdFromMessage(String msg) {
    JSONObject jsonMsg;
    JSONParser parser = new JSONParser();

    try {/*from  w w w .  j a va  2  s  .com*/
        jsonMsg = (JSONObject) parser.parse(msg);
        JSONObject msgObject = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE);
        return (String) msgObject.get(JsonStrings.LOG_ID);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Transfer the Notary's answer from a JSON-representation into a HashSet of ConvergenceCertObservation
 * /*w  w  w  .  ja va 2s.c o  m*/
 * @param notaryAnswer The Response-String that the Notary sent as an answer. It should contain a JSON-encoded list of ConvergenceCertificateObservations 
 * @param hostPort The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Notary's answer as a Set of ConvergenceCertObservations
 * @throws ParseException
 */
private static HashSet<ConvergenceCertObservation> parseNotaryAnswer(String notaryAnswer, String hostPort)
        throws ParseException {

    // Create a empty Set of ConvergenceCertObservations
    HashSet<ConvergenceCertObservation> re = new HashSet<ConvergenceCertObservation>();

    // Try to decode the Notary's answer as a JSONObject
    JSONParser parser = new JSONParser();
    JSONObject obj = (JSONObject) parser.parse(notaryAnswer);

    // If that worked extract the field called fingerprintList (which is basically a list of ConvergenceCertObservations in JSON encoding)
    JSONArray array = (JSONArray) obj.get("fingerprintList");

    // Go through the list ...
    for (int i = 0; i < array.size(); i++) {

        // ... read each entry ...
        JSONObject entry = (JSONObject) array.get(i);

        // .. extract its content ...
        byte[] fingerprint = Message.hexStringToByteArray(((String) entry.get("fingerprint")).replace(":", ""));
        JSONObject ts = (JSONObject) entry.get("timestamp");
        Timestamp firstObservation = new Timestamp(1000 * Long.valueOf((String) ts.get("start")));
        Timestamp lastObservation = new Timestamp(1000 * Long.valueOf((String) ts.get("finish")));
        Timestamp lastUpdate = new Timestamp(System.currentTimeMillis());

        // ... and create a new ConvergenceCertObservation-object based on that content.
        re.add(new ConvergenceCertObservation(hostPort, Message.byteArrayToHexString(fingerprint),
                firstObservation, lastObservation, lastUpdate));
    }

    // Finally return the Set containing all of the extracted ConvergenceCertObservations.
    return re;
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

public static Class getFieldClass(Message parent, JSONObject jo, Field f, Registry<Class> r) {
    Class fc;/*  w w w .java 2  s .c om*/
    fc = f.getType();
    if (fc.isArray())
        fc = f.getType().getComponentType();
    if (Indication.isIndicated(f) && (jo != null)) {
        //fc = Indication.getIndication(parent,
        //        (String) jo.get(Indication.getIndicatorName(parent.getClass())));
        fc = r.lookup(parent.getClass(), (String) jo.get(Indication.getIndicatorName(parent.getClass())));
        //System.out.println("JSON.getFieldClass: parent class " + parent.getClass().getName() +
        //        " Indicator: " + Indication.getIndicatorName(parent.getClass()) + 
        //        " result: " + fc.getName());
    }
    return fc;
}

From source file:com.jql.gcmccsmock.GCMMessageHandler.java

/**
 * Create Delivery Receipt/*from   ww  w .  j  a  v a  2  s.co  m*/
        
 <message id="">
   <gcm xmlns="google:mobile:data">
   {
     "category":"com.example.yourapp", // to know which app sent it
     "data":
     {
 message_status":"MESSAGE_SENT_TO_DEVICE",
 original_message_id?:?m-1366082849205?,
 device_registration_id?: REGISTRATION_ID?,
 "message_sent_timestamp": "1430277821658"
     },
     "message_id":"dr2:m-1366082849205",
     "message_type":"receipt",
     "time_to_live": 0,
     "from":"gcm.googleapis.com"
   }
   </gcm>
 </message>
        
 * @param original
 * @param jsonObject
 * @return
 * @throws EntityFormatException
 */
private static Stanza createDeliveryReceiptMessageStanza(Stanza original, JSONObject jsonObject)
        throws EntityFormatException {

    Map<String, Object> message = new HashMap<>();
    message.put(JSON_MESSAGE_TYPE, JSON_RECEIPT);
    message.put(JSON_FROM, "gcm.googleapis.com");
    // TODO made up
    message.put(JSON_CATEGORY, "com.itsoninc.client");
    message.put(JSON_MESSAGE_ID, "dr2:" + jsonObject.get(JSON_MESSAGE_ID));
    Map<String, Object> data = new HashMap<>();
    data.put(JSON_MESSAGE_STATUS, JSON_MESSAGE_STATUS_SENT_TO_DEVICE);
    data.put(JSON_ORIGINAL_MESSAGE_ID, jsonObject.get(JSON_MESSAGE_ID));
    data.put(JSON_DEVICE_REG_ID, jsonObject.get(JSON_TO));
    data.put(JSON_SENT_TIMESTAMP, Long.toString(System.currentTimeMillis()));
    message.put("data", data);
    String payload = JSONValue.toJSONString(message);

    StanzaBuilder builder = new StanzaBuilder("message");
    builder.addAttribute("id",
            original.getAttributeValue("id") == null ? "" : original.getAttributeValue("id"));
    GCMMessage.Builder gcmMessageBuilder = new GCMMessage.Builder();
    gcmMessageBuilder.addText(payload);
    builder.addPreparedElement(gcmMessageBuilder.build());
    return builder.build();
}

From source file:com.stratio.deep.commons.utils.CellsUtils.java

/**
 * converts from cell class to JSONObject
 *
 * @param Json      the json//w w w  . j  av  a 2 s .  c om
 * @param tableName the table name
 * @return cell from json
 * @throws IllegalAccessException the illegal access exception
 * @throws IllegalAccessException the instantiation exception
 * @throws IllegalAccessException the invocation target exception
 */
public static Cells getCellFromJson(JSONObject Json, String tableName)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {

    Cells cells = tableName != null ? new Cells(tableName) : new Cells();

    Set<String> entrySet = Json.keySet();

    for (String key : entrySet) {
        try {
            Object value = Json.get(key);

            if (List.class.isAssignableFrom(value.getClass())) {
                List<Cells> innerCell = new ArrayList<>();
                for (JSONObject innerBson : (List<JSONObject>) value) {
                    innerCell.add(getCellFromJson(innerBson, null));
                }
                cells.add(Cell.create(key, innerCell));
            } else if (JSONObject.class.isAssignableFrom(value.getClass())) {
                Cells innerCells = getCellFromJson((JSONObject) value, null);
                cells.add(Cell.create(key, innerCells));
            } else {
                if (key.equalsIgnoreCase("id")) {
                    cells.add(Cell.create(key, value, true));
                } else {
                    cells.add(Cell.create(key, value));

                }
            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException
                | IllegalArgumentException e) {
            LOG.error("impossible to create a java cell from Json field:" + key);
        }

    }
    return cells;
}

From source file:com.bigdata.dastor.tools.SSTableImport.java

/**
 * Convert a JSON formatted file to an SSTable.
 * // ww  w.j  ava2 s.co  m
 * @param jsonFile the file containing JSON formatted data
 * @param keyspace keyspace the data belongs to
 * @param cf column family the data belongs to
 * @param ssTablePath file to write the SSTable to
 * @throws IOException for errors reading/writing input/output
 * @throws ParseException for errors encountered parsing JSON input
 */
public static void importJson(String jsonFile, String keyspace, String cf, String ssTablePath)
        throws IOException, ParseException {
    ColumnFamily cfamily = ColumnFamily.create(keyspace, cf);
    String cfType = cfamily.type(); // Super or Standard
    IPartitioner<?> partitioner = DatabaseDescriptor.getPartitioner();
    DataOutputBuffer headerBuffer = new DataOutputBuffer(); // BIGDATA
    DataOutputBuffer dob = new DataOutputBuffer();

    try {
        JSONObject json = (JSONObject) JSONValue.parseWithException(new FileReader(jsonFile));

        SSTableWriter writer = new SSTableWriter(ssTablePath, json.size(), partitioner);
        List<DecoratedKey<?>> decoratedKeys = new ArrayList<DecoratedKey<?>>();

        for (String key : (Set<String>) json.keySet())
            decoratedKeys.add(partitioner.decorateKey(key));
        Collections.sort(decoratedKeys);

        for (DecoratedKey<?> rowKey : decoratedKeys) {
            if (cfType.equals("Super"))
                addToSuperCF((JSONObject) json.get(rowKey.key), cfamily);
            else
                addToStandardCF((JSONArray) json.get(rowKey.key), cfamily);

            ColumnFamily.serializer().serializeWithIndexes(cfamily, headerBuffer, dob,
                    DatabaseDescriptor.getCompressAlgo(keyspace, cf)); // BIGDATA
            writer.append(rowKey, headerBuffer, dob);
            headerBuffer.reset(); // BIGDATA
            dob.reset();
            cfamily.clear();
        }

        writer.closeAndOpenReader();
    } catch (ClassCastException cce) {
        throw new RuntimeException("Invalid JSON input, or incorrect column family.", cce);
    }
}

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

private static void doImport(String cliwixServerUrl, Options options) {
    waitForServerReady(cliwixServerUrl, options);

    String importReportFolder = options.getImportReportFolder();
    if (importReportFolder == null) {
        importReportFolder = ".";
    }//from w ww.  j a v a  2  s .  co m
    File outputDir = null;
    try {
        outputDir = new File(importReportFolder);
        outputDir.mkdirs();
    } catch (Exception e) {
        console.printlnError("Error: Invalid import report folder: " + importReportFolder);
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    String input = options.getImportInput();
    if (input == null) {
        console.printlnError("Error: Property import.input is required.");
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    File inputFile = new File(input);
    if (!inputFile.exists()) {
        console.printlnError("Error: Input does not exist: " + inputFile.getAbsolutePath());
        console.exit(EXIT_STATUS_FAIL);
    }

    if (inputFile.isDirectory()) {
        try {
            File tempFile = File.createTempFile("import", ".zip");
            tempFile.delete(); //Must not exist
            ZipFile zipFile = new ZipFile(tempFile);
            ZipParameters zipParams = new ZipParameters();
            zipParams.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            zipParams.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FASTEST);
            zipParams.setIncludeRootFolder(false);
            zipFile.addFolder(inputFile, zipParams);
            inputFile = tempFile;
        } catch (IOException | ZipException e) {
            if (debug)
                console.printStacktrace(e);
            console.printlnError("Error: Unable to create zip file");
            console.exit(EXIT_STATUS_FAIL);
            return;
        }

    } else if (!inputFile.getName().endsWith(".xml") && !inputFile.getName().endsWith(".zip")) {
        console.printlnError("Error: Invalid input (must be a folder or a XML file or a ZIP archive): "
                + inputFile.getAbsolutePath());
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    JSONObject uploadResult = uploadFile(cliwixServerUrl, "/services/uploads", inputFile);
    String tmpFileName = (String) ((JSONObject) uploadResult.get("uploadResult")).get("tmpFileName");

    JSONObject importSettings = options.getImportSettings(tmpFileName);

    JSONObject importResult = postJson(cliwixServerUrl, "/services/imports", importSettings);

    String importId = (String) ((JSONObject) importResult.get("importResult")).get("importId");
    console.println("Import started. Id: " + importId);

    boolean success = waitForImportExport(false, importId, cliwixServerUrl, options);

    if (success) {
        console.println("Import succeeded.");
    } else {
        console.printlnError("Error: Import failed!");
    }

    String path = "/services/imports/" + importId + "/report";
    if (debug)
        console.println("Sending GET request: " + path);
    Response reportResponse = getHandler.get(cliwixServerUrl, path, cookieManager);
    handleError(reportResponse);

    File reportFile = new File(outputDir, "import-report.html");

    try (OutputStream outputStream = new FileOutputStream(reportFile)) {
        outputStream.write(reportResponse.getResponseAsString().getBytes("UTF-8"));
        console.println("Import report written to: " + reportFile.getAbsolutePath());

    } catch (IOException e) {
        if (debug)
            console.printStacktrace(e);
        console.printlnError("Error: No import report found");
        success = false;
    } finally {
        reportResponse.disconnect();
    }

    if (options.isImportDeleteOnServerAfterTransfer()) {
        Response deleteResponse = deleteHandler.delete(cliwixServerUrl, "/services/imports/" + importId,
                cookieManager);
        if (deleteResponse.getStatusCode() == 200) {
            console.println("Successfully deleted import folder on server.");
        } else {
            console.printlnError("Failed to delete import folder on server!");
        }
    }

    if (!success) {
        console.exit(EXIT_STATUS_FAIL);
    }
}

From source file:com.stratio.deep.commons.utils.CellsUtils.java

public static Cells getCellWithMapFromJson(JSONObject Json, String tableName)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {

    Cells cells = tableName != null ? new Cells(tableName) : new Cells();

    Set<String> entrySet = Json.keySet();

    for (String key : entrySet) {
        try {//from   ww w. j  av  a 2 s .  c o  m
            Object value = Json.get(key);

            if (List.class.isAssignableFrom(value.getClass())) {
                List<String> innerCell = new ArrayList<>();
                for (String innerBson : (List<String>) value) {
                    innerCell.add(innerBson);
                }
                cells.add(Cell.create(key, innerCell));
            } else if (JSONObject.class.isAssignableFrom(value.getClass())) {
                Map<String, Object> map = new HashMap<>();
                Cells innerCells = getCellFromJson((JSONObject) value, null);
                for (Cell cell : innerCells) {
                    map.put(cell.getName(), cell.getValue());
                }
                cells.add(Cell.create(key, map));
            } else {
                if (key.equalsIgnoreCase("id")) {
                    cells.add(Cell.create(key, value, true));
                } else {
                    cells.add(Cell.create(key, value));

                }
            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException
                | IllegalArgumentException e) {
            LOG.error("impossible to create a java cell from Json field:" + key);
        }

    }
    return cells;
}