Example usage for org.json.simple.parser JSONParser JSONParser

List of usage examples for org.json.simple.parser JSONParser JSONParser

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser JSONParser.

Prototype

JSONParser

Source Link

Usage

From source file:ch.newscron.encryption.Encryption.java

/**
 * Given a String, it is decoded and the result is returned as a String as well.
 * @param encodedUrl is a String that have the full data encrypted
 * @return decoded String/*from ww w. jav  a 2 s. c  o m*/
 */
public static String decode(String encodedUrl) {

    try {

        //Decode URL
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));

        String result = new String(cipher.doFinal(Base64.decodeBase64(encodedUrl)));

        //Extract and remove hash from JSONObject
        JSONParser parser = new JSONParser();
        JSONObject receivedData = (JSONObject) parser.parse(result);
        String receivedHash = (String) receivedData.get("hash");
        receivedData.remove("hash");

        //Compare received hash with newly computed hash
        if (checkDataValidity(receivedData)) {
            byte[] hashOfData = createMD5Hash(receivedData);

            if (receivedHash.equals(new String(hashOfData, "UTF-8"))) { //Valid data
                return receivedData.toString();
            }
        }
    } catch (Exception e) {
    } //Invalid data (including encryption algorithm exceptions

    return null;
}

From source file:eu.riscoss.rdc.GithubAPI_Test.java

/**
 * GIT API Test method /*from   w  ww  .j a v  a 2 s .c o m*/
 * @param req
 * @return
 */
