Example usage for org.json.simple JSONArray addAll

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

Introduction

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

Prototype

public boolean addAll(Collection<? extends E> c) 

Source Link

Document

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

Usage

From source file:biomine.bmvis2.pipeline.sources.QueryGraphSource.java

@Override
public JSONObject toJSON() {
    JSONObject ret = new JSONObject();
    JSONArray queryArr = new JSONArray();
    queryArr.addAll(query);
    ret.put("query", queryArr);
    ret.put("neighborhood", new Boolean(neighborhood));
    return ret;// www.  j a v a 2s  .  com
}

From source file:br.bireme.prvtrm.PreviousTermServlet.java

/**
 * Processes requests for both HTTP//from w  w  w . 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(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json; charset=UTF-8");
    final PrintWriter out = response.getWriter();

    try {
        final String init = request.getParameter("init");
        if (init == null) {
            throw new ServletException("missing 'init' parameter");
        }

        int maxSize = previous.getMaxSize();
        String maxTerms = request.getParameter("maxTerms");
        if (maxTerms != null) {
            maxSize = Integer.parseInt(maxTerms);
        }

        List<String> fields = previous.getFields();
        String fldsParam = request.getParameter("fields");
        if (fldsParam != null) {
            fields = Arrays.asList(fldsParam.split("[,;\\-]"));
        }

        final List<String> terms;
        String direction = request.getParameter("direction");
        if ((direction == null) || (direction.compareToIgnoreCase("next") == 0)) {
            terms = previous.getNextTerms(init, fields, maxSize);
            direction = "next";
        } else {
            terms = previous.getPreviousTerms(init, fields, maxSize);
            direction = "previous";
        }

        final JSONObject jobj = new JSONObject();
        final JSONArray jlistTerms = new JSONArray();
        final JSONArray jlistFields = new JSONArray();

        jlistTerms.addAll(terms);
        jlistFields.addAll(fields);
        jobj.put("init", init);
        jobj.put("direction", direction);
        jobj.put("maxTerms", maxSize);
        jobj.put("fields", jlistFields);
        jobj.put("terms", jlistTerms);

        out.println(jobj.toJSONString());
    } finally {
        out.close();
    }
}

From source file:com.p000ison.dev.simpleclans2.JSONFlags.java

@Override
public String serialize() {
    if (data.isEmpty()) {
        return null;
    }/*  ww  w .  ja v a2 s  . co  m*/
    JSONObject json = new JSONObject();

    for (Map.Entry<String, Object> entry : data.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (key == null || value == null) {
            continue;
        }

        if (value instanceof Collection) {
            Collection collection = (Collection) value;
            if (collection.isEmpty()) {
                continue;
            }
            JSONArray list = new JSONArray();
            list.addAll(collection);
            value = list;
        }

        json.put(key, value);
    }

    return json.toJSONString();
}

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

public JSONObject toJSONObject() {
    JSONObject object = new JSONObject();
    if (billable != null) {
        object.put("billable", billable);
    }//from   ww w  . j  a v  a2 s  .  c  om
    if (description != null) {
        object.put("description", description);
    }
    if (duration != 0) {
        object.put("duration", duration);
    }
    if (id != null) {
        object.put("id", id);
    }
    if (duronly != null) {
        object.put("duronly", duronly);
    }
    if (start != null) {
        object.put("start", DateUtil.convertDateToString(start));
    }
    if (stop != null) {
        object.put("stop", DateUtil.convertDateToString(stop));
    }
    if (created_with != null) {
        object.put("created_with", created_with);
    }

    if (!this.tag_names.isEmpty()) {
        JSONArray tag_names_arr = new JSONArray();
        tag_names_arr.addAll(this.tag_names);
        object.put("tags", tag_names_arr);
    }

    if (project != null) {
        object.put("project", this.project.toJSONObject());
    }
    if (pid != null) {
        object.put("pid", this.pid);
    }
    if (workspace != null) {
        object.put("workspace", this.workspace.toJSONObject());
    }
    if (wid != null) {
        object.put("wid", this.wid);
    }
    if (tid != null) {
        object.put("tid", this.tid);
    }
    return object;
}

From source file:com.mediaworx.intellij.opencmsplugin.connector.OpenCmsPluginConnector.java

/**
 * Internal utility method to convert a List of Strings into a JSON array
 * @param list The List of Strings to be converted
 * @return the list of Strings converted into a JSON array
 *///w  w w. ja v a  2 s . c om
@SuppressWarnings("unchecked")
private String getJSONArrayForStringList(List<String> list) {
    JSONArray jsonArray = new JSONArray();
    jsonArray.addAll(list);
    return jsonArray.toJSONString();
}

