Example usage for org.json.simple JSONArray get

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

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * The function gets a JSON array with the ratings and returns an average
 * rating value, which is rounded to 0.5.
 * /*from   w  ww.j av a2 s .com*/
 * @param arr
 *            the array with the ratings.
 * 
 * @return the averaged rating value rounded to 0.5-
 */
protected static double calculateAverageRating(JSONArray arr) {
    // check the parameter
    if (arr == null) {
        return -1;
    }

    int accumulatedRatingValue = 0;
    for (int i = 0; i < arr.size(); i++) {
        Map rating = (Map) arr.get(i);
        String ratingValue = (String) rating.get("ratingValue");
        accumulatedRatingValue += Integer.parseInt(ratingValue);
    }

    // round to 0.5
    double toreturn = ((double) accumulatedRatingValue) / ((double) arr.size());
    if ((toreturn - (int) toreturn) > 0.25 && (toreturn - (int) toreturn) < 0.75) {
        toreturn = ((int) toreturn) + 0.5;
    } else if ((toreturn - (int) toreturn) >= 0.75) {
        toreturn = ((int) toreturn) + 1.0;
    } else if ((toreturn - (int) toreturn) <= 0.75) {
        toreturn = ((int) toreturn);
    }

    return toreturn;
}

From source file:com.greatmancode.tools.utils.Updater.java

private boolean read() {
    try {//from   www . j a  va 2 s. c o  m
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", "Updater (by Gravity)");

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            caller.getLogger().warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1))
                .get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            caller.getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            caller.getLogger().warning("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            caller.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
            caller.getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

From source file:gui.WvWReader.java

@Override
public void run() {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    //HttpClient client = new DefaultHttpClient();

    HttpGet request = new HttpGet(
            "https://api.guildwars2.com/v1/wvw/match_details.json?match_id=" + this.matchId);

    HttpResponse response;//from   w ww.ja v  a  2s.  c  om

    String line = "";
    String out = "";

    this.timeDifference = 0;

    while (!this.isInterrupted()) {

        try {

            response = client.execute(request);

            if (response.getStatusLine().toString().contains("200")) {

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")));

                line = "";
                out = "";

                while ((line = rd.readLine()) != null) {

                    out = out + line;
                }

                JSONParser parser = new JSONParser();

                Object obj;

                //this.result.clear();
                this.resultMapRed.clear();
                this.resultMapBlue.clear();
                this.resultMapGreen.clear();
                this.resultMapCenter.clear();
                this.resultMapScores.clear();

                try {

                    obj = parser.parse(out);

                    JSONObject obj2 = (JSONObject) obj;
                    JSONArray data = (JSONArray) obj2.get("maps");
                    JSONArray scores = (JSONArray) obj2.get("scores");

                    /*
                    this.result.put("0", scores.get(0) + ","
                        + scores.get(1) + "," + scores.get(2));*/

                    this.resultMapScores.put("all",
                            new String[] { "" + scores.get(0), "" + scores.get(1), "" + scores.get(2) });

                    for (int i = 0; i < data.size(); i++) {

                        obj2 = (JSONObject) data.get(i);
                        String type = (String) obj2.get("type");
                        scores = (JSONArray) obj2.get("scores");
                        JSONArray innerData = (JSONArray) obj2.get("objectives");

                        this.resultMapScores.put(type,
                                new String[] { "" + scores.get(0), "" + scores.get(1), "" + scores.get(2) });

                        for (int j = 0; j < innerData.size(); j++) {

                            JSONObject innerObj = (JSONObject) innerData.get(j);

                            //this.result.put("" + innerObj.get("id"), "" + innerObj.get("owner"));

                            if (type.equals("RedHome")) {
                                this.resultMapRed.put("" + innerObj.get("id"), innerObj.get("owner"));
                            } else if (type.equals("BlueHome")) {
                                this.resultMapBlue.put("" + innerObj.get("id"), innerObj.get("owner"));
                            } else if (type.equals("GreenHome")) {
                                this.resultMapGreen.put("" + innerObj.get("id"), innerObj.get("owner"));
                            } else {
                                this.resultMapCenter.put("" + innerObj.get("id"), innerObj.get("owner"));
                            }

                            //this.result.put("" + innerObj.get("id"), "" + innerObj.get("owner") + "," + type);
                            //System.out.println(result);
                        }
                    }

                    try {

                        request.releaseConnection();
                        this.wvwOverlayGui.refresh(this.timeDifference);

                        this.timeDifference = 0;

                        Thread.sleep(10000);
                    } catch (InterruptedException ex) {

                        Logger.getLogger(WvWReader.class.getName()).log(Level.SEVERE, null, ex);

                        this.interrupt();
                    }
                } catch (ParseException ex) {

                    try {

                        Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex);

                        request.releaseConnection();
                        //this.wvwOverlayGui.refresh();

                        if (this.timeDifference < 291) {
                            this.timeDifference = this.timeDifference + 3;
                        } else {
                            this.timeDifference = 3;
                        }

                        Thread.sleep(3000);
                    } catch (InterruptedException ex1) {

                        Logger.getLogger(WvWReader.class.getName()).log(Level.SEVERE, null, ex1);

                        this.interrupt();
                    }
                }
            } else {

                try {

                    Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, "Connection error.");

                    request.releaseConnection();
                    //this.wvwOverlayGui.refresh();

                    if (this.timeDifference < 286) {
                        this.timeDifference = this.timeDifference + 13;
                    } else {
                        this.timeDifference = 13;
                    }

                    Thread.sleep(3000);
                } catch (InterruptedException ex) {

                    Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex);

                    this.interrupt();
                }
            }
        } catch (IOException | IllegalStateException ex) {

            try {

                Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);

                request.releaseConnection();
                //this.wvwOverlayGui.refresh();

                if (this.timeDifference < 286) {
                    this.timeDifference = this.timeDifference + 13;
                } else {
                    this.timeDifference = 13;
                }

                Thread.sleep(3000);
            } catch (InterruptedException ex1) {

                Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex1);

                this.interrupt();
            }
        }
    }
}

