Example usage for twitter4j Query Query

List of usage examples for twitter4j Query Query

Introduction

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

Prototype

public Query(String query) 

Source Link

Usage

From source file:MapDemo.java

public static void main(String[] args) throws TwitterException, IOException, Exception {

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();//from ww  w.j  a  v  a 2 s . c o  m
    boolean flag = true;
    // Ask the user for a search string.
    String searchStr = "ParkandGoUNL";

    // Create a Query object.
    Query query = new Query(searchStr);

    // Send API request to execute a search with the given query.
    QueryResult result = twitter.search(query);

    // Display search results.
    result.getTweets().stream().forEach((Status status) -> {
        System.out.println("\n" + status.getText() + status.getCreatedAt());
    });

    if (flag) {

        GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");
        List<Marker> markers = new ArrayList<>();
        Marker e = new Marker(GeocodingApi.geocode(context, "616 North 16th Street, Lincoln, Nebraska, USA")
                .await()[0].geometry.location, "marker1", "KKG", new Date());
        markers.add(e);

        StreetExtractor se = new StreetExtractor();
        List<Address> address = se.find("Park and Go 601 North 16th Street");
        address.forEach(((Address a) -> {

            try {
                Marker m = new Marker(
                        GeocodingApi.geocode(context, a.getAddress()).await()[0].geometry.location, "marker0",
                        "A Tweet", new Date());
                markers.add(m);
            } catch (Exception ex) {
                Logger.getLogger(MapDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }));

        Map map = new Map(markers);
        map.create();
    }
}

From source file:TweetMapManager.java

public static void main(String[] args) {

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();/*from  ww w  .j a v  a  2s .com*/
    String searchStr = "#ParkandGoUNL";
    Query query = new Query(searchStr);

    GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");
    List<Marker> markers = new LinkedList<>();
    StreetExtractor se = new StreetExtractor();
    LocalTime now = LocalTime.now();

    while (true) {
        DayOfWeek today = LocalDate.now().getDayOfWeek();
        if (today.getValue() < WEEKEND) {
            if (now.isAfter(STARTTIME) && now.isBefore(ENDTIME)) {

                // Send API request to execute a search with the given query.
                QueryResult results = null;
                try {
                    results = twitter.search(query);
                } catch (TwitterException ex) {
                    LOGGER.warn(ex.getMessage());
                }

                // Display search results.
                if (results != null) {
                    results.getTweets().stream().forEach((Status status) -> {
                        try {

                            Date created = status.getCreatedAt();
                            String text = status.getText();
                            LOGGER.info(status.getText());
                            LatLng location;
                            if (status.getGeoLocation() != null) {
                                location = new LatLng(status.getGeoLocation().getLatitude(),
                                        status.getGeoLocation().getLongitude());
                            } else {
                                String modified = text.replace("#ParkAndGoUNL", "");
                                List<Address> address = se.find(modified);

                                location = GeocodingApi.geocode(context, address.get(0).getAddress())
                                        .await()[0].geometry.location;
                            }
                            String id = UUID.randomUUID().toString().substring(0, 8);
                            Marker m = new Marker(location, "m" + id, text, created);
                            markers.add(m);
                        } catch (Exception ex) {
                            LOGGER.warn(ex.getMessage());
                        }

                    });
                }
                if (!markers.isEmpty()) {
                    Marker m = markers.get(markers.size() - 1);

                    if (m.getTimestamp().getTime() < Time.valueOf(now.minusMinutes(30)).getTime()) {
                        DailyLogs.addMarkerToLog(m, today);
                        markers.remove(m);
                    }
                }
                Map map = new Map(markers);
                map.create();
            } else {
                //wait 5 hours
                try {
                    LOGGER.info("Sleeping 5 hours");
                    Thread.sleep((long) 1.8e+7);
                } catch (InterruptedException ex) {
                    LOGGER.warn(ex.getMessage());
                }
            }

            now = LocalTime.now();
        } else {
            try {
                //Wait a day
                LOGGER.info("Sleeping 1 day");
                Thread.sleep((long) 8.64e+7);
            } catch (InterruptedException ex) {
                LOGGER.warn(ex.getMessage());
            }
        }
        try {
            LOGGER.info("Successful Loop, Resting");
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            LOGGER.warn(ex.getMessage());
        }
    }
}

From source file:AwsConsoleApp.java

License:Open Source License

public static void searchTweets(String searchString) throws Exception {
    Twitter twitter = new TwitterFactory().getInstance();
    QueryResult result;/*from www .  j  a va2  s .com*/
    Query query = new Query(searchString);
    query.setRpp(100);
    for (int i = 1; i < 16; i++) {
        System.out.println("CURRENT PAGE: " + i);
        query.setPage(i);
        result = twitter.search(query);
        for (Tweet tweet : result.getTweets()) {
            System.out.println(tweet.getFromUser() + ":" + tweet.getText());
        }
    }
}

From source file:Pencarian.java

private void btSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSearchActionPerformed
    // TODO add your handling code here:
    txtSearchTimeline.setText("");

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();/*from w  ww  . ja  v a  2s . c  o  m*/

    Query query = new Query(txSearch.getText());
    QueryResult result = null;

    try {
        result = twitter.search(query);

        result.getTweets().stream().forEach((status) -> {
            txtSearchTimeline.append("@" + status.getUser().getScreenName() + ":" + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });
    } catch (TwitterException ex) {
        Logger.getLogger(Pencarian.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(rootPane, "Failed !! " + ex.getMessage());
    }
}

From source file:Demo.java

/**
 * Main method.// w w  w  .  j a  va  2s  .  c o m
 *
 * @param args
 * @throws TwitterException
 */
public static void main(String[] args) throws TwitterException, IOException {

    // The TwitterFactory object provides an instance of a Twitter object
    // via the getInstance() method. The Twitter object is the API consumer.
    // It has the methods for interacting with the Twitter API.
    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();

    boolean keepItGoinFullSteam = true;
    do {
        // Main menu
        Scanner input = new Scanner(System.in);
        System.out.print("\n--------------------" + "\nH. Home Timeline\nS. Search\nT. Tweet"
                + "\n--------------------" + "\nA. Get Access Token\nQ. Quit" + "\n--------------------\n> ");
        String choice = input.nextLine();

        try {

            // Home Timeline
            if (choice.equalsIgnoreCase("H")) {

                // Display the user's screen name.
                User user = twitter.verifyCredentials();
                System.out.println("\n@" + user.getScreenName() + "'s timeline:");

                // Display recent tweets from the Home Timeline.
                for (Status status : twitter.getHomeTimeline()) {
                    System.out.println("\n@" + status.getUser().getScreenName() + ": " + status.getText());
                }

            } // Search
            else if (choice.equalsIgnoreCase("S")) {

                // Ask the user for a search string.
                System.out.print("\nSearch: ");
                String searchStr = input.nextLine();

                // Create a Query object.
                Query query = new Query(searchStr);

                // Send API request to execute a search with the given query.
                QueryResult result = twitter.search(query);

                // Display search results.
                result.getTweets().stream().forEach((Status status) -> {
                    System.out.println("\n@" + status.getUser().getName() + ": " + status.getText());
                });

            } // Tweet
            else if (choice.equalsIgnoreCase("T")) {

                boolean isOkayLength = true;
                String tweet;
                do {
                    // Ask the user for a tweet.
                    System.out.print("\nTweet: ");
                    tweet = input.nextLine();

                    // Ensure the tweet length is okay.
                    if (tweet.length() > 140) {
                        System.out.println("Too long! Keep it under 140.");
                        isOkayLength = false;
                    }
                } while (isOkayLength == false);

                // Send API request to create a new tweet.
                Status status = twitter.updateStatus(tweet);
                System.out.println("Just tweeted: \"" + status.getText() + "\"");

            } // Get Access Token
            else if (choice.equalsIgnoreCase("A")) {

                // First, we ask Twitter for a request token.
                RequestToken reqToken = twitter.getOAuthRequestToken();
                System.out.println("\nRequest token: " + reqToken.getToken() + "\nRequest token secret: "
                        + reqToken.getTokenSecret());

                AccessToken accessToken = null;
                while (accessToken == null) {

                    // The authorization URL sends the request token to Twitter in order
                    // to request an access token. At this point, Twitter asks the user
                    // to authorize the request. If the user authorizes, then Twitter
                    // provides a PIN.
                    System.out
                            .print("\nOpen this URL in a browser: " + "\n    " + reqToken.getAuthorizationURL()
                                    + "\n" + "\nAuthorize the app, then enter the PIN here: ");
                    String pin = input.nextLine();
                    try {
                        // We use the provided PIN to get the access token. The access
                        // token allows this app to access the user's account without
                        // knowing his/her password.
                        accessToken = twitter.getOAuthAccessToken(reqToken, pin);
                    } catch (TwitterException te) {
                        System.out.println(te.getMessage());
                    }
                }
                System.out.println("\nAccess token: " + accessToken.getToken() + "\nAccess token secret: "
                        + accessToken.getTokenSecret() + "\nSuccess!");

            } // Quit
            else if (choice.equalsIgnoreCase("Q")) {

                keepItGoinFullSteam = false;
                GeoApiContext context = new GeoApiContext()
                        .setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");

                System.out.println(GeocodingApi.geocode(context, "Sigma Phi Epsilon, Lincoln, Nebraska, USA")
                        .await()[0].geometry.location.toString());
                System.out.println(GeocodingApi.geocode(context, "16th and R, Lincoln, Nebraska, USA")
                        .await()[0].geometry.location.toString());
                File htmlFile = new File("map.html");
                Desktop.getDesktop().browse(htmlFile.toURI());
            } // Bad choice
            else {

                System.out.println("Invalid option.");
            }

        } catch (IllegalStateException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

    } while (keepItGoinFullSteam == true);
}

From source file:TwitterPull.java

public void retrieveTweets() {
    try {/* w  w w .  j  ava2 s . co m*/
        Query query = new Query(this.queryString);
        query.setLang("en");
        query.setCount(100);
        QueryResult result;
        int i = 0;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            //                int i = 0;
            for (Status tweet : tweets) {
                System.out.println(tweet.getText().replaceAll("\n", "").replaceAll("\r", ""));
                //                    appendTweetDocument(tweet.getText());
            }
            i++;
        } while ((query = result.nextQuery()) != null && i < 10);
        //            setTwitterFeed(tweets);

        //            System.exit(0);
    } catch (TwitterException te) {
        Logger.getLogger(TwitterPull.class.getName()).log(Level.SEVERE, null, te);
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:TwitterRetrieval.java

License:Apache License

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out;/*from w ww.  ja  v  a 2s . co m*/
    try {

        // img stuff not req'd for source code html showing
        // all links relative
        // XXX
        // making these absolute till we work out the
        // addition of a PathInfo issue

        ConfigurationBuilder cb = new ConfigurationBuilder();
        System.setProperty("twitter4j.http.httpClient", "twitter4j.internal.http.HttpClientImpl");
        cb.setOAuthConsumerKey("56NAE9lQHSOZIGXRktd5Qw")
                .setOAuthConsumerSecret("zJjJrUUs1ubwKjtPOyYzrwBJzpwq7ud8Aryq1VhYH2E")
                .setOAuthAccessTokenURL("https://api.twitter.com/oauth/access_token")
                .setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token")
                .setOAuthAuthorizationURL("https://api.twitter.com/oauth/authorize")
                .setOAuthAccessToken("234742739-I1l0VGTTjRUbZrfH1jvKnTVFU9ZEvkxxUDpvsAJ2")
                .setOAuthAccessTokenSecret("jLe3imI3JiPgmHCatt6SqYgRAcX5q8s6z38oUrqMc");

        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        Query query = new Query(request.getParameter("q"));

        String tags = request.getParameter("tags");

        String zone = request.getParameter("zone");

        String users = request.getParameter("users");

        Map<String, LatLon> latslongs = new HashMap();

        String[] tagsArray = null;
        if (tags != null) {
            tagsArray = tags.split(",");
        }

        String[] userArray = null;

        if (users != null) {
            userArray = users.split(",");
            int count = userArray.length;
            usuarios = new String[count];
            latitud = new String[count];
            longitud = new String[count];
            for (int i = 0; i < userArray.length; i++) {
                temp = userArray[i];
                if (temp != null) {
                    int hit1 = temp.indexOf("[");
                    int hit2 = temp.indexOf(";");
                    int hit3 = temp.indexOf("]");
                    latslongs.put(temp.substring(0, hit1),
                            new LatLon(temp.substring(hit1 + 1, hit2), temp.substring(hit2 + 1, hit3)));
                    /*
                     * usuarios[i] = temp.substring(0, hit1); latitud[i] =
                     * temp.substring(hit1 + 1, hit2); longitud[i] =
                     * temp.substring(hit2 + 1, hit3);
                     */
                }
            }
        }

        QueryResult result;

        result = twitter.search(query);

        List<Post> postList = new ArrayList();
        List<PostType> postsList = new ArrayList();

        Post solrPost;
        PostType post;
        //List<LinkType> links = new ArrayList();
        List<ActionType> actions;
        ArrayList<User> toUsers = new ArrayList();

        ArrayList<LinkType> links;
        int d;

        InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/servlet.properties");
        Properties props = null;
        if (props == null) {
            props = new Properties();
            props.load(stream);
        }
        ZoneDao zoneDao = new ZoneDao(props.getProperty("db_host"),
                Integer.valueOf(props.getProperty("db_port")), props.getProperty("db_name"));
        PlaceDao placeDao = new PlaceDao(props.getProperty("db_host"),
                Integer.valueOf(props.getProperty("db_port")), props.getProperty("db_name"));
        Place place = null;
        org.zonales.tagsAndZones.objects.Zone zoneObj = zoneDao
                .retrieveByExtendedString(Utils.normalizeZone(zone));

        for (Tweet tweet : (List<Tweet>) result.getTweets()) {
            d = MAX_TITLE_LENGTH;
            actions = new ArrayList();
            try {
                actions.add(new ActionType("retweets", twitter.getRetweets(tweet.getId()).size()));
                actions.add(new ActionType("replies",
                        twitter.getRelatedResults(tweet.getId()).getTweetsWithReply().size()));
            } catch (TwitterException ex) {
                Logger.getLogger(TwitterRetrieval.class.getName()).log(Level.SEVERE,
                        "Error intentando obtener retweets o replies: {0}", new Object[] { ex });
            }

            solrPost = new Post();
            solrPost.setZone(new Zone(String.valueOf(zoneObj.getId()), zoneObj.getName(),
                    zoneObj.getType().getName(), zoneObj.getExtendedString()));
            solrPost.setSource("Twitter");

            solrPost.setId(String.valueOf(tweet.getId()));

            if (request.getParameter(tweet.getFromUser() + "Place") != null) {
                place = placeDao.retrieveByExtendedString(request.getParameter(tweet.getFromUser() + "Place"));
            } else {
                place = null;
            }
            User usersolr = new User(String.valueOf(tweet.getFromUserId()), tweet.getFromUser(),
                    "http://twitter.com/#!/" + tweet.getFromUser(), tweet.getSource(),
                    place != null
                            ? new org.zonales.entities.Place(String.valueOf(place.getId()), place.getName(),
                                    place.getType().getName())
                            : null);

            if (users != null) {
                /*
                 * for (int i = 0; i < usuarios.length; i++) { if
                 * (tweet.getFromUser().equals(usuarios[i])) {
                 * usersolr.setLatitude(Double.parseDouble(latitud[i]));
                 * usersolr.setLongitude(Double.parseDouble(longitud[i])); }
                }
                 */
                //usersolr.setLatitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).latitud));
                //usersolr.setLongitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).longitud));
            }

            solrPost.setFromUser(usersolr);
            if (tweet.getToUser() != null) {
                toUsers.add(new User(String.valueOf(tweet.getToUserId()), tweet.getToUser(), null,
                        tweet.getSource(), null));
                solrPost.setToUsers(toUsers);
            }
            if (tweet.getText().length() > d) {
                while (d > 0 && tweet.getText().charAt(d - 1) != ' ') {
                    d--;
                }
            } else {
                d = tweet.getText().length() - 1;
            }
            solrPost.setTitle(tweet.getText().substring(0, d)
                    + (tweet.getText().length() > MAX_TITLE_LENGTH ? "..." : ""));
            solrPost.setText(tweet.getText());
            //post.setLinks(new LinksType(links));
            solrPost.setActions((ArrayList<ActionType>) actions);
            solrPost.setCreated(tweet.getCreatedAt().getTime());
            solrPost.setModified(tweet.getCreatedAt().getTime());
            solrPost.setRelevance(
                    actions.size() == 2 ? actions.get(0).getCant() * 3 + actions.get(1).getCant() : 0);
            solrPost.setPostLatitude(
                    tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLatitude() : null);
            solrPost.setPostLongitude(
                    tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLongitude() : null);

            links = new ArrayList<LinkType>();
            links.add(new LinkType("avatar", tweet.getProfileImageUrl()));
            if (tweet.getText() != null && getLinks(tweet.getText()) != null) {
                links.addAll(getLinks(tweet.getText()));
            }

            if (solrPost.getLinks() == null) {
                solrPost.setLinks(new ArrayList<LinkType>());
            }
            solrPost.setLinks(links);

            if (tagsArray != null && tagsArray.length > 0) {
                solrPost.setTags(new ArrayList<String>(Arrays.asList(tagsArray)));
            }

            solrPost.setExtendedString(WordUtils.capitalize((solrPost.getFromUser().getPlace() != null
                    ? solrPost.getFromUser().getPlace().getName() + ", "
                    : "") + solrPost.getZone().getExtendedString().replace("_", " ")));
            postList.add(solrPost);

            post = new PostType();
            post.setZone(new Zone(String.valueOf(zoneObj.getId()), zoneObj.getName(),
                    zoneObj.getType().getName(), zoneObj.getExtendedString()));
            post.setSource("Twitter");

            post.setId(String.valueOf(tweet.getId()));
            User user = new User(String.valueOf(tweet.getFromUserId()), tweet.getFromUser(),
                    "http://twitter.com/#!/" + tweet.getFromUser(), tweet.getSource(),
                    place != null
                            ? new org.zonales.entities.Place(String.valueOf(place.getId()), place.getName(),
                                    place.getType().getName())
                            : null);

            if (users != null) {
                /*
                 * for (int i = 0; i < usuarios.length; i++) { if
                 * (tweet.getFromUser().equals(usuarios[i])) {
                 * user.setLatitude(Double.parseDouble(latitud[i]));
                 * user.setLongitude(Double.parseDouble(longitud[i])); }
                }
                 */
                //user.setLatitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).latitud));
                //user.setLongitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).longitud));
            }

            post.setFromUser(user);

            if (tweet.getToUser() != null) {
                toUsers.add(new User(String.valueOf(tweet.getToUserId()), tweet.getToUser(), null,
                        tweet.getSource(), null));
                post.setToUsers(new ToUsersType(toUsers));
            }

            post.setTitle(tweet.getText().substring(0, d)
                    + (tweet.getText().length() > MAX_TITLE_LENGTH ? "..." : ""));
            post.setText(tweet.getText());
            //post.setLinks(new LinksType(links));
            post.setActions(new ActionsType(actions));
            post.setCreated(String.valueOf(tweet.getCreatedAt().getTime()));
            post.setModified(String.valueOf(tweet.getCreatedAt().getTime()));
            post.setRelevance(
                    actions.size() == 2 ? actions.get(0).getCant() * 3 + actions.get(1).getCant() : 0);
            post.setPostLatitude(tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLatitude() : null);
            post.setPostLongitude(
                    tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLongitude() : null);

            links = new ArrayList<LinkType>();
            links.add(new LinkType("avatar", tweet.getProfileImageUrl()));

            post.setLinks(new LinksType(getLinks(tweet.getText())));

            if (tagsArray != null && tagsArray.length > 0) {
                post.setTags(new TagsType(Arrays.asList(tagsArray)));
            }

            postsList.add(post);

        }
        PostsType posts = new PostsType(postsList);
        Gson gson = new Gson();
        if ("xml".equalsIgnoreCase(request.getParameter("format"))) {
            response.setContentType("application/xml");
            out = response.getWriter();
            try {
                for (PostType postIt : posts.getPost()) {
                    postIt.setVerbatim(gson.toJson(postIt));
                }
                Twitter2XML(posts, out);
            } catch (Exception ex) {
                Logger.getLogger(TwitterRetrieval.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            response.setContentType("text/javascript");
            out = response.getWriter();
            out.println("{post: " + gson.toJson(postList) + "}");
        }

    } catch (TwitterException ex) {
        Logger.getLogger(TwitterRetrieval.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:SearchTweets.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param args/*from   ww w  .j  a v  a2  s . c o  m*/
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("java twitter4j.examples.search.SearchTweets [query]");
        System.exit(-1);
    }
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        Query query = new Query(args[0]);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:GetLiveMedia.java

License:Open Source License

public void TweetCollect(String searchString) throws TwitterException {
    tXCoord = 0;//from   w w  w .  j a  v a  2 s  .c  om
    tYCoord = 0;
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("0c1v1wqqNATaVcWpINaHoW3o5")
            .setOAuthConsumerSecret("a6sEAJ1NLY3cXhkMTrMZF62bIfww6qLvlEetDAU9O09Mp04lyh")
            .setOAuthAccessToken("330427831-RJig6B6YycJL3xQVoEjjyRaujwnr1xHEQGtSHOOc")
            .setOAuthAccessTokenSecret("Da71qk4SN6Nu88mLkugDDR6CftVcgOcz3QB8dHNw4hVbD");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
    query = new Query("#" + searchString);
    result = twitter.search(query);
    for (Status status : result.getTweets()) {
        try {
            System.out.println(status.getGeoLocation());
            System.out.println(status.getCreatedAt());
            tXCoord = status.getGeoLocation().getLatitude();
            tYCoord = status.getGeoLocation().getLongitude();
            twitterString = ("@" + status.getUser().getScreenName() + ": " + status.getText() + " : " + "("
                    + tXCoord + ", " + tYCoord + ")");
            twitterURL = "https://twitter.com/" + status.getUser().getScreenName() + "/status/"
                    + status.getId();
        } catch (Exception e) {
        }
    }
}

From source file:ai.ilikeplaces.logic.Listeners.ListenerMain.java

License:Open Source License

/**
 * @param request__/*from   w ww .j  av a 2s. co  m*/
 * @param response__
 */
@Override
public void processRequest(final ItsNatServletRequest request__, final ItsNatServletResponse response__) {
    new AbstractListener(request__, response__) {
        protected String location;

        protected String superLocation;

        protected Long WOEID;

        /**
         * Initialize your document here by appending fragments
         */
        @Override
        @SuppressWarnings("unchecked")
        @_todo(task = "If location is not available, it should be added through a w" + "id"
                + "get(or fragment maybe?)")
        protected final void init(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__,
                final Object... initArgs) {
            final SmartLogger sl = SmartLogger.start(Loggers.LEVEL.DEBUG, "Location Page.", 60000, null, true);

            //this.location = (String) request_.getServletRequest().getAttribute(RBGet.config.getString("HttpSessionAttr.location"));
            getLocationSuperLocation: {
                final String[] attr = ((String) request__.getServletRequest()
                        .getAttribute(RBGet.globalConfig.getString(HTTP_SESSION_ATTR_LOCATION))).split("_");
                location = attr[0];
                if (attr.length == 3) {
                    superLocation = attr[2];
                } else {
                    superLocation = EMPTY;
                }
                tryLocationId: {
                    try {
                        final String w = request__.getServletRequest().getParameter(Location.WOEID);
                        if (w != null) {
                            WOEID = Long.parseLong(request__.getServletRequest().getParameter(Location.WOEID));
                        }
                    } catch (final NumberFormatException e) {
                        Loggers.USER_EXCEPTION.error(WRONG_WOEID_FORMAT, e);
                    }
                }
            }

            sl.appendToLogMSG(RETURNING_LOCATION + location + TO_USER);

            final ResourceBundle gUI = ResourceBundle.getBundle(AI_ILIKEPLACES_RBS_GUI);

            layoutNeededForAllPages: {
                setLoginWidget: {
                    try {
                        new SignInOn(request__, $(Main_login_widget),
                                new SignInOnCriteria().setHumanId(new HumanId(getUsername()))
                                        .setSignInOnDisplayComponent(
                                                SignInOnCriteria.SignInOnDisplayComponent.MOMENTS)) {
                        };
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOGIN_WIDGET, t);
                    }
                }

                SEO: {
                    try {
                        setMainTitle: {
                            $(mainTitle).setTextContent(
                                    MessageFormat.format(gUI.getString("woeidpage.title"), location));
                        }
                        setMetaDescription: {
                            $(mainMetaDesc).setAttribute(MarkupTag.META.content(),
                                    MessageFormat.format(gUI.getString("woeidpage.desc"), location));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SEO, t);
                    }
                }
                signOnDisplayLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0004)
                                            + getUsernameAsValid());
                        } else {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0005)
                                            + location);
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SIGN_ON_DISPLAY_LINK, t);
                    }
                }
                setProfileLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.Profile.getURL());
                        } else {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.signup.getURL());
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_LINK, t);
                    }
                }
                setProfilePhotoLink: {
                    try {
                        if (getUsername() != null) {
                            /**
                             * TODO check for db failure
                             */
                            String url = DB.getHumanCRUDHumanLocal(true)
                                    .doDirtyRHumansProfilePhoto(new HumanId(getUsernameAsValid()))
                                    .returnValueBadly();
                            url = url == null ? null : RBGet.globalConfig.getString(PROFILE_PHOTOS) + url;
                            if (url != null) {
                                $(Main_profile_photo).setAttribute(MarkupTag.IMG.src(), url);
                                //displayBlock($(Main_profile_photo));
                            } else {
                                //displayNone($(Main_profile_photo));
                            }
                        } else {
                            //displayNone($(Main_profile_photo));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_PHOTO_LINK, t);
                    }
                }
            }

            final Return<Location> r;
            if (WOEID != null) {
                r = DB.getHumanCRUDLocationLocal(true).doRLocation(WOEID, REFRESH_SPEC);
            } else {
                r = new ReturnImpl<Location>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION,
                        "Search Unavailable", false);
                //r = DB.getHumanCRUDLocationLocal(true).dirtyRLocation(location, superLocation);
            }

            if (r.returnStatus() == 0 && r.returnValue() != null) {
                final Location existingLocation_ = r.returnValue();

                GEO: {
                    if (existingLocation_.getLocationGeo1() == null
                            || existingLocation_.getLocationGeo2() == null) {
                        final Client ygpClient = YAHOO_GEO_PLANET_FACTORY
                                .getInstance(RBGet.globalConfig.getString("where.yahooapis.com.v1.place"));
                        final Place place = ygpClient.getPlace(existingLocation_.getLocationId().toString());
                        existingLocation_.setLocationGeo1(Double.toString(place.getCoordinates().getY()));
                        existingLocation_.setLocationGeo2(Double.toString(place.getCoordinates().getX()));

                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                DB.getHumanCRUDLocationLocal(true).doULocationLatLng(
                                        new Obj<Long>(existingLocation_.getLocationId()),
                                        new Obj<Double>(place.getCoordinates().getY()),
                                        new Obj<Double>(place.getCoordinates().getX()));
                            }
                        }).run();
                    }
                }

                final Location locationSuperSet = existingLocation_.getLocationSuperSet();
                GEO_WIDGET: {
                    new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Comment(request__,
                            new CommentCriteria(), $(Controller.Page.Main_right_column)) {
                        @Override
                        protected void init(CommentCriteria commentCriteria) {
                            final ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place place = new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place(
                                    request__, new PlaceCriteria()
                                            //This Place
                                            .setPlaceNamePre("Exciting events in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(existingLocation_.getLocationGeo1())
                                            .setPlaceLng(existingLocation_.getLocationGeo2())
                            //Parent Place
                            //.setPlaceSuperName(locationSuperSet.getLocationName())
                            //.setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                            //.setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                            //Parent WOEID
                            //.setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())
                            , $$(CommentIds.commentPerson));
                            place.$$displayNone(place.$$(
                                    ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place.PlaceIds.placeWidget));
                        }
                    };
                }

                final List<String> titleManifest = new ArrayList<String>();

                EVENTS_WIDGETS: {
                    try {
                        /* final JSONObject jsonObject = Modules.getModules().getYahooUplcomingFactory()
                            .getInstance("http://upcoming.yahooapis.com/services/rest/")
                            .get("",
                                    new HashMap<String, String>() {
                                        {//Don't worry, this is a static initializer of this map :)
                                            put("method", "event.search");
                                            put("woeid", WOEID.toString());
                                            put("format", "json");
                                        }
                                    }
                                
                            );
                         final JSONArray events = jsonObject.getJSONObject("rsp").getJSONArray("event");*/

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("http://api.eventful.com/json/events/search/")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("location", "" + existingLocation_.getLocationGeo1() + ","
                                                + existingLocation_.getLocationGeo2());
                                        put("within", "" + 100);
                                    }
                                }

                        );

                        Loggers.debug("Eventful Reply:" + jsonObject.toString());

                        //                            final String eventName = eventJSONObject.getString("title");
                        //                            final String eventUrl = eventJSONObject.getString("url");
                        //                            final String eventDate = eventJSONObject.getString("start_time");
                        //                            final String eventVenue = eventJSONObject.getString("venue_name");

                        final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event");

                        for (int i = 0; i < events.length(); i++) {
                            final JSONObject eventJSONObject = new JSONObject(events.get(i).toString());

                            titleManifest.add(eventJSONObject.get("title").toString());

                            final String photoUrl;
                            String temp = null;
                            try {
                                temp = eventJSONObject.getJSONObject("image").get("url").toString();
                            } catch (final Throwable e) {
                                SmartLogger.g().l(e.getMessage());
                            } finally {
                                photoUrl = temp;
                            }
                            //The pain I go through to make variables final :D

                            new Event(request__, new EventCriteria()
                                    .setEventName(eventJSONObject.get("title").toString())
                                    .setEventStartDate(eventJSONObject.get("start_time").toString())
                                    .setEventPhoto(photoUrl)
                                    .setPlaceCriteria(new PlaceCriteria()
                                            .setPlaceNamePre("This event is taking place in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(eventJSONObject.get("latitude").toString())
                                            .setPlaceLng(eventJSONObject.get("longitude").toString())
                                            //Parent Place
                                            .setPlaceSuperNamePre(
                                                    existingLocation_.getLocationName() + " is located in ")
                                            .setPlaceSuperName(locationSuperSet.getLocationName())
                                            .setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                                            .setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                                            //Parent WOEID
                                            .setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())

                            ), $(Controller.Page.Main_right_column));
                        }
                    } catch (final JSONException e) {
                        sl.l("Error fetching data from Yahoo Upcoming: " + e.getMessage());
                    }
                }

                TWITTER_WIDGETS: {
                    try {
                        final Query _query = new Query(
                                "fun OR happening OR enjoy OR nightclub OR restaurant OR party OR travel :)");
                        _query.geoCode(
                                new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()),
                                        Double.parseDouble(existingLocation_.getLocationGeo2())),
                                40, Query.MILES);
                        _query.setResultType(Query.MIXED);
                        final QueryResult result = TWITTER.search(_query);

                        //final QueryResult result = TWITTER.search(new Query("Happy").geoCode(new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()), Double.parseDouble(existingLocation_.getLocationGeo2())), 160, Query.MILES));
                        for (Status tweet : result.getTweets()) {
                            new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Person(request__,
                                    new PersonCriteria().setPersonName(tweet.getUser().getName())
                                            .setPersonPhoto(tweet.getUser().getProfileImageURL())
                                            .setPersonData(tweet.getText()),
                                    $(Main_right_column));
                            titleManifest.add(tweet.getText());
                        }
                        if (result.getTweets().size() == 0) {
                            sl.l("No twitter results found");
                        }
                    } catch (final Throwable t) {
                        sl.l("An error occurred during twitter fetch:" + t.getMessage());
                    }
                }

                SEO: {
                    setMetaGEOData: {
                        $(Main_ICBM).setAttribute(MarkupTag.META.content(), existingLocation_.getLocationGeo1()
                                + COMMA + existingLocation_.getLocationGeo2());
                        $(Main_geoposition).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationGeo1() + COMMA
                                        + existingLocation_.getLocationGeo2());
                        $(Main_geoplacename).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationName());
                        $(Main_georegion).setAttribute(MarkupTag.META.content(),
                                locationSuperSet.getLocationName());
                    }
                }

                setLocationIdForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationId);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationId().toString());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);

                        $(Main_location_name).setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + "");
                        $(Main_super_location_name).setAttribute(INPUT.value(),
                                locationSuperSet.getLocationName() + "");
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_ID_FOR_JSREFERENCE, t);
                    }
                }

                setLocationNameForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationName);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + OF + locationSuperSet.getLocationName());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_NAME_FOR_JSREFERENCE, t);
                    }
                }

                setLocationAsPageTopic: {
                    try {

                        final StringBuilder title = new StringBuilder();

                        for (final String titleGuest : titleManifest) {
                            title.append(titleGuest);
                        }

                        final String finalTitle = title.toString();

                        $(Main_center_main_location_title).setTextContent(finalTitle.isEmpty()
                                ? (THIS_IS + existingLocation_.getLocationName() + OF + locationSuperSet)
                                : finalTitle);

                        for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true)
                                .doDirtyRLocationsBySuperLocation(existingLocation_))) {
                            $(Main_location_list).appendChild(element);
                            displayBlock($(Main_notice_sh));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_AS_PAGE_TOPIC, t);
                    }
                }
            } else {
                noSupportForNewLocations: {
                    try {
                        //                            $(Main_notice).appendChild(($(P).appendChild(
                        //                                    hTMLDocument__.createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")
                        //                                            + " Were you looking for "
                        //                                    ))));
                        //                            for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true).dirtyRLikeLocations(location))) {
                        //                                $(Main_notice).appendChild(element);
                        //                                displayBlock($(Main_notice_sh));
                        //                            }
                        NotSupportingLikeSearchTooForNow: {
                            $(Main_notice).appendChild(($(P).appendChild(hTMLDocument__
                                    .createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")))));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_NO_SUPPORT_FOR_NEW_LOCATIONS, t);
                    }
                }
            }
            sl.complete(Loggers.LEVEL.SERVER_STATUS, Loggers.DONE);
        }

        /**
         * Use ItsNatHTMLDocument variable stored in the AbstractListener class
         */
        @Override
        protected void registerEventListeners(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__) {
        }

        private List<Element> generateLocationLinks(final List<Location> locationList) {
            final ElementComposer UList = ElementComposer.compose($(UL)).$ElementSetAttribute(MarkupTag.UL.id(),
                    PLACE_LIST);

            for (Location location : locationList) {
                final Element link = $(A);

                link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.href(),
                        PAGE + location.getLocationName() + _OF_
                                + location.getLocationSuperSet().getLocationName()
                                + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

                link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.title(), CLICK_TO_EXPLORE + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.classs(), VTIP);

                final Element linkDiv = $(DIV);

                linkDiv.appendChild(link);

                UList.wrapThis(ElementComposer.compose($(LI)).wrapThis(linkDiv).get());
            }

            final List<Element> elements = new ArrayList<Element>();
            elements.add(UList.get());
            return elements;
        }

        private Element generateLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                    + location.getLocationSuperSet().getLocationName());
            link.setAttribute(A.href(),
                    PAGE + location.getLocationName() + _OF_ + location.getLocationSuperSet().getLocationName()
                            + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                    + location.getLocationSuperSet().getLocationName());
            return link;
        }

        private Element generateSimpleLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(location.getLocationName());
            link.setAttribute(A.href(), PAGE + location.getLocationName()
                    + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName());
            return link;
        }
    };//Listener
}