From source file:com.nubits.nubot.RPC.NuRPCClient.java

private JSONObject invokeRPC(String id, String method, List params) {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    JSONObject json = new JSONObject();
    json.put("id", id);
    json.put("method", method);
    if (null != params) {
        JSONArray array = new JSONArray();
        array.addAll(params);
        json.put("params", params);
    }//from  w w w  .  jav  a2s. c o  m
    JSONObject responseJsonObj = null;
    try {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(this.ip, this.port),
                new UsernamePasswordCredentials(this.rpcUsername, this.rpcPassword));
        StringEntity myEntity = new StringEntity(json.toJSONString());
        if (Global.options.verbose) {
            LOG.info("RPC : " + json.toString());
        }
        HttpPost httppost = new HttpPost("http://" + this.ip + ":" + this.port);
        httppost.setEntity(myEntity);

        if (Global.options.verbose) {
            LOG.info("RPC executing request :" + httppost.getRequestLine());
        }
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        if (Global.options.verbose) {
            LOG.info("RPC----------------------------------------");
            LOG.info("" + response.getStatusLine());

            if (entity != null) {
                LOG.info("RPC : Response content length: " + entity.getContentLength());
            }
        }
        JSONParser parser = new JSONParser();
        String entityString = EntityUtils.toString(entity);
        LOG.debug("Entity = " + entityString);
        /* TODO In case of wrong username/pass the response would be the following .Consider parsing it.
        Entity = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
                <HTML>
                <HEAD>
                <TITLE>Error</TITLE>
                <META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>
                </HEAD>
                <BODY><H1>401 Unauthorized.</H1></BODY>
                </HTML>
         */
        responseJsonObj = (JSONObject) parser.parse(entityString);
    } catch (ClientProtocolException e) {
        LOG.error("Nud RPC Connection problem:" + e.toString());
        this.connected = false;
    } catch (IOException e) {
        LOG.error("Nud RPC Connection problem:" + e.toString());
        this.connected = false;
    } catch (ParseException ex) {
        LOG.error("Nud RPC Connection problem:" + ex.toString());
        this.connected = false;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return responseJsonObj;
}

From source file:be.iminds.aiolos.ui.NodeServlet.java

@SuppressWarnings("unchecked")
protected void writeJSON(final Writer w, final Locale locale) throws IOException {
    final Collection<NodeInfo> allNodes = this.getNodes();
    final Object[] status = getStatus(allNodes);

    JSONObject obj = new JSONObject();

    JSONArray stat = new JSONArray();
    for (int i = 0; i < status.length; i++)
        stat.add(status[i]);/*  w  ww.  ja  v  a2s  . co m*/
    obj.put("status", stat);

    JSONArray nodes = new JSONArray();
    for (NodeInfo node : allNodes) {
        JSONObject nodeObj = new JSONObject();
        JSONArray components = new JSONArray();

        // TODO extend functionality
        nodeObj.put("id", node.getNodeId());
        nodeObj.put("state", "Unknown"); // TODO hardcoded in javascript
        components.addAll(getComponents(node.getNodeId()));
        nodeObj.put("components", components);
        nodeObj.put("ip", node.getIP());
        //         nodeObj.put("proxy", node.getProxyInfoMap());
        //         nodeObj.put("hostname", node.getHostname());
        if (node.getHttpPort() != -1)
            nodeObj.put("console", "http://" + node.getIP() + ":" + node.getHttpPort() + "/system/console");
        //         nodeObj.put("stoppable", (node.getVMInstance()!=null));
        nodes.add(nodeObj);
    }
    obj.put("nodes", nodes);

    JSONArray components = new JSONArray();
    components.addAll(getComponents());
    obj.put("components", components);

    try {
        JSONArray bndruns = new JSONArray();
        bndruns.addAll(cloudTracker.getService().getBndrunFiles());
        obj.put("bndruns", bndruns);
    } catch (NullPointerException e) {
    }

    w.write(obj.toJSONString());
}

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

