Example usage for org.json.simple JSONArray writeJSONString

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

Introduction

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

Prototype

public static void writeJSONString(List list, Writer out) throws IOException 

Source Link

Usage

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

/**
 * Parse a JSON file from CoNE with authors, and return a JSON which can be read by imeji autocomplete
 * //from   w  w w  .  j a  v a  2s .co m
 * @param cone
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private String parseConeAuthor(String cone) throws IOException {
    Object obj = JSONValue.parse(cone);
    JSONArray array = (JSONArray) obj;
    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("http_purl_org_dc_elements_1_1_title"));
        sendObject.put("family", parseObject.get("http_xmlns_com_foaf_0_1_family_name"));
        sendObject.put("givenname", parseObject.get("http_xmlns_com_foaf_0_1_givenname"));
        sendObject.put("id", parseObject.get("id"));
        sendObject.put("orgs",
                writeJsonArrayToOneString(parseObject.get("http_purl_org_escidoc_metadata_terms_0_1_position"),
                        "http_purl_org_eprint_terms_affiliatedInstitution"));
        sendObject.put("alternatives",
                writeJsonArrayToOneString(parseObject.get("http_purl_org_dc_terms_alternative"), ""));
        result.add(sendObject);
    }
    StringWriter out = new StringWriter();
    JSONArray.writeJSONString(result, out);
    return out.toString();
}

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

private String parseCCLicense(String str) {
    str = "<licences>" + str + "</licences>";
    try {//from  ww w.j  av  a 2 s . c om
        JSONArray json = new JSONArray();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        org.w3c.dom.Document doc = dBuilder.parse(new ByteArrayInputStream(str.getBytes()));
        doc.getDocumentElement().normalize();
        NodeList nList = ((org.w3c.dom.Document) doc).getElementsByTagName("option");
        for (int i = 0; i < nList.getLength(); i++) {
            Node nNode = nList.item(i);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                JSONObject license = new JSONObject();
                Element eElement = (Element) nNode;
                license.put("label", eElement.getTextContent());
                license.put("value", eElement.getTextContent());
                license.put("licenseId", eElement.getAttribute("value"));
                json.add(license);
            }
        }
        StringWriter out = new StringWriter();
        JSONArray.writeJSONString(json, out);
        return out.toString();
    } catch (Exception e) {
        log("Error Parsing CC License", e);
    }
    return str;
}

From source file:at.localhost.vectorworldmap.util.FeatureJSON.java

/**
 * Writes a feature collection as GeoJSON.
 *
 * @param features The feature collection.
 * @param output The output. See {@link GeoJSONUtil#toWriter(Object)} for details.
 *//*from  w w  w .  j a  v  a  2s  . com*/
public void writeFeatureCollection(FeatureCollection features, Object output) throws IOException {
    LinkedHashMap obj = new LinkedHashMap();
    obj.put("type", "FeatureCollection");
    if (encodeFeatureCollectionBounds || encodeFeatureCollectionCRS) {
        final ReferencedEnvelope bounds = features.getBounds();

        if (encodeFeatureCollectionBounds) {
            obj.put("bbox", new JSONStreamAware() {
                public void writeJSONString(Writer out) throws IOException {
                    JSONArray.writeJSONString(Arrays.asList(bounds.getMinX(), bounds.getMinY(),
                            bounds.getMaxX(), bounds.getMaxY()), out);
                }
            });
        }

        if (encodeFeatureCollectionCRS) {
            obj.put("crs", createCRS(bounds.getCoordinateReferenceSystem()));
        }
    }
    if (encodeDistanceTolerance) {
        obj.put("tolerance", Double.toString(distanceTolerance));
    }
    obj.put("features", new FeatureCollectionEncoder(features, gjson));
    GeoJSONUtil.encode(obj, output);
}

From source file:org.mskcc.cbio.portal.servlet.ClinicalAttributesServlet.java

