Example usage for twitter4j JSONObject JSONObject

List of usage examples for twitter4j JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String json) throws JSONException 

Source Link

Document

Creates a new JSONObject with name/value mappings from the JSON string.

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 {//w  w w .  jav  a  2  s  . co  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 w w .j av  a  2  s .  c  om
 * @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.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  ww  .  j av  a 2 s. c  o m*/
    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.dataspawn.twitterstreamer.Streamer.java

License:Apache License

public boolean run() {
    System.out.println("Thread is interrupted:" + Thread.currentThread().isInterrupted());
    Authentication auth;//from   w  w  w. jav a2 s  . c om

    BlockingQueue<String> queue;

    queue = new LinkedBlockingQueue<String>(10000);
    endpoint = new StatusesFilterEndpoint();

    endpoint.trackTerms(terms);

    //endpoint.locations(locations);

    //Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password);
    auth = new OAuth1(consumerKey, consumerSecret, token, secret);

    client = new ClientBuilder().name("Streamer Client").hosts(Constants.STREAM_HOST).endpoint(endpoint)
            .authentication(auth).processor(new StringDelimitedProcessor(queue)).build();

    client.connect();
    try {
        ArrayList<String> tweets = new ArrayList<String>();
        Long msgRead = 0L;
        for (msgRead = 0L; msgRead < 1000L; msgRead++) {
            if (client.isDone()) {
                System.out.println(
                        "Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
                break;
            }

            String msg = queue.poll(5, TimeUnit.SECONDS);
            if (msg == null) {
                System.out.println("Did not receive a message in 5 seconds");
            } else {
                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }
                try {
                    JSONObject tweet = new JSONObject(msg);
                    mStore.add(tweet.toString(4));
                    System.out.println(msg);
                } catch (IOException e) {
                    System.out.println("Tweet Store failed: " + e.getMessage());
                    return false;
                }

            }
        }

        System.out.println("Streamer read: " + msgRead);
        client.stop();

    } catch (Exception e) {
        System.out.print("Caught exception when reading tweets");
        // Print some stats
        System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());
        return false;
    }
    // Print some stats
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());
    return true;
}

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

License:Open Source License

public String[] trySearch(String searchQuery, String searchEngineID) {
    try {/*from w ww.  ja v  a2 s .c om*/
        String query = URLEncoder.encode(searchQuery);
        URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + API_KEY + "&cx=" + searchEngineID
                + "&q=" + query);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        InputStream inputStream = conn.getInputStream();
        String jsonStr = null;
        if (inputStream != null)
            jsonStr = Util.convertInputStreamToString(inputStream);

        JSONObject jsonObj = new JSONObject(
                jsonStr.substring(jsonStr.indexOf("{"), jsonStr.lastIndexOf("}") + 1));

        String[] results = null;

        if (searchEngineID.equals(SEARCH_WIKI))
            results = parseWiki(jsonObj);

        else if (searchEngineID.equals(SEARCH_YELP))
            results = parseYelp(jsonObj);

        conn.disconnect();

        return results;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

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

License:Open Source License

/**
 * //from  w  w  w  .  ja va  2 s  .  com
 * @param contenido
 * @param body
 * @return
 */
public static List<String> recibirTweet(String contenido, boolean body) {
    String api = "http://api.meaningcloud.com/topics-2.0";
    String key = "c4b916eee1c44d9d6cd670b19ce6470e";
    String txt = contenido;
    String lang = "es"; // es/en/fr/it/pt/ca
    List<String> provincia = new ArrayList<String>();
    try {
        Post post = new Post(api);
        post.addParameter("key", key);
        post.addParameter("txt", txt);
        post.addParameter("lang", lang);
        if (body) {
            post.addParameter("tt", "ec");
        } else {
            post.addParameter("tt", "e");
        }
        post.addParameter("uw", "y");
        post.addParameter("cont", "City");
        post.addParameter("of", "json");

        JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(post.getResponse());
            boolean seguir = false;
            if (body) {
                seguir = conceptTopics(jsonObj);
                if (!seguir) {//quitamos '#' de los hashtag
                    Post post2 = new Post(api);
                    post2.addParameter("key", key);
                    post2.addParameter("txt", txt.replaceAll("#", ""));
                    post2.addParameter("lang", lang);
                    post2.addParameter("tt", "ec");
                    post2.addParameter("uw", "y");
                    post2.addParameter("cont", "City");
                    post2.addParameter("of", "json");
                    JSONObject jsonObj2 = new JSONObject(post.getResponse());
                    seguir = conceptTopics(jsonObj2);
                }
            }
            if (seguir || !body) {//la parte del tweet analizada es el cuerpo y tiene contenido relacionado con contaminacion o no es el cuerpo y se quiere buscar localizacion
                provincia = entidadTopics(jsonObj);
                if (provincia.size() == 0) {
                    if (body) {
                        provincia = analisisRegex(txt, true);
                        if (provincia.size() == 0) {
                            Post post2 = new Post(api);
                            post2.addParameter("key", key);
                            post2.addParameter("txt", txt.replaceAll("#", ""));
                            post2.addParameter("lang", lang);
                            post2.addParameter("tt", "ec");
                            post2.addParameter("uw", "y");
                            post2.addParameter("cont", "City");
                            post2.addParameter("of", "json");
                            JSONObject jsonObj2 = new JSONObject(post.getResponse());
                            provincia = entidadTopics(jsonObj2);
                        }
                    } else {
                        provincia = analisisRegex(txt, false);
                    }
                }
            } else {//la parte del tweet analizada es el cuerpo y no tiene ningun contenido relacionado con contaminacion
                return null;
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            //            System.err.println("No es posible analizar '"+contenido+"' en base a entidades\n");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (UnsupportedEncodingException 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 a  v  a 2s  .  c  om
    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.joeygallegos.skypebot.updater.Updater.java

License:Open Source License

public JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {//  w  w w  .jav a 2  s .  co  m
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}

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  .j  a  v  a  2s.  co 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.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;//from  w  w  w .  j  ava 2  s.  c om
    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();
    }
}