@SuppressWarnings("unchecked")
private void printTrackInfo(ResourceRequest request, ResourceResponse response) throws IOException {
    String _rowID = request.getParameter("rowId");
    String pk = request.getParameter("key");

    Gson gson = new Gson();
    String pin_strand = null;/*from   w  ww  . ja v  a  2s  .  c o  m*/
    CRTrack crTrack = null;
    String pseed_ids = null;
    try {
        CRResultSet crRS = gson.fromJson(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk),
                CRResultSet.class);
        pin_strand = crRS.getPinStrand();
        crTrack = crRS.getTrackMap().get(Integer.parseInt(_rowID));
        pseed_ids = crTrack.getSeedIds();
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        LOGGER.debug("{}", SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
    }

    int _window_size = 0;
    try {
        _window_size = Integer
                .parseInt(SessionHandler.getInstance().get(SessionHandler.PREFIX + "_windowsize" + pk));
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        LOGGER.debug("pk:{}, {}", SessionHandler.getInstance().get(SessionHandler.PREFIX + "_windowsize" + pk));
    }

    int features_count = 0;
    try {
        crTrack.relocateFeatures(_window_size, pin_strand);
        Collections.sort(crTrack.getFeatureList());
        features_count = crTrack.getFeatureList().size();
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    }

    Map<String, GenomeFeature> pseedMap = getPSeedMapping(request, pseed_ids);

    // formatting
    JSONArray nclist = new JSONArray();
    CRFeature feature;
    GenomeFeature feature_patric;
    for (int i = 0; i < features_count; i++) {

        feature = crTrack.getFeatureList().get(i);
        feature_patric = pseedMap.get(feature.getfeatureID());

        if (feature_patric != null) {

            JSONArray alist = new JSONArray();

            alist.addAll(Arrays.asList(0, feature.getStartPosition(), feature.getStartString(),
                    feature.getEndPosition(), (feature.getStrand().equals("+") ? 1 : -1), feature.getStrand(),

                    feature_patric.getId(), feature_patric.getPatricId(), feature_patric.getRefseqLocusTag(),
                    feature_patric.getAltLocusTag(), "PATRIC", feature_patric.getFeatureType(),
                    feature_patric.getProduct(),

                    feature_patric.getGene(), feature_patric.getGenomeName(), feature_patric.getAccession(),
                    feature.getPhase()));

            nclist.add(alist);
        }
    }
    // formatter.close();

    JSONObject track = new JSONObject();
    track.put("featureCount", features_count);
    track.put("formatVersion", 1);
    track.put("histograms", new JSONObject());

    JSONObject intervals = new JSONObject();
    JSONArray _clses = new JSONArray();
    JSONObject _cls = new JSONObject();
    _cls.put("attributes",
            Arrays.asList("Start", "Start_str", "End", "Strand", "strand_str", "id", "patric_id",
                    "refseq_locus_tag", "alt_locus_tag", "source", "type", "product", "gene", "genome_name",
                    "accession", "phase"));
    _cls.put("isArrayAttr", new JSONObject());
    _clses.add(_cls);
    intervals.put("classes", _clses);
    intervals.put("lazyClass", 5);
    intervals.put("minStart", 1);
    intervals.put("maxEnd", 20000);
    intervals.put("urlTemplate", "lf-{Chunk}.json");
    intervals.put("nclist", nclist);
    track.put("intervals", intervals);

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

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

@SuppressWarnings("unchecked")
private void printTrackList(ResourceRequest request, ResourceResponse response) throws IOException {

    String contextType = request.getParameter("cType");
    String contextId = request.getParameter("cId");
    String pinFeatureSeedId = request.getParameter("feature"); // pin feature
    String windowSize = request.getParameter("window"); // window size

    int _numRegion = Integer.parseInt(request.getParameter("regions")); // number of genomes to compare
    int _numRegion_buffer = 10; // number of genomes to use as a buffer in case that PATRIC has no genome data,
    // which was retrieved from API
    String _key = "";

    DataApiHandler dataApi = new DataApiHandler(request);

    // if pin feature is not given, retrieve from the database based on na_feature_id
    if (pinFeatureSeedId == null
            && (contextType != null && contextType.equals("feature") && contextId != null)) {

        GenomeFeature feature = dataApi.getFeature(contextId);
        pinFeatureSeedId = feature.getPatricId();
    }/*w w  w  .  j av  a  2 s . c o m*/

    if (pinFeatureSeedId != null && !pinFeatureSeedId.equals("") && windowSize != null) {
        CRResultSet crRS = null;

        try {
            SAPserver sapling = new SAPserver("http://servers.nmpdr.org/pseed/sapling/server.cgi");
            crRS = new CRResultSet(pinFeatureSeedId, sapling.compared_regions(pinFeatureSeedId,
                    _numRegion + _numRegion_buffer, Integer.parseInt(windowSize) / 2));

            long pk = (new Random()).nextLong();
            _key = "" + pk;

            Gson gson = new Gson();
            SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, gson.toJson(crRS, CRResultSet.class));
            SessionHandler.getInstance().set(SessionHandler.PREFIX + "_windowsize" + pk, windowSize);

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        JSONObject trackList = new JSONObject();
        JSONArray tracks = new JSONArray();
        JSONObject trStyle = new JSONObject();
        trStyle.put("className", "feature5");
        trStyle.put("showLabels", false);
        trStyle.put("label", "function( feature ) { return feature.get('patric_id'); }");
        JSONObject trHooks = new JSONObject();
        trHooks.put("modify",
                "function(track, feature, div) { div.style.backgroundColor = ['red','#1F497D','#938953','#4F81BD','#9BBB59','#806482','#4BACC6','#F79646'][feature.get('phase')];}");

        // query genome metadata
        SolrQuery query = new SolrQuery("genome_id:(" + StringUtils.join(crRS.getGenomeIds(), " OR ") + ")");
        query.setFields(
                "genome_id,genome_name,isolation_country,host_name,disease,collection_date,completion_date");
        query.setRows(_numRegion + _numRegion_buffer);

        String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);
        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");

        List<Genome> patricGenomes = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Genome.class);

        int count_genomes = 1;
        if (crRS.getGenomeNames().size() > 0) {
            for (Integer idx : crRS.getTrackMap().keySet()) {
                if (count_genomes > _numRegion) {
                    break;
                }
                CRTrack crTrack = crRS.getTrackMap().get(idx);
                Genome currentGenome = null;
                for (Genome genome : patricGenomes) {
                    if (genome.getId().equals(crTrack.getGenomeID())) {
                        currentGenome = genome;
                    }
                }
                if (currentGenome != null) {
                    count_genomes++;
                    crRS.addToDefaultTracks(crTrack);
                    JSONObject tr = new JSONObject();
                    tr.put("style", trStyle);
                    tr.put("hooks", trHooks);
                    tr.put("type", "FeatureTrack");
                    tr.put("tooltip",
                            "<div style='line-height:1.7em'><b>{patric_id}</b> | {refseq_locus_tag} | {alt_locus_tag} | {gene}<br>{product}<br>{type}:{start}...{end} ({strand_str})<br> <i>Click for detail information</i></div>");
                    tr.put("urlTemplate",
                            "/portal/portal/patric/CompareRegionViewer/CRWindow?action=b&cacheability=PAGE&mode=getTrackInfo&key="
                                    + _key + "&rowId=" + crTrack.getRowID() + "&format=.json");
                    tr.put("key", crTrack.getGenomeName());
                    tr.put("label", "CR" + idx);
                    tr.put("dataKey", _key);
                    JSONObject metaData = new JSONObject();

                    if (currentGenome.getIsolationCountry() != null) {
                        metaData.put("Isolation Country", currentGenome.getIsolationCountry());
                    }
                    if (currentGenome.getHostName() != null) {
                        metaData.put("Host Name", currentGenome.getHostName());
                    }
                    if (currentGenome.getDisease() != null) {
                        metaData.put("Disease", currentGenome.getDisease());
                    }
                    if (currentGenome.getCollectionDate() != null) {
                        metaData.put("Collection Date", currentGenome.getCollectionDate());
                    }
                    if (currentGenome.getCompletionDate() != null) {
                        metaData.put("Completion Date", currentGenome.getCompletionDate());
                    }

                    tr.put("metadata", metaData);
                    tracks.add(tr);
                }
            }
        }
        trackList.put("tracks", tracks);

        JSONObject facetedTL = new JSONObject();
        JSONArray dpColumns = new JSONArray();
        dpColumns.addAll(Arrays.asList("key", "Isolation Country", "Host Name", "Disease", "Collection Date",
                "Completion Date"));
        facetedTL.put("displayColumns", dpColumns);
        facetedTL.put("type", "Faceted");
        facetedTL.put("escapeHTMLInData", false);
        trackList.put("trackSelector", facetedTL);
        trackList.put("defaultTracks", crRS.getDefaultTracks());

        response.setContentType("application/json");
        trackList.writeJSONString(response.getWriter());
        response.getWriter().close();
    } else {
        response.getWriter().write("{}");
    }
}

From source file:com.googlecode.fascinator.common.JsonSimpleConfig.java

@SuppressWarnings(value = { "unchecked" })
private void mergeConfig(Map targetMap, Map srcMap) {
    for (Object key : srcMap.keySet()) {
        Object src = srcMap.get(key);
        Object target = targetMap.get(key);
        if (target == null) {
            targetMap.put(key, src);/*  w ww  . j  a  v  a  2s  .c o m*/
        } else {
            if (src instanceof Map && target instanceof Map) {
                mergeConfig((Map) target, (Map) src);
            } else if (src instanceof JSONArray && target instanceof JSONArray) {
                JSONArray srcArray = (JSONArray) src;
                JSONArray targetArray = (JSONArray) target;
                targetArray.addAll(srcArray);
            } else {
                targetMap.put(key, src);
            }
        }
    }
}