/**
 * Takes any sort of patient list parameter in the request
 *
 * Returns a list of clinical attributes in json format
 *
 * @param request//from   w ww  .jav a  2s.com
 * @param response
 * @throws ServletException
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        JSONArray toWrite = new JSONArray();
        response.setContentType("text/json");

        int cancerStudyId = DaoCancerStudy
                .getCancerStudyByStableId(WebserviceParserUtils.getCancerStudyId(request)).getInternalId();
        List<ClinicalAttribute> clinicalAttributes = DaoClinicalAttribute.getDataByStudy(cancerStudyId);

        for (ClinicalAttribute attr : clinicalAttributes) {
            toWrite.add(ClinicalJSON.reflectToMap(attr));
        }
        PrintWriter out = response.getWriter();
        JSONArray.writeJSONString(toWrite, out);
    } catch (DaoException e) {
        throw new ServletException(e);
    } catch (IOException e) {
        throw new ServletException(e);
    }
}

From source file:org.mskcc.cbio.portal.servlet.ClinicalJSON.java

/**
 * Using post request to increase URL length, actually this should not be a POST request
 *
 * @param request//from   w ww  . j  a v a  2  s.c o m
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String query = request.getParameter("q");
    String type = request.getParameter("t");

    String samples = request.getParameter("samples");
    String cancerStudyId = request.getParameter("cancer_study_id");

    List<ClinicalData> clinicals;
    JSONArray maps = null;

    try {
        if (samples == null || samples.equals(ALL)) {
            clinicals = DaoClinicalData.getData(cancerStudyId);
            maps = clinicals2JSONArray(clinicals);
        } else {
            clinicals = DaoClinicalData.getData(cancerStudyId,
                    Arrays.asList(samples.trim().split(SAMPLES_DELIMITER)));
            maps = clinicals2JSONArray(clinicals);
        }
    } catch (DaoException e) {
        throw new ServletException(e);
    }

    for (ClinicalData c : clinicals) {
        maps.add(reflectToMap(c));
    }

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    JSONArray.writeJSONString(maps, out);
}

From source file:org.mskcc.cbio.portal.servlet.GeneDataJSON.java

/**
 *
 * @param request/*  w ww . j av a  2 s.  com*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // OncoQuery Language string
    String oql = request.getParameter("oql");

    if (request instanceof XssRequestWrapper) {
        oql = ((XssRequestWrapper) request).getRawParameter("oql");
    }

    oql = oql.replaceAll("\n", " \n ");

    List<String> sampleIdList;
    try {
        sampleIdList = WebserviceParserUtils.getSampleIds(request);
    } catch (ProtocolException e) {
        throw new ServletException(e);
    } catch (DaoException e) {
        throw new ServletException(e);
    }

    String _geneticProfileIds = request.getParameter("geneticProfileIds");
    // list of geneticProfileIds separated by a space
    // e.g. gbm_mutations, gbm_cna_consensus

    HashSet<String> geneticProfileIdSet = new HashSet<String>(
            Arrays.asList(_geneticProfileIds.trim().split(" ")));

    // map geneticProfileIds -> geneticProfiles
    Iterator<String> gpSetIterator = geneticProfileIdSet.iterator();
    ArrayList<GeneticProfile> profileList = new ArrayList<GeneticProfile>();
    while (gpSetIterator.hasNext()) {
        String gp_str = gpSetIterator.next();

        GeneticProfile gp = DaoGeneticProfile.getGeneticProfileByStableId(gp_str);
        profileList.add(gp);
        // pointer to gp is local, but gets added to profileList which is outside
    }

    double zScoreThreshold = Double.valueOf(request.getParameter("z_score_threshold"));
    double rppaScoreThreshold = Double.valueOf(request.getParameter("rppa_score_threshold"));

    // todo: this is code duplication!
    // this is a duplication of work that is being done in QueryBuilder.
    // For now, we cannot remove it from QueryBuilder because other parts use it...for now
    // ...this is a temporary solution
    ParserOutput theOncoPrintSpecParserOutput = OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(oql,
            geneticProfileIdSet, profileList, zScoreThreshold, rppaScoreThreshold);

    ArrayList<String> listOfGenes = theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes();

    String[] listOfGeneNames = new String[listOfGenes.size()];
    listOfGeneNames = listOfGenes.toArray(listOfGeneNames);

    ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>();
    Iterator<String> profileIterator = geneticProfileIdSet.iterator();

    XDebug xdebug = new XDebug(request);
    while (profileIterator.hasNext()) {
        String profileId = profileIterator.next();
        GeneticProfile profile = GeneticProfileUtil.getProfile(profileId, profileList);
        if (null == profile) {
            continue;
        }

        xdebug.logMsg(this, "Getting data for:  " + profile.getProfileName());

        GetProfileData remoteCall;
        List<Sample.Type> excludes = new ArrayList<Sample.Type>();
        excludes.add(Sample.Type.SOLID_NORMAL);
        excludes.add(Sample.Type.BLOOD_NORMAL);
        String sampleIds = StringUtils.join(sampleIdList, " ");

        try {
            remoteCall = new GetProfileData(profile, listOfGenes, sampleIds);
        } catch (DaoException e) {
            throw new ServletException(e);
        }
        ProfileData pData = remoteCall.getProfileData();
        if (pData == null) {
            System.err.println("pData == null");
        } else {
            if (pData.getGeneList() == null) {
                System.err.println("pData.getValidGeneList() == null");
            }
            if (pData.getCaseIdList().size() == 0) {
                System.err.println("pData.length == 0");
            }
        }
        if (pData != null) {
            xdebug.logMsg(this, "Got number of genes:  " + pData.getGeneList().size());
            xdebug.logMsg(this, "Got number of cases:  " + pData.getCaseIdList().size());
        }
        xdebug.logMsg(this, "Number of warnings received:  " + remoteCall.getWarnings().size());
        profileDataList.add(pData);
    }

    xdebug.logMsg(this, "Merging Profile Data");
    ProfileMerger merger = new ProfileMerger(profileDataList);
    ProfileData mergedProfile = merger.getMergedProfile();

    ProfileDataSummary dataSummary = new ProfileDataSummary(mergedProfile,
            theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold, rppaScoreThreshold);

    GeneticEvent geneticEvents[][] = ConvertProfileDataToGeneticEvents.convert(dataSummary, listOfGeneNames,
            theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold, rppaScoreThreshold);

    // out.write the matrix

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    JSONArray jsonArray = mapGeneticEventMatrix(geneticEvents);
    JSONArray.writeJSONString(jsonArray, out);
}

From source file:org.mskcc.cbio.portal.servlet.PancancerMutationsJSON.java

/**
 * the request requires a parameter "mutation_keys" which is a JSON list of strings.
 *
 * @param request/* ww  w.ja v a2 s  .c  o m*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Collection<Map<String, Object>> data = null;
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");

    String cmd = request.getParameter("cmd");
    String query = request.getParameter("q");

    if (query == null || query.equals("")) {
        throw new ServletException("no q parameter provided");
    }
    List<String> queryTerms = Arrays.asList(query.split(","));

    if (cmd.equals("byKeywords")) {
        try {
            data = byKeywords(queryTerms);
        } catch (DaoException e) {
            throw new ServletException(e);
        } catch (ProtocolException e) {
            throw new ServletException(e);
        }
    } else if (cmd.equals("byHugos")) {
        try {
            data = byHugos(queryTerms);
        } catch (DaoException e) {
            throw new ServletException(e);
        } catch (ProtocolException e) {
            throw new ServletException(e);
        }
    } else if (cmd.equals("byMutations")) {
        try {
            data = byProteinChanges(queryTerms);
        } catch (DaoException e) {
            throw new ServletException(e);
        } catch (ProtocolException e) {
            throw new ServletException(e);
        }
    } else if (cmd.equals("byProteinPos")) {
        try {
            data = byProteinPosStarts(queryTerms);
        } catch (DaoException e) {
            throw new ServletException(e);
        } catch (ProtocolException e) {
            throw new ServletException(e);
        }
    } else {
        throw new ServletException("cmd not found");
    }

    JSONArray.writeJSONString((List) data, writer);
}

From source file:uk.co.didz.hypersignsbukkit.HyperSignsBukkit.java

/**
 * Attempt to save signs. If the data file doesn't exist, create it.
 *///from www. j a va 2  s .  co  m
protected void saveSignsData() {
    File signsFile = new File(getDataFolder(), "signs.json");
    FileWriter fileWriter;
    try {
        fileWriter = new FileWriter(signsFile);
    } catch (IOException e) {
        log.severe("Unable to open signs.json for writing.");
        e.printStackTrace();
        return;
    }

    List<Map<String, Object>> signsList = new ArrayList<Map<String, Object>>();

    for (Entry<Location, URL> entry : loadedSigns.entrySet()) {
        Location location = entry.getKey();
        URL url = entry.getValue();

        // Using LinkedHashMap for the insertion-order retention
        Map<String, Object> obj = new LinkedHashMap<String, Object>();
        obj.put("world", location.getWorld().getName());
        obj.put("x", (int) location.getX());
        obj.put("y", (int) location.getY());
        obj.put("z", (int) location.getZ());
        obj.put("url", url.toString());
        signsList.add(obj);
    }

    try {
        // Save the file
        JSONArray.writeJSONString(signsList, fileWriter);
        fileWriter.close();
    } catch (IOException e) {
        log.severe("Unable to open signs.json for writing.");
        e.printStackTrace();
        return;
    }
}