Example usage for org.json.simple JSONObject writeJSONString

List of usage examples for org.json.simple JSONObject writeJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONObject writeJSONString.

Prototype

public void writeJSONString(Writer out) throws IOException 

Source Link

Usage

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);//from w w  w  .j  a  va  2 s  . co  m
    jsonIdTypes.add(grpPATRIC1);
    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:edu.vt.vbi.patric.proteinfamily.FIGfamData.java

@SuppressWarnings("unchecked")
public void getGenomeDetails(ResourceRequest request, PrintWriter writer) throws IOException {

    String cType = request.getParameter("context_type");
    String cId = request.getParameter("context_id");
    String keyword = "";
    if (cType != null && cType.equals("taxon") && cId != null && !cId.equals("")) {
        keyword = "patric_cds:[1 TO *] AND taxon_lineage_ids:" + cId;
    } else if (request.getParameter("keyword") != null) {
        keyword = request.getParameter("keyword");
    }/*from   ww  w.  ja  va 2s . co m*/
    String fields = request.getParameter("fields");

    DataApiHandler dataApi = new DataApiHandler(request);

    SolrQuery query = new SolrQuery(keyword);
    if (fields != null && !fields.equals("")) {
        query.addField(fields);
    }
    query.setRows(DataApiHandler.MAX_ROWS).addSort("genome_name", SolrQuery.ORDER.asc);

    String pk = request.getParameter("param_key");
    Map<String, String> key = null;
    if (pk != null) {
        key = jsonReader.readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
    }

    if (key != null && key.containsKey("genomeIds") && !key.get("genomeIds").equals("")) {
        query.addFilterQuery("genome_id:(" + key.get("genomeIds").replaceAll(",", " OR ") + ")");
    }

    LOGGER.trace("getGenomeDetails(): [{}] {}", SolrCore.GENOME.getSolrCoreName(), query);

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

    int numFound = (Integer) respBody.get("numFound");
    List<Map> sdl = (List<Map>) respBody.get("docs");

    JSONArray docs = new JSONArray();
    for (Map doc : sdl) {
        JSONObject item = new JSONObject();
        item.putAll(doc);
        docs.add(item);
    }

    JSONObject jsonResult = new JSONObject();
    jsonResult.put("results", docs);
    jsonResult.put("total", numFound);
    jsonResult.writeJSONString(writer);
}

From source file:filesscanner.MainWindow.java

private void saveToJSONBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveToJSONBtnActionPerformed

    JSONObject object = new JSONObject();

    for (int i = 0; i < modelFiles.getSize(); i++) {

        object.put("filename" + i, modelFiles.get(i).toString());

    }//  w ww .  j a v a2  s  . c o  m

    File file = new File("C:");
    JFileChooser chooser = ShowChooser(file);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    int res = chooser.showDialog(this, "  ? ??!!!");
    if (res == JFileChooser.APPROVE_OPTION) {

        try {
            Writer writer = new FileWriter(chooser.getSelectedFile());
            object.writeJSONString(writer);
            JOptionPane.showMessageDialog(rootPane, "SAVED SUCCESFULLY!!!");
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(rootPane, "Something bad!!!");
        }

    }

}

From source file:cc.siara.csv_ml_demo.MainActivity.java

/**
 * Transforms csv_ml to JSON Object/*from  w w  w.j  a va  2s  .c  om*/
 */
