List of usage examples for twitter4j JSONArray length
public int length()
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 .j a v a2 s . 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") + "®ion=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") + "®ion=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") + "®ion=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:ac.simons.tweetarchive.web.ArchiveHandlingController.java
License:Apache License
/** * As you can see, it get's nasty here... * <br>// w w w.j ava 2s . c om * Twitter4j doesn't offer an official way to parse Twitters JSON, so I * brute force my way into the twitter4j.StatusJSONImpl implementation of * Status. * <br> * And even if there was an official way, the JSON files inside the * official(!) Twitter archive differ from the API, even if they are said to * be identical. By the way, I'm not the only one, who * <a href="https://twittercommunity.com/t/why-does-twitter-json-archive-have-a-different-format-than-the-rest-api-1-1/35530">noticed * that</a>. * <br> * Furthermore, I didn't even bother to add error handling or tests. * * @param archive The uploaded archive * @return Redirect to the index * @throws java.io.IOException * @throws twitter4j.JSONException */ @PostMapping public String store(@NotNull final MultipartFile archive, final RedirectAttributes redirectAttributes) throws IOException, JSONException { try (final ZipInputStream archiv = new ZipInputStream(archive.getInputStream())) { ZipEntry entry; while ((entry = archiv.getNextEntry()) != null) { if (!entry.getName().startsWith("data/js/tweets/") || entry.isDirectory()) { continue; } log.debug("Reading archive entry {}...", entry.getName()); final BufferedReader buffer = new BufferedReader( new InputStreamReader(archiv, StandardCharsets.UTF_8)); final String content = buffer.lines().skip(1).map(l -> { Matcher m = PATTERN_CREATED_AT.matcher(l); String rv = l; if (m.find()) { try { rv = m.replaceFirst( "$1\"" + DATE_FORMAT_OUT.format(DATE_FORMAT_IN.parse(m.group(2))) + "\""); } catch (ParseException ex) { log.warn("Unexpected date format in twitter archive", ex); } } return rv; }).collect(Collectors.joining("")).replaceAll("\"sizes\" : \\[.+?\\],", "\"sizes\" : {},"); final JSONArray statuses = new JSONArray(content); for (int i = 0; i < statuses.length(); ++i) { final JSONObject rawJSON = statuses.getJSONObject(i); // https://twitter.com/lukaseder/status/772772372990586882 ;) final Status status = statusFactory.create(rawJSON).as(Status.class); this.tweetStorageService.store(status, rawJSON.toString()); } } } redirectAttributes.addFlashAttribute("message", "Done."); return "redirect:/upload"; }
From source file:com.adobe.ibm.watson.traits.impl.TwitterServiceClient.java
License:Apache License
/** * Fetches all of the Tweets for a given screen name. * @param screenName/* ww w . j ava 2s .c o m*/ * @param maxTweets * @return ArrayList of the user's timeline tweets. * @throws IOException */ public ArrayList<String> fetchTimelineTweets(String screenName, int maxTweets, Resource pageResource) throws IOException { HttpsURLConnection connection = null; String bearerToken = requestBearerToken("https://api.twitter.com/oauth2/token", pageResource); String endPointUrl = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + screenName + "&count=" + maxTweets; try { URL url = new URL(endPointUrl); connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Host", "api.twitter.com"); connection.setRequestProperty("User-Agent", "Your Program Name"); connection.setRequestProperty("Authorization", "Bearer " + bearerToken); connection.setUseCaches(false); // Parse the JSON response into a JSON mapped object to fetch fields from. JSONArray obj = new JSONArray(readResponse(connection)); ArrayList<String> tweets = new ArrayList<String>(); if (obj != null) { for (int j = 0; j < obj.length(); j++) { if (obj.getJSONObject(j).has("retweeted_status") == false) { tweets.add(obj.getJSONObject(j).get("text").toString()); } } return tweets; } else { return null; } } 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.isdp.twitterposter.GoogleManager.java
License:Open Source License
public String[] parseWiki(JSONObject jsonObj) { try {/*from w w w . ja v a 2 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 {//w ww . ja v a 2s .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 w ww. ja v a 2s . com * @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 {// w ww . 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;//ww w . j a v a2 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.joeygallegos.skypebot.updater.Updater.java
License:Open Source License
@Override public void run() { while (!isInterrupted()) { try {// ww w . ja va2 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: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 w w . j ava2s. c om*/ 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(); }