Example usage for org.json.simple JSONValue parse

List of usage examples for org.json.simple JSONValue parse

Introduction

In this page you can find the example usage for org.json.simple JSONValue parse.

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * //from w  w  w .j  a v a  2  s.  c om
 * @param latitude
 * @param longitude
 * @return 
 */
public static HashMap reverse(double latitude, double longitude) {
    HashMap a = new HashMap();
    try {
        //URL url=new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude));            
        URL url = new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng="
                + String.valueOf(latitude) + "," + String.valueOf(longitude));
        URL file_url = new URL(
                url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery()));
        //BufferedReader lector=new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedReader lector = new BufferedReader(new InputStreamReader(file_url.openStream()));
        String textJson = "", tempJs;
        while ((tempJs = lector.readLine()) != null)
            textJson += tempJs;
        if (textJson == null)
            throw new Exception("Don't found item");
        JSONObject google = ((JSONObject) JSONValue.parse(textJson));
        a.put("status", google.get("status").toString());
        if (a.get("status").toString().equals("OK")) {
            JSONArray results = (JSONArray) google.get("results");
            JSONArray address_components = (JSONArray) ((JSONObject) results.get(2)).get("address_components");
            for (int i = 0; i < address_components.size(); i++) {
                JSONObject items = (JSONObject) address_components.get(i);
                //if(((JSONObject)types.get(0)).get("").toString().equals("country"))
                if (items.get("types").toString().contains("country")) {
                    a.put("country", items.get("long_name").toString());
                    a.put("iso", items.get("short_name").toString());
                    break;
                }
            }
        }
    } catch (Exception ex) {
        a = null;
        System.out.println("Error Google Geocoding: " + ex);
    }
    return a;
}

From source file:com.plancake.api.client.PlancakeApiClient.java