void toJSON() {
    EditText etInput = (EditText) findViewById(R.id.etInput);
    CheckBox cbPretty = (CheckBox) findViewById(R.id.cbPretty);
    MultiLevelCSVParser parser = new MultiLevelCSVParser();
    try {
        JSONObject jo = parser.parseToJSO(new StringReader(etInput.getText().toString()), false);
        String ex_str = parser.getEx().get_all_exceptions();
        if (ex_str.length() > 0) {
            Toast.makeText(getApplicationContext(), ex_str, Toast.LENGTH_LONG).show();
            if (parser.getEx().getErrorCode() > 0)
                return;
        }
        String outStr = null;
        if (cbPretty.isChecked()) {
            JSONWriter jw = new JSONWriter();
            try {
                jo.writeJSONString(jw);
            } catch (IOException e) {
                e.printStackTrace();
            }
            outStr = jw.toString();
        } else
            outStr = jo.toJSONString();
        EditText etOutput = (EditText) findViewById(R.id.etOutput);
        etOutput.setText(outStr);
        // tfOutputSize.setText(String.valueOf(outStr.length()));
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

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

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    String sraction = request.getParameter("sraction");

    if (sraction != null && sraction.equals("save_params")) {

        Map<String, String> key = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String from = request.getParameter("from");
        String fromGroup = request.getParameter("fromGroup");
        String to = request.getParameter("to");
        String toGroup = request.getParameter("toGroup");

        if (!keyword.equals("")) {
            key.put("keyword", keyword.replaceAll("\n", " OR ").replaceAll(",", " OR "));
        }/*ww w  . ja  va 2  s . c  o  m*/

        key.put("from", from);
        key.put("to", to);
        key.put("fromGroup", fromGroup);
        key.put("toGroup", toGroup);

        // random
        long pk = (new Random()).nextLong();

        SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

        PrintWriter writer = response.getWriter();
        writer.write("" + pk);
        writer.close();
    } else if (sraction != null && sraction.equals("filters")) {
        // this.responseWriteFilters(response);
        this.responseWriteFiltersStatic(response);
    } else if (sraction != null && sraction.equals("download")) {
        processDownload(request, response);
    } else {

        DataApiHandler dataApi = new DataApiHandler(request);

        String pk = request.getParameter("pk");

        Map<String, String> key = jsonReader
                .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));

        LOGGER.debug("id mapping param: {}", key);

        JSONObject jsonResult = processIDMapping(dataApi, key.get("from"), key.get("fromGroup"), key.get("to"),
                key.get("toGroup"), key.get("keyword"));

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

From source file:de.jaide.courier.email.SmtpConfiguration.java

/**
 * Returns the SMTP configuration as a JSON string.
 * //from  w w w. j ava  2  s .  c o m
 * @return The SMTP configuration as a JSON string.
 */
@SuppressWarnings("unchecked")
@Override
public String toJSONString() {
    JSONObject entry = new JSONObject();

    Map<String, Object> configuration = new LinkedHashMap<String, Object>();
    configuration.put("smtpHostname", smtpHostname);
    configuration.put("smtpPort", new Integer(smtpPort));
    configuration.put("tls", tls);
    configuration.put("ssl", ssl);
    configuration.put("username", username);
    configuration.put("password", password);
    configuration.put("fromEMail", fromEMail);
    configuration.put("fromSenderName", fromSenderName);

    entry.put(configurationName, configuration);

    /*
     * The JSONWriter will pretty-print the output
     */
    Writer jsonWriter = new JSONWriter();
    try {
        entry.writeJSONString(jsonWriter);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    return jsonWriter.toString();
}

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

public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    String need = request.getParameter("need");

    DataApiHandler dataApi = new DataApiHandler(request);

    String pathwayClass = request.getParameter("pathway_class");
    String pathwayId = request.getParameter("pathway_id");
    String ecNumber = request.getParameter("ec_number");
    String annotation = request.getParameter("algorithm");
    String contextId = request.getParameter("cId");
    String contextType = request.getParameter("cType");

    JSONObject jsonResult;

    switch (need) {
    case "0":
        jsonResult = this.processPathwayTab(dataApi, pathwayClass, pathwayId, ecNumber, annotation, contextType,
                contextId);//from w w  w. ja va2s.co  m
        response.setContentType("application/json");
        jsonResult.writeJSONString(response.getWriter());
        break;
    case "1":
        jsonResult = this.processEcNumberTab(dataApi, pathwayClass, pathwayId, ecNumber, annotation,
                contextType, contextId);
        response.setContentType("application/json");
        jsonResult.writeJSONString(response.getWriter());
        break;
    case "2":
        jsonResult = this.processGeneTab(dataApi, pathwayClass, pathwayId, ecNumber, annotation, contextType,
                contextId);
        response.setContentType("application/json");
        jsonResult.writeJSONString(response.getWriter());
        break;
    case "filter":
        getFilterData(request, response);
        break;
    case "download":
        this.processDownload(request, response);
        break;
    case "getFeatureIds":
        this.processFeatureIds(request, response);
        break;
    }
}

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

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    String sraction = request.getParameter("sraction");

    if (sraction != null && sraction.equals("save_params")) {

        String search_on = request.getParameter("search_on");
        String keyword = request.getParameter("keyword");
        String taxonId = request.getParameter("taxonId");
        String algorithm = request.getParameter("algorithm");
        String genomeId = request.getParameter("genomeId");
        String feature_id = request.getParameter("feature_id");

        Map<String, String> key = new HashMap<>();

        if (search_on != null) {
            key.put("search_on", search_on.trim());
            if (search_on.equalsIgnoreCase("Map_ID")) {
                key.put("map", keyword.trim());
            } else if (search_on.equalsIgnoreCase("Ec_Number")) {
                key.put("ec_number", keyword.trim());
            } else if (search_on.equalsIgnoreCase("Keyword")) {
                key.put("keyword", keyword.trim());
            }/*  ww  w  .  ja  v  a 2  s . c  om*/
        }
        if (taxonId != null && !taxonId.equals("")) {
            key.put("taxonId", taxonId);
        }

        if (genomeId != null && !genomeId.equals("")) {
            key.put("genomeId", genomeId);
        }

        if (algorithm != null && !algorithm.equals("")) {
            key.put("algorithm", algorithm);
        }

        if (feature_id != null && !feature_id.equals("")) {
            key.put("feature_id", feature_id);
        }

        long pk = (new Random()).nextLong();

        SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

        PrintWriter writer = response.getWriter();
        writer.write("" + pk);
        writer.close();
    } else {

        String need = request.getParameter("need");
        String pk = request.getParameter("pk");
        Map<String, String> key = null;
        if (pk != null && !pk.isEmpty()) {
            key = jsonReader.readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
        }

        DataApiHandler dataApi = new DataApiHandler(request);
        switch (need) {
        case "0":
            JSONObject jsonResult = processPathwayTab(dataApi, key.get("map"), key.get("ec_number"),
                    key.get("algorithm"), key.get("taxonId"), key.get("genomeId"), key.get("keyword"));
            response.setContentType("application/json");
            jsonResult.writeJSONString(response.getWriter());
            break;
        case "1":
            jsonResult = processEcNumberTab(dataApi, key.get("map"), key.get("ec_number"), key.get("algorithm"),
                    key.get("taxonId"), key.get("genomeId"), key.get("keyword"));
            response.setContentType("application/json");
            jsonResult.writeJSONString(response.getWriter());
            break;
        case "2":
            jsonResult = processGeneTab(dataApi, key.get("map"), key.get("ec_number"), key.get("algorithm"),
                    key.get("taxonId"), key.get("genomeId"), key.get("keyword"));
            response.setContentType("application/json");
            jsonResult.writeJSONString(response.getWriter());
            break;
        case "download":
            processDownload(request, response);
            break;
        case "downloadMapFeatureTable":
            processDownloadMapFeatureTable(request, response);
            break;
        }
    }
}

