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.dubture.twig.core.model.TwigCallable.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void addArgs(List arguments) {

    JSONArray args = new JSONArray();

    for (Object o : arguments) {

        FormalParameter param = (FormalParameter) o;

        if (param == null)
            continue;

        JSONObject arg = new JSONObject();
        ASTNode init = param.getInitialization();

        String defaultValue = init != null ? init.getClass().toString() : "";

        if (init instanceof Scalar) {
            Scalar scalar = (Scalar) init;
            defaultValue = scalar.getValue();

        }//from  ww w.  ja  va 2  s.com

        this.arguments.put(param.getName(), defaultValue);
        arg.put(param.getName(), defaultValue);
        args.add(arg);

    }

    filterArguments = args;

}

From source file:edu.vt.vbi.patric.portlets.IDMapping.java

@SuppressWarnings("unchecked")
private void responseWriteFilters(ResourceResponse response) throws IOException {

    final String idGroupPATRIC = "PATRIC";
    final String idGroupOther = "Other";

    JSONObject grpPATRIC = new JSONObject();
    JSONObject grpPATRIC1 = new JSONObject();
    JSONObject grpPATRIC2 = new JSONObject();
    JSONObject grpPATRIC3 = new JSONObject();
    JSONObject grpPATRIC4 = new JSONObject();

    JSONObject grpRefSeq = new JSONObject();
    JSONObject grpRefSeq1 = new JSONObject();
    JSONObject grpRefSeq2 = new JSONObject();
    JSONObject grpRefSeq3 = new JSONObject();
    JSONObject grpRefSeq4 = new JSONObject();

    JSONObject grpOther = new JSONObject();

    // PATRIC Identifiers
    grpPATRIC.put("id", "<h5>PATRIC Identifier</h5>");
    grpPATRIC.put("value", "");

    grpPATRIC1.put("id", "PATRIC ID");
    grpPATRIC1.put("value", "patric_id");
    grpPATRIC1.put("group", idGroupPATRIC);

    grpPATRIC2.put("id", "Feature ID");
    grpPATRIC2.put("value", "feature_id");
    grpPATRIC2.put("group", idGroupPATRIC);

    grpPATRIC3.put("id", "Alt Locus Tag");
    grpPATRIC3.put("value", "alt_locus_tag");
    grpPATRIC3.put("group", idGroupPATRIC);

    grpPATRIC4.put("id", "P2 Feature ID");
    grpPATRIC4.put("value", "p2_feature_id");
    grpPATRIC4.put("group", idGroupPATRIC);

    // RefSeq Identifiers
    grpRefSeq.put("id", "<h5>RefSeq Identifiers</h5>");
    grpRefSeq.put("value", "");

    grpRefSeq1.put("id", "RefSeq");
    grpRefSeq1.put("value", "protein_id");
    grpRefSeq1.put("group", idGroupPATRIC);

    grpRefSeq2.put("id", "RefSeq Locus Tag");
    grpRefSeq2.put("value", "refseq_locus_tag");
    grpRefSeq2.put("group", idGroupPATRIC);

    grpRefSeq3.put("id", "Gene ID");
    grpRefSeq3.put("value", "gene_id");
    grpRefSeq3.put("group", idGroupPATRIC);

    grpRefSeq4.put("id", "GI");
    grpRefSeq4.put("value", "gi");
    grpRefSeq4.put("group", idGroupPATRIC);

    // Other Identifiers
    grpOther.put("id", "<h5>Other Identifiers</h5>");
    grpOther.put("value", "");

    JSONArray jsonIdTypes = new JSONArray();
    jsonIdTypes.add(grpPATRIC);
    jsonIdTypes.add(grpPATRIC1);//  w  ww  .  ja  v a2  s . co m
    jsonIdTypes.add(grpPATRIC2);
    jsonIdTypes.add(grpPATRIC3);
    jsonIdTypes.add(grpPATRIC4);

    jsonIdTypes.add(grpRefSeq);
    jsonIdTypes.add(grpRefSeq1);
    jsonIdTypes.add(grpRefSeq2);
    jsonIdTypes.add(grpRefSeq3);
    jsonIdTypes.add(grpRefSeq4);

    jsonIdTypes.add(grpOther);
    List<String> otherTypes = getIdTypes();
    for (String type : otherTypes) {
        JSONObject item = new JSONObject();
        item.put("id", type);
        item.put("value", type);
        item.put("group", idGroupOther);

        jsonIdTypes.add(item);
    }
    // add UniProtKB-Accession, for easier processing, treat UniProtKB-Accession as a PATRIC attribute
    JSONObject item = new JSONObject();
    item.put("id", "UniProtKB-ID");
    item.put("value", "UniProtKB-ID");
    item.put("group", idGroupOther);
    int idx = jsonIdTypes.indexOf(item);
    item.put("id", "UniProtKB-Accession");
    item.put("value", "uniprotkb_accession");
    item.put("group", idGroupPATRIC);
    jsonIdTypes.add(idx + 1, item);

    JSONObject json = new JSONObject();
    json.put("id_types", jsonIdTypes);

    response.setContentType("application/json");
    json.writeJSONString(response.getWriter());
}

