Example usage for org.json.simple JSONArray toArray

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

Introduction

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

Prototype

public Object[] toArray() 

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

Usage

From source file:fr.ribesg.bukkit.ncore.updater.FileDescription.java

public static SortedMap<String, FileDescription> parse(final String jsonString) {
    final SortedMap<String, FileDescription> result = new TreeMap<>(new Comparator<String>() {

        @Override//www  . ja  va2  s.  c  om
        public int compare(final String a, final String b) {
            return -a.compareTo(b);
        }
    });
    final JSONArray array = (JSONArray) JSONValue.parse(jsonString);
    for (final Object o : array.toArray()) {
        final JSONObject object = (JSONObject) o;
        final String fileName = (String) object.get(FILENAME_KEY);
        final String version = VersionUtil.getVersion((String) object.get(VERSION_KEY));
        final String bukkitVersion = (String) object.get(BUKKIT_VERSION_KEY);
        final String type = (String) object.get(TYPE_KEY);
        final String link = (String) object.get(DOWNLOAD_URL_KEY);
        final FileDescription fileDescription = new FileDescription(fileName, version, link, type,
                bukkitVersion);
        if (VersionUtil.isRelease(version)) {
            result.put(version, fileDescription);
        }
    }
    return result;
}

From source file:org.uom.fit.level2.datavis.controllers.chatController.ChatController.java

@RequestMapping(value = "/allmessage", method = RequestMethod.GET)
public JSONArray AllMessage() {
    JSONArray message = new JSONArray();

    JSONArray messagelength = chatServices.getAllChatDataAllMessage();
    for (int i = 0; i < messagelength.toArray().length; i++) {
        message.add(chatServices.getAllChatData(messagelength.get(i).toString()));
    }/*from w w w.j a va  2  s.com*/
    return message;
}

From source file:com.thesmartweb.swebrank.GoogleResults.java

/**
 * Method to get the results number for a specific query
 * @param quer the query to search for/*from   w ww  . j  av  a 2s. c  om*/
 * @param config_path the directory to get the keys from
 * @return the number of results
 */
