Example usage for twitter4j JSONObject getString

List of usage examples for twitter4j JSONObject getString

Introduction

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

Prototype

public String getString(String name) throws JSONException 

Source Link

Document

Returns the value mapped by name if it exists, coercing it if necessary, or throws if no such mapping exists.

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  ww w .  j  a va2s. c o m
        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:WebsocketServer.java

/**
 * When a user sends a message to the server, this method will intercept the message
 * and allow us to react to it. For now the message is read as a String.
 * @param message/*w ww.j  a  v  a2  s . c  o  m*/
 * @param session
 * @throws twitter4j.TwitterException
 * @throws java.io.IOException
 * @throws java.lang.InterruptedException
 * @throws java.util.concurrent.ExecutionException
 */
@OnMessage
public void onMessage(String message, Session session)
        throws TwitterException, IOException, InterruptedException, ExecutionException, JSONException {
    if (WebsocketServer.session == session) {
        System.out.println("Message from " + session.getId() + ": " + message);

        JSONObject data = new JSONObject(message);
        String messageType = data.getString("message");

        switch (messageType) {
        case "startStreaming":
            // Initialize application's access token.
            streaming.initializeToken();
            break;
        case "accessTokenPin":
            streaming.createApplicationAccessToken(data.getString("pin"));
            break;
        case "stopStreaming":
            streaming.stopStreaming();
            break;
        }
    }
}

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

License:Open Source License

public String[] parseWiki(JSONObject jsonObj) {
    try {/* ww  w .  j  a va 2  s. c o  m*/
        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 {/*from w w w  .  jav  a  2 s . c o  m*/
        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 a  2 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 a2 s .  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;//from w  ww.j  ava  2  s  .c  o  m
    try {
        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.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:com.waves_rsp.ikb4stream.scoring.twitter.TwitterScoreProcessor.java

License:Open Source License

/**
 * Parse a JSONObject from a tweet and check if the twitter account is certified
 *
 * @param json JSONObject to parse//  w  w  w  .  j a  v  a  2 s .  co  m
 * @return true if the twitter account is certified
 * @throws JSONException        if json is an invalid tweet
 * @throws NullPointerException if json is null
 */
private boolean isCertified(JSONObject json) throws JSONException {
    Objects.requireNonNull(json);
    String isCertified = json.getString("user_certified");
    isCertified = isCertified.substring(1, isCertified.length() - 1);
    return "true".equalsIgnoreCase(isCertified);
}

From source file:com.waves_rsp.ikb4stream.scoring.twitter.TwitterScoreProcessor.java

License:Open Source License

/**
 * Parse a JSONObject from a tweet and extract the tweet description
 *
 * @param json JSONObject to parse/*  w w  w .jav  a 2s  . c  o m*/
 * @return the description of a tweet
 * @throws JSONException        if json is an invalid json
 * @throws NullPointerException if json is null
 */
private String getParseDescription(JSONObject json) throws JSONException {
    Objects.requireNonNull(json);
    return json.getString("description");
}