Example usage for twitter4j JSONObject get

List of usage examples for twitter4j JSONObject get

Introduction

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

Prototype

public Object get(String name) throws JSONException 

Source Link

Document

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

Usage

From source file:com.adobe.ibm.watson.traits.impl.TwitterServiceClient.java

License:Apache License

private String requestBearerToken(String endPointUrl, Resource pageResource) throws IOException {
    HttpsURLConnection connection = null;
    String appKey;/* w  w w  . ja  v a  2  s  . com*/
    String appSecret;

    // Load the Twitter Connect Cloud Service Configuration from the current page.
    // If none is found (e.g. Segment Builder page, use the Geometrixx Outdoors Twitter configuration.
    log.info("Looking for Twitter Cloud Configuration at: " + pageResource.getPath());
    Configuration twitterConfig = findCloudConfiguration(pageResource.adaptTo(Page.class));
    if (twitterConfig == null) {
        log.error(
                "Unable to locate Twitter Connect Cloud Configuration for {}. Using Geometrixx Outdoors defaults.",
                pageResource.getPath());
        Resource resource = pageResource.getResourceResolver().getResource("/content/geometrixx-outdoors/en");
        twitterConfig = findCloudConfiguration(resource.adaptTo(Page.class));
    }
    if (twitterConfig != null) {
        // Get the configuration settings from the cloudservice config.
        Resource twitterResource = twitterConfig.getContentResource().listChildren().next();
        ValueMap twitterProps = twitterResource.adaptTo(ValueMap.class);
        appKey = twitterProps.get("oauth.client.id", String.class);
        appSecret = twitterProps.get("oauth.client.secret", String.class);
    } else {
        // Fall back to defaut credentials configured in OSGi
        appKey = this.twitterId;
        appSecret = this.twitterSecret;
    }

    String encodedCredentials = encodeKeys(appKey, appSecret);

    try {
        URL url = new URL(endPointUrl);
        connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "IBM Watson AEM Application");
        connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        connection.setRequestProperty("Content-Length", "29");
        connection.setUseCaches(false);

        writeRequest(connection, "grant_type=client_credentials");

        // Parse the JSON response into a JSON mapped object to fetch fields from.
        JSONObject obj = new JSONObject(readResponse(connection));

        if (obj != null) {
            String tokenType = (String) obj.get("token_type");
            String token = (String) obj.get("access_token");

            return ((tokenType.equals("bearer")) && (token != null)) ? token : "";
        }
        return new String();
    } catch (MalformedURLException e) {
        throw new IOException("Invalid endpoint URL specified.", e);
    } catch (JSONException e) {
        throw new IOException("Unable to process JSON content.", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

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

License:Open Source License

/**
 * //from  w  w w.  j a va2  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   ww w.ja  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 ww  w  .  ja v a  2s  .  com
    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.SentimentalResponse.java

public static String readJsonFromUrl(String text) throws IOException, JSONException {
    // System.out.println(text);
    // text=text.replaceAll(" ","%20");
    text = text.replaceAll("\n", " ");
    String[] str;// w ww  .  j  a v  a2s  .c o m
    str = text.split("http");
    text = str[0];
    text = text.replaceAll(" ", "%20").replaceAll(":", "%3A").replaceAll("/", "%2F").replaceAll(";", "%3B")
            .replaceAll("@", "%40").replaceAll("<", "%3C").replaceAll(">", "%3E").replaceAll("=", "%3D")
            .replaceAll("&", "%26").replaceAll("%", "%25").replaceAll("$", "%24").replaceAll("#", "%23")
            .replaceAll(",", "%2C");
    //.replaceAll("++","%2B").replaceAll("?","%3F");
    //System.out.println(text);
    url = sentimentalAnalysistUrl + "apikey=" + apiKey + "&text=" + text + "&outputMode=" + outputMode;
    System.out.println(url);
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        if (json == null) {
            return "No tweets detection";
        } else {
            if (!json.has("docSentiment")) {
                return "language not detection";
            } else {
                JSONObject json2 = (JSONObject) json.get("docSentiment");
                return json2.get("type").toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.toString());
        return "error occur, retrying";
    } finally {
        is.close();
    }
}

From source file:com.tweettrends.pravar.FilterStreamExample.java

License:Apache License

public static void run(String consumerKey, String consumerSecret, String token, String secret,
        SimpleQueueService simpleQueueService) throws InterruptedException {
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
    StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
    // add some track terms
    endpoint.trackTerms(Lists.newArrayList("modi", "India", "Trump", "New York", "English", "London",
            "Tuesday Motivation", "Celtics", "GA06"));
    endpoint.languages(Lists.newArrayList("en"));

    Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
    // Authentication auth = new BasicAuth(username, password);

    // Create a new BasicClient. By default gzip is enabled.
    Client client = new ClientBuilder().hosts(Constants.STREAM_HOST).endpoint(endpoint).authentication(auth)
            .processor(new StringDelimitedProcessor(queue)).build();

    // Establish a connection
    client.connect();//from  w ww  .j a  va2 s.co m

    while (true) {
        // Do whatever needs to be done with messages
        for (int msgRead = 0; msgRead < 1000; msgRead++) {
            String msg = queue.take();

            try {
                JSONObject tweet = new JSONObject(msg);
                if (tweet.has("coordinates")) {
                    String geoInfo = tweet.get("coordinates").toString();
                    if (!geoInfo.equals("null")) {
                        simpleQueueService.sendMessage(msg);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //client.stop();

    }
}