private void resetToken() throws UnsupportedEncodingException, NoSuchAlgorithmException, URISyntaxException,
        RuntimeException, PlancakeApiException {
    // we don't have a token yet or it has been reset as
    // it was probably expired
    this.token = "";

    Map<String, String> params = new HashMap<String, String>();
    params.put("token", "");
    params.put("api_key", this.apiKey);
    params.put("api_ver", Integer.toString(PlancakeApiClient.API_VERSION));

    if (this.extraInfoForGetTokenCall.length() > 0) {
        params.put("extra_info", this.extraInfoForGetTokenCall);
    }//from www  .j  a  v a2s . com

    if (this.emailAddress != null) {
        params.put("user_email", this.emailAddress);
    }

    if (this.password != null) {
        params.put("user_pwd", this.password);
    }

    if (this.userKey != null) {
        params.put("user_key", this.userKey);
    }

    String request = this.prepareRequest(params, "getToken");

    String response;
    try {
        response = this.getResponse(request);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Object obj = JSONValue.parse(response);
    JSONObject jobj = (JSONObject) obj;

    String token = (String) jobj.get("token");

    if (token == null) {
        throw new PlancakeApiException("problem resetting the token - " + response);
    }

    this.token = token;
}

From source file:com.net.h1karo.sharecontrol.ShareControl.java

public void updateCheck() {
    String CBuildString = "", NBuildString = "";

    int CMajor = 0, CMinor = 0, CMaintenance = 0, CBuild = 0, NMajor = 0, NMinor = 0, NMaintenance = 0,
            NBuild = 0;//from  ww w  .  j  a v a  2s  .com

    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectids=90354");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "ShareControl Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.getLogger().warning("No files found, or Feed URL is bad.");
            result = UpdateResult.ERROR;
            return;
        }
        String newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name"));
        newVersion = newVersionTitle.replace("ShareControl v", "").trim();

        /**\\**/
        /**\\**//**\\**/
        /**\    GET VERSIONS    /**\
          /**\\**/
        /**\\**//**\\**/

        String[] CStrings = currentVersion.split(Pattern.quote("."));

        CMajor = Integer.parseInt(CStrings[0]);
        if (CStrings.length > 1)
            if (CStrings[1].contains("-")) {
                CMinor = Integer.parseInt(CStrings[1].split(Pattern.quote("-"))[0]);
                CBuildString = CStrings[1].split(Pattern.quote("-"))[1];
                if (CBuildString.contains("b")) {
                    beta = true;
                    CBuildString = CBuildString.replace("b", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 1;
                } else if (CBuildString.contains("a")) {
                    alpha = true;
                    CBuildString = CBuildString.replace("a", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 10;
                } else
                    CBuild = Integer.parseInt(CBuildString);
            } else {
                CMinor = Integer.parseInt(CStrings[1]);
                if (CStrings.length > 2)
                    if (CStrings[2].contains("-")) {
                        CMaintenance = Integer.parseInt(CStrings[2].split(Pattern.quote("-"))[0]);
                        CBuildString = CStrings[2].split(Pattern.quote("-"))[1];
                        if (CBuildString.contains("b")) {
                            beta = true;
                            CBuildString = CBuildString.replace("b", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 1;
                        } else if (CBuildString.contains("a")) {
                            alpha = true;
                            CBuildString = CBuildString.replace("a", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 10;
                        } else
                            CBuild = Integer.parseInt(CBuildString);
                    } else
                        CMaintenance = Integer.parseInt(CStrings[2]);
            }

        String[] NStrings = newVersion.split(Pattern.quote("."));

        NMajor = Integer.parseInt(NStrings[0]);
        if (NStrings.length > 1)
            if (NStrings[1].contains("-")) {
                NMinor = Integer.parseInt(NStrings[1].split(Pattern.quote("-"))[0]);
                NBuildString = NStrings[1].split(Pattern.quote("-"))[1];
                if (NBuildString.contains("b")) {
                    beta = true;
                    NBuildString = NBuildString.replace("b", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 1;
                } else if (NBuildString.contains("a")) {
                    alpha = true;
                    NBuildString = NBuildString.replace("a", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 10;
                } else
                    NBuild = Integer.parseInt(NBuildString);
            } else {
                NMinor = Integer.parseInt(NStrings[1]);
                if (NStrings.length > 2)
                    if (NStrings[2].contains("-")) {
                        NMaintenance = Integer.parseInt(NStrings[2].split(Pattern.quote("-"))[0]);
                        NBuildString = NStrings[2].split(Pattern.quote("-"))[1];
                        if (NBuildString.contains("b")) {
                            beta = true;
                            NBuildString = NBuildString.replace("b", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 1;
                        } else if (NBuildString.contains("a")) {
                            alpha = true;
                            NBuildString = NBuildString.replace("a", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 10;
                        } else
                            NBuild = Integer.parseInt(NBuildString);
                    } else
                        NMaintenance = Integer.parseInt(NStrings[2]);
            }

        /**\\**/
        /**\\**//**\\**/
        /**\   CHECK VERSIONS   /**\
          /**\\**/
        /**\\**//**\\**/
        if ((CMajor < NMajor) || (CMajor == NMajor && CMinor < NMinor)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance < NMaintenance)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance == NMaintenance && CBuild < NBuild))
            result = UpdateResult.UPDATE_AVAILABLE;
        else
            result = UpdateResult.NO_UPDATE;
        return;
    } catch (Exception e) {
        console.sendMessage(" There was an issue attempting to check for the latest version.");
    }
    result = UpdateResult.ERROR;
}

From source file:ch.simas.jtoggl.JToggl.java

/**
 * Update a time entry./*from  w  w  w  . j ava2s.c o  m*/
 * 
 * @param timeEntry
 * @return created {@link TimeEntry}
 */
public TimeEntry updateTimeEntry(TimeEntry timeEntry) {
    Client client = prepareClient();
    String url = TIME_ENTRY.replace(PLACEHOLDER, timeEntry.getId().toString());
    WebResource webResource = client.resource(url);

    JSONObject object = createTimeEntryRequestParameter(timeEntry);
    String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE)
            .put(String.class);

    object = (JSONObject) JSONValue.parse(response);
    JSONObject data = (JSONObject) object.get(DATA);
    return new TimeEntry(data.toJSONString());
}

From source file:be.cytomine.client.Cytomine.java

private <T extends Collection> T fetchCollection(T collection) throws CytomineException {
    HttpClient client = null;//w  ww  .j  a  v a2 s. c  o m

    String url = collection.toURL();
    if (!url.contains("?")) {
        url = url + "?";
    }
    url = url + collection.getPaginatorURLParams();
    log.info("fetchCollection=" + url);

    try {
        client = new HttpClient(publicKey, privateKey, getHost());
        client.authorize("GET", url, "", "application/json,*/*");
        client.connect(getHost() + url);

        int code = client.get();
        String response = client.getResponseData();
        client.disconnect();
        log.debug(response);
        log.info(code);
        Object obj = JSONValue.parse(response);

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            analyzeCode(code, json);
            collection.setList((JSONArray) json.get("collection"));
        } else {
            collection.setList((JSONArray) obj);
        }
    } catch (IOException e) {
        throw new CytomineException(e);
    }
    return collection;
}

From source file:de.dailab.plistacontest.client.ContestHandlerOfflineCheating.java

/**
 * Method to handle incoming messages from the server.
 * /*from ww w.j  ava 2  s . c o  m*/
 * @param messageType
 *            the messageType of the incoming contest server message
 * @param _jsonMessageBody
 *            the incoming contest server message
 * @return the response to the contest server
 */
@SuppressWarnings("unused")
private String handleTraditionalMessage(final String messageType, final String _jsonMessageBody) {

    // write all data from the server to a file
    logger.info(messageType + "\t" + _jsonMessageBody);

    // create an jSON object from the String
    final JSONObject jObj = (JSONObject) JSONValue.parse(_jsonMessageBody);

    // define a response object
    String response = null;

    // TODO handle "item_create"

    // in a complex if/switch statement we handle the differentTypes of
    // messages
    if ("item_update".equalsIgnoreCase(messageType)) {

        // we extract itemID, domainID, text and the timeTime, create/update
        final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody);

        response = ";item_update successfull";
    }

    else if ("recommendation_request".equalsIgnoreCase(messageType)) {
        // THIS ISN'T WORKING BECAUSE REQUEST HAS A DIFFRENT JSON FORMAT THEN ITEM UPDATE
        //final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody);

        // we handle a recommendation request
        try {
            // parse the new recommender request
            RecommenderItem currentRequest = RecommenderItem.parseRecommendationRequest(_jsonMessageBody);

            // gather the items to be recommended
            List<Long> resultList = recommenderItemTable.getFutureItems(currentRequest.getTimeStamp(),
                    currentRequest.getDomainID(), currentRequest.getUserID());
            if (resultList == null) {
                response = "[]";
                System.out.println("invalid resultList");
            } else {
                response = resultList.toString();
            }
            response = getRecommendationResultJSON(response);

            // TODO? might handle the the request as impressions
        } catch (Throwable t) {
            t.printStackTrace();
        }
    } else if ("event_notification".equalsIgnoreCase(messageType)) {

        // parse the type of the event
        final RecommenderItem item = RecommenderItem.parseEventNotification(_jsonMessageBody);
        final String eventNotificationType = item.getNotificationType();

        // impression refers to articles read by the user
        if ("impression".equalsIgnoreCase(eventNotificationType)
                || "impression_empty".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {
                response = "handle impression eventNotification successful";
            }
            // click refers to recommendations clicked by the user
        } else if ("click".equalsIgnoreCase(eventNotificationType)) {

            response = "handle click eventNotification successful";

        } else {
            System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)");
        }

    } else if ("error_notification".equalsIgnoreCase(messageType)) {

        System.out.println("error-notification: " + _jsonMessageBody);

    } else {
        System.out.println("unknown MessageType: " + messageType);
        // Error handling
        logger.info(jObj.toString());
        // this.contestRecommender.error(jObj.toString());
    }
    return response;
}

From source file:de.dailab.plistacontest.client.RecommenderItem.java

/**
 * Parse the ORP json Messages./*from   w  w  w .  j  a v a  2  s.c  om*/
 * 
 * @param _jsonMessageBody
 * @return the parsed values encapsulated in a map; null if an error has
 *         been detected.
 */
public static RecommenderItem parseRecommendationRequest(String _jsonMessageBody) {

    try {
        final JSONObject jsonObj = (JSONObject) JSONValue.parse(_jsonMessageBody);

        // parse JSON structure to obtain "context.simple"
        JSONObject jsonObjectContext = (JSONObject) jsonObj.get("context");
        JSONObject jsonObjectContextSimple = (JSONObject) jsonObjectContext.get("simple");

        Long domainID = -3L;
        try {
            domainID = Long.valueOf(jsonObjectContextSimple.get("27").toString());
        } catch (Exception ignored) {
            try {
                domainID = Long.valueOf(jsonObjectContextSimple.get("domainId").toString());
            } catch (Exception e) {
                System.err.println("[Exception] no domainID found in " + _jsonMessageBody);
            }
        }

        Long itemID = null;
        try {
            itemID = Long.valueOf(jsonObjectContextSimple.get("25").toString());
        } catch (Exception ignored) {
            try {
                itemID = Long.valueOf(jsonObjectContextSimple.get("itemId").toString());
            } catch (Exception e) {
                System.err.println("[Exception] no itemID found in " + _jsonMessageBody);
            }
        }

        Long userID = -2L;
        try {
            userID = Long.valueOf(jsonObjectContextSimple.get("57").toString());
        } catch (Exception ignored) {
            try {
                userID = Long.valueOf(jsonObjectContextSimple.get("userId").toString());
            } catch (Exception e) {
                System.err.println("[INFO] no userID found in " + _jsonMessageBody);
            }
        }

        long timeStamp = 0;
        try {
            timeStamp = (Long) jsonObj.get("created_at") + 0L;
        } catch (Exception ignored) {
            timeStamp = (Long) jsonObj.get("timestamp");
        }

        try {
            userID = Long.valueOf(jsonObjectContextSimple.get("userId").toString());
        } catch (Exception e) {
            System.err.println("[INFO] no userID found in " + _jsonMessageBody);
        }

        Long limit = 0L;
        try {
            limit = (Long) jsonObj.get("limit");
        } catch (Exception e) {
            System.err.println("[Exception] no limit found in " + _jsonMessageBody);
        }

        RecommenderItem result = new RecommenderItem(userID, itemID, domainID, timeStamp);
        result.setNumberOfRequestedResults(limit.intValue());

        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:edu.pitt.dbmi.facebase.hd.FileManager.java

/** populates an ArrayList with Instruction objects using the JSON-formatted fb_queue.instructions column data
 * The JSON string (from the database) is keyed by "csv", "text" and "files" depending on the type of data. 
 * Instructions descendants (InstructionsCsv, InstructionsText, InstructionsFiles) are constructed. 
 * File objects are constructed (and stuffed into their container Instructions objects). 
 * As an example, the JSON shown here would result in 6 Instructions objects, 2 of each kind shown:
 * </ b>// w  ww . j av a2 s  .  c o  m
 * <pre>
 * {
 *     "csv": [
 *         {
 *             "content": "SELECT name FROM user",
 *             "path": "/Data/User Names.csv"
 *         },
 *         {
 *             "content": "SELECT uid FROM user",
 *             "path": "/Data/User IDs.csv"
 *         }
 *     ],
 *     "text": [
 *         {
 *             "content": "Your data was retrieved on 11-02-2011 and has 28 missing values...",
 *             "path": "/Data/Summary.txt"
 *         },
 *         {
 *             "content": "The Facebase Data User Agreement specifies...",
 *             "path": "/FaceBase Agreement.txt"
 *         }
 *     ],
 *     "files": [
 *         {
 *             "content": "/path/on/server/1101.obj",
 *             "path": "/meshes/1101.obj"
 *         },
 *         {
 *             "content": "/path/on/server/1102.obj",
 *             "path": "/meshes/1102.obj"
 *         }
 *     ]
 * }
 * </pre>
 * </ b>
 * 
 * @param instructionsString the JSON from the data request.
 * @param ali the list of Instructions objects that will be populated during execution of this method.
 * @return true if Instructions object creation effort succeeds.
 */
public boolean makeInstructionsObjects(String instructionsString, ArrayList<Instructions> ali) {
    log.debug("FileManager.makeInstructionsObjects() called.");
    long unixEpicTime = System.currentTimeMillis() / 1000L;
    String unixEpicTimeString = (new Long(unixEpicTime)).toString();
    this.setDataName(dataNamePrefix + unixEpicTimeString);
    trueCryptPath = trueCryptBasePath + dataName + trueCryptExtension;
    trueCryptFilename = dataName + trueCryptExtension;
    trueCryptVolumePath = trueCryptBasePath + dataName + trueCryptMountpoint;
    File trueCryptVolumePathDir = new File(trueCryptVolumePath);
    if (!trueCryptVolumePathDir.isDirectory()) {
        trueCryptVolumePathDir.mkdirs();
    }
    JSONObject jsonObj = (JSONObject) JSONValue.parse(instructionsString);

    if (jsonObj.containsKey("csv")) {
        log.debug("FileManager.makeInstructionsObjects() has a csv.");
        JSONArray jsonCsvArray = (JSONArray) jsonObj.get("csv");
        if (jsonCsvArray.size() > 0) {
            for (Object jsonObjectCsvItem : jsonCsvArray) {
                JSONObject jsonObjSql = (JSONObject) jsonObjectCsvItem;
                String sqlString = (String) jsonObjSql.get("content");
                JSONObject jsonObjSqlPath = (JSONObject) jsonObjectCsvItem;
                String sqlPathString = (String) jsonObjSql.get("path");
                File file = new File(trueCryptBasePath + dataName + sqlPathString);
                InstructionsCsv i = new InstructionsCsv(sqlString, file, sqlPathString);
                ali.add(i);
            }
        }
    }

    if (jsonObj.containsKey("text")) {
        log.debug("FileManager.makeInstructionsObjects() has a text.");
        JSONArray jsonTextArray = (JSONArray) jsonObj.get("text");
        if (jsonTextArray.size() > 0) {
            for (Object jsonObjectTextItem : jsonTextArray) {
                JSONObject jsonObjText = (JSONObject) jsonObjectTextItem;
                String contentString = (String) jsonObjText.get("content");
                JSONObject jsonObjTextPath = (JSONObject) jsonObjectTextItem;
                String textPathString = (String) jsonObjText.get("path");
                File file = new File(trueCryptBasePath + dataName + textPathString);
                InstructionsText i = new InstructionsText(contentString, file, textPathString);
                ali.add(i);
            }
        }
    }

    if (jsonObj.containsKey("files")) {
        log.debug("FileManager.makeInstructionsObjects() has a files.");
        JSONArray jsonFilesArray = (JSONArray) jsonObj.get("files");
        if (jsonFilesArray.size() > 0) {
            for (Object jsonObjectFilesItem : jsonFilesArray) {
                JSONObject jsonObjFiles = (JSONObject) jsonObjectFilesItem;
                String serverPathString = (String) jsonObjFiles.get("content");
                JSONObject jsonObjFilesPath = (JSONObject) jsonObjectFilesItem;
                String archivePathString = (String) jsonObjFiles.get("path");
                File fileSource = new File(serverPathString);
                File fileDest = new File(trueCryptBasePath + dataName + archivePathString);
                InstructionsFiles i = new InstructionsFiles(fileSource, fileDest, archivePathString);
                ali.add(i);
            }
        }
    }
    return true;
}

From source file:com.dsdev.mupdate.MainForm.java

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    //Set window properties
    this.setLocationRelativeTo(null);
    this.setIconImage(Resources.getImageResource("icon.png").getImage());
    popupDialog.setIconImage(Resources.getImageResource("icon.png").getImage());
    UpdateLogoLabel.setIcon(Resources.getImageResource("update.png"));
    popupDialogImageLabel.setIcon(Resources.getImageResource("alert.png"));

    SimpleSwingWorker worker = new SimpleSwingWorker() {

        @Override// w  w  w .  j ava  2 s .  co m
        protected void task() {

            //Copy updates
            copyDirectoryAndBackUpOldFiles(new File("./launcherpatch"), new File(".."));

            //Load version config
            JSONObject versionConfig;
            try {
                versionConfig = (JSONObject) JSONValue
                        .parse(FileUtils.readFileToString(new File("./version.json")));
            } catch (IOException ex) {
                showPopupDialog("Warning:  The version file could not be updated!  This may cause problems.");
                System.exit(0);
                return;
            }

            //Get new version from arguments
            String newVersion = "0";
            for (String arg : Arguments) {
                if (arg.startsWith("--version=")) {
                    newVersion = arg.substring(10);
                    break;
                }
            }

            //Save new version file
            try {
                versionConfig.put("moddleversion", newVersion);
                FileUtils.writeStringToFile(new File("./version.json"), versionConfig.toJSONString());
            } catch (IOException ex) {
                showPopupDialog("Warning:  The version file could not be updated!  This may cause problems.");
                System.exit(0);
                return;
            }

            //Start Moddle
            try {
                ProcessBuilder moddle = new ProcessBuilder(new String[] { "javaw.exe", "-jar",
                        "\"" + new File("../Moddle.jar").getCanonicalPath() + "\"" });
                moddle.directory(new File(".."));
                moddle.start();
            } catch (IOException ex) {
                try {
                    ProcessBuilder moddle = new ProcessBuilder(
                            new String[] { "javaw.exe", "-jar", "\"../Moddle.jar\"" });
                    moddle.directory(new File(".."));
                    moddle.start();
                } catch (IOException ex2) {
                    showPopupDialog("Failed to start Moddle!");
                }
            }

            //Exit
            System.exit(0);

        }

    };
    worker.execute();
}

From source file:compare.handler.get.CompareGetHandler.java

/**
 * Use this method to retrieve the doc just to see its format
 * @param db the database to fetch from/*  w  ww  .  j  a  v  a  2  s .c om*/
 * @param docID the doc's ID
 * @return a JSON doc as returned by Mongo
 * @throws AeseException 
 */
JSONObject loadJSONObject(String db, String docID) throws CompareException {
    try {
        String data = Connector.getConnection().getFromDb(db, docID);
        if (data.length() > 0) {
            JSONObject doc = (JSONObject) JSONValue.parse(data);
            if (doc != null)
                return doc;
        }
        throw new CompareException("Doc not found " + docID);
    } catch (Exception e) {
        throw new CompareException(e);
    }
}