From source file:cc.siara.csv_ml_demo.MultiLevelCSVSwingDemo.java

/**
 * Parses csv_ml from input box to JSON object and sets to output text box
 *//* w w  w. j  ava 2 s  .  c o m*/
void toJSON() {

    try {
        JSONObject jo = parser.parseToJSO(new StringReader(taInput.getText()), false);
        String ex_str = parser.getEx().get_all_exceptions();
        if (ex_str.length() > 0) {
            JOptionPane.showMessageDialog(null, ex_str);
            if (parser.getEx().getErrorCode() > 0)
                return;
        }
        String outStr;
        if (cbPretty.isSelected()) {
            JSONWriter jw = new JSONWriter();
            try {
                jo.writeJSONString(jw);
            } catch (IOException e) {
                e.printStackTrace();
            }
            outStr = jw.toString();
        } else
            outStr = jo.toJSONString();
        taOutput.setText(outStr);
        tfOutputSize.setText(String.valueOf(outStr.length()));
        taOutput.setCaretPosition(0);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
        e.printStackTrace();
    }

}

From source file:com.intel.genomicsdb.GenomicsDBImporter.java

/**
 * Setup the importer after all the buffer streams are added, but before any
 * data is inserted into any stream//from w ww.  j  ava 2  s .  co m
 * No more buffer streams can be added once setupGenomicsDBImporter() is called
 * @throws IOException throws IOException if modified callsets JSON cannot be written
 */
public void setupGenomicsDBImporter() throws IOException {
    if (mIsLoaderSetupDone)
        return;
    //Callset mapping JSON - convert to string
    JSONObject topCallsetJSON = new JSONObject();
    topCallsetJSON.put("callsets", mCallsetMappingJSON);
    StringWriter stringWriter = new StringWriter();
    topCallsetJSON.writeJSONString(stringWriter);
    //Call native setupGenomicsDBImporter()
    mMaxBufferStreamIdentifiers = jniSetupGenomicsDBLoader(mGenomicsDBImporterObjectHandle,
            stringWriter.toString());
    //Why 2* - each identifier is a pair<buffer_stream_idx, partition_idx>
    //Why +1 - the last element will contain the number of exhausted stream identifiers
    //when importBatch() is called
    mExhaustedBufferStreamIdentifiers = new long[2 * ((int) mMaxBufferStreamIdentifiers) + 1];
    //Set all streams to empty
    //Add all streams to mExhaustedBufferStreamIdentifiers - this way when importBatch is
    //called the first time all streams' data are written
    for (int i = 0, idx = 0; i < mBufferStreamWrapperVector.size(); ++i, idx += 2) {
        SilentByteBufferStream currStream = mBufferStreamWrapperVector.get(i).mStream;
        currStream.setNumValidBytes(0);
        mExhaustedBufferStreamIdentifiers[idx] = i;
        mExhaustedBufferStreamIdentifiers[idx + 1] = 0;
    }
    //Set number of exhausted buffer streams - all streams are exhausted the first time
    mNumExhaustedBufferStreams = mBufferStreamWrapperVector.size();
    mExhaustedBufferStreamIdentifiers[(int) (2 * mMaxBufferStreamIdentifiers)] = mNumExhaustedBufferStreams;
    mIsLoaderSetupDone = true;
}