From source file:br.bireme.mlts.MoreLikeThatServlet.java

/**
 * Processes requests for both HTTP//from w ww  . j  a  v a  2 s.c o  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        final String content = request.getParameter("content");
        final String fieldsName = request.getParameter("fieldsName");

        if (content == null) {
            throw new ServletException("missing 'content' parameter");
        }
        if (fieldsName == null) {
            throw new ServletException("missing 'fieldsName' parameter");
        }
        final String[] fldsName = fieldsName.trim().split(" *, *");
        final StringReader reader = new StringReader(content);
        final List<MoreLikeThat.DocJ> docs = mlt.moreLikeThat(reader, fldsName);
        final JSONObject jobj = new JSONObject();

        if (docs.size() > 0) {
            final MoreLikeThat.DocJ first = docs.get(0);
            final JSONObject fobj = first.doc;
            final JSONObject auxjobj1 = new JSONObject();
            final JSONObject auxjobj2 = new JSONObject();
            final JSONObject auxjobj3 = new JSONObject();
            final JSONObject auxjobj4 = new JSONObject();
            final JSONArray list0 = new JSONArray();
            final JSONArray list1 = new JSONArray();
            final JSONArray list2 = new JSONArray();
            final Object obj = fobj.get("id");
            final String _id = (obj == null) ? Integer.toString(first.hit.doc) : obj.toString();

            auxjobj2.put("q", content);
            for (String fld : fldsName) {
                list0.add(fld);
            }
            auxjobj2.put("fields", list0);
            auxjobj1.put("params", auxjobj2);
            jobj.put("responseHeader", auxjobj1);

            auxjobj3.put("numFound", 1);
            auxjobj3.put("start", 0);
            auxjobj3.put("maxScore", first.hit.score);
            auxjobj3.put("docs", list1);
            fobj.put("score", first.hit.score);
            fobj.put("id", _id);
            list1.add(fobj);
            jobj.put("match", auxjobj3);

            auxjobj4.put("numFound", docs.size());
            auxjobj4.put("start", 0);
            auxjobj4.put("maxScore", first.hit.score);
            auxjobj4.put("docs", list2);

            for (MoreLikeThat.DocJ doc : docs) {
                final JSONObject cobj = doc.doc;
                final Object obj2 = cobj.get("id");
                final String _id2 = (obj2 == null) ? Integer.toString(doc.hit.doc) : obj2.toString();
                cobj.put("score", doc.hit.score);
                cobj.put("id", _id2);
                list2.add(cobj);
            }
            jobj.put("response", auxjobj4);
        }
        out.println(jobj.toJSONString());
    } finally {
        out.close();
    }
}

From source file:com.mythesis.userbehaviouranalysis.ProfileAnalysis.java

/**
 * finds the profiles that match user's interests given his web history
 * @param userID the user's id/* w w w . j a  va  2 s .  com*/
 * @param history the user's web history
 * @param input a txt file that contains the necessary parameters
 */
