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:botvn.libraries.StorageCookies.java

public boolean Save() {
    if (mCookieStore != null) {
        FileWriter file = null;/*from   www.j a  v  a 2 s. c  o  m*/
        try {
            List<Cookie> ckss = mCookieStore.getCookies();
            HashMap<String, Object> d;
            JSONArray allCks = new JSONArray();
            for (Cookie cks : ckss) {
                d = new HashMap<>(ckss.size());
                String name = cks.getName();
                long expires = cks.getExpiryDate() != null ? cks.getExpiryDate().getTime() : 0;
                String path = cks.getPath();
                String domain = cks.getDomain();
                boolean secure = cks.isSecure();

                d.put("name", name);
                d.put("expires", expires);
                d.put("path", path);
                d.put("domain", domain);
                d.put("secure", secure);
                allCks.add(d);
            }

            String jsonStr = allCks.toJSONString();
            String currentDir = System.getProperty(USER_DIR);
            file = new FileWriter(currentDir + "/" + COOKIE_FILE);
            file.write(jsonStr);
            file.flush();
            file.close();
            return true;
        } catch (IOException ex) {
            Logger.getLogger(StorageCookies.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return false;
}

From source file:com.telefonica.iot.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  ww .  j a va2s  . c o  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:bhl.pages.handler.PagesListHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws MissingDocumentException {
    try {/*from   w  w  w  .j  a v  a 2  s . c  o m*/
        String docid = request.getParameter(Params.DOCID);
        if (docid != null) {
            Connection conn = Connector.getConnection();
            String[] keys = new String[2];
            keys[0] = JSONKeys.BHL_PAGE_ID;
            keys[1] = JSONKeys.PAGE_SEQUENCE;
            String[] pages = conn.listCollectionBySubKey(Database.PAGES, JSONKeys.IA_IDENTIFIER, docid, keys);
            JSONArray list = new JSONArray();
            for (int i = 0; i < pages.length; i++) {
                JSONObject jobj = (JSONObject) JSONValue.parse(pages[i]);
                Number pageNo = (Number) jobj.get(JSONKeys.PAGE_SEQUENCE);
                Number pageId = (Number) jobj.get(JSONKeys.BHL_PAGE_ID);
                System.out.println("pageNo=" + pageNo + " pageId=" + pageId);
                PageDesc ps = new PageDesc(new Integer(pageNo.intValue()).toString(),
                        new Integer(pageId.intValue()).toString());
                list.add(ps.toJSONObject());
            }
            PagesGetHandler.sortList(list);
            response.setContentType("application/json");
            response.getWriter().print(list.toJSONString());
        } else
            throw new Exception("Must specify document identifier");
    } catch (Exception e) {
        throw new MissingDocumentException(e);
    }
}

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);
                }/* ww w  .  j a  v a 2s  .c  om*/
                obj1.put(field.getName(), s);
            }
        }
        jsonList.add(obj1);
    }
    return jsonList.toJSONString();
}

From source file:net.nexxus.nntp.NntpArticleHeader.java

public String getPartsAsJSON() {
    if (multipart) {
        JSONArray partsArray = new JSONArray();
        for (int x = 0; x < parts.length; x++) {
            // incomplete multiparts have null elements
            if (parts[x] != null) {
                JSONArray part = new JSONArray();
                part.add(parts[x].getId());
                part.add(parts[x].getMsgID());
                partsArray.add(part);//w w  w  . ja  va 2s .  co m
            }
        }
        return partsArray.toJSONString();
    }
    return "";
}

From source file:net.duckling.ddl.web.controller.LynxSearchController.java

private String getJSONFromMap(String baseTagURL, Map<Integer, String> map) {
    JSONArray array = new JSONArray();
    if (null != map && !map.isEmpty()) {

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            JSONObject obj = new JSONObject();
            obj.put("id", entry.getKey());
            obj.put("title", entry.getValue());
            obj.put("tagurl", baseTagURL);
            array.add(obj);/*from w  w w .  ja va2  s  .c om*/
        }
    }
    return array.toJSONString();
}

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

