Example usage for org.json.simple JSONArray toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:com.imagelake.control.InterfaceDAOImp.java

public String listPrivilages() {
    String sb = "";
    JSONArray ja = new JSONArray();
    try {/*from www  .  ja  va 2  s .c om*/
        String sql3 = "SELECT * FROM user_type WHERE user_type_id!=4";
        PreparedStatement ps3 = DBFactory.getConnection().prepareStatement(sql3);
        ResultSet rs3 = ps3.executeQuery();
        while (rs3.next()) {
            JSONObject jo = new JSONObject();
            jo.put("id", rs3.getString(1));
            jo.put("type", rs3.getString(2));
            ja.add(jo);
        }
        sb = "json=" + ja.toJSONString();
    } catch (Exception e) {
        e.printStackTrace();
        sb = "msg=Internal server error,Please try again later.";
    }
    return sb;
}

From source file:com.orthancserver.SelectImageDialog.java

public String Serialize() {
    JSONArray servers = new JSONArray();

    for (int i = 0; i < root_.getChildCount(); i++) {
        MyTreeNode node = (MyTreeNode) root_.getChildAt(i);
        servers.add(node.GetConnection().Serialize());
    }//www .j  ava2  s .c o  m

    String config = servers.toJSONString();
    return DatatypeConverter.printBase64Binary(config.getBytes());
}

From source file:com.imagelake.control.InterfaceDAOImp.java

public String listInterfaces() {
    String sb = "";
    JSONArray ja = new JSONArray();
    try {/* w w w .  j  av  a2s  .  c o  m*/
        String sql = "SELECT * FROM interfaces";
        PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);

        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            JSONObject jo = new JSONObject();
            jo.put("id", rs.getInt(1));
            jo.put("name", rs.getString(3));
            jo.put("state", rs.getInt(4));
            ja.add(jo);

        }
        sb = "json=" + ja.toJSONString();
    } catch (Exception e) {
        e.printStackTrace();
        sb = "msg=Internal server error,Please try again later.";
    }
    return sb;
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*  ww w .  j a  v a2s.  c o  m*/
@Path("users.json")
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", restParameters = {
        @RestParameter(defaultValue = "0", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING),
        @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(responseCode = SC_OK, description = "The user accounts.") })
