Example usage for twitter4j JSONObject getJSONArray

List of usage examples for twitter4j JSONObject getJSONArray

Introduction

In this page you can find the example usage for twitter4j JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String name) throws JSONException 

Source Link

Document

Returns the value mapped by name if it exists and is a JSONArray , or throws otherwise.

Usage

From source file:TwitterGateway.java

@Override
public void onStatus(Status status) {
    user = status.getUser().getScreenName();

    String mentionStatus = status.getText();
    System.out.println("@" + user + " - " + mentionStatus);
    String paramScreenName = screenName.toLowerCase();
    mentionStatus = mentionStatus.toLowerCase().replace(paramScreenName, "").trim();
    String locale = new String();
    if (mentionStatus.contains(" to ")) {
        location = mentionStatus.split(" to ");
        locale = "en";
    } else if (mentionStatus.contains(" ke ")) {
        location = mentionStatus.split(" ke ");
        locale = "id";
    } else {/*from   w ww.j a v  a 2s. c  om*/
        location = null;
    }
    boolean statusLocation1 = false;
    boolean statusLocation2 = false;

    if (mentionStatus.equals("help") || mentionStatus.equals(("bantuan"))) {
        try {
            if (mentionStatus.equals("help")) {
                Tweet(user,
                        "For using this Twitter bot for searching public transport route, you can mention...");
                Tweet(user, "'First location' to 'second location', example : BIP to PVJ");
            } else {
                Tweet(user, "Format penggunaan Twitter bot untuk mencari jalur transportasi publik adalah...");
                Tweet(user, "'Lokasi awal' ke 'lokasi tujuan', contoh : BIP ke PVJ.");
            }
        } catch (TwitterException ex) {
            System.out.println("Tweet help error");
        }
    } else if (location.length == 2 && !location[0].contains("@") && !location[1].contains("@")) {
        try {
            if (location[0].equals(location[1])) {
                if (locale.equals("id")) {
                    Tweet(user, "Pencarian tidak dapat dilakukan karena lokasi awal dan lokasi tujuan sama");
                } else if (locale.equals("en")) {
                    Tweet(user, "Route can't be found. Starting location and destination are similar");
                }
            } else {
                System.out.println("Lokasi 1 : " + location[0].trim());
                System.out.println("Lokasi 2 : " + location[1].trim());
                //string destination menampung hasil dari JSONObject hasil pencarian apa saja yang ditemukan dari KIRIGateway.getLatLong
                String destination1 = KIRIGateway.GetLatLong(location[0]);
                String destination2 = KIRIGateway.GetLatLong(location[1]);

                //dimasukan ke JSONObject 
                JSONObject objDest1 = new JSONObject(destination1);
                JSONObject objDest2 = new JSONObject(destination2);

                //memasukan hasil pencarian pertama dari JSONObject ke abribut routingResponse
                JSONObject res1 = objDest1.getJSONArray("searchresult").getJSONObject(0);
                String hasilDest1 = res1.getString("placename");
                latlon[0] = res1.getString("location");
                if (hasilDest1 != null) {
                    statusLocation1 = true;
                }

                JSONObject res2 = objDest2.getJSONArray("searchresult").getJSONObject(0);
                String hasilDest2 = res2.getString("placename");
                latlon[1] = res2.getString("location");
                if (hasilDest2 != null) {
                    statusLocation2 = true;
                }

                //Mendapatkan hasil pencarian lalu dimasukan ke JSONArray paramSteps untuk dipisah-pisah lalu dimasukan ke RoutingResponse
                String hasilPencarian = KIRIGateway.GetTrack(latlon[0], latlon[1], locale);
                JSONObject objTrack = new JSONObject(hasilPencarian);
                JSONObject routingresults = objTrack.getJSONArray("routingresults").getJSONObject(0);
                JSONArray paramSteps = routingresults.getJSONArray("steps");
                //buat variable step, steps, dan routing response
                step = new Step[paramSteps.length()];
                for (int i = 0; i < step.length; i++) {
                    step[i] = new Step(paramSteps.getJSONArray(i).getString(3) + "");
                }
                steps = new Steps(step);

                routingResponse = new RoutingResponse(objTrack.getString("status"), steps);
                if (routingResponse.getStatus().equals("ok")) {
                    for (int i = 0; i < routingResponse.getRoutingResult().getSteps().length; i++) {
                        date = new Date();
                        Tweet(user, routingResponse.getRoutingResult().getSteps()[i].getHumanDescription());
                    }
                    if (locale.equals("id")) {
                        Tweet(user,
                                "Untuk lebih lengkapnya dapat dilihat pada http://kiri.travel?start="
                                        + location[0].replace(" ", "%20") + "&finish="
                                        + location[1].replace(" ", "%20") + "&region=bdo");
                    } else if (locale.equals("en")) {
                        Tweet(user,
                                "For futher information you can visit http://kiri.travel?start="
                                        + location[0].replace(" ", "%20") + "&finish="
                                        + location[1].replace(" ", "%20") + "&region=bdo");
                    }

                    for (int i = 0; i < routingResponse.getRoutingResult().getSteps().length; i++) {
                        System.out.println("@" + user + " "
                                + routingResponse.getRoutingResult().getSteps()[i].getHumanDescription());
                    }
                    System.out.println(
                            "@" + user + " Untuk lebih lengkap silahkan lihat di http://kiri.travel?start="
                                    + location[0].replace(" ", "%20") + "&finish="
                                    + location[1].replace(" ", "%20") + "&region=bdo");
                } else {
                    System.out.println("status error");
                }
            }
        } catch (Exception ex) {
            try {
                if (!statusLocation1) {
                    date = new Date();
                    Tweet(user, location[0] + " tidak ditemukan");
                    System.out.println("@" + user + " " + location[0] + " tidak ditemukan");
                } else if (!statusLocation2) {
                    date = new Date();
                    Tweet(user, location[1] + " tidak ditemukan");
                    System.out.println("@" + user + " " + location[1] + " tidak ditemukan");
                } else {
                    date = new Date();
                    Tweet(user, "Gangguan Koneksi");
                    System.out.println("Gangguan Koneksi");
                }
                //java.util.logging.Logger.getLogger(TwitterGateway.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TwitterException ex1) {
                System.out.println("Error2");
                java.util.logging.Logger.getLogger(TwitterGateway.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }

}

From source file:com.isdp.twitterposter.GoogleManager.java

License:Open Source License

public String[] parseWiki(JSONObject jsonObj) {
    try {/* w  w w  . j a v a2 s  .com*/
        ArrayList<String> results = new ArrayList<String>();

        JSONArray itemsArray = jsonObj.getJSONArray("items");

        for (int i = 0; i < itemsArray.length(); ++i) {
            JSONObject item = itemsArray.getJSONObject(i);
            String itemSnippet = item.getString("snippet");
            results.add(itemSnippet);
        }

        String[] resultsArray = new String[results.size()];
        return results.toArray(resultsArray);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.isdp.twitterposter.GoogleManager.java

License:Open Source License

public String[] parseYelp(JSONObject jsonObj) {
    try {/* ww  w  .jav a 2  s  .  com*/
        ArrayList<String> results = new ArrayList<String>();

        JSONArray itemsArray = jsonObj.getJSONArray("items");

        for (int i = 0; i < itemsArray.length(); ++i) {
            try {
                JSONObject item = itemsArray.getJSONObject(i);
                JSONObject localbusiness = item.getJSONObject("pagemap").getJSONArray("localbusiness")
                        .getJSONObject(0);
                JSONObject postaladdress = item.getJSONObject("pagemap").getJSONArray("postaladdress")
                        .getJSONObject(0);
                JSONObject aggregaterating = item.getJSONObject("pagemap").getJSONArray("aggregaterating")
                        .getJSONObject(0);

                String textString = Util.generateRandomString(5) + "\n";
                textString += Util.truncateString(localbusiness.getString("name"), 30) + "\n";
                textString += localbusiness.getString("telephone") + "\n";
                textString += postaladdress.getString("streetaddress") + "\n";
                textString += postaladdress.getString("addresslocality") + " "
                        + postaladdress.getString("addressregion") + "\n";
                textString += postaladdress.getString("postalcode") + "\n";
                textString += "R|" + aggregaterating.getString("ratingvalue") + "\n";
                textString += "P|" + localbusiness.getString("pricerange") + "\n";

                results.add(textString);
            } catch (Exception e) {
            }
        }

        String[] resultsArray = new String[results.size()];
        return results.toArray(resultsArray);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.isi.master.meaningcloudAPI.topicsextraction.TopicsClient.java

License:Open Source License

/**
 * /*from  ww w. j  av a2  s  .c o  m*/
 * @param jsonObj
 * @return
 */
private static boolean conceptTopics(JSONObject jsonObj) {
    try {
        JSONArray array = jsonObj.getJSONArray("concept_list");

        for (int i = 0; i < array.length(); i++) {
            JSONObject doc = (JSONObject) array.getJSONObject(i);
            JSONObject doc1 = (JSONObject) doc.get("sementity");
            if (doc1.getString("type").contains("Top>")) {
                return true;
            }
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        //         e.printStackTrace();
    }
    return false;
}

From source file:com.isi.master.meaningcloudAPI.topicsextraction.TopicsClient.java

License:Open Source License

private static List<String> entidadTopics(JSONObject jsonObj) {
    List<String> provincia = new ArrayList<String>();
    try {//from w ww .  j  a  v a  2s  .c o m
        JSONArray array = jsonObj.getJSONArray("entity_list");
        for (int i = 0; i < array.length(); i++) {
            try {
                JSONObject doc = (JSONObject) array.getJSONObject(i);
                JSONObject doc1 = (JSONObject) doc.get("sementity");
                if (doc1.getString("id").equals("ODENTITY_CITY")
                        && doc1.getString("type").equals("Top>Location>GeoPoliticalEntity>City")) {
                    JSONArray doc2 = (JSONArray) doc.get("semgeo_list");
                    JSONObject doc21 = (JSONObject) doc2.get(0);
                    if (((JSONObject) doc21.get("country")).getString("form").equals("Espaa")) {
                        try {
                            provincia.add(((JSONObject) doc21.get("adm2")).getString("form"));
                        } catch (JSONException e) {
                            provincia.add(((JSONObject) doc21.get("adm1")).getString("form"));
                        }
                    } else {
                        //                     System.err.println(((JSONObject)array.get(i)).get("form")+" en el texto se refiere a un lugar de "+((JSONObject)doc21.get("country")).getString("form"));
                    }
                } else if (doc1.getString("id").equals("ODENTITY_ADM2")
                        && doc1.getString("type").equals("Top>Location>GeoPoliticalEntity>Adm2")) {
                    JSONArray doc2 = (JSONArray) doc.get("semgeo_list");
                    JSONObject doc21 = (JSONObject) doc2.get(0);
                    if (((JSONObject) doc21.get("country")).getString("form").equals("Espaa")) {//insertamos la entidad
                        provincia.add(doc.getString("form"));
                    } else {
                        //                     System.err.println(((JSONObject)array.get(i)).get("form")+" en el texto se refiere a un lugar de "+((JSONObject)doc21.get("country")).getString("form"));
                    }
                } else {
                    //                  System.err.println(((JSONObject)array.get(i)).get("form")+" no es una ciudad\n");
                }
            } catch (JSONException e) {
                //               System.err.println(((JSONObject)array.get(i)).get("form")+" no es una ciudad\n");
            }
        }
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        //         e1.printStackTrace();
    }
    return provincia;
}

From source file:com.isi.master.meaningcloudAPI.topicsextraction.TopicsClient.java

License:Open Source License

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
    // We define the variables needed to call the API
    String api = "http://api.meaningcloud.com/topics-2.0";
    String key = "67d2d31e37c2ba1d032188b1233f19bf";
    String txt = "Los vehculos AUDI con tres ocupantes podrn circular por Real Madrid, Alcobendas y Miranda de Ebro los das de contaminacin porque Carmena no les deja debido al aire sucio";
    //      String txt = "Madrid est con altos niveles de contaminacin, como el NO2";
    //      String txt = "La ciudad Madrid est con altos niveles de contaminacin, como el NO2";
    //      String txt = "Avils";
    String lang = "es"; // es/en/fr/it/pt/ca

    Post post = new Post(api);
    post.addParameter("key", key);
    post.addParameter("txt", txt);
    post.addParameter("lang", lang);
    post.addParameter("tt", "ec");
    post.addParameter("uw", "y");
    post.addParameter("cont", "City");
    post.addParameter("of", "json");

    //      String response = post.getResponse();
    JSONObject jsonObj = null;
    try {//w w  w.  ja  v  a2 s . co m
        jsonObj = new JSONObject(post.getResponse());
        System.out.println("AAAAAAAAAAAAAAAAAAAAAAAA");
        System.out.println(jsonObj.toString());
        JSONArray array2 = jsonObj.getJSONArray("concept_list");
        System.out.println(array2);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // Show response
    System.out.println("Response");
    System.out.println("============");
    try {
        System.out.println(jsonObj);
        JSONArray array = jsonObj.getJSONArray("entity_list");
        System.out.println(array);
        for (int i = 0; i < array.length(); i++) {
            try {
                //            System.out.println("_--------------------_");
                JSONObject doc = (JSONObject) array.getJSONObject(i);
                System.out.println(doc);
                //                           System.out.println("_---------------------_");
                JSONObject doc1 = (JSONObject) doc.get("sementity");
                System.out.println(doc1);
                //               System.out.println("_A---------------------_");
                if (doc1.getString("id").equals("ODENTITY_CITY")
                        && doc1.getString("type").equals("Top>Location>GeoPoliticalEntity>City")) {
                    JSONArray doc2 = (JSONArray) doc.get("semgeo_list");
                    JSONObject doc21 = (JSONObject) doc2.get(0);
                    if (((JSONObject) doc21.get("country")).getString("form").equals("Espaa")) {
                        //                     System.out.println("Entidad_: "+((JSONObject)array.get(i)).get("form"));
                        //                     System.out.println("IDENTIFICADORES DE ENTIDAD CIUDAD_: "+doc1.getString("id")+" - "+doc1.getString("type"));
                        //                     System.out.println("PAIS_: "+((JSONObject)doc21.get("country")).get("form"));
                        try {
                            System.out.println(
                                    "PROVINCIA_: " + ((JSONObject) doc21.get("adm2")).get("form") + "\n");
                        } catch (JSONException e) {
                            System.out.println(
                                    "PROVINCIA_: " + ((JSONObject) doc21.get("adm1")).get("form") + "\n");
                        }
                    } else {
                        System.err.println(((JSONObject) array.get(i)).get("form")
                                + " en el texto se refiere a un lugar de "
                                + ((JSONObject) doc21.get("country")).getString("form"));
                    }
                } else if (doc1.getString("id").equals("ODENTITY_ADM2")
                        && doc1.getString("type").equals("Top>Location>GeoPoliticalEntity>Adm1")) {
                    System.out.println(doc.get("form"));
                    JSONArray doc2 = (JSONArray) doc.get("semgeo_list");
                    JSONObject doc21 = (JSONObject) doc2.get(0);
                    if (((JSONObject) doc21.get("country")).getString("form").equals("Espaa")) {
                        System.out.println("PAIS_: " + ((JSONObject) doc21.get("country")).get("form"));
                    }
                } else {
                    System.err.println(((JSONObject) array.get(i)).get("form") + " no es una ciudad\n");
                }
            } catch (JSONException e) {
                System.err.println(((JSONObject) array.get(i)).get("form") + " no es una ciudad\n");
            }

        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Prints the specific fields in the response (topics)
    //      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    //      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    //      Document doc = docBuilder.parse(new ByteArrayInputStream(response.getBytes("UTF-8")));
    //      doc.getDocumentElement().normalize();
    //      Element response_node = doc.getDocumentElement();
    //      System.out.println("\nInformation:");
    //      System.out.println("----------------\n");
    //      try {
    //        NodeList status_list = response_node.getElementsByTagName("status");
    //        Node status = status_list.item(0);
    //        NamedNodeMap attributes = status.getAttributes();
    //        Node code = attributes.item(0);
    //        if(!code.getTextContent().equals("0")) {
    //          System.out.println("Not found");
    //        } else {
    //          String output = "";
    //          output += "Entities:\n";
    //          output += "=============\n";
    //          output += printInfoEntityConcept(response_node, "entity");
    ////          output += "\n";
    ////          output += "Concepts:\n";
    ////          output += "============\n";
    ////          output += printInfoEntityConcept(response_node, "concept");
    ////          output += "\n";
    ////          output += "Time expressions:\n";
    ////          output += "==========\n";
    ////          output += printInfoGeneral(response_node, "time_expression");
    ////          output += "\n";
    ////          output += "Money expressions:\n";
    ////          output += "===========\n";
    ////          output += printInfoGeneral(response_node, "money_expression");
    ////          output += "\n";
    ////          output += "Quantity expressions:\n";
    ////          output += "======================\n";
    ////          output += printInfoGeneral(response_node, "quantity_expression");
    ////          output += "\n";
    ////          output += "Other expressions:\n";
    ////          output += "====================\n";
    ////          output += printInfoGeneral(response_node, "other_expression");
    ////          output += "\n";
    ////          output += "Quotations:\n";
    ////          output += "====================\n";
    ////          output += printInfoQuotes(response_node);
    ////          output += "\n";
    ////          output += "Relations:\n";
    ////          output += "====================\n";
    ////          output += printInfoRelation(response_node);
    //          output += "\n";
    //          if(output.isEmpty())
    //            System.out.println("Not found");
    //          else
    //            System.out.print(output);
    //        }
    //      } catch (Exception e) {
    //        System.out.println("Not found");
    //      }
}

From source file:com.joeygallegos.skypebot.updater.Updater.java

License:Open Source License

@Override
public void run() {
    while (!isInterrupted()) {
        try {/* w  ww .  j a  v a 2 s  .  com*/
            JSONObject json = readJsonFromUrl("http://joeygallegos.com/bot/updates/updates.json");
            JSONArray updates = json.getJSONArray("updates");

            if (updates == null)
                return;
            for (int i = 0; i < updates.length(); ++i) {

                if (this.firstRun) {
                    System.out.println("First run");
                    if (!updateids.contains(i)) {
                        updateids.add(i);
                        System.out.println("Added update id: " + i);
                    }
                } else {
                    // NOT FIRST RUN
                    if (!updateids.contains(i)) {
                        Resource.message("Found a new update!");
                        BotCore.getInstance().restart();
                        stop();
                        return;
                    }
                }
            }

            if (this.firstRun) {
                this.firstRun = false;
                System.out.println("Loaded " + updates.length() + " updates!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.sampleapp.db.DBUtil.java

License:Open Source License

private DBUtil() {
    Map<String, String> env;
    env = System.getenv();/*from  w  w  w.java 2 s .c o  m*/
    String vcap = env.get("VCAP_SERVICES");

    if (vcap == null) {
        System.out.println("No VCAP_SERVICES found");
        return;
    }

    System.out.println("VCAP_SERVICES found");

    try {
        JSONObject vcap_services = new JSONObject(vcap);

        @SuppressWarnings("rawtypes")
        Iterator iter = vcap_services.keys();
        JSONArray cloudant = null;

        // find instance of cloudant bound to app
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (key.startsWith("cloudantNoSQLDB")) {
                cloudant = vcap_services.getJSONArray(key);
            }
        }

        JSONObject instance = cloudant.getJSONObject(0); // Grab the first instance of mongoDB for this app (there is only one)
        JSONObject credentials = instance.getJSONObject("credentials");

        // Get all VCAP_SERVICES credentials
        String host = credentials.getString("host");
        String port = credentials.getString("port");
        String username = credentials.getString("username");
        String password = credentials.getString("password");
        String url = credentials.getString("url");

        System.out.println("Found all the params: " + username + " " + password + " " + url);

        // Create the client connection the the database and then create the database
        client = new CloudantClient(url, username, password);
        db = client.database(dbname, true);

        System.out.println("Connected to cloudant on " + host + ":" + port);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.csi.yucca.storage.datamanagementapi.model.metadata.ckan.MetadataCkanFactory.java

protected static String formatMessages(Locale locale, String element) {

    JSONObject messages = loadMessages(locale, element);

    StringBuffer sb = new StringBuffer("");
    String loc = locale.getLanguage().substring(0, 1).toUpperCase() + locale.getLanguage().substring(1);

    String label1 = (element.equals("tags") ? "streamTags" : "streamDomains");
    String label2 = (element.equals("tags") ? "tagCode" : "codDomain");

    try {//from w ww .j a v a2s.c o  m
        JSONObject streamTags = messages.getJSONObject(label1);
        JSONArray elements = streamTags.getJSONArray("element");
        for (int i = 0; i < elements.length(); i++) {
            String tagCode = elements.getJSONObject(i).getString(label2);
            String langEl = elements.getJSONObject(i).getString("lang" + loc);
            sb.append(tagCode + " = " + langEl + "\n");
        }

    } catch (JSONException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

    return sb.toString();
}

From source file:org.csi.yucca.storage.datamanagementapi.service.StoreService.java

protected static String formatMessages(Locale locale, String element) {

    JSONObject messages = loadMessages(locale, element);

    log.debug("[StoreService::formatMessages] - START");
    StringBuffer sb = new StringBuffer("");
    String loc = locale.getLanguage().substring(0, 1).toUpperCase() + locale.getLanguage().substring(1);

    String label1 = (element.equals("tags") ? "streamTags" : "streamDomains");
    String label2 = (element.equals("tags") ? "tagCode" : "codDomain");

    try {/*  w w  w  .  j  a va 2s  . co m*/
        JSONObject streamTags = messages.getJSONObject(label1);
        JSONArray elements = streamTags.getJSONArray("element");
        for (int i = 0; i < elements.length(); i++) {
            String tagCode = elements.getJSONObject(i).getString(label2);
            String langEl = elements.getJSONObject(i).getString("lang" + loc);
            sb.append(tagCode + " = " + langEl + "\n");
        }

    } catch (JSONException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    } finally {
        log.debug("[StoreService::formatMessages] - END");
    }
    return sb.toString();
}