public void perform(String userID, String[] history, File input) {

    System.out.println("total urls = " + history.length);
    //default parameters
    //number of random queries for each profile
    int numQueriesSuggestion = 5;
    //number of random webpages per query to suggest - total number of suggestions = 
    // numQueriesSuggestion*pagesPerQuerySuggestion
    int pagesPerQuerySuggestion = 1;
    //number of random queries to return as examples for alternatives profiles
    int numQueriesExample = 2;

    //we get the current date/time
    DateTime current = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
    String timestamp = fmt.print(current);

    //update user info - i'll store the results when i'll perform the last analysis
    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("profileAnalysis");
    DBCollection userinfo = db.getCollection("userinfo");
    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put("$set", new BasicDBObject().append("timestamp", timestamp));
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("userID", userID);
    userinfo.update(searchQuery, newDocument, true, false);

    //read the neccessary parameters
    Utils utils = new Utils();
    utils.readInput(input);
    HashMap<String, ArrayList<String>> wordvectors = utils.wordvectors;
    HashMap<String, String> crawlerOutputPaths = utils.crawlerOutputPaths;

    //get the urls' content
    ArrayList<String> webpages = new ArrayList<>();
    ArrayList<String> urls = new ArrayList<>();
    for (int i = 0; i < history.length; i++) {
        WebParser pageParser = new WebParser(history[i]);
        pageParser.parse();
        String content = pageParser.getContent();
        if ("".equals(content) || content == null)
            continue;
        webpages.add(content);
        urls.add(history[i]);
    }

    //calculate the urls' scores
    HashMap<String, double[]> historyScores = new HashMap<>();
    String[] webpagesArr = new String[webpages.size()];
    webpagesArr = webpages.toArray(webpagesArr);
    String[] urlsArr = new String[urls.size()];
    urlsArr = urls.toArray(urlsArr);
    for (String profile : wordvectors.keySet()) {
        Scorer scorer = new Scorer(webpagesArr, urlsArr, wordvectors.get(profile));
        double[] semanticScores = scorer.getSemanticScores();
        double[] relevanceScores = scorer.getRelevanceScores();
        double[] confidenceScores = scorer.getConfidenceScores();
        double[] scores = scoreFormula(semanticScores, relevanceScores, confidenceScores);
        historyScores.put(profile, scores);
    }

    //find the maximum score of every url and get summation of the scores for each profile
    HashMap<String, Double> userProfilesScore = new HashMap<>();
    for (int i = 0; i < webpages.size(); i++) {
        double max = 0.0;
        String info = "undefined";
        for (String profile : historyScores.keySet()) {
            if (historyScores.get(profile)[i] > max) {
                max = historyScores.get(profile)[i];
                info = profile;
            }
        }
        if (!"undefined".equals(info)) {
            Double prevscore = userProfilesScore.get(info);
            userProfilesScore.put(info, (prevscore == null) ? max : prevscore + max);
        }
    }

    //find which profile level has maximum score e.g. if football/level=0 score is greater
    //than football/level=1 score then the user is better described as a football/level=0 user
    HashMap<String, Double> userProfileScores = new HashMap<>();
    HashMap<String, String> userProfileLevels = new HashMap<>();
    for (String s : userProfilesScore.keySet()) {
        String[] info = s.split("/");
        Double prevscore = userProfileScores.get(info[0] + "/" + info[1] + "/");
        if (prevscore == null) {
            userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s));
            userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]);
        } else if (userProfilesScore.get(s) > prevscore) {
            userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s));
            userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]);
        }
    }

    //put the final profiles together in this simple form: domain/profile/level of expertise and rank them
    Double totalScore = 0.0;
    for (String s : userProfileScores.keySet())
        totalScore += userProfileScores.get(s);

    Map<String, Double> userProfiles = new HashMap<>();
    for (String s : userProfileLevels.keySet())
        userProfiles.put(s + userProfileLevels.get(s), round(userProfileScores.get(s) * 100 / totalScore, 2));

    userProfiles = sortByValue(userProfiles);

    //find page suggestions for every profile
    HashMap<String, ArrayList<String>> pageSuggestions = new HashMap<>();
    for (String profile : userProfiles.keySet()) {
        String path = crawlerOutputPaths.get(profile);
        ArrayList<String> suggestions = getSuggestions(path, numQueriesSuggestion, pagesPerQuerySuggestion,
                history);
        pageSuggestions.put(profile, suggestions);
    }

    //find alternative profiles for every profile and representative queries
    HashMap<String, HashMap<String, ArrayList<String>>> alternativeProfiles = new HashMap<>();
    for (String userProfile : userProfiles.keySet()) {
        String[] userProfileInfo = userProfile.split("/");
        HashMap<String, ArrayList<String>> profileQueries = new HashMap<>();
        for (String profile : wordvectors.keySet()) {
            String[] profileInfo = profile.split("/");
            if (profileInfo[0].equals(userProfileInfo[0]) && profileInfo[1].equals(userProfileInfo[1])
                    && !profileInfo[2].equals(userProfileInfo[2])) {
                String path = crawlerOutputPaths.get(profile);
                ArrayList<String> queries = getQueries(path, numQueriesExample);
                for (int i = 0; i < queries.size(); i++) {
                    String query = queries.get(i);
                    queries.set(i, query.substring(query.lastIndexOf("\\") + 1).replace("-query", "")
                            .replace("+", " "));
                }
                profileQueries.put(profile, queries);
            }
        }
        alternativeProfiles.put(userProfile, profileQueries);
    }

    //prepare JSON response
    JSONObject response = new JSONObject();
    response.put("userID", userID);
    response.put("timestamp", timestamp);
    JSONArray list = new JSONArray();

    for (String profile : userProfiles.keySet()) {
        JSONObject profileInfo = new JSONObject();
        profileInfo.put("profile", profile);
        profileInfo.put("score", userProfiles.get(profile));

        JSONArray temp = new JSONArray();
        ArrayList<String> suggestions = pageSuggestions.get(profile);
        for (String s : suggestions)
            temp.add(s);
        profileInfo.put("suggestions", temp);

        JSONArray alternativesArray = new JSONArray();
        for (String s : alternativeProfiles.get(profile).keySet()) {
            JSONObject alternativeInfo = new JSONObject();
            alternativeInfo.put("alternative", s);
            ArrayList<String> queries = alternativeProfiles.get(profile).get(s);
            JSONArray queriesArray = new JSONArray();
            for (String str : queries) {
                queriesArray.add(str);
            }
            alternativeInfo.put("queries", queriesArray);
            alternativesArray.add(alternativeInfo);
        }

        profileInfo.put("alternatives", alternativesArray);
        list.add(profileInfo);
    }
    response.put("profiles", list);
    System.out.println("JSON response is ready: " + response);

    //delete previous analysis and store results
    DBCollection collection = db.getCollection("history");
    BasicDBObject previous = new BasicDBObject();
    previous.put("userID", userID);
    collection.remove(previous);
    DBObject dbObject = (DBObject) JSON.parse(response.toString());
    collection.insert(dbObject);
    System.out.println("I saved the analysis...");

}