From source file:com.tremolosecurity.provisioning.core.providers.SugarCRM.java

@Override
public void deleteUser(User user, Map<String, Object> request) throws ProvisioningException {
    try {//from   w  w w . j  av  a 2  s. com

        String sessionId = sugarLogin();
        Gson gson = new Gson();

        SugarGetEntryList sgel = new SugarGetEntryList();
        sgel.setSession(sessionId);
        sgel.setModule_name("Contacts");
        StringBuffer b = new StringBuffer();
        b.append(
                "contacts.id in (SELECT eabr.bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (ea.id = eabr.email_address_id) WHERE eabr.deleted=0 AND ea.email_address = '")
                .append(user.getUserID()).append("')");
        sgel.setQuery(b.toString());
        sgel.setOrder_by("");
        sgel.setOffset(0);
        ArrayList<String> reqFields = new ArrayList<String>();
        reqFields.add("id");
        sgel.setSelect_fields(reqFields);
        sgel.setMax_results(-1);
        sgel.setDeleted(false);
        sgel.setLink_name_to_fields_array(new HashMap<String, List<String>>());

        String searchJson = gson.toJson(sgel);
        String respJSON = execJson(searchJson, "get_entry_list");
        JSONObject jsonObj = (JSONObject) JSONValue.parse(respJSON);
        JSONArray jsonArray = (JSONArray) jsonObj.get("entry_list");

        if (jsonArray.size() == 0) {
            throw new Exception("User " + user.getUserID() + " not found");
        }

        String id = (String) ((JSONObject) jsonArray.get(0)).get("id");

        SugarEntry newContact = new SugarEntry();
        newContact.setSession(sessionId);
        newContact.setModule("Contacts");
        Map<String, String> nvps = new HashMap<String, String>();
        nvps.put("id", id);
        nvps.put("deleted", "1");

        newContact.setName_value_list(nvps);
        String createUserJSON = gson.toJson(newContact);

        execJson(createUserJSON, "set_entry");
    } catch (Exception e) {
        throw new ProvisioningException("Could not delete user", e);
    }

}

From source file:mml.handler.get.MMLGetMMLHandler.java

