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:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method that builds a {@link MessageType#CHECK_OUT} message relative to the passed {@link Entity}
 *///from   w ww  . jav a2s  .co  m
public static String buildCheckOutMessage(Entity e, boolean isValid) {
    JSONObject mesg = new JSONObject();
    JSONObject checkOutMsg = new JSONObject();
    checkOutMsg.put(JsonStrings.SENDER, e.getEntityID());
    checkOutMsg.put(JsonStrings.MSG_TYPE, MessageType.CHECK_OUT.name());
    checkOutMsg.put(JsonStrings.ENTITY, ((JSONObject) e.getJsonDescriptor().get(JsonStrings.ENTITY)));
    checkOutMsg.put(JsonStrings.VALID, isValid);
    mesg.put(JsonStrings.MESSAGE, checkOutMsg);

    return mesg.toJSONString();
}

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

/**
 * Method that builds the {@link MessageType#SYNC_RESP} message corresponding to a {@link MessageType#SYNC_REQ}
 *///from  w  w  w .j a v a  2s.c o m
public static String buildSyncRespMessage(Entity e, String topicReply) {
    JSONObject msg = new JSONObject();
    JSONObject syncRespMsg = new JSONObject();
    syncRespMsg.put(JsonStrings.SENDER, e.getEntityID());
    syncRespMsg.put(JsonStrings.MSG_TYPE, MessageType.SYNC_RESP.name());

    /*
     * Only for logging
     */
    syncRespMsg.put(JsonStrings.TOPIC_REPLY, topicReply);

    syncRespMsg.put(JsonStrings.ENTITY, ((JSONObject) e.getJsonDescriptor().get(JsonStrings.ENTITY)));
    msg.put(JsonStrings.MESSAGE, syncRespMsg);

    return msg.toJSONString();
}

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

/**
 * Method that build a {@link MessageType#SYNC_REQ}, passed a {@link String} representing the topic reply where
 * other entities have to send the corresponding {@link MessageType#SYNC_RESP} message
 *///from w ww.  jav a 2 s .  c  om
public static String buildSyncReqMessage(String senderID, String topicReply, ArrayList<Entity> beacons,
        Group group, DistanceRange distance, String logId) {
    JSONObject mesg = new JSONObject();
    JSONObject syncReqMsg = new JSONObject();
    syncReqMsg.put(JsonStrings.SENDER, senderID);
    syncReqMsg.put(JsonStrings.MSG_TYPE, MessageType.SYNC_REQ.name());
    syncReqMsg.put(JsonStrings.TOPIC_REPLY, topicReply);
    syncReqMsg.put(JsonStrings.BEACONS, ((JSONArray) buildBeaconsJsonArray(beacons)));

    JSONObject jsonGroup = new JSONObject();
    jsonGroup.put(JsonStrings.FILTER, (group.getFilter() != null) ? group.getFilter().toString() : "");
    jsonGroup.put(JsonStrings.ENTITY_ID, group.getEntity_id());
    jsonGroup.put(JsonStrings.ENTITY_TYPE, group.getType().name());
    jsonGroup.put(JsonStrings.GROUP_DESCRIPTOR, group.toString());

    syncReqMsg.put(JsonStrings.GROUP, jsonGroup);

    syncReqMsg.put(JsonStrings.DISTANCE_RANGE, distance.name());
    syncReqMsg.put(JsonStrings.LOG_ID, logId);
    mesg.put(JsonStrings.MESSAGE, syncReqMsg);

    return mesg.toJSONString();
}

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRData(String body) throws ParseException, InterruptedException, APIException {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONArray jsonBody = (JSONArray) parser.parse(body);

    Map<String, Object> data = new HashMap<>();

    class GetObjectData implements Runnable {
        private String psrNumber;
        private Map<String, Object> data;
        private IServiceRequest psr;

        public GetObjectData(String psrNumber, Map<String, Object> data)
                throws APIException, InterruptedException {
            this.psrNumber = psrNumber;
            this.data = data;

            psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber);
        }//from   www  . j a  va2  s .  c o m

        @Override
        public void run() {
            this.data.put(psrNumber, new HashMap<String, Object>());

            try {
                if (psr != null) {
                    getCellValues();
                    getAttachments();
                    getHistory();
                }
            } catch (APIException ex) {
                Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        private void getCellValues() throws APIException {
            Map<String, Object> cellValues = new HashMap<>();

            long startTime = System.currentTimeMillis();

            // Get cell values
            ICell[] cells = psr.getCells();
            for (ICell cell : cells) {
                if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                    if (cell.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                        sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                        cellValues.put(cell.getName(), sdf.format((Date) cell.getValue()));
                    } else {
                        cellValues.put(cell.getName(), cell.toString());
                    }
                } else {
                    cellValues.put(cell.getName(), cell.toString());
                }
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getCellValues executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("cellValues", cellValues);
        }

        private void getAttachments() throws APIException {
            List<Map<String, String>> attachments = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get attachments information
            ITable table = psr.getTable("Attachments");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> attachment = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            attachment.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            attachment.put(cell.getName(), cell.toString());
                        }
                    } else {
                        attachment.put(cell.getName(), cell.toString());
                    }
                }

                attachments.add(attachment);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getAttachments executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("attachments", attachments);
        }

        private void getHistory() throws APIException {
            List<Map<String, String>> histories = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get history information
            ITable table = psr.getTable("History");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> history = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            history.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            history.put(cell.getName(), cell.toString());
                        }
                    } else {
                        history.put(cell.getName(), cell.toString());
                    }
                }

                histories.add(history);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getHistory executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("history", histories);
        }
    }

    synchronized (data) {
        // Do something funky with the first one
        Thread t = new Thread(new GetObjectData(jsonBody.get(0).toString(), data));
        t.start();
        t.join();

        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (Object object : jsonBody.subList(1, jsonBody.size() - 1)) {
            executor.execute(new Thread(new GetObjectData(object.toString(), data)));
        }

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

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

From source file:com.github.lgi2p.obirs.utils.JSONConverter.java

public static String jsonifyObirsResults(List<ObirsResult> results, IndexerJSON indexer,
        Map<URI, String> indexURI2Label) throws IOException {

    Map<String, String> namespace2prefix = new HashMap<String, String>();

    JSONArray jsonResults = new JSONArray();

    Set<URI> infoConcepts = new HashSet();

    StringWriter json = new StringWriter();

    for (ObirsResult result : results) {

        JSONObject jsonResult = new JSONObject();
        URI itemResultURI = result.getItemURI();

        ItemMetadata metadata = indexer.getMetadata(itemResultURI);

        jsonResult.put("itemTitle", metadata.title);
        jsonResult.put("href", metadata.href);
        jsonResult.put("itemId", metadata.idLiteral);
        jsonResult.put("itemURI", buildShortURI(result.getItemURI(), namespace2prefix));
        jsonResult.put("score", result.getScore());

        JSONArray jsonConcepts = new JSONArray();

        if (result.getConcepts() != null) {

            for (ConceptMatch concept : result.getConcepts()) {

                JSONObject jsonConcept = new JSONObject();

                jsonConcept.put("queryConceptURI",
                        buildShortURI(concept.getQueryConceptURI(), namespace2prefix));
                jsonConcept.put("matchingConceptURI",
                        buildShortURI(concept.getMatchingConceptURI(), namespace2prefix));

                infoConcepts.add(concept.getQueryConceptURI());
                infoConcepts.add(concept.getMatchingConceptURI());

                jsonConcept.put("relationType", buildShortURI(concept.getRelationType(), namespace2prefix));
                jsonConcept.put("score", concept.getScore());
                jsonConcepts.add(jsonConcept);
            }/*from w  ww . j  a v  a 2s  .  c  o  m*/
        }
        jsonResult.put("concepts", jsonConcepts);
        jsonResults.add(jsonResult);
    }

    JSONArray jsonInfoConcepts = new JSONArray();
    for (URI uri : infoConcepts) {

        JSONObject jsonQueryConcept = new JSONObject();
        jsonQueryConcept.put("uri", buildShortURI(uri, namespace2prefix));
        jsonQueryConcept.put("label", indexURI2Label.get(uri));

        jsonInfoConcepts.add(jsonQueryConcept);
    }

    JSONArray jsonInfoNamespace = new JSONArray();
    for (Map.Entry<String, String> e : namespace2prefix.entrySet()) {

        JSONObject jsonQueryConcept = new JSONObject();
        jsonQueryConcept.put("ns", e.getKey());
        jsonQueryConcept.put("prefix", e.getValue());

        jsonInfoNamespace.add(jsonQueryConcept);
    }

    JSONObject finalJSONresult = new JSONObject();
    finalJSONresult.put("prefixes", jsonInfoNamespace);
    finalJSONresult.put("results", jsonResults);
    finalJSONresult.put("infoConcepts", jsonInfoConcepts);
    finalJSONresult.writeJSONString(json);
    return json.toString();
}

From source file:bizlogic.Sensors.java

public static void list(Connection DBcon) throws IOException, ParseException, SQLException {

    Statement st = null;// w  w w  . j  a v a2s  . co m
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Sensors.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }
    try {
        FileWriter sensorsFile = new FileWriter("/var/lib/tomcat8/webapps/ROOT/Records/sensors.json");
        sensorsFile.write("");
        sensorsFile.flush();

        JSONParser parser = new JSONParser();

        JSONObject Records = new JSONObject();

        JSONObject operation_Obj = new JSONObject();
        JSONObject operand_Obj = new JSONObject();
        JSONObject unit_Obj = new JSONObject();
        JSONObject name_Obj = new JSONObject();
        JSONObject ip_Obj = new JSONObject();
        JSONObject port_Obj = new JSONObject();

        int _total = 0;

        JSONArray sensorList = new JSONArray();

        while (rs.next()) {

            JSONObject sensor_Obj = new JSONObject();
            int id = rs.getInt("sensor_id");
            String operation = rs.getString("operation");
            int operand = rs.getInt("operand");
            String unit = rs.getString("unit");
            String name = rs.getString("name");
            String ip = rs.getString("IP");
            int port = rs.getInt("port");

            sensor_Obj.put("recid", id);
            sensor_Obj.put("operation", operation);
            sensor_Obj.put("operand", operand);
            sensor_Obj.put("unit", unit);
            sensor_Obj.put("name", name);
            sensor_Obj.put("IP", ip);
            sensor_Obj.put("port", port);

            sensorList.add(sensor_Obj);
            _total++;

        }
        rs.close();

        Records.put("total", _total);
        Records.put("records", sensorList);

        sensorsFile.write(Records.toJSONString());
        sensorsFile.flush();
        sensorsFile.close();
    }

    catch (IOException ex) {
        Logger.getLogger(Sensors.class.getName()).log(Level.WARNING, null, ex);
    }
}

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