@SuppressWarnings("unchecked")
public String getUsersAsJson(@QueryParam("limit") int limit, @QueryParam("offset") int offset)
        throws IOException {
    if (limit < 1) {
        limit = 100;
    }
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("users").setMaxResults(limit).setFirstResult(offset);
        q.setParameter("o", securityService.getOrganization().getId());
        List<JpaUser> jpaUsers = q.getResultList();
        JSONArray jsonArray = new JSONArray();
        for (JpaUser user : jpaUsers) {
            Set<String> roles = user.getRoles();
            jsonArray.add(toJson(new User(user.getUsername(), user.getOrganization(),
                    roles.toArray(new String[roles.size()]))));
        }
        return jsonArray.toJSONString();
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.wso2telco.dep.mediator.executor.ExecutorInfoHostObject.java

private NativeArray getExecutorObjects() {

    Object[] values = executors.values().toArray();
    NativeArray nativeArray = new NativeArray(1);
    JSONArray jsonArray = new JSONArray();

    for (Object obj : values) {

        ExecutorObj executorObj = (ExecutorObj) obj;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("executorName", executorObj.getExecutorName());
        jsonObject.put("executorFQN", executorObj.getFullQulifiedName());

        jsonArray.add(jsonObject);//from  w  w  w .  j a  va  2 s  .  co m
    }

    nativeArray.put(0, nativeArray, jsonArray.toJSONString());
    return nativeArray;
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANCache.java

/**
 * Populates the package map of a given orgName with the package information from the CKAN response.
 * @param packages JSON vector from the CKAN response containing package information
 * @param orgName Organization name/*w ww.j  a v  a 2  s.  c  o  m*/
 * @throws Exception
 */
private void populatePackagesMap(JSONArray packages, String orgName) throws Exception {
    // this check is for debuging purposes
    if (packages.size() == 0) {
        logger.debug("The pacakges list is empty, nothing to cache");
        return;
    } // if

    logger.debug("Packages to be populated: " + packages.toJSONString() + "(orgName=" + orgName + ")");

    // iterate on the packages
    Iterator<JSONObject> iterator = packages.iterator();

    while (iterator.hasNext()) {
        // get the package name
        JSONObject pkg = (JSONObject) iterator.next();
        String pkgName = (String) pkg.get("name");

        // check if the package is in "deleted" state
        String pkgState = pkg.get("state").toString();

        if (pkgState.equals("deleted")) {
            throw new CygnusBadConfiguration("The package exists but it is in a deleted state (orgName="
                    + orgName + ", pkgName=" + pkgName + ")");
        } // if

        // put the package in the tree and in the packages map
        String pkgId = pkg.get("id").toString();
        tree.get(orgName).put(pkgName, new ArrayList<String>());
        pkgMap.put(pkgName, pkgId);
        logger.debug("Package found in CKAN, now cached (orgName=" + orgName + " -> pkgName/pkgId=" + pkgName
                + "/" + pkgId + ")");

        // get the resources
        JSONArray resources = null;

        // this piece of code tries to make the code compatible with CKAN 2.0, whose "organization_show"
        // method returns no resource lists for its packages! (not in CKAN 2.2)
        // more info --> https://github.com/telefonicaid/fiware-connectors/issues/153
        // if the resources list is null we must try to get it package by package
        if (ckanVersion.equals("2.0")) {
            logger.debug("CKAN version is 2.0, try to discover the resources for this package (pkgName="
                    + pkgName + ")");
            resources = discoverResources(pkgName);
        } else { // 2.2 or higher
            logger.debug("CKAN version is 2.2 (or higher), the resources list can be obtained from the "
                    + "organization information (pkgName=" + pkgName + ")");
            resources = (JSONArray) pkg.get("resources");
        } // if else

        // populate the resources map
        logger.debug(
                "Going to populate the resources cache (orgName=" + orgName + ", pkgName=" + pkgName + ")");
        populateResourcesMap(resources, orgName, pkgName, false);
    } // while
}

From source file:hoot.services.controllers.ingest.FileUploadResource.java

/**
 * <NAME>FileUpload Service</NAME>
 * <DESCRIPTION>/*from  w  w  w . ja v a  2  s  .  com*/
 * Purpose of this service is to provide ingest service for uploading shape and osm file and performing ETL operation on the uploaded file(s).
* This service is multipart post service which accepts sigle or multiple files sent by multipart client.
 * </DESCRIPTION>
 * <PARAMETERS>
 *    <TRANSLATION>
 *    Translation script used during OGR ETL process.
 *    </TRANSLATION>
 *    <INPUT_TYPE>
 *    [OSM | OGR ] OSM for osm file and OGR for shapefile.
 *    </INPUT_TYPE>
 *    <INPUT_NAME>
 *    optional input name which is used in hoot db. Defaults to the file name.
 *    </INPUT_NAME>
 * </PARAMETERS>
 * <OUTPUT>
 * Array of job status
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ingest/ingest/upload?TRANSLATION=NFDD.js&INPUT_TYPE=OSM&INPUT_NAME=ToyTest</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * Multipart data
 * </INPUT>
 * <OUTPUT>[{"jobid":"1234-456-789","input":"1234.osm","output":"test_output", "status":"running"}]</OUTPUT>
 * </EXAMPLE>
 * @param translation
 * @param inputType
 * @param inputName
 * @param request
 * @return
 */

@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)
public Response processUpload2(@QueryParam("TRANSLATION") final String translation,
        @QueryParam("INPUT_TYPE") final String inputType, @QueryParam("INPUT_NAME") final String inputName,
        @Context HttpServletRequest request) {
    String etlName = inputName;
    String jobId = UUID.randomUUID().toString();
    JSONArray resA = new JSONArray();

    try {
        // Save multipart data into file
        log.debug("Starting ETL Process for:" + inputName);
        Map<String, String> uploadedFiles = new HashMap<String, String>();
        ;
        Map<String, String> uploadedFilesPaths = new HashMap<String, String>();

        MultipartSerializer ser = new MultipartSerializer();
        ser.serializeUpload(jobId, inputType, uploadedFiles, uploadedFilesPaths, request);

        int shpCnt = 0;
        int osmCnt = 0;
        int fgdbCnt = 0;

        int zipCnt = 0;
        int shpZipCnt = 0;
        int osmZipCnt = 0;
        int fgdbZipCnt = 0;
        List<String> zipList = new ArrayList<String>();

        JSONArray reqList = new JSONArray();
        List<String> inputsList = new ArrayList<String>();

        Iterator it = uploadedFiles.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            String fName = pairs.getKey().toString();
            String ext = pairs.getValue().toString();

            if (etlName == null || etlName.length() == 0) {
                etlName = fName;
            }

            String inputFileName = uploadedFilesPaths.get(fName);
            inputsList.add(inputFileName);

            // for osm
            // for shp
            // for zip - can not mix different types in zip
            //      -- for fgdb zip
            // for fgdb

            JSONObject zipStat = new JSONObject();
            _buildNativeRequest(jobId, fName, ext, inputFileName, reqList, zipStat);
            if (ext.equalsIgnoreCase("zip")) {
                shpZipCnt += (Integer) zipStat.get("shpzipcnt");
                fgdbZipCnt += (Integer) zipStat.get("fgdbzipcnt");
                osmZipCnt += (Integer) zipStat.get("osmzipcnt");

                zipList.add(fName);
                zipCnt++;
            } else {
                shpCnt += (Integer) zipStat.get("shpcnt");
                fgdbCnt += (Integer) zipStat.get("fgdbcnt");
                osmCnt += (Integer) zipStat.get("osmcnt");
            }
        }

        if ((shpZipCnt + fgdbZipCnt + shpCnt + fgdbCnt) > 0 && (osmZipCnt + osmCnt) > 0) {
            throw new Exception("Can not mix osm and ogr type.");
        }

        String batchJobReqStatus = "success";
        String batchJobId = UUID.randomUUID().toString();
        JSONArray jobArgs = _createNativeRequest(reqList, zipCnt, shpZipCnt, fgdbZipCnt, osmZipCnt, shpCnt,
                fgdbCnt, osmCnt, zipList, translation, jobId, etlName, inputsList);

        log.debug("Posting Job Request for Job :" + batchJobId + " With Args: " + jobArgs.toJSONString());
        postChainJobRquest(batchJobId, jobArgs.toJSONString());

        String mergedInputList = StringUtils.join(inputsList.toArray(), ';');
        JSONObject res = new JSONObject();
        res.put("jobid", batchJobId);
        res.put("input", mergedInputList);
        res.put("output", etlName);
        res.put("status", batchJobReqStatus);

        resA.add(res);
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Failed upload: " + ex.toString(), Status.INTERNAL_SERVER_ERROR, log);
    }
    return Response.ok(resA.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANCache.java

/**
 * Populates the resourceName-resource map of a given orgName with the package information from the CKAN response.
 * @param resources JSON vector from the CKAN response containing resource information
 * @param orgName Organization name/*from   w w w.j  a  v a2s. co m*/
 * @param pkgName Package name
 * @param checkExistence If true, checks if the queried resource already exists in the cache
 */
private void populateResourcesMap(JSONArray resources, String orgName, String pkgName, boolean checkExistence) {
    // this check is for debuging purposes
    if (resources.size() == 0) {
        logger.debug("The resources list is empty, nothing to cache");
        return;
    } // if

    logger.debug("Resources to be populated: " + resources.toJSONString() + "(orgName=" + orgName + ", pkgName="
            + pkgName + ")");

    // iterate on the resources
    Iterator<JSONObject> iterator = resources.iterator();

    while (iterator.hasNext()) {
        // get the resource name and id (resources cannot be in deleted state)
        JSONObject factObj = (JSONObject) iterator.next();
        String resourceName = (String) factObj.get("name");
        String resourceId = (String) factObj.get("id");

        // put the resource in the tree and in the resource map
        if (checkExistence) {
            if (tree.get(orgName).get(pkgName).contains(resourceName)) {
                continue;
            } // if
        } // if

        tree.get(orgName).get(pkgName).add(resourceName);
        resMap.put(resourceName, resourceId);
        logger.debug("Resource found in CKAN, now cached (orgName=" + orgName + " -> pkgName=" + pkgName
                + " -> " + "resourceName/resourceId=" + resourceName + "/" + resourceId + ")");
    } // while
}

From source file:generate.ShowArticlesAction.java

public String execute() throws ClassNotFoundException, SQLException, IOException {
    List<DBObject> documents = new ArrayList<>();
    System.out.println("Mark 0");
    try {/*  www. j a v  a 2s .  c  om*/
        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("Major");
        DBCollection collection = db.getCollection("ConceptMap");
        DBCursor cursor = collection.find();
        documents = cursor.toArray();
        cursor.close();
    } catch (MongoException e) {
        System.out.println("ERRRRRORRR: " + e.getMessage());
        return ERROR;
    } catch (UnknownHostException ex) {
        Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Mark 1");
    Map<String, ArrayList<String>> chap_to_section = new HashMap<>();
    Map<String, String> id_to_section = new HashMap<>();
    for (DBObject document : documents) {
        String c_name = document.get("ChapterName").toString();
        boolean has_key = chap_to_section.containsKey(c_name);
        ArrayList<String> sections = new ArrayList<>();
        sections.add(document.get("SectionName").toString());
        if (has_key) {
            sections.addAll(chap_to_section.get(c_name));
            chap_to_section.put(c_name, sections);
        } else {
            chap_to_section.put(c_name, sections);
        }
        id_to_section.put(document.get("SectionName").toString(), document.get("UniqueID").toString());
    }
    FileWriter file = null;
    try {
        file = new FileWriter("/home/chanakya/NetBeansProjects/Concepto/web/Chapters_Sections.json");
    } catch (IOException ex) {
        Logger.getLogger(ShowArticlesAction.class.getName()).log(Level.SEVERE, null, ex);
    }
    JSONArray jarr = new JSONArray();

    for (String key : chap_to_section.keySet()) {
        JSONObject jobj = new JSONObject();
        JSONArray arr = new JSONArray();

        for (String val : chap_to_section.get(key)) {
            JSONObject temp = new JSONObject();
            temp.put("name", val);
            temp.put("id", id_to_section.get(val).toString());
            arr.add(temp);
        }
        jobj.put("sname", arr);
        jobj.put("cname", key);
        jarr.add(jobj);
    }
    System.out.println("Mark 2");
    //JSONObject obj = new JSONObject();
    //obj.put("cmap", jarr);
    file.write(jarr.toJSONString());
    file.flush();
    file.close();
    System.out.println("Mark 3");
    return SUCCESS;
}

From source file:com.telefonica.iot.cygnus.backends.ckan.CKANCache.java

/**
 * Populates the package map of a given orgName with the package information from the CKAN response.
 * @param packages JSON vector from the CKAN response containing package information
 * @param orgName Organization name//from   w w w .j a v a2s  .c  o m
 * @throws Exception
 */
private void populatePackagesMap(JSONArray packages, String orgName) throws Exception {
    // this check is for debuging purposes
    if (packages.size() == 0) {
        LOGGER.debug("The pacakges list is empty, nothing to cache");
        return;
    } // if

    LOGGER.debug("Packages to be populated: " + packages.toJSONString() + "(orgName=" + orgName + ")");

    // iterate on the packages
    Iterator<JSONObject> iterator = packages.iterator();

    while (iterator.hasNext()) {
        // get the package name
        JSONObject pkg = (JSONObject) iterator.next();
        String pkgName = (String) pkg.get("name");

        // check if the package is in "deleted" state
        String pkgState = pkg.get("state").toString();

        if (pkgState.equals("deleted")) {
            throw new CygnusBadConfiguration("The package exists but it is in a deleted state (orgName="
                    + orgName + ", pkgName=" + pkgName + ")");
        } // if

        // put the package in the tree and in the packages map
        String pkgId = pkg.get("id").toString();
        tree.get(orgName).put(pkgName, new ArrayList<String>());
        pkgMap.put(pkgName, pkgId);
        LOGGER.debug("Package found in CKAN, now cached (orgName=" + orgName + " -> pkgName/pkgId=" + pkgName
                + "/" + pkgId + ")");

        // get the resources
        JSONArray resources;

        // this piece of code tries to make the code compatible with CKAN 2.0, whose "organization_show"
        // method returns no resource lists for its packages! (not in CKAN 2.2)
        // more info --> https://github.com/telefonicaid/fiware-cygnus/issues/153
        // if the resources list is null we must try to get it package by package
        if (ckanVersion.equals("2.0")) {
            LOGGER.debug("CKAN version is 2.0, try to discover the resources for this package (pkgName="
                    + pkgName + ")");
            resources = discoverResources(pkgName);
        } else { // 2.2 or higher
            LOGGER.debug("CKAN version is 2.2 (or higher), the resources list can be obtained from the "
                    + "organization information (pkgName=" + pkgName + ")");
            resources = (JSONArray) pkg.get("resources");
        } // if else

        // populate the resources map
        LOGGER.debug(
                "Going to populate the resources cache (orgName=" + orgName + ", pkgName=" + pkgName + ")");
        populateResourcesMap(resources, orgName, pkgName, false);
    } // while
}