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:mml.handler.get.MMLGetHandler.java

/**
 * Get a resource from the database if it already exists
 * @param db the collection name//from  www . ja v a2s  .  c o m
 * @param docID the resource docID
 * @return the resource or null
 * @throws MMLException 
 */
public static AeseResource doGetResource(String db, String docID) throws MMLException {
    String res = null;
    JSONObject doc = null;
    AeseResource resource = null;
    try {
        res = Connector.getConnection().getFromDb(db, docID);
    } catch (Exception e) {
        throw new MMLException(e);
    }
    if (res != null)
        doc = (JSONObject) JSONValue.parse(res);
    if (doc != null) {
        String format = (String) doc.get(JSONKeys.FORMAT);
        if (format == null)
            throw new MMLException("doc missing format");
        String version1 = (String) doc.get(JSONKeys.VERSION1);
        resource = new AeseResource();
        if (version1 != null)
            resource.setVersion1(version1);
        if (doc.containsKey(JSONKeys.DESCRIPTION) && format.equals(Formats.TEXT))
            resource.setDescription((String) doc.get(JSONKeys.DESCRIPTION));
        resource.setFormat(format);
        resource.setContent((String) doc.get(JSONKeys.BODY));
    }
    return resource;
}

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

public static String addLogField(String message, String logId) {
    JSONParser parser = new JSONParser();
    try {//ww w  . java  2 s  .c  o  m
        JSONObject msg = (JSONObject) parser.parse(message);
        JSONObject m = (JSONObject) msg.get(JsonStrings.MESSAGE);
        MessageType msgType = MessageType.valueOf((String) m.get(JsonStrings.MSG_TYPE));
        if (msgType.equals(MessageType.CHECK_OUT)) {
            m.put(JsonStrings.LOG_ID, logId);
            JSONObject newJsonMsg = new JSONObject();
            newJsonMsg.put(JsonStrings.MESSAGE, m);
            return newJsonMsg.toJSONString();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return message;
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Checks the modsecurity current status whether its running or stopped.
 * @param json// w  w  w  . ja  v a2 s . com
 */
@SuppressWarnings("unchecked")
public static void onStatusRequest(JSONObject json) {

    log.info("onStatusRequest called.. : " + json.toJSONString());
    MSConfig config = MSConfig.getInstance();
    String cmd = config.getConfigMap().get("MSStatus");

    JSONObject resp = executeShScript(cmd, json);
    if (((String) resp.get("status")).equals("0")) {

        log.info("Message After Execution:" + (String) resp.get("message"));
        if (((String) resp.get("message")).contains("running")) {
            resp.put("msStatus", "1");
        } else {
            resp.put("msStatus", "0");
        }

    }

    log.info("Sending Json :" + resp.toJSONString());
    ConnectorService.getConnectorProducer().send(resp.toJSONString());
    resp.clear();

}

From source file:it.polimi.diceH2020.plugin.control.FileManager.java

private static boolean setMachineLearningHadoop(InstanceDataMultiProvider data) {
    // Set mapJobMLProfile - MACHINE LEARNING
    Map<String, JobMLProfile> jmlMap = new HashMap<String, JobMLProfile>();
    JSONParser parser = new JSONParser();

    try {/* www. j  a  va 2  s  . c  o m*/
        for (ClassDesc cd : Configuration.getCurrent().getClasses()) {
            Map<String, SVRFeature> map = new HashMap<String, SVRFeature>();

            Object obj = parser.parse(new FileReader(cd.getMlPath()));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject parameter = (JSONObject) jsonObject.get("mlFeatures");

            Map<String, String> toCheck = cd.getAltDtsmHadoop()
                    .get(cd.getAltDtsmHadoop().keySet().iterator().next());
            for (String st : toCheck.keySet()) {
                if (!st.equals("file")) {
                    if (!parameter.containsKey(st)) {
                        JOptionPane.showMessageDialog(null, "Missing field in machine learning file: " + st
                                + "\n" + "for class: " + cd.getId(), "Error: ", JOptionPane.ERROR_MESSAGE);
                        return false;
                    }
                }
            }

            double b = (double) jsonObject.get("b");
            double mu_t = (double) jsonObject.get("mu_t");
            double sigma_t = (double) jsonObject.get("sigma_t");

            if (!parameter.containsKey("x")) {
                JOptionPane.showMessageDialog(null,
                        "Missing field in machine learning file: " + "x " + "\n" + "for class: " + cd.getId(),
                        "Error: ", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            if (!parameter.containsKey("h")) {
                JOptionPane.showMessageDialog(null,
                        "Missing field in machine learning file: " + "h" + "\n" + "for class: " + cd.getId(),
                        "Error: ", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            Iterator<?> iterator = parameter.keySet().iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();

                if (!toCheck.containsKey(key) && !key.equals("x") && !key.equals("h"))
                    continue;

                JSONObject locObj = (JSONObject) parameter.get(key);
                SVRFeature feat = new SVRFeature();
                feat.setMu((double) locObj.get("mu"));
                feat.setSigma((double) locObj.get("sigma"));
                feat.setW((double) locObj.get("w"));
                map.put(key, feat);
            }

            jmlMap.put(String.valueOf(cd.getId()), new JobMLProfile(map, b, mu_t, sigma_t));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    JobMLProfilesMap jML = JobMLProfilesMapGenerator.build();
    jML.setMapJobMLProfile(jmlMap);
    data.setMapJobMLProfiles(jML);

    return true;
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Helper function to determine if an obj is the package we're looking for.
 *//*from  w w  w. j  av  a 2  s  . co m*/
private static boolean isPkg(String publisher, String pkgName, String version, JSONObject obj) {
    boolean ispkg = true;
    if (publisher != null && pkgName != null && version != null) {
        ispkg = (publisher.equals(obj.get("publisher").toString())
                && version.equals(obj.get("version").toString()));
    }
    ispkg &= pkgName.equals(obj.get("package").toString());
    return ispkg;
}

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

private static Entity createEntity(MessageType type, JSONObject jsonEntity) {

    Builder builder;// www  .jav  a2s.  c  o m

    String entityId = (String) jsonEntity.get(JsonStrings.ENTITY_ID);
    String jsonEntityType = (String) jsonEntity.get(JsonStrings.ENTITY_TYPE);
    JSONObject jsonProperties;
    if (type.ordinal() == MessageType.PROPERTIES_UPDATE.ordinal())
        jsonProperties = (JSONObject) jsonEntity.get(JsonStrings.CURRENT_PROPERTIES);
    else {
        jsonProperties = (JSONObject) jsonEntity.get(JsonStrings.PROPERTIES);
    }

    Type entityType = null;
    for (Type t : Type.values())
        if (jsonEntityType.equalsIgnoreCase(t.name()))
            entityType = t;

    String jsonDistance = (String) jsonEntity.get(JsonStrings.DISTANCE_RANGE);
    DistanceRange distanceRange = null;
    for (DistanceRange d : DistanceRange.values())
        if (jsonDistance.equalsIgnoreCase(d.name()))
            distanceRange = d;

    if (entityType != null) {
        builder = new Builder(entityId, entityType).setDistance(distanceRange).addProperties(jsonProperties);

        return builder.build();
    }

    return null;
}

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  .  ja v a  2 s. c om*/

        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:com.fujitsu.dc.test.utils.ResourceUtils.java

/**
 * ??.//from ww  w .  jav a  2 s. c o m
 * @param cell ??
 * @param account ??
 * @param pass 
 * @return 
 */
public static String getMyCellLocalToken(String cell, String account, String pass) {
    JSONObject json = ResourceUtils.getLocalTokenByPassAuth(cell, account, pass, -1);
    assertEquals(EXPIRE, json.get(OAuth2Helper.Key.REFRESH_TOKEN_EXPIRES_IN));
    return (String) json.get("access_token");
}

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

private static Message convertJSONObjectToMessage(JSONObject jo, Class c, Registry<Class> r) {
    //System.out.println("JSON.convertJSONObjectToMessage: " + jo.toJSONString());
    try {//from  w  w  w .j  a  va 2 s.  co m
        Message result = (Message) c.newInstance();
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, jo, f, r);
            Object lookup = jo.get(f.getName());
            if (lookup != null) {
                Object value = convertElementToField(lookup, fc, f, r);
                f.set(result, value);
            }
        }
        return result;
    } catch (Exception ex) {
        //ex.printStackTrace();
        return null;
    }
}

From source file:com.orthancserver.DicomDecoder.java

private static void ExtractDicomInfo(ImagePlus image, JSONObject tags) {
    String info = new String();

    ArrayList<String> tagsIndex = new ArrayList<String>();
    for (Object tag : tags.keySet()) {
        tagsIndex.add((String) tag);
    }/*from  www.  j  a va  2s . c  o  m*/

    Collections.sort(tagsIndex);
    for (String tag : tagsIndex) {
        JSONObject value = (JSONObject) tags.get(tag);

        if (((String) value.get("Type")).equals("String")) {
            info += (tag + " " + (String) value.get("Name") + ": " + (String) value.get("Value") + "\n");
        }
    }

    image.setProperty("Info", info);
}