Example usage for twitter4j JSONObject toString

List of usage examples for twitter4j JSONObject toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Encodes this object as a compact JSON string, such as:
{"query":"Pizza","locations":[94043,90210]}

Usage

From source file:ac.simons.tweetarchive.web.ArchiveHandlingController.java

License:Apache License

/**
 * As you can see, it get's nasty here...
 * <br>//from www .  j a v a  2  s . co  m
 * 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.isi.master.meaningcloudAPI.topicsextraction.TopicsClient.java

License:Open Source License

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

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

    //      String response = post.getResponse();
    JSONObject jsonObj = null;
    try {/*from   w w  w.  j av  a 2s .c  om*/
        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.marpies.ane.twitter.functions.FollowUserFunction.java

License:Apache License

@Override
public void createdFriendship(User user) {
    AIR.log("Success following user: " + user.getScreenName());
    try {//from   w  ww. j  a  va 2s .  c o m
        JSONObject userJSON = UserUtils.getJSON(user);
        userJSON.put("listenerID", mCallbackID);
        userJSON.put("success", "true");
        AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_SUCCESS, userJSON.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_SUCCESS,
                StringUtils.getEventErrorJSON(mCallbackID, e.getMessage()));
    }
}

From source file:com.marpies.ane.twitter.functions.GetLoggedInUserFunction.java

License:Apache License

private void dispatchUser(User user) throws JSONException {
    JSONObject userJSON = UserUtils.getJSON(user);
    userJSON.put("listenerID", mCallbackID);
    userJSON.put("success", true);
    userJSON.put("loggedInUser", true); // So that we can cache the user object in AS3
    AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_SUCCESS, userJSON.toString());
}

From source file:com.marpies.ane.twitter.functions.GetUserFunction.java

License:Apache License

@Override
public void gotUserDetail(User user) {
    AIR.log("Successfully retrieved user info");
    try {/* ww  w . ja v  a 2  s .  co  m*/
        JSONObject userJSON = UserUtils.getJSON(user);
        userJSON.put("listenerID", mCallbackID);
        userJSON.put("success", true);
        AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_SUCCESS, userJSON.toString());
    } catch (JSONException e) {
        AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_SUCCESS,
                StringUtils.getEventErrorJSON(mCallbackID, "Error parsing returned user info."));
    }
}

From source file:com.marpies.ane.twitter.functions.SendDirectMessageFunction.java

License:Apache License

@Override
public void sentDirectMessage(DirectMessage message) {
    AIR.log("Success sending DM '" + message.getText() + "'");
    try {//from  w ww . jav  a2 s.  com
        JSONObject dmJSON = DirectMessageUtils.getJSON(message);
        dmJSON.put("listenerID", mCallbackID);
        dmJSON.put("success", "true");
        AIR.dispatchEvent(AIRTwitterEvent.DIRECT_MESSAGE_QUERY_SUCCESS, dmJSON.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        AIR.dispatchEvent(AIRTwitterEvent.DIRECT_MESSAGE_QUERY_SUCCESS,
                StringUtils.getEventErrorJSON(mCallbackID, e.getMessage()));
    }
}

From source file:com.marpies.ane.twitter.functions.UnfollowUserFunction.java

License:Apache License

@Override
public void destroyedFriendship(User user) {
    AIR.log("Success unfollowing user: " + user.getScreenName());
    try {/*from   w ww  . j  a va2s.c  o  m*/
        JSONObject userJSON = UserUtils.getJSON(user);
        userJSON.put("listenerID", mCallbackID);
        userJSON.put("success", "true");
        AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_SUCCESS, userJSON.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_SUCCESS,
                StringUtils.getEventErrorJSON(mCallbackID, e.getMessage()));
    }
}

From source file:com.marpies.ane.twitter.functions.UpdateStatusFunction.java

License:Apache License

@Override
public void updatedStatus(Status status) {
    AIR.log("Updated status w/ message " + status.getText());
    try {// www.  j  a v  a  2 s  .  com
        JSONObject statusJSON = StatusUtils.getJSON(status);
        statusJSON.put("listenerID", mCallbackID);
        statusJSON.put("success", true);
        AIR.dispatchEvent(AIRTwitterEvent.STATUS_QUERY_SUCCESS, statusJSON.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        AIR.dispatchEvent(AIRTwitterEvent.STATUS_QUERY_SUCCESS, StringUtils.getEventErrorJSON(mCallbackID,
                "Status update succeeded but could not parse returned status."));
    }
}

From source file:com.marpies.ane.twitter.utils.DirectMessageUtils.java

License:Apache License

/**
 * Creates JSON from given response list and dispatches generic event.
 * Helper method for queries like getDirectMessages, getSentDirectMessages...
 * @param messages/*from   ww  w. ja  v  a 2  s .co  m*/
 * @param callbackID
 */
public static void dispatchDirectMessages(ResponseList<DirectMessage> messages, int callbackID) {
    try {
        AIR.log("Got response with " + messages.size() + " direct messages");
        /* Create array of messages */
        JSONArray dms = new JSONArray();
        for (DirectMessage message : messages) {
            /* Create JSON for the message and put it to the array */
            dms.put(getJSON(message).toString());
        }
        JSONObject result = new JSONObject();
        result.put("messages", dms);
        result.put("listenerID", callbackID);
        AIR.dispatchEvent(AIRTwitterEvent.DIRECT_MESSAGES_QUERY_SUCCESS, result.toString());
    } catch (JSONException e) {
        AIR.dispatchEvent(AIRTwitterEvent.DIRECT_MESSAGES_QUERY_ERROR,
                StringUtils.getEventErrorJSON(callbackID, "Error creating result JSON: " + e.getMessage()));
    }
}

From source file:com.marpies.ane.twitter.utils.StatusUtils.java

License:Apache License

/**
 * Creates JSON from given response list and dispatches generic event.
 * Helper method for queries like getHomeTimeline, getLikes...
 * @param statuses/*from  w  ww . j a v a  2 s . co m*/
 * @param excludeReplies
 * @param callbackID
 */
public static void dispatchStatuses(ResponseList<Status> statuses, boolean excludeReplies,
        final int callbackID) {
    try {
        AIR.log("Got response with " + statuses.size() + " statuses"
                + (excludeReplies ? " (yet to filter out replies)" : ""));
        /* Create array of statuses (tweets) */
        JSONArray tweets = new JSONArray();
        for (Status status : statuses) {
            /* Exclude reply if requested */
            if (excludeReplies && status.getInReplyToUserId() >= 0)
                continue;
            /* Create JSON for the status and put it to the array */
            JSONObject statusJSON = getJSON(status);
            tweets.put(statusJSON.toString());
        }
        JSONObject result = new JSONObject();
        result.put("statuses", tweets);
        result.put("listenerID", callbackID);
        AIR.dispatchEvent(AIRTwitterEvent.TIMELINE_QUERY_SUCCESS, result.toString());
    } catch (JSONException e) {
        AIR.dispatchEvent(AIRTwitterEvent.TIMELINE_QUERY_ERROR,
                StringUtils.getEventErrorJSON(callbackID, "Error creating result JSON: " + e.getMessage()));
    }
}