private void addAbsoluteOffsets(JSONArray arr) {
    int offset = 0;
    for (int i = 0; i < arr.size(); i++) {
        JSONObject jObj = (JSONObject) arr.get(i);
        Number reloff = (Number) jObj.get(JSONKeys.RELOFF);
        offset += reloff.intValue();//from  w w  w  . j a v  a 2s .  c om
        jObj.put(JSONKeys.OFFSET, offset);
    }
}

From source file:com.respam.comniq.Controller.java

private void outputText() {
    JSONParser parser = new JSONParser();
    textArea.setEditable(false);// www.ja va  2s .  c  o m
    String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output";
    try {
        Object obj = parser.parse(new FileReader(path + File.separator + "MovieInfo.json"));
        JSONArray parsedArr = (JSONArray) obj;

        if (parsedArr.size() == 0) {
            textArea.setEditable(false);
            textArea.clear();
            textArea.appendText("No Movies found from the provided Directory !!!");
        } else {
            textArea.clear();
            // Loop JSON Array

            for (int i = 0; i < parsedArr.size(); i++) {
                JSONObject parsedObj = (JSONObject) parsedArr.get(i);
                textArea.setWrapText(true);
                textArea.appendText("Title: " + (String) parsedObj.get("Title") + "\n");
                textArea.appendText("Release Date: " + (String) parsedObj.get("Released") + "\n");
                textArea.appendText("Genre: " + (String) parsedObj.get("Genre") + "\n");

                textArea.appendText(
                        "IMDB Link: " + "http://www.imdb.com/title/" + (String) parsedObj.get("imdbID") + "\n");
                textArea.appendText("IMDB Rating: " + (String) parsedObj.get("imdbRating") + "\n");
                textArea.appendText("Actors: " + (String) parsedObj.get("Actors") + "\n");
                textArea.appendText("Plot: " + (String) parsedObj.get("Plot") + "\n");

                textArea.appendText("\n\n");
            }
            textArea.positionCaret(0);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.searchbox.collection.oppfin.TopicCollection.java

public ItemProcessor<JSONObject, FieldMap> topicProcessor() {
    return new ItemProcessor<JSONObject, FieldMap>() {

        public FieldMap process(JSONObject topicObject) throws IOException {

            /**// w w  w  .  j  a va  2  s . c  o  m
             * Sample Topic object { "tags":[], "callTitle": "Marie
             * Skaodowska-Curie Research and Innovation Staff Exchange
             * (RISE) " , "title": "Marie Skaodowska-Curie Research and
             * Innovation Staff Exchange (RISE)" ,
             * "flags":["Gender","IntlCoop","SSH"],
             * "callIdentifier":"H2020-MSCA-RISE-2014", "description":
             * "Objective:\r\n\r\nThe RISE scheme will promote international
             * and inter-sector collaboration \r\nthrough" ,
             * "callFileName":"h2020-msca-rise-2014",
             * "callDeadline":1398351600000, "callStatus":"Open",
             * "topicFileName":"59-msca-rise-2014",
             * "identifier":"MSCA-RISE-2014" }
             */
            // Populating useful variables
            String topicIdentifier = (String) topicObject.get("identifier");
            String topicFileName = (String) topicObject.get("topicFileName");
            String callFileName = (String) topicObject.get("callFileName");

            // Pulling full HTML description from the web
            String topicDetailHtml = getTopicDescription(topicFileName);
            // Converting HTML to plain text for Solr
            String topicDetailRaw = new HtmlToPlainText().getPlainText(Jsoup.parse(topicDetailHtml));

            // Creating a new enhancedTopic
            JSONObject enhancedTopic = new JSONObject();
            enhancedTopic.put("eur_topic_description_html", topicDetailHtml);
            enhancedTopic.put("eur_topic_description_raw", topicDetailRaw);
            enhancedTopic.put("eur_topic_timestamp", Calendar.getInstance().getTime());
            enhancedTopic.put("eur_topic_topicFileName", topicFileName);
            enhancedTopic.put("eur_topic_identifier", topicIdentifier);

            // Saving the enhanced file
            try {
                File file = new File("output/topics/" + topicFileName + ".json");
                file.getParentFile().mkdirs();

                FileWriter writer = new FileWriter(file);
                writer.write(enhancedTopic.toJSONString());
                writer.flush();
                writer.close();
                LOGGER.debug("File saved under " + file.getAbsolutePath());

                // Saving the list of calls identifiers
                File file2 = new File("output/topics/call_identifiers.txt");
                FileWriter writer2 = new FileWriter(file2, true);
                writer2.write(topicObject.get("callIdentifier") + "\n");
                writer2.flush();
                writer2.close();
            } catch (IOException e) {
                LOGGER.error(e.getLocalizedMessage());
            }

            // Creating the Field Map
            FieldMap doc = new FieldMap();

            // Lazzy Load the call description:
            //TODO check if not found 
            if (callList == null || callList.get(callFileName) == null)
                return null;
            //end check 
            if (!callList.get(callFileName).containsKey("callDescriptionHtml")) {
                getCallDescription(callFileName);
            }

            // Merging
            for (Entry<String, List<Object>> entry : callList.get(callFileName).entrySet()) {
                doc.put(entry.getKey(), entry.getValue());
            }

            LOGGER.info("Inserting call {} into topic {}", callFileName, topicFileName);

            doc.put("docSource", "H2020");
            doc.put("docType", "Funding");
            doc.put("programme", "H2020");

            doc.put("topicIdentifier", topicIdentifier);
            doc.put("topicFileName", topicFileName);
            doc.put("topicTitle", (String) topicObject.get("title"));
            doc.put("topicDescriptionRaw", topicDetailRaw);
            doc.put("topicDescriptionHtml", topicDetailHtml);

            doc.put("topicTags", (JSONArray) topicObject.get("tags"));
            doc.put("topicFlags", (JSONArray) topicObject.get("keywords"));
            //TODO: add debug 
            JSONArray arrDeadline = (JSONArray) topicObject.get("deadlineDatesLong");
            Long lDate = (Long) arrDeadline.get(0);
            String utcDate = df.format(new Date(lDate));
            doc.put("callDeadline", utcDate);
            doc.put("callIdentifier", (String) topicObject.get("callIdentifier"));

            if (LOGGER.isDebugEnabled()) {
                for (String key : doc.keySet()) {
                    LOGGER.debug("field: {}\t{}", key, doc.get(key));
                }
            }

            /*
            * LOGGER.info("***************************");
            * LOGGER.info(doc.toString());
            * LOGGER.info("***************************"); System.exit(0);
             */
            return doc;
        }
    };
}

From source file:com.mp.gw2api.data.GW2APIMap.java

@Override
public void LoadFromJsonText(String text) {
    JSONParser parser = new JSONParser();
    JSONObject json = null;/*from ww  w .  j av a2s.  c o  m*/
    JSONArray ja = null;
    JSONArray jb = null;

    try {
        //Parse json array
        json = (JSONObject) parser.parse(text);

        id = (long) json.get("id");
        name = (String) json.get("name");
        minLevel = (long) json.get("min_level");
        maxLevel = (long) json.get("max_level");
        defFloor = (long) json.get("default_floor");

        ja = (JSONArray) json.get("floors");
        if (ja != null)
            if (ja.size() > 0) {
                floors = new long[ja.size()];
                for (int i = 0; i < ja.size(); i++)
                    floors[i] = (long) ja.get(i);
            }

        region = new GW2APIMapRegion((long) json.get("region_id"), (String) json.get("region_name"));
        continent = new GW2APIMapContinent((long) json.get("continent_id"),
                (String) json.get("continent_name"));

        mapRect = new PointRectangle();
        ja = (JSONArray) json.get("map_rect");
        jb = (JSONArray) ja.get(0);
        mapRect.begin.x = (long) jb.get(0);
        mapRect.begin.y = (long) jb.get(1);
        jb = (JSONArray) ja.get(1);
        mapRect.end.x = (long) jb.get(0);
        mapRect.end.y = (long) jb.get(1);

        contRect = new PointRectangle();
        ja = (JSONArray) json.get("continent_rect");
        jb = (JSONArray) ja.get(0);
        contRect.begin.x = (long) jb.get(0);
        contRect.begin.y = (long) jb.get(1);
        jb = (JSONArray) ja.get(1);
        contRect.end.x = (long) jb.get(0);
        contRect.end.y = (long) jb.get(1);

    } catch (ParseException ex) {
        Logger.getLogger(GW2APIMapList.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:assignment3.Populate.java

CreateUser() {
    try {/*from   w  w  w.  ja v  a  2s.  co m*/

        Class.forName("oracle.jdbc.driver.OracleDriver");

    } catch (ClassNotFoundException e) {

        System.out.println("JDBC Driver Missing");
        e.printStackTrace();
        return;

    }

    System.out.println("Oracle JDBC Driver Connected");

    Connection conn = null;

    try {

        conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "MAYUR", "123456");
        conn.setAutoCommit(false);

        PreparedStatement ps = conn
                .prepareStatement("insert into yelp_user values (?, ?, ?,?, ?, ?,?, ?, ?,?,?)");

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new BufferedReader(new FileReader(
                "C:\\Users\\mayur\\Downloads\\YelpDataset\\YelpDataset-CptS451\\yelp_user.json")));

        //Object obj = parser.parse(new BufferedReader(new FileReader("C:\\Users\\mayur\\Downloads\\YelpDataset\\YelpDataset-CptS451\\yelp_user1.json")));

        JSONArray jsonArray = (JSONArray) (obj);

        // JSONArray jsonArray = (JSONArray)(obj1);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject t = (JSONObject) jsonArray.get(i);

            String c = t.get("yelping_since").toString();

            Date yelping_since = (Date) java.sql.Date.valueOf(c + "-01");

            JSONObject votes = (JSONObject) t.get("votes"); // get all votes details
            Long votes_funny = (Long) votes.get("funny");
            Long votes_useful = (Long) votes.get("useful");
            Long votes_cool = (Long) votes.get("cool");

            Long review_count = (Long) t.get("review_count");
            String name = t.get("name").toString();
            String user_id = t.get("user_id").toString();

            JSONArray friends = (JSONArray) (t).get("friends");
            int numfriends = 0;
            if (friends != null) {
                Iterator<String> iterator = friends.iterator();
                ArrayList<String> friendid_list = new ArrayList<String>();

                while (iterator.hasNext()) {
                    friendid_list.add(iterator.next());
                }

                if (friendid_list != null)
                    numfriends = friendid_list.size();

                friendid_list = null;
                iterator = null;

            }
            Long fans = (Long) t.get("fans");
            double average_stars = (double) t.get("average_stars");
            String type = t.get("type").toString();

            ps.setDate(1, yelping_since);
            ps.setLong(2, votes_funny);
            ps.setLong(3, votes_useful);
            ps.setLong(4, votes_cool);
            ps.setLong(5, review_count);
            ps.setString(6, name);
            ps.setString(7, user_id);
            ps.setLong(8, fans);
            ps.setDouble(9, average_stars);
            ps.setString(10, type);
            ps.setInt(11, numfriends);

            ps.executeUpdate();
            System.out.println("Record inserted " + i);

        }

        conn.commit();

        ps.close();

    } catch (Exception e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;

    }

}

From source file:de.fhg.fokus.odp.middleware.unittest.xTestCKANGateway.java

/**
 * Test the getPackageComments method.//from  ww  w .  j  a  va 2  s  .  c o m
 */
@Test
public void testGetDataSetComments() {
    log.fine("########### GET COMMENTS ###########");
    JSONArray arr = ckanGW.getDataSetComments(DATASET_NAME);

    boolean res = false;
    for (int i = 0; i < arr.size(); i++) {
        Map m = (Map) (arr.get(i));
        log.fine(m.get("userId") + " " + m.get("comment") + " " + m.get("date"));
        String userId = (String) m.get("userId");
        String comment = (String) m.get("comment");
        String date = (String) m.get("date");

        if (userId.equals("niko2") && comment.equals("Bla bla545")) {
            res = true;
        }
    }

    assertEquals(true, res);
}