public String getFullSliceDetails() {
    String sb = "";
    JSONArray ja = new JSONArray();
    try {//from   w ww.j a v a2 s.c om

        String sql2 = "SELECT * FROM credits WHERE state='1'";
        PreparedStatement ps2 = DBFactory.getConnection().prepareStatement(sql2);
        ResultSet rs2 = ps2.executeQuery();

        while (rs2.next()) {
            JSONObject jo = new JSONObject();
            jo.put("id", rs2.getInt(1));
            jo.put("credits", rs2.getInt(2));
            jo.put("size", rs2.getString(3));
            jo.put("width", rs2.getInt(4));
            jo.put("height", rs2.getInt(5));
            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.wso2telco.dep.mediator.executor.ExecutorInfoHostObject.java

private NativeArray getHandlerObjects() {

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

    for (Object obj : values) {

        HandlerObj object = (HandlerObj) obj;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("handlerName", object.getHandlerName());
        jsonObject.put("handlerFQN", object.getHandlerFullQulifiedName());

        jsonArray.add(jsonObject);//from  w ww.  jav  a2  s.  c  om

        //NativeObject nativeObject = new NativeObject();
        //nativeObject.put(object.getHandlerName(), nativeObject, object.getHandlerFullQulifiedName());
    }

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

From source file:com.skelril.ShivtrAuth.AuthenticationCore.java

public synchronized void updateWhiteList(JSONArray object) {

    // Load the storage directory
    File charactersDirectory = new File(plugin.getDataFolder().getPath() + "/characters");
    if (!charactersDirectory.exists())
        charactersDirectory.mkdir();/*  ww w  .  j  a  v a  2s  .  c o m*/
    log.info("Updating white list...");

    // Remove outdated JSON backup files
    for (File file : charactersDirectory.listFiles(filenameFilter)) {
        file.delete();
    }

    // Create new JSON backup file
    BufferedWriter out = null;

    File characterList = new File(charactersDirectory, "character-list.json");
    try {
        if (characterList.createNewFile()) {
            out = new BufferedWriter(new FileWriter(characterList));
            out.write(object.toJSONString());
        } else {
            log.warning("Could not create the new character list offline file!");
        }
    } catch (IOException ignored) {
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }
    }

    loadCharacters((JSONObject[]) object.toArray(new JSONObject[object.size()]));

    log.info("The white list has updated successfully.");
}

From source file:com.googlecode.fascinator.transformer.basicVersioning.BasicVersioningTransformer.java

private void createVersionIndex(String rootPath) {
    String jsonPath = rootPath + "/" + "Version_Index.json";
    log.debug("Indexing a version into: " + jsonPath);

    JSONArray jArr = null;
    try {//from   w ww  . j  a v  a  2s.c o m
        File oldf = new File(jsonPath);
        if (oldf.exists()) {
            log.debug("Need to update a version index file: " + jsonPath);
            JsonSimple js = new JsonSimple(oldf);
            jArr = js.getJsonArray();
        } else {
            log.debug("Need to create a new version index file: " + jsonPath);
            jArr = new JSONArray();
        }
        JsonObject newVer = new JsonObject();
        newVer.put("timestamp", getTimestamp());
        newVer.put("file_name", payloadName());
        try {
            jArr.add(newVer);
            try {
                FileWriter fw = new FileWriter(jsonPath);
                fw.write(jArr.toJSONString());
                fw.flush();
                fw.close();
            } catch (IOException e) {
                log.error("Failed to save versioning property file.", e);
            }
        } catch (Exception eStrange) {
            log.error("Failed to add a new version.", eStrange);
        }
    } catch (Exception eOther) {
        log.error("Failed to create/edit versioning property file.", eOther);
    }
}