Example usage for org.json.simple JSONArray add

List of usage examples for org.json.simple JSONArray add

Introduction

In this page you can find the example usage for org.json.simple JSONArray add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Gets the recent challenges and splits them to active and past challenges
 * Maximum 3 past challenges and all active challenges will be returned
 * @param sessionId//  www  .  j  a v  a 2 s .  c o  m
 * @param username
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static JSONObject getProcessedChallengesM2(String sessionId, String username)
        throws MalformedURLException, IOException {
    JSONArray recentChallenges = getRecentParticipantChallengesByUsername(sessionId, username);
    JSONArray activeChallenges = new JSONArray();
    JSONArray pastChallenges = new JSONArray();

    Iterator<JSONObject> iterator = recentChallenges.iterator();
    while (iterator.hasNext()) {
        JSONObject participantChallenge = iterator.next();
        JSONObject challenge = (JSONObject) participantChallenge.get("Challenge__r");
        if (challenge.get("Status__c").equals(PSContants.STATUS_CREATED)) { //active challenge
            activeChallenges.add(participantChallenge);
            JSONArray categories = getCategoriesByChallenge(sessionId,
                    (String) participantChallenge.get("Challenge__c"));
            participantChallenge.put("categories", categories);
        } else { //past challenges
            if (pastChallenges.size() < 3) {
                pastChallenges.add(participantChallenge);
                JSONArray categories = getCategoriesByChallenge(sessionId,
                        (String) participantChallenge.get("Challenge__c"));
                participantChallenge.put("categories", categories);
            }
        }
    }
    JSONObject challenges = new JSONObject();
    challenges.put("activeChallenges", activeChallenges);
    challenges.put("pastChallenges", pastChallenges);
    challenges.put("totalChallenges", getChallengeCountByUser(sessionId, username));
    return challenges;
}

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

/**
 * Convert a given ObirsQuery object into a JSON format
 *
 * @param query//w ww .j ava 2 s . c  o m
 * @return
 * @throws IOException
 */
public static String jsonifyObirsQuery(ObirsQuery query) throws IOException {
    JSONObject jsonObject = new JSONObject();

    jsonObject.put("aggregator", query.getAggregator());
    jsonObject.put("aggregatorParameter", query.getAggregatorParameter());
    jsonObject.put("similarityMeasure", query.getSimilarityMeasure());
    jsonObject.put("scoreThreshold", query.getScoreThreshold());
    jsonObject.put("numberOfResults", query.getNumberOfResults());

    StringWriter jsonQuery = new StringWriter();

    JSONArray jsonConcepts = new JSONArray();
    for (Map.Entry<URI, Double> queryConcept : query.getConcepts().entrySet()) {
        JSONObject jsonConcept = new JSONObject();
        URI conceptURI = queryConcept.getKey();
        jsonConcept.put("uri", conceptURI.stringValue());
        jsonConcept.put("weight", queryConcept.getValue());
        jsonConcepts.add(jsonConcept);
    }
    jsonObject.put("concepts", jsonConcepts);

    jsonObject.writeJSONString(jsonQuery);
    return jsonQuery.toString();
}

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Uses MemberChallenge service to get all the associated challenge information for a user
 * Sorts the challenge information with end date
 * Returns all the active challenges and 3 most recent past challenge 
 * @param sessionId/*from  w  w w .j  av  a2 s .co m*/
 * @param username
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static JSONObject getProcessedChallengesM1(String sessionId, String username)
        throws MalformedURLException, IOException {
    //get all challenges
    JSONArray challenges = getChallenges(sessionId, username);

    JSONArray activeChallenges = new JSONArray();
    JSONArray pastChallenges = new JSONArray();
    SortedMap<Long, JSONObject> pastChallengesByDate = new TreeMap<Long, JSONObject>();
    Iterator<JSONObject> iterator = challenges.iterator();

    DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-ddhh:mm:ss");

    while (iterator.hasNext()) {
        JSONObject challenge = iterator.next();
        //identify active challenge with status
        if (challenge.get("Status__c").equals(PSContants.STATUS_CREATED)) {
            activeChallenges.add(challenge);
        } else {
            String endDateStr = ((String) challenge.get("End_Date__c")).replace("T", "");
            Date date = new Date();
            try {
                date = dateFormat.parse(endDateStr);
            } catch (ParseException pe) {
                logger.log(Level.SEVERE, "Error occurent while parsing date " + endDateStr);
            }
            pastChallengesByDate.put(date.getTime(), challenge);
        }
    }

    //from the sorted map extract the recent challenge
    int pastChallengeSize = pastChallengesByDate.size();
    if (pastChallengeSize > 0) {
        Object[] challengeArr = (Object[]) pastChallengesByDate.values().toArray();
        int startIndex = pastChallengeSize > 3 ? pastChallengeSize - 3 : 0;
        for (int i = startIndex; i < pastChallengeSize; i++) {
            pastChallenges.add(challengeArr[i]);
        }
    }
    JSONObject resultChallenges = new JSONObject();
    resultChallenges.put("activeChallenges", activeChallenges);
    resultChallenges.put("pastChallenges", pastChallenges);
    resultChallenges.put("totalChallenges", challenges.size());
    return resultChallenges;
}

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 .ja v a2  s. c o m*/
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:luceneindexdemo.LuceneIndexDemo.java