static JSONArray gitJSONGetter() {
    String json = "";
    //String repository = values.get("repository");

    String owner = "RISCOSS/";
    //String repo = "riscoss-analyser/";
    String repo = "riscoss-data-collector/";

    String r = owner + repo;

    String req;
    req = r + "commits";

    //NST: needs some time to be calculated. 1st time it returns Status 202!
    req = r + "stats/contributors"; //NST single contributors with weekly efforts: w:week, a:add, d:del, c:#commits

    //https://developer.github.com/v3/repos/statistics/#commit-activity
    req = r + "stats/commit_activity";//NST data per week (1y):  The days array is a group of commits per day, starting on Sunday.

    req = r + "collaborators"; //needs authorization! Error 401

    req = r + "events"; //committs and other events. Attention: max 10x30 events, max 90days!

    req = r + "issues?state=all"; //all issues. Of interest: state=open, closed, 

    //      req = r + "stats/participation";//NST  weekly commit count

    //req = r + "stats/code_frequency";  //NST: week,  number of additions, number of deletions per week

    //HttpGet( "https://api.github.com/rate_limit");  //rate limit is 60 requests per hour!!
    /**
     * TODO:
     * participation: week list, analysis value
     * issues open, issues closed today status
     *  
     */

    HttpGet get = new HttpGet("https://api.github.com/repos/" + req);
    //get = new HttpGet( "https://api.github.com/rate_limit");

    //only for getting the License
    //get.setHeader("Accept", "application/vnd.github.drax-preview+json");

    HttpResponse response;
    try {
        response = client.execute(get);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            json = EntityUtils.toString(entity);

        } else if (response.getStatusLine().getStatusCode() == 202) {
            System.err.println("WARNING 202 Accept: Computing....try again in some seconds.");
            return null;
        } else {
            // something has gone wrong...
            System.err.println(response.getStatusLine().getStatusCode());
            System.err.println(response.getStatusLine().toString());
            return null;
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    System.out.println("****JSON****\n" + json + "\n************");

    try {
        JSONAware jv = (JSONAware) new JSONParser().parse(json);

        if (jv instanceof JSONObject) {
            JSONObject jo = (JSONObject) jv;
            System.out.println("JO: ");
            for (Object o : jo.entrySet()) {
                System.out.println("\t" + o);
            }

        }

        if (jv instanceof JSONArray) {
            JSONArray ja = (JSONArray) jv;

            int size = ja.size();
            System.out.println("JA Size = " + size);
            for (Object o : ja) {
                if (o instanceof JSONObject) {
                    JSONObject jo = (JSONObject) o;
                    System.out.println("JA Object:");
                    for (Object o2 : jo.entrySet()) {
                        System.out.println("\t" + o2);
                    }
                } else {
                    System.out.println("JA Array: " + (JSONArray) o);
                }
            }
            return ja;
        }

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.blogspot.jadecalyx.webtools.jcPageObjectHelper.java

private void loadIndexFromJson(String site, String pageHandle) throws Exception {

    String s = System.getProperty("file.separator");
    String runPath = System.getProperty("user.dir");
    String fileToRead = pageHandle + ".json";
    String fullPath = String.join(s, runPath, "SiteInfo", site, "PageInfo", fileToRead);
    File f = new File(fullPath);
    if (!f.isFile()) {
        throw new Exception(
                String.format("loadIndex unable to find file for site: %s and file %s", site, fullPath));
    }// w  w w . j a v a 2s .c o m

    //load json file
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(fullPath));
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray objectList = (JSONArray) jsonObject.get("object-list");

    try {
        if (objectList.size() > 0) {
            for (int i = 0; i < objectList.size(); i++) {
                JSONObject theObject = (JSONObject) objectList.get(i);
                JSONArray lookups = (JSONArray) theObject.get("lookup");
                List<jcPageObjectSet> currList = new ArrayList<jcPageObjectSet>();
                for (int j = (lookups.size() - 1); j > -1; j--) {
                    JSONObject currLookup = (JSONObject) lookups.get(j);
                    currList.add(new jcPageObjectSet(currLookup.get("type").toString(),
                            currLookup.get("detail").toString()));
                }
                _objectIndex.put(theObject.get("handle").toString(), currList);
            }
        }
    } catch (Exception e) {
        int x = 1;
    }

    //load include list
    JSONArray includeList = (JSONArray) jsonObject.get("include-list");
    if (includeList.size() > 0) {
        for (int i = 0; i < includeList.size(); i++) {
            loadIndexFromJson(site, includeList.get(i).toString());
        }
    }

}

From source file:alexaactions.SmartThingsAgent.java

String getById(String path, String id) {
    String devices_json = get(path);

    System.out.println(devices_json);

    JSONParser parser = new JSONParser();
    Object obj = null;/*from   w  w w . ja va  2s .c  o m*/
    JSONObject device;
    JSONArray arr;

    // the whole purpose of this code is to determine if the id is valid
    try {
        obj = parser.parse(devices_json);
    } catch (ParseException ex) {
        Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex);
    }

    arr = (JSONArray) obj;
    if (arr != null) {
        int i, j;

        for (i = 0; i < arr.size(); i++) {
            device = (JSONObject) arr.get(i);
            String d_id = (String) device.get("id");
            if (d_id == null ? id == null : d_id.equals(id)) {
                for (j = 0; j < endpoints.size(); j++) {
                    JSONObject e = (JSONObject) endpoints.get(j);
                    String url = (String) e.get("uri") + "/" + path + "/" + d_id;
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Authorization", "Bearer " + access_token);

                    return smartthings.get(url, headers);
                }
            }
        }
    }
    return null;
}

From source file:biomine.bmvis2.pipeline.GraphOperationSerializer.java

public static List<GraphOperation> loadList(String json) throws GraphOperationSerializationException {

    JSONParser par = new JSONParser();
    JSONArray arr = null;//w ww  .j  ava  2s.  com

    try {
        System.out.println("obj = " + par.parse(json));
        arr = (JSONArray) par.parse(json);
    } catch (ParseException e) {
        System.out.println(e);
    }
    return loadList(arr);

}

From source file:com.lang.pat.kafkairc.Consumer.java

public void consume() throws ParseException, InterruptedException, Throwable {
    ConsumerIterator<byte[], byte[]> it = m_stream.iterator();
    JSONParser parse = new JSONParser();
    SimpleDateFormat formatDate = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
    while (it.hasNext() && listen) {
        if (ClientMain.ChannelList.contains(Topic)) {
            String temp = new String(it.next().message());
            if (!temp.contains("{")) {
                System.out.println(temp);
            } else {
                JSONObject JSONMessage = (JSONObject) parse.parse(temp);

                Date sendDat = new Date();
                sendDat.setTime((long) JSONMessage.get("timestamp"));
                System.out.println("[" + Topic + "] " + "[" + JSONMessage.get("username") + "] "
                        + JSONMessage.get("message") + " || " + formatDate.format(sendDat));

                if (JSONMessage.get("username").toString().equals(ClientMain.USERNAME)) {
                    if (!JSONMessage.get("token").toString().equals(ClientMain.token)) {
                        System.out.print("! Duplicate username, please change to avoid conflict!");
                    }/*from   w  w w.j a v a  2  s  .c  o m*/
                }
            }
            System.out.print("> ");
        } else {
            listen = false;
            break;
        }
    }
}

From source file:net.phyloviz.upgma.json.UPGMAItemFactory.java

@Override
public ProjectItem loadData(DataSet dataset, TypingData<? extends AbstractProfile> td, String directory,
        String filename, AbstractDistance ad, int level) {

    JsonValidator jv = new JsonValidator();
    try {/* w  ww  . j  a va 2s  . c o  m*/
        if (!jv.validate(directory, filename)) {
            return null;
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
    UPGMAItem upgma = null;

    try (FileReader reader = new FileReader(new File(directory, filename))) {

        JSONParser parser = new JSONParser();
        JSONObject json;
        json = (JSONObject) parser.parse(reader);

        JSONArray leafsArr = (JSONArray) json.get("leaf");
        JSONArray unionsArr = (JSONArray) json.get("union");
        JSONObject rootObj = (JSONObject) json.get("root");

        Map<Integer, UPGMALeafNode> leafs = createLeafs(td, leafsArr);

        Map<Integer, UPGMAUnionNode> unions = new HashMap();
        if (unionsArr != null) {
            unions = createUnions(unionsArr, leafs);
        }

        UPGMARoot root = createRoot(rootObj, leafs, unions);

        HierarchicalClusteringMethod cm = getMethodProvider(filename, td);

        OutputPanel op = new OutputPanel(dataset.toString() + ": Hierarchical Clustering - " + cm.toString()
                + " - (" + ad.toString() + ")");

        upgma = new UPGMAItem(root, (ClusteringDistance) ad, cm, op);

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

    return upgma;
}

From source file:com.ibm.bluemix.hack.image.ImageEvaluator.java

@SuppressWarnings("unchecked")
public JSONObject analyzeImage(byte[] buf) throws IOException {

    JSONObject imageProcessingResults = new JSONObject();

    JSONObject creds = VcapServicesHelper.getCredentials("watson_vision_combined", null);

    String baseUrl = creds.get("url").toString();
    String apiKey = creds.get("api_key").toString();
    String detectFacesUrl = baseUrl + "/v3/detect_faces?api_key=" + apiKey + "&version=2016-05-20";
    String classifyUrl = baseUrl + "/v3/classify?api_key=" + apiKey + "&version=2016-05-20";

    OkHttpClient client = new OkHttpClient();

    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("images_file", "sample.jpg", RequestBody.create(MediaType.parse("image/jpg"), buf))
            .build();/*from w w w . j a  va2s.c o m*/

    Request request = new Request.Builder().url(detectFacesUrl).post(requestBody).build();

    Response response = client.newCall(request).execute();
    String result = response.body().string();

    JSONParser jsonParser = new JSONParser();

    try {
        JSONObject results = (JSONObject) jsonParser.parse(result);
        // since we only process one image at a time, let's simplfy the json 
        // we send to the JSP.
        JSONArray images = (JSONArray) results.get("images");
        if (images != null && images.size() > 0) {
            JSONObject firstImage = (JSONObject) images.get(0);
            JSONArray faces = (JSONArray) firstImage.get("faces");
            imageProcessingResults.put("faces", faces);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // now request classification
    request = new Request.Builder().url(classifyUrl).post(requestBody).build();

    response = client.newCall(request).execute();
    result = response.body().string();
    try {
        JSONObject results = (JSONObject) jsonParser.parse(result);
        // since we only process one image at a time, let's simplfy the json 
        // we send to the JSP.
        JSONArray images = (JSONArray) results.get("images");
        if (images != null && images.size() > 0) {
            JSONObject firstImage = (JSONObject) images.get(0);
            JSONArray classifiers = (JSONArray) firstImage.get("classifiers");
            imageProcessingResults.put("classifiers", classifiers);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return imageProcessingResults;
}

From source file:com.nubits.nubot.launch.toolkit.NuCMC.java

private boolean readOptions() {
    boolean ok = false;
    NuBotOptions options = null;// w w w. ja  va2  s  . c  o  m
    JSONParser parser = new JSONParser();
    String optionsString = FilesystemUtils.readFromFile(optionsPath);
    try {
        org.json.JSONObject jsonString = new org.json.JSONObject(optionsString);
        org.json.JSONObject optionsJSON = (org.json.JSONObject) jsonString.get("options");

        String ccedkKey = (String) optionsJSON.get("ccedk-key");
        String ccedkSecret = (String) optionsJSON.get("ccedk-secret");
        String bterKey = (String) optionsJSON.get("bter-key");
        String bterSecret = (String) optionsJSON.get("bter-secret");

        threshold = Utils.getDouble(optionsJSON.get("threshold"));

        Exchange ccedk = new Exchange("ccedk");
        Exchange bter = new Exchange("bter");
        //Create e ExchangeLiveData object to accomodate liveData from the Global.exchange
        ExchangeLiveData liveDataC = new ExchangeLiveData();
        ExchangeLiveData liveDataB = new ExchangeLiveData();
        ccedk.setLiveData(liveDataC);
        bter.setLiveData(liveDataB);

        ccedk.setTrade(new CcedkWrapper(new ApiKeys(ccedkSecret, ccedkKey), ccedk));
        bter.setTrade(new BterWrapper(new ApiKeys(bterSecret, bterKey), bter));

        String cp = (String) optionsJSON.get("pair");

        pair = CurrencyPair.getCurrencyPairFromString(cp, "_");

        ok = true;
    } catch (JSONException | NumberFormatException ex) {
        LOG.error(ex.toString());
        ok = false;
    }
    return ok;
}

From source file:eu.celarcloud.celar_ms.ServerPack.SubProcessor.java

public void run() {
    if (this.server.inDebugMode())
        System.out.println("\nSubProcessor>> processing the following message...\n" + msg[0] + " " + msg[1]
                + "\n" + msg[2]);

    try {//from  w  w w .j  a va 2 s .  c  om
        JSONParser parser = new JSONParser();
        JSONObject json;

        json = (JSONObject) parser.parse(msg[2]); //parse content

        if (msg[1].equals("SUBSCRIPTION.ADD"))
            this.addSubscription(json);
        else if (msg[1].equals("SUBSCRIPTION.ADDAGENT"))
            this.addAgentToSub(json);
        else if (msg[1].equals("SUBSCRIPTION.REMOVEAGENT"))
            this.removeAgentFromSub(json);
        else if (msg[1].equals("SUBSCRIPTION.DELETE"))
            this.deleteSubscription(json);
        else
            this.response(Status.ERROR, msg[1] + " request does not exist");
    } catch (NullPointerException e) {
        this.server.writeToLog(Level.SEVERE, e);
        this.response(Status.SYNTAX_ERROR, msg[1] + " Subscription is not valid");
    } catch (IllegalArgumentException e) {
        this.server.writeToLog(Level.SEVERE, e);
        this.response(Status.SYNTAX_ERROR,
                "Grouping function either does not exist or is not currently supported");
    } catch (Exception e) {
        this.server.writeToLog(Level.SEVERE, e);
        this.response(Status.ERROR, msg[1] + " an error msg");
    }

}