From source file:com.romb.hashfon.helper.Helper.java

public String getJson(List list) {
    JSONArray jsonList = new JSONArray();
    for (Object o : list) {
        JSONObject obj1 = new JSONObject();
        for (Field field : o.getClass().getDeclaredFields()) {
            if (!field.getName().equals("serialVersionUID")) {
                field.setAccessible(true);
                String s = "";
                try {
                    s = field.get(o) + "";
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
                }//w  w  w .  j av  a2  s. co m
                obj1.put(field.getName(), s);
            }
        }
        jsonList.add(obj1);
    }
    return jsonList.toJSONString();
}

From source file:mnc.beacon.mainservice.BeaconListForwardService.java

private void checkEvent(final boolean enable) {
    if (enable) {
        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed(new Runnable() {
            @Override// w  w  w.ja v a  2s .co  m
            public void run() {

                Http qq = new Http();
                Map data1 = new HashMap();
                beaconManager = BeaconManager.instance();
                JSONObject sendObject = new JSONObject();
                JSONArray objArray = new JSONArray();
                Iterator<BeaconPacket> iterator = beaconManager.beaconList.iterator();

                while (iterator.hasNext()) {
                    JSONObject obj = new JSONObject();
                    BeaconPacket beacon = iterator.next();
                    obj.put("TIMESTAMP", System.currentTimeMillis());
                    obj.put("UUID", beacon.getUUID());
                    obj.put("MAJOR", beacon.getMajor());
                    obj.put("MINOR", beacon.getMinor());
                    obj.put("TXPOWER", beacon.getPower());
                    obj.put("RSSI", beacon.getRssi());
                    objArray.add(obj);

                }

                sendObject.put("sendData", objArray);
                data1.put("abc", sendObject);
                String resul1t = qq.get("http://164.125.34.173:8080/test.jsp", data1);

                checkEvent(true);
            }
        }, SCAN_PERIOD);

    }

}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Merge two corcode sets//from ww  w  . j  a v a  2  s.  c  o  m
 * @param cc1 the first corcode as a STIL JSON object
 * @param cc2 the second corcode as a STIL JSON object
 * @return a STIL object with the two merged arrays
 */