public Long Get_Results_Number(String quer, String config_path) {//it gets the results number for a specific query
    long results_number = 0;
    //we connect through the google api JSON custom search
    String check_quer = quer.substring(quer.length() - 1, quer.length());
    char plus = "+".charAt(0);
    char check_plus = check_quer.charAt(0);
    if (check_plus == plus) {
        quer = quer.substring(0, quer.length() - 1);
    }
    String[] keys = GetKeys(config_path);
    int flag_key = 0;
    int i = 0;
    while (flag_key == 0 && i < (keys.length)) {
        try {
            String key = keys[i];
            i++;
            URL link_ur = new URL(
                    "https://www.googleapis.com/customsearch/v1?key=" + key + "&q=" + quer + "&alt=json");
            APIconn apicon = new APIconn();
            String line = apicon.connect(link_ur);
            if (!line.equalsIgnoreCase("fail")) {
                flag_key = 1;
                JSONParser parser = new JSONParser();
                //Create the map
                Map json = (Map) parser.parse(line);
                // Get a set of the entries
                Set set = json.entrySet();
                Object[] obj = set.toArray();
                Map.Entry entry = (Map.Entry) obj[2];
                //get to the second level
                String you = entry.getValue().toString();
                json = (Map) parser.parse(you);
                set = json.entrySet();
                obj = set.toArray();
                entry = (Map.Entry) obj[obj.length - 1];
                //get to the third level
                you = entry.getValue().toString();
                JSONArray json_arr = (JSONArray) parser.parse(you);
                obj = json_arr.toArray();
                you = obj[0].toString();
                //get to the fourth level
                json = (Map) parser.parse(you);
                set = json.entrySet();
                obj = set.toArray();
                entry = (Map.Entry) obj[4];
                results_number = (Long) entry.getValue();
            }
        } catch (MalformedURLException | ParseException ex) {
            Logger.getLogger(GoogleResults.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return results_number;

}

From source file:com.valygard.aohruthless.utils.inventory.InventoryHandler.java

/**
 * Restore the player's inventory back to them.
 *//*from  www. ja v a  2 s .co m*/
public void restoreInventory(Player p) {
    UUID uuid = p.getUniqueId();

    // Grab disk file
    File file = new File(dir, uuid.toString());
    JsonConfiguration json = new JsonConfiguration(dir, uuid.toString());

    // Try to grab the items from memory first
    ItemStack[] items = this.items.remove(p.getName());
    ItemStack[] armor = this.armor.remove(p.getName());

    // If we can't restore from memory, restore from file
    if (items == null || armor == null) {
        JSONArray itemsList = (JSONArray) json.getValue("items");
        JSONArray armorList = (JSONArray) json.getValue("armor");

        // Turn the lists into arrays
        items = (ItemStack[]) itemsList.toArray();
        armor = (ItemStack[]) armorList.toArray();
    }

    // Set the player inventory contents
    p.getInventory().setContents(items);
    p.getInventory().setArmorContents(armor);

    // Delete the file
    file.delete();
}

From source file:eumetsat.pn.solr.SolrFeeder.java

private SolrInputDocument createInputDoc(JSONObject jsObj) {
    SolrInputDocument input = new SolrInputDocument();
    // field values should match schema.xml

    // solr can add new fields on the fly: http://heliosearch.org/solr/getting-started/
    String id = (String) jsObj.get(FILE_IDENTIFIER_PROPERTY);
    input.addField("id", id);

    JSONObject info = (JSONObject) jsObj.get("identificationInfo");
    input.addField("title", info.get("title"));
    input.addField("description", info.get("abstract"));
    if (!info.get("thumbnail").toString().isEmpty()) {
        input.addField("thumbnail_s", info.get("thumbnail"));
    }//from  ww  w  .  j  a  va2s  .c o m

    JSONArray keywords = (JSONArray) info.get("keywords");
    if (!keywords.isEmpty()) {
        input.addField("keywords", keywords.toArray());
    }

    if (!info.get("status").toString().isEmpty()) {
        input.addField("status_s", info.get("status"));
    }

    JSONObject hierarchy = (JSONObject) jsObj.get("hierarchyNames");

    //public static final ImmutableMap<String, String> FACETS2HIERACHYNAMES = ImmutableMap.of("satellites", "hierarchyNames.satellite",
    //"instruments", "hierarchyNames.instrument",
    //"categories", "hierarchyNames.category",
    //"societalBenefitArea", "hierarchyNames.societalBenefitArea",
    //"distribution", "hierarchyNames.distribution");
    if (hierarchy.get("satellite") != null && !hierarchy.get("satellite").toString().isEmpty()) {
        input.addField("satellite_s", hierarchy.get("satellite"));
    }

    if (hierarchy.get("instrument") != null && !hierarchy.get("instrument").toString().isEmpty()) {
        input.addField("instrument_s", hierarchy.get("instrument"));
    }

    JSONArray categories = (JSONArray) hierarchy.get("category");
    if (categories != null && !categories.isEmpty()) {
        input.addField("category", categories);
    }

    JSONArray sbas = (JSONArray) hierarchy.get("societalBenefitArea");
    if (sbas != null && !sbas.isEmpty()) {
        input.addField("societalBenefitArea_ss", sbas);
    }

    Collection<String> distrs = (Collection<String>) hierarchy.get("distribution");
    if (distrs != null && !distrs.isEmpty()) {
        input.addField("distribution_ss", distrs);
    }

    // https://cwiki.apache.org/confluence/display/solr/Spatial+Search
    JSONObject location = (JSONObject) jsObj.get("location");
    String type = (String) location.get("type");
    if ("envelope".equals(type)) {
        StringBuilder envelope = new StringBuilder();
        // ISO2JSON: envelope.add(leftTopPt); envelope.add(rightDownPt);
        JSONArray coords = (JSONArray) location.get("coordinates");
        JSONArray leftTopPoint = (JSONArray) coords.get(0);
        JSONArray rightDownPoint = (JSONArray) coords.get(1);

        // Spatial search envelope: minX, maxX, maxY, minY
        envelope.append("ENVELOPE(").append(leftTopPoint.get(0)).append(", ");
        envelope.append(rightDownPoint.get(0)).append(", ");
        envelope.append(leftTopPoint.get(1)).append(", ");
        envelope.append(rightDownPoint.get(1)).append(")");
        input.addField("boundingbox", envelope.toString());
    } else {
        log.warn("Unsupported location field value: {}", location.toJSONString());
    }

    JSONObject contact = (JSONObject) jsObj.get("contact");
    input.addField("email_s", contact.get("email"));
    input.addField("address_s", contact.get("address"));

    input.addField("xmldoc", jsObj.get("xmldoc"));

    return input;
}

From source file:com.krypc.hl.pr.controller.PatientRecordController.java

@RequestMapping(value = "/invokeChaincode", method = { RequestMethod.POST, RequestMethod.GET })
public ResponseWrapper invokeChaincode(HttpServletRequest request, HttpServletResponse response) {
    logger.info("PatientRecordController---invokeChaincode()--STARTS");
    ResponseWrapper wrapper = new ResponseWrapper();
    String data = request.getParameter("data");
    try {//from  w ww .ja  va2s  .c  o  m
        if (utils.verifychaincode()) {
            if (data != null && !data.isEmpty()) {
                JSONObject invokeData = (JSONObject) new JSONParser().parse(data);
                String functionName = ((String) invokeData.get("functionName"));
                String user = ((String) invokeData.get("user"));
                JSONArray args = ((JSONArray) invokeData.get("args"));
                String[] arr = Arrays.copyOf(args.toArray(), args.toArray().length, String[].class);
                if (!StringUtils.isEmpty(functionName) && !StringUtils.isEmpty(user)) {
                    InvokeRequest invokerequest = new InvokeRequest();
                    ArrayList<String> argss = new ArrayList<>(Arrays.asList(functionName));
                    argss.addAll(Arrays.asList(arr));
                    invokerequest.setArgs(argss);
                    invokerequest.setChaincodeID(utils.getChaincodeName().getChainCodeID());
                    invokerequest.setChaincodeName(utils.getChaincodeName().getTransactionID());
                    invokerequest.setChaincodeLanguage(ChaincodeLanguage.JAVA);
                    Member member = peerMembershipServicesAPI.getChain().getMember(user);
                    wrapper.resultObject = member.invoke(invokerequest);
                } else {
                    wrapper.setError(ERROR_CODES.MANDATORY_FIELDS_MISSING);
                }
            } else {
                wrapper.setError(ERROR_CODES.MANDATORY_FIELDS_MISSING);
            }
        } else {
            wrapper.setError(ERROR_CODES.CHAINCODE_NOT_DEPLOYED);
        }
    } catch (Exception e) {
        wrapper.setError(ERROR_CODES.INTERNAL_ERROR);
        logger.error("PatientRecordController---invokeChaincode()--ERROR " + e);
    }
    logger.info("PatientRecordController---invokeChaincode()--ENDS");
    return wrapper;
}

From source file:com.krypc.hl.pr.controller.PatientRecordController.java

@RequestMapping(value = "/queryChaincode", method = { RequestMethod.POST, RequestMethod.GET })
public ResponseWrapper queryChaincode(HttpServletRequest request, HttpServletResponse response) {
    logger.info("PatientRecordController---queryChaincode()--STARTS");
    ResponseWrapper wrapper = new ResponseWrapper();
    String data = request.getParameter("data");
    try {//from   w w  w.  ja  v  a 2s.com
        if (utils.verifychaincode()) {
            if (data != null && !data.isEmpty()) {
                JSONObject queryData = (JSONObject) new JSONParser().parse(data);
                String functionName = ((String) queryData.get("functionName"));
                String user = ((String) queryData.get("user"));
                JSONArray args = ((JSONArray) queryData.get("args"));
                String[] arr = Arrays.copyOf(args.toArray(), args.toArray().length, String[].class);
                if (!StringUtils.isEmpty(functionName) && !StringUtils.isEmpty(user)) {
                    ArrayList<String> argss = new ArrayList<>(Arrays.asList(functionName));
                    argss.addAll(Arrays.asList(arr));
                    QueryRequest queryrequest = new QueryRequest();
                    queryrequest.setArgs(argss);
                    queryrequest.setChaincodeID(utils.getChaincodeName().getChainCodeID());
                    queryrequest.setChaincodeName(utils.getChaincodeName().getTransactionID());
                    queryrequest.setChaincodeLanguage(ChaincodeLanguage.JAVA);
                    Member member = peerMembershipServicesAPI.getChain().getMember(user);
                    wrapper.resultObject = member.query(queryrequest);
                    wrapper = convertQueryResponse(wrapper);
                } else {
                    wrapper.setError(ERROR_CODES.MANDATORY_FIELDS_MISSING);
                }
            } else {
                wrapper.setError(ERROR_CODES.MANDATORY_FIELDS_MISSING);
            }
        } else {
            wrapper.setError(ERROR_CODES.CHAINCODE_NOT_DEPLOYED);
        }
    } catch (Exception e) {
        wrapper.setError(ERROR_CODES.INTERNAL_ERROR);
        logger.error("PatientRecordController---queryChaincode()--ERROR " + e);
    }
    logger.info("PatientRecordController---queryChaincode()--ENDS");
    return wrapper;
}

From source file:cc.pinel.mangue.storage.MangaStorage.java

public void addManga(Manga manga) throws IOException {
    JSONObject json = null;//from www  .j  a v a  2s .c om

    try {
        json = readJSON();
    } catch (Exception e) {
        // ignored
    }
    if (json == null)
        json = new JSONObject();

    JSONArray jsonMangas = (JSONArray) json.get("mangas");
    if (jsonMangas == null) {
        jsonMangas = new JSONArray();
        json.put("mangas", jsonMangas);
    }

    JSONObject jsonManga = findManga(jsonMangas, manga.getId());
    if (jsonManga == null) {
        jsonManga = new JSONObject();
        jsonManga.put("id", manga.getId());
        jsonManga.put("name", manga.getName());
        jsonManga.put("path", manga.getPath());

        jsonMangas.add(jsonManga);

        Object[] sortedArray = jsonMangas.toArray();
        Arrays.sort(sortedArray, new Comparator() {
            public int compare(Object o1, Object o2) {
                JSONObject manga1 = (JSONObject) o1;
                JSONObject manga2 = (JSONObject) o2;
                return manga1.get("name").toString().compareTo(manga2.get("name").toString());
            }
        });

        JSONArray sortedJSONArray = new JSONArray();
        for (int i = 0; i < sortedArray.length; i++)
            sortedJSONArray.add(sortedArray[i]);
        json.put("mangas", sortedJSONArray);

        writeJSON(json);
    }
}

From source file:com.fujitsu.dc.test.jersey.box.odatacol.UserDataListDeclaredDoubleTest.java

@SuppressWarnings("unchecked")
private JSONArray skipNullResults(JSONArray source, String propertyName) {
    JSONArray result = new JSONArray();
    for (Object item : source.toArray()) {
        if (((JSONObject) item).get(propertyName) == null) {
            continue;
        }/*from   w  ww .jav a2s.  c o  m*/
        result.add(item);
    }
    return result;
}

From source file:org.arkanos.pivotal_analytics.pivotal.PivotalAPI.java

/**
 * Downloads the stories for a given project.
 * //from w  w  w .  ja  v a2 s.c  o  m
 * @param projectID specifies Pivotal ID reference to the Project.
 * @return a vector with a JSON String in an array per iteration.
 */
public Vector<String> downloadProjectContent(int projectID) {
    Vector<String> pages_iterations = new Vector<String>();
    Vector<String> pages_icebox = new Vector<String>();
    int max = 1;
    int current = 0;
    int page = 100000;
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    System.out.println("----------------------------------------");
    try {
        /** Downloading Scheduled via Iterations for data transfer optimization **/
        System.out.println("-- Downloading iterations --");
        HttpGet httpget = new HttpGet(API_LOCATION_URL + "/projects/" + projectID + "/iterations?limit=100000");
        httpget.addHeader("X-TrackerToken", token);
        System.out.println("Executing request for Project Content:\n" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (response.getFirstHeader("X-Tracker-Pagination-Total") != null) {
            max = Integer.parseInt(response.getFirstHeader("X-Tracker-Pagination-Total").getValue());
        }
        if (response.getFirstHeader("X-Tracker-Pagination-Limit") != null) {
            page = Integer.parseInt(response.getFirstHeader("X-Tracker-Pagination-Limit").getValue());
        }
        while (entity != null && current < max) {
            System.out.println("Response content length: " + entity.getContentLength());
            String result = "";
            int r = 0;
            byte[] b = new byte[10240];
            do {

                r = entity.getContent().read(b);
                if (r > 0) {
                    result += new String(b, 0, r);
                }
            } while (r > 0);

            pages_iterations.add(result);

            current += page;
            if (current < max) {
                httpclient.close();
                httpclient = HttpClientBuilder.create().build();
                httpget = new HttpGet(API_LOCATION_URL + "/projects/" + projectID + "/iterations?limit=" + page
                        + "&offset=" + current);
                httpget.addHeader("X-TrackerToken", token);
                System.out.println("Executing request for Project Content:\n" + httpget.getRequestLine());
                response = httpclient.execute(httpget);
                entity = response.getEntity();
                System.out.println(response.getStatusLine());
            }
        }
        httpclient.close();

        /** Downloading the icebox (unscheduled) **/
        max = 1;
        current = 0;
        page = 100000;
        httpclient = HttpClientBuilder.create().build();

        System.out.println("-- Downloading icebox --");
        httpget = new HttpGet(
                API_LOCATION_URL + "/projects/" + projectID + "/stories?limit=100000&with_state=unscheduled");
        httpget.addHeader("X-TrackerToken", token);
        System.out.println("Executing request for Project Content:\n" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (response.getFirstHeader("X-Tracker-Pagination-Total") != null) {
            max = Integer.parseInt(response.getFirstHeader("X-Tracker-Pagination-Total").getValue());
        }
        if (response.getFirstHeader("X-Tracker-Pagination-Limit") != null) {
            page = Integer.parseInt(response.getFirstHeader("X-Tracker-Pagination-Limit").getValue());
        }
        while (entity != null && current < max) {
            System.out.println("Response content length: " + entity.getContentLength());
            String result = "";
            int r = 0;
            byte[] b = new byte[10240];
            do {

                r = entity.getContent().read(b);
                if (r > 0) {
                    result += new String(b, 0, r);
                }
            } while (r > 0);

            pages_icebox.add(result);

            current += page;
            if (current < max) {
                httpclient.close();
                httpclient = HttpClientBuilder.create().build();
                httpget = new HttpGet(API_LOCATION_URL + "/projects/" + projectID + "/iterations?limit=" + page
                        + "&offset=" + current);
                httpget.addHeader("X-TrackerToken", token);
                System.out.println("Executing request for Project Content:\n" + httpget.getRequestLine());
                response = httpclient.execute(httpget);
                entity = response.getEntity();
                System.out.println(response.getStatusLine());
            }
        }
        /**Releasing System and Connection resources**/
        httpclient.close();
    } catch (ClientProtocolException e) {
        System.out.println(
                "[ERROR:ClientProtocolException] Error while downloading file, see error logs for stack trace.");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println(
                "[ERROR:IOException] Error while saving the downloaded file, see error logs for stack trace.");
        e.printStackTrace();
    }
    System.out.println("----------------------------------------");

    JSONParser jp = new JSONParser();
    Vector<String> iterations = new Vector<String>();
    try {
        if (pages_icebox.size() > 0) {
            String icebox = "[";
            for (String p : pages_icebox) {
                icebox += p.substring(1, p.length() - 1) + ",";
            }
            icebox = icebox.substring(0, icebox.length() - 1) + "]";
            iterations.add(icebox);
        } else {
            iterations.add("[]");
        }
        for (String p : pages_iterations) {
            JSONArray ja = (JSONArray) jp.parse(p);
            for (Object i : ja.toArray()) {
                JSONArray stories = (JSONArray) ((JSONObject) i).get("stories");
                iterations.add(stories.toJSONString());
            }
        }
    } catch (ParseException e) {
        System.out.println("[ERROR:ParseException] There was a problem parsing the iterations/icebox.");
        e.printStackTrace();
    }

    return iterations;
}