private static void putStringToJSON(JSONObject obj, String key, String value) {
    if (StringUtils.isNotEmpty(value)) {
        obj.put(key, value);
    }//from   w  w w . ja v  a  2s.com
}

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

/**
 * Helper method building a {@link JSONArray} containing beacons data to include in some framework messages
 *//*from   w w w  .  j a v  a 2s  . c om*/
private static JSONArray buildBeaconsJsonArray(ArrayList<Entity> beacons) {
    JSONArray beaconsArray = new JSONArray();
    for (Entity b : beacons) {
        JSONObject beacon = new JSONObject();
        String beaconId = b.getEntityID();
        beacon.put(JsonStrings.BEACON_ID, beaconId);
        beacon.put(JsonStrings.DISTANCE_RANGE, b.getDistanceRange().name());
        beaconsArray.add(beacon);
    }
    return beaconsArray;
}

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

@SuppressWarnings("unchecked")
public static void sizeSeveralJSONWithTypes(JSONizable[] objects, String feature, String type) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream stream;/*from  w ww .  j av a2  s.  c  om*/
    FeatureMap featureMap = mock(FeatureMap.class);
    when(featureMap.getPrefix(feature)).thenReturn("ps");

    try {
        stream = new ObjectOutputStream(baos);

        for (JSONizable object : objects) {

            JSONObject payLoad = new JSONObject();
            payLoad.put(type, object.toJSON());

            ImmutableMessage msg = new ImmutableMessage(feature, type, payLoad, "0");
            String codedMsg = msg.toJSONObject(featureMap).toJSONString();

            stream.writeObject(codedMsg);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    int size = baos.size();
    int sizePerMessage = size / objects.length;
    System.out.println("   Size indicating type " + objects.length + " messages - JSON: " + size + " bytes ("
            + sizePerMessage + " bytes/msg)");
}

From source file:ProfileManager.java

/**
 * <p>Runs during first-time setup.  Creates a new configuration file, who's
 * name was previously determined by <code>DATA_FILE_NAME</code>.</p>
 * /*from  w  w  w  . j a v a2  s . c om*/
 * <p>Parameters beginning with a '<code>@</code>' are place holders.</p>
 * 
 * @param file     Configuration file, whose name is determined by
 *                 <code>DATA_FILE_NAME</code>.
 * 
 * @param name     Name of active profile, need to fix this.
 */
//private static void initConfig (File file, String name) {
private static void initConfig(File file) {

    System.out.println("\nInitializing configuration settings...");

    //  DEBUG:
    characters.get(0).setIdentified(true);
    characters.get(0).setName("Test Name");

    if (verifyScannedBackups() > 0) {
        //OLD: while (unidentifiedCharacters.size() > 0) {
        while (unidentifiedCharacters) {

            identifyCharacter();

        } //  while unidentifiedCharacters (has objects within)

    } //  if there is at least one unverified character

    //  =================================================================

    System.out.println("Initializing " + DATA_FILE_NAME);
    System.out.println("Writing JSON file...");

    //  Root
    JSONObject rootJSON = new JSONObject();
    rootJSON.put("Active Character", "@Not_Selected");
    rootJSON.put("Active Profile", "@Not_Selected");
    JSONObject charactersJSON = new JSONObject();

    //  TODO:  This is just to make it work, for now...
    int increment = 0;

    for (Character character : characters) {

        //System.out.println("\nCreating character in JSON (" + character.getId() + ")...");

        JSONObject characterJSON = new JSONObject();
        characterJSON.put("ID", character.getId());
        String name = character.getName() != null ? character.getName() : "@Unknown_" + increment++;

        //  TODO:  Implement this:
        //characterJSON.put("Active Profile", character.getActiveProfile().name);

        /*
        //  Add profiles/backups:
        JSONArray profileJSON = new JSONArray();
        profileJSON.add("Backup1 Timestamp");
        profileJSON.add("Backup2 Timestamp");
        characterJSON.put("MyProfile", myProfile);
        */

        charactersJSON.put(name, characterJSON);

        //System.out.println("\nJSON Snapshot:\n" + charactersJSON);

    }

    rootJSON.put("Characters", charactersJSON);

    // try-with-resources statement based on post comment below :)
    try (FileWriter fileWriter = new FileWriter(DATA_FILE_NAME)) {
        fileWriter.write(rootJSON.toJSONString());
        System.out.println("Successfully Copied JSON Object to File...");
        System.out.println("\nJSON Object: " + rootJSON);
    } catch (IOException e) {
        System.out.println("IOException: " + e.getLocalizedMessage());
    }

}