JSONObject mergeCorcodes(JSONObject cc1, JSONObject cc2) {
    JSONArray iArr = (JSONArray) cc1.get("ranges");
    JSONArray jArr = (JSONArray) cc2.get("ranges");
    String style = (String) cc1.get(JSONKeys.STYLE);
    addAbsoluteOffsets(iArr);
    addAbsoluteOffsets(jArr);
    int i = 0;
    int j = 0;
    JSONArray all = new JSONArray();
    while (i < iArr.size() || j < jArr.size()) {
        if (i == iArr.size())
            all.add(jArr.get(j++));
        else if (j == jArr.size())
            all.add(iArr.get(i++));
        else {
            JSONObject iObj = (JSONObject) iArr.get(i);
            JSONObject jObj = (JSONObject) jArr.get(j);
            int iOffset = ((Number) iObj.get(JSONKeys.OFFSET)).intValue();
            int jOffset = ((Number) jObj.get(JSONKeys.OFFSET)).intValue();
            if (iOffset < jOffset) {
                all.add(iObj);
                i++;
            } else if (jOffset < iOffset) {
                all.add(jObj);
                j++;
            } else // equal
            {
                int iLen = ((Number) iObj.get(JSONKeys.LEN)).intValue();
                int jLen = ((Number) jObj.get(JSONKeys.LEN)).intValue();
                if ((iLen == 0 && jLen != 0) || (iLen > jLen)) {
                    all.add(iObj);
                    i++;
                } else if ((jLen == 0 && iLen != 0) || (jLen > iLen)) {
                    all.add(jObj);
                    j++;
                } else {
                    all.add(iObj);
                    i++;
                }
            }
        }
    }
    JSONObject combined = new JSONObject();
    combined.put(JSONKeys.STYLE, style);
    int prev = 0;
    for (i = 0; i < all.size(); i++) {
        JSONObject jObj = (JSONObject) all.get(i);
        int offset = ((Number) jObj.get(JSONKeys.OFFSET)).intValue();
        int reloff = offset - prev;
        prev = offset;
        jObj.remove(JSONKeys.OFFSET);
        jObj.put(JSONKeys.RELOFF, reloff);
    }
    combined.put(JSONKeys.RANGES, all);
    return combined;
}

From source file:de.mpg.imeji.presentation.servlet.autocompleter.java

/**
 * Parse a json input from Google Geo API
 * /* w  w  w.ja v  a  2s  .  com*/
 * @param google
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private String parseGoogleGeoAPI(String google) throws IOException {
    JSONObject obj = (JSONObject) JSONValue.parse(google);
    JSONArray array = (JSONArray) obj.get("results");
    JSONArray result = new JSONArray();
    for (int i = 0; i < array.size(); ++i) {
        JSONObject parseObject = (JSONObject) array.get(i);
        JSONObject sendObject = new JSONObject();
        sendObject.put("label", parseObject.get("formatted_address"));
        sendObject.put("value", parseObject.get("formatted_address"));
        JSONObject location = (JSONObject) ((JSONObject) parseObject.get("geometry")).get("location");
        sendObject.put("latitude", location.get("lat"));
        sendObject.put("longitude", location.get("lng"));
        result.add(sendObject);
    }
    StringWriter out = new StringWriter();
    result.writeJSONString(out);
    return out.toString();
}

From source file:modelo.ParametrizacionManagers.Tarifas.java

/**
 * //from   ww w  .  j a va2  s  .com
 * Obtiene la informacion de las unidades de medida y
 * guarda todo en un JSONArray para entregarselo a la vista.
 * 
 * @return JSONArray
 * @throws SQLException 
 */
public JSONArray getTarifas() throws SQLException {

    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarTarifas select = new SeleccionarTarifas();
    ResultSet rset = select.getTarifas();

    //Creamos los JSONArray para guardar los objetos JSON
    JSONArray jsonArray = new JSONArray();
    JSONArray jsonArreglo = new JSONArray();
    //Recorremos el ResultSet, armamos el objeto JSON con la info y guardamos
    //en el JSONArray.
    while (rset.next()) {

        //Armamos el objeto JSON con la informacion del registro
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("codigo", rset.getString("CODIGO"));
        jsonObject.put("valor", rset.getString("VALOR"));
        jsonObject.put("codParm", rset.getString("FK_PARAMFISICOQUIMICO"));
        jsonObject.put("descpParm", rset.getString("DESPARM"));

        //Guardamos el JSONObject en el JSONArray y lo enviamos a la vista.
        jsonArray.add(jsonObject.clone());

    }
    select.desconectar();
    jsonArreglo.add(jsonArray);

    return jsonArreglo;

}

From source file:com.rr.generic.ui.calendar.calendarController.java

@RequestMapping(value = "/getEventType.do", method = RequestMethod.GET)
public @ResponseBody JSONArray getEventType(HttpSession session, HttpServletRequest request) throws Exception {

    String eventTypeId = request.getParameter("eventTypeId");
    JSONArray array = new JSONArray();

    calendarEventTypes eventTypeObject = calendarManager.getEventType(Integer.parseInt(eventTypeId));

    array.add(eventTypeObject.getId());
    array.add(eventTypeObject.getProgramId());
    array.add(eventTypeObject.getEventType());
    array.add(eventTypeObject.getEventTypeColor());
    array.add(eventTypeObject.getAdminOnly());

    return array;

}