public static void searchIndex(String s) throws IOException, ParseException, SQLException,
        FileNotFoundException, org.json.simple.parser.ParseException {

    Directory directory = FSDirectory.getDirectory(INDEX_DIRECTORY);
    IndexReader reader = IndexReader.open(directory);
    IndexSearcher search = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    QueryParser queryparser = new QueryParser(FIELD_CONTENTS, analyzer);
    Query query = queryparser.parse(s);
    Hits hits = search.search(query);/*from   ww w . j a  va 2s .  com*/
    Iterator<Hit> it = hits.iterator();
    //System.out.println("hits:"+hits.length());
    float f_score;
    List<String> names = new ArrayList<>();
    while (it.hasNext()) {
        Hit hit = it.next();
        f_score = hit.getScore();

        //System.out.println(f_score);
        Document document = hit.getDocument();
        Field f = document.getField(FIELD_PATH);

        //System.out.println(f.readerValue());
        //System.out.println(document.getValues(FIELD_PATH));
        String path = document.get(FIELD_PATH);
        System.out.println(document.getValues(path));
        Field con = document.getField(FIELD_PATH);
        //System.out.println("hit:"+path+" "+hit.getId()+" "+con);
        names.add(new File(path).getName());
    }

    //ProcessBuilder pb=new ProcessBuilder();
    FileReader fReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/inntell.json");
    JSONParser jsParser = new JSONParser();
    //System.out.println("This is an assumption that you belong to US");
    FileReader freReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/location.json");
    Connection con = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
    System.out.println(names);
    if (names.get(0).equals("miss")) {

        System.out.println(s);
        StringTokenizer stringTokenizer = new StringTokenizer(s);
        Connection con1 = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
        String querySearch = "match ()-[r:KNOWS]-() where has(r.relType) return distinct r.relType";
        ResultSet rSet = con.createStatement().executeQuery(querySearch);
        List<String> allRels = new ArrayList<>();
        while (rSet.next()) {
            System.out.println();
            allRels.add(rSet.getString("r.relType"));
        }
        //System.out.println(rSet);

        while (stringTokenizer.hasMoreTokens()) {
            String next = stringTokenizer.nextToken();
            if (allRels.contains(next)) {
                missOperation(next);
            }
            //System.out.println(resSet.getString("r.relType"));

        }
        System.out.println(names.get(1));
        //missOperation(names.get(1));
    } else {
        try {
            JSONObject jsonObj = (JSONObject) jsParser.parse(fReader);
            System.out.println(names.get(0));

            JSONObject jsObj = (JSONObject) jsonObj.get(names.get(0));
            JSONObject results = new JSONObject();
            System.out.println(jsObj.get("explaination"));
            results.put("explaination", jsObj.get("explaination"));
            JSONArray reqmts = (JSONArray) jsObj.get("true");
            System.out.println("Let me look out for the places that contains ");
            List<String> lis = new ArrayList<>();
            JSONObject locObj = (JSONObject) jsParser.parse(freReader);
            JSONArray jsArray = (JSONArray) locObj.get("CHENNAI");
            Iterator<JSONArray> ite = reqmts.iterator();
            int k = 0;
            String resQuery = "START n=node:restaurant('withinDistance:[" + jsArray.get(0) + ","
                    + jsArray.get(1) + ",7.5]') where";
            Iterator<JSONArray> ite1 = reqmts.iterator();
            while (ite1.hasNext())
                System.out.println(ite1.next());

            while (ite.hasNext()) {
                lis.add("n.type=" + "'" + ite.next() + "'");
                if (k == 0)
                    resQuery += " " + lis.get(k);
                else
                    resQuery += " or " + lis.get(k);
                //System.out.println(attrib);
                k++;

            }
            resQuery += " return n.name,n.place,n.type";
            File writeTo = new File(
                    "/home/rishav12/NetBeansProjects/LuceneIndexDemo/filestoIndex1/" + names.get(0));
            FileOutputStream fop = new FileOutputStream(writeTo, true);
            String writeTOFile = s + "\n";
            fop.write(writeTOFile.getBytes());
            //System.out.println(resQuery);
            ResultSet res = con.createStatement().executeQuery(resQuery);
            JSONArray resSet = new JSONArray();

            while (res.next()) {
                System.out.println(" name:" + res.getString("n.name") + " located:" + res.getString("n.place")
                        + " type:" + res.getString("n.type"));
                JSONObject jsPart = new JSONObject();
                jsPart.put("name", res.getString("n.name"));
                jsPart.put("located", res.getString("n.place"));
                jsPart.put("type", res.getString("n.type"));
                resSet.add(jsPart);
            }
            results.put("results", resSet);
            File resultFile = new File("result.json");
            FileOutputStream fop1 = new FileOutputStream(resultFile);
            System.out.println(results);
            fop1.write(results.toJSONString().getBytes());
            //String resQuery="START n=node:restaurant('withinDistance:[40.7305991, -73.9865812,10.0]') where n.coffee=true return n.name,n.address;";
            //System.out.println("Sir these results are for some coffee shops nearby NEW YORK");
            //ResultSet res=con.createStatement().executeQuery(resQuery);
            //while(res.next())
            //System.out.println("name: "+res.getString("n.name")+" address: "+res.getString("n.address"));
        } catch (org.json.simple.parser.ParseException ex) {
            Logger.getLogger(LuceneIndexDemo.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:edu.iu.incntre.flowscale.util.JSONConverter.java

public static JSONArray toPortStat(List<OFStatistics> ofs) {
    JSONArray jsonArray = new JSONArray();

    for (OFStatistics ofst : ofs) {

        OFPortStatisticsReply st = (OFPortStatisticsReply) ofst;

        JSONObject jsonObject = new JSONObject();
        if (st.getPortNumber() < -2) {
            continue;
        }// w ww .ja v  a  2s  .com
        jsonObject.put("port_id", st.getPortNumber());
        jsonObject.put("receive_packets", st.getreceivePackets());
        jsonObject.put("transmit_packets", st.getTransmitPackets());
        jsonObject.put("receive_bytes", st.getReceiveBytes());
        jsonObject.put("transmit_bytes", st.getTransmitBytes());

        jsonArray.add(jsonObject);

    }

    return jsonArray;

}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static JSONArray pullNovaConfig(String host, String tenantId, String token) throws IOException {

    // Get list of compute nodes
    String url = String.format("http://%s:8774/v2/%s/os-hosts", host, tenantId);
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String responseStr = sendGET(obj, con, "", token);
    JSONObject responseJSON = (JSONObject) JSONValue.parse(responseStr);

    JSONArray novaDescription = new JSONArray();
    JSONArray nodes = (JSONArray) responseJSON.get("hosts");

    for (Object h : nodes) {
        if (((JSONObject) h).get("service").equals("compute")) {
            String nodeName = (String) ((JSONObject) h).get("host_name");

            url = String.format("http://%s:8774/v2/%s/os-hosts/%s", host, tenantId, nodeName);
            obj = new URL(url);
            con = (HttpURLConnection) obj.openConnection();

            responseStr = sendGET(obj, con, "", token);
            responseJSON = (JSONObject) JSONValue.parse(responseStr);

            novaDescription.add(responseJSON);
        } else if (((JSONObject) h).get("service").equals("network")) {
            String hostName = (String) ((JSONObject) h).get("host_name");
            JSONObject networkNode = (JSONObject) JSONValue
                    .parse(String.format("{\"network_host\": {\"host_name\": \"%s\", }}", hostName));
            novaDescription.add(networkNode);
        }/*from   www. j  a  v a2s.  c o m*/
    }

    return novaDescription;
}

From source file:edu.usc.polar.CoreNLP.java

public static void StanfordCoreNLP(String doc, String args[]) {
    try {/* w w  w. j av  a2s. c  om*/
        String text;
        AutoDetectParser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();

        if (args.length > 0) {
            serializedClassifier = args[0];
        }

        if (args.length > 1) {
            String fileContents = IOUtils.slurpFile(args[1]);
            List<List<CoreLabel>> out = classifier.classify(fileContents);
            for (List<CoreLabel> sentence : out) {
                for (CoreLabel word : sentence) {
                    System.out
                            .print(word.word() + '/' + word.get(CoreAnnotations.AnswerAnnotation.class) + ' ');
                }
                System.out.println();
            }

            out = classifier.classifyFile(args[1]);
            for (List<CoreLabel> sentence : out) {
                for (CoreLabel word : sentence) {
                    System.out
                            .print(word.word() + '/' + word.get(CoreAnnotations.AnswerAnnotation.class) + ' ');
                }
                System.out.println();
            }

        } else {

            InputStream stream = new FileInputStream(doc);
            //ParsingExample.class.getResourceAsStream(doc) ;
            //   System.out.println(stream.toString());
            parser.parse(stream, handler, metadata);
            // return handler.toString();
            text = handler.toString();
            String metaValue = metadata.toString();
            // System.out.println("Desc:: "+metadata.get("description"));

            String[] example = new String[1];
            example[0] = text;
            String name = doc.replace("C:\\Users\\Snehal\\Documents\\TREC-Data\\Data", "polar.usc.edu")
                    .replace("\\", ".");
            List<Triple<String, Integer, Integer>> list = classifier.classifyToCharacterOffsets(text);
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("DOI", name);
            jsonObj.put("metadata", metaValue.replaceAll("\\s\\s+|\n|\t", " "));
            JSONArray tempArray = new JSONArray();
            JSONObject tempObj = new JSONObject();
            for (Triple<String, Integer, Integer> item : list) {
                //          String jsonOut="{ DOI:"+name+"  ,"
                //                + ""+item.first() + "\": \"" + text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t"," ")+"\""
                //                + "\"metadata\":\""+metaValue+"\""
                //                + "}";
                // System.out.println(jsonOut);
                tempObj.put(item.first(),
                        text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t", " "));
            }
            tempArray.add(tempObj);
            jsonObj.put("NER", tempArray);
            jsonArray.add(jsonObj);
        }
        // System.out.println("---");

    } catch (Exception e) {
        System.out.println("ERROR : CoreNLP" + "|File Name"
                + doc.replaceAll("C:\\Users\\Snehal\\Documents\\TREC-Data", "") + " direct" + e.toString());
    }
}

From source file:edu.usc.polar.NLTKRest.java

public static void ApacheNLTKRest(String doc, String args[]) {
    try {//from   w ww.j a  v a  2 s.  co m
        String text;
        AutoDetectParser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();

        InputStream stream = new FileInputStream(doc);
        // System.out.println(stream.toString());
        parser.parse(stream, handler, metadata);
        // return handler.toString();
        text = handler.toString();
        //System.out.println(text);
        String metaValue = metadata.toString();
        System.out.println("Desc:: " + metadata.toString());

        String[] example = new String[1];
        example[0] = text;
        String name = doc.replace("C:\\Users\\Snehal\\Documents\\TREC-Data\\Data", "polar.usc.edu");
        //System.out.println(text);
        Map<String, Set<String>> list = tikaNLTKRest(text);
        System.out.println(list);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("DOI", name);
        jsonObj.put("metadata", metaValue.replaceAll("\\s\\s+|\n|\t", " "));
        JSONArray tempArray = new JSONArray();
        JSONObject tempObj = new JSONObject();
        for (Map.Entry<String, Set<String>> entry : list.entrySet()) {
            System.out.println("\"" + entry.getKey() + "/" + ":\"" + entry.getValue() + "\"");
            tempObj.put(entry.getKey(), entry.getValue());
            //          String jsonOut="{ DOI:"+name+"  ,"
            //                + ""+item.first() + "\": \"" + text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t"," ")+"\""
            //                + "\"metadata\":\""+metaValue+"\""
            //                + "}";
            // System.out.println(jsonOut);
            //     tempObj.put(item.first(),text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t"," "));
        }
        tempArray.add(tempObj);
        jsonObj.put("NER", tempArray);
        jsonArray.add(jsonObj);

        // System.out.println("---");

    } catch (Exception e) {
        System.out.println("ERROR : NLTKRest" + "|File Name"
                + doc.replaceAll("C:\\Users\\Snehal\\Documents\\TREC-Data", "") + " direct" + e.toString());
    }
}

From source file:edu.usc.polar.OpenNLP.java

public static void ApacheOpenNLP(String doc, String args[]) {
    try {/*from   w  w  w  . j av  a2  s  .c  om*/
        String text;
        AutoDetectParser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();

        InputStream stream = new FileInputStream(doc);

        //   System.out.println(stream.toString());
        parser.parse(stream, handler, metadata);
        // return handler.toString();
        text = handler.toString();
        String metaValue = metadata.toString();
        System.out.println("Desc:: " + metadata.get("description"));

        String[] example = new String[1];
        example[0] = text;
        String name = doc.replace("C:\\Users\\Snehal\\Documents\\TREC-Data\\Data", "polar.usc.edu");
        Map<String, Set<String>> list = tikaOpenNLP(text);
        System.out.println(combineSets(list));
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("DOI", name);
        jsonObj.put("metadata", metaValue.replaceAll("\\s\\s+|\n|\t", " "));
        JSONArray tempArray = new JSONArray();
        JSONObject tempObj = new JSONObject();
        for (Map.Entry<String, Set<String>> entry : list.entrySet()) {
            System.out.println("\"" + entry.getKey() + "/" + ":\"" + entry.getValue() + "\"");
            tempObj.put(entry.getKey(), entry.getValue());
            //          String jsonOut="{ DOI:"+name+"  ,"
            //                + ""+item.first() + "\": \"" + text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t"," ")+"\""
            //                + "\"metadata\":\""+metaValue+"\""
            //                + "}";
            // System.out.println(jsonOut);
            //     tempObj.put(item.first(),text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t"," "));
        }
        tempArray.add(tempObj);
        jsonObj.put("NER", tempArray);
        jsonArray.add(jsonObj);

        // System.out.println("---");

    } catch (Exception e) {
        System.out.println("ERROR : OpenNLP" + "|File Name"
                + doc.replaceAll("C:\\Users\\Snehal\\Documents\\TREC-Data", "") + " direct" + e.toString());
    }
}