Example usage for twitter4j Query MILES

List of usage examples for twitter4j Query MILES

Introduction

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

Prototype

Unit MILES

To view the source code for twitter4j Query MILES.

Click Source Link

Usage

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

License:Open Source License

/**
 * @param request__/* w ww . j a va  2 s .  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
}

From source file:com.daiv.android.twitter.ui.drawer_activities.discover.NearbyTweets.java

License:Apache License

public void getTweets() {

    canRefresh = false;/*from w ww  .  jav a  2 s . c o m*/

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, DrawerActivity.settings);

                boolean manualLoc = sharedPrefs.getBoolean("manually_config_location", false);

                int i = 0;
                while (!connected && i < 5 && !manualLoc) {
                    try {
                        Thread.sleep(1500);
                    } catch (Exception e) {

                    }

                    i++;
                }

                double latitude = -1;
                double longitude = -1;

                if (manualLoc) {
                    // need to query yahoos api for the location...
                    double[] loc = getLocationFromYahoo(sharedPrefs.getInt("woeid", 2379574));
                    latitude = loc[0];
                    longitude = loc[1];
                } else {
                    // set it from the location client
                    Location location = mLastLocation;
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }

                query = new Query();
                query.setGeoCode(new GeoLocation(latitude, longitude), 10, Query.MILES);

                QueryResult result = twitter.search(query);

                if (result.hasNext()) {
                    hasMore = true;
                    query = result.nextQuery();
                } else {
                    hasMore = false;
                }

                for (Status s : result.getTweets()) {
                    statuses.add(s);
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new TimelineArrayAdapter(context, statuses);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);

                        LinearLayout spinner = (LinearLayout) layout.findViewById(R.id.list_progress);
                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Throwable e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getString(R.string.error), Toast.LENGTH_SHORT).show();
                        } catch (IllegalStateException e) {
                            // not attached to activity
                        }
                    }
                });
            }

            canRefresh = true;
        }
    }).start();
}

From source file:com.javielinux.database.EntitySearch.java

License:Apache License

public Query getQuery(Context cnt) {
    String q = this.getString("words_and");

    if (!this.getString("words_or").equals("")) {
        q += Utils.getQuotedText(this.getString("words_or"), "OR ", false);
    }/*  w  w  w  .  j  a va  2s . c  o  m*/

    if (!this.getString("words_not").equals("")) {
        q += Utils.getQuotedText(this.getString("words_not"), "-", true);
    }

    if (!this.getString("from_user").equals("")) {
        q += " from:" + this.getString("from_user");
    }

    if (!this.getString("to_user").equals("")) {
        q += " to:" + this.getString("to_user");
    }

    if (!this.getString("source").equals("")) {
        q += " source:" + this.getString("source");
    }

    if (this.getInt("attitude") == 1)
        q += " :)";
    if (this.getInt("attitude") == 2)
        q += " :(";

    String modLinks = "filter:links";
    String websVideos = "twitvid OR youtube OR vimeo OR youtu.be";
    String webPhotos = "lightbox.com OR mytubo.net OR imgur.com OR instagr.am OR twitpic OR yfrog OR plixi OR twitgoo OR img.ly OR picplz OR lockerz";

    if (this.getInt("filter") == 1)
        q += " " + modLinks;
    if (this.getInt("filter") == 2)
        q += " " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 3)
        q += " " + websVideos + " " + modLinks;
    if (this.getInt("filter") == 4)
        q += " " + websVideos + " OR " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 5)
        q += " source:twitterfeed " + modLinks;
    if (this.getInt("filter") == 6)
        q += " ?";
    if (this.getInt("filter") == 7)
        q += " market.android.com OR androidzoom.com OR androlib.com OR appbrain.com OR bubiloop.com OR yaam.mobi OR slideme.org "
                + modLinks;

    Log.d(Utils.TAG, "Buscando: " + q);

    Query query = new Query(q);

    if (this.getInt("use_geo") == 1) {
        if (this.getInt("type_geo") == 0) { // coordenadas del mapa
            GeoLocation gl = new GeoLocation(this.getDouble("latitude"), this.getDouble("longitude"));
            String unit = Query.KILOMETERS;
            if (this.getInt("type_distance") == 0)
                unit = Query.MILES;
            query.setGeoCode(gl, this.getDouble("distance"), unit);
        }

        if (this.getInt("type_geo") == 1) { // coordenadas del gps
            Location loc = LocationUtils.getLastLocation(cnt);
            if (loc != null) {
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                String unit = Query.KILOMETERS;
                if (this.getInt("type_distance") == 0)
                    unit = Query.MILES;
                query.setGeoCode(gl, this.getDouble("distance"), unit);
            } else {
                mErrorLastQuery = cnt.getString(R.string.no_location);
            }
        }
    }

    PreferenceManager.setDefaultValues(cnt, R.xml.preferences, false);
    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(cnt);

    int count = Integer.parseInt(preference.getString("prf_n_max_download", "60"));
    if (count <= 0)
        count = 60;

    query.setCount(count);

    String lang = "";
    if (!this.getString("lang").equals(""))
        lang = this.getString("lang");
    if (!lang.equals("all"))
        query.setLang(lang);

    // obtener desde donde quiero hacer la consulta

    if (getInt("notifications") == 1) {
        String where = "search_id = " + this.getId() + " AND favorite = 0";
        int nResult = DataFramework.getInstance().getEntityListCount("tweets", where);
        if (nResult > 0) {
            long mLastIdNotification = DataFramework.getInstance().getTopEntity("tweets", where, "date desc")
                    .getLong("tweet_id");
            query.setSinceId(mLastIdNotification);
        }
    }

    //query.setResultType(Query.POPULAR);

    return query;
}

From source file:com.klinker.android.twitter.ui.drawer_activities.discover.NearbyTweets.java

License:Apache License

public void getTweets() {

    canRefresh = false;//w  w  w  .  j  a  va 2 s.  co  m

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, DrawerActivity.settings);

                boolean manualLoc = sharedPrefs.getBoolean("manually_config_location", false);

                int i = 0;
                while (!connected && i < 5 && !manualLoc) {
                    try {
                        Thread.sleep(1500);
                    } catch (Exception e) {

                    }

                    i++;
                }

                double latitude = -1;
                double longitude = -1;

                if (manualLoc) {
                    // need to query yahoos api for the location...
                    double[] loc = getLocationFromYahoo(sharedPrefs.getInt("woeid", 2379574));
                    latitude = loc[0];
                    longitude = loc[1];
                } else {
                    // set it from the location client
                    Location location = mLocationClient.getLastLocation();
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }

                query = new Query();
                query.setGeoCode(new GeoLocation(latitude, longitude), 10, Query.MILES);

                QueryResult result = twitter.search(query);

                if (result.hasNext()) {
                    hasMore = true;
                    query = result.nextQuery();
                } else {
                    hasMore = false;
                }

                for (Status s : result.getTweets()) {
                    statuses.add(s);
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new TimelineArrayAdapter(context, statuses);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);

                        LinearLayout spinner = (LinearLayout) layout.findViewById(R.id.list_progress);
                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Throwable e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getString(R.string.error), Toast.LENGTH_SHORT).show();
                        } catch (IllegalStateException e) {
                            // not attached to activity
                        }
                    }
                });
            }

            canRefresh = true;
        }
    }).start();
}

From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java

/**
 * Entry point for a Lappsgrid service./*from  w w w . j  ava 2 s.c  o  m*/
 * <p>
 * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object
 * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container}
 * payload.
 * <p>
 * Errors and exceptions that occur during processing should be wrapped in a {@code Data}
 * object with the discriminator set to http://vocab.lappsgrid.org/ns/error
 * <p>
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br />
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br />
 *
 * @param input A JSON string representing a Data object
 * @return A JSON string containing a Data object with a Container payload.
 */
@Override
public String execute(String input) {
    Data<String> data = Serializer.parse(input, Data.class);
    String discriminator = data.getDiscriminator();

    // Return ERRORS back
    if (Discriminators.Uri.ERROR.equals(discriminator)) {
        return input;
    }

    // Generate an error if the used discriminator is wrong
    if (!Discriminators.Uri.GET.equals(discriminator)) {
        return generateError(
                "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator);
    }

    Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false)
            .build();

    // Authentication using saved keys
    Twitter twitter = new TwitterFactory(config).getInstance();
    String key = readProperty(KEY_PROPERTY);
    if (key == null) {
        return generateError("The Twitter Consumer Key property has not been set.");
    }

    String secret = readProperty(SECRET_PROPERTY);
    if (secret == null) {
        return generateError("The Twitter Consumer Secret property has not been set.");
    }

    twitter.setOAuthConsumer(key, secret);

    try {
        twitter.getOAuth2Token();
    } catch (TwitterException te) {
        String errorData = generateError(te.getMessage());
        logger.error(errorData);
        return errorData;
    }

    // Get query String from data payload
    Query query = new Query(data.getPayload());

    // Set the type to Popular or Recent if specified
    // Results will be Mixed by default.
    if (data.getParameter("type") == "Popular")
        query.setResultType(Query.POPULAR);
    if (data.getParameter("type") == "Recent")
        query.setResultType(Query.RECENT);

    // Get lang string
    String langCode = (String) data.getParameter("lang");

    // Verify the validity of the language code and add it to the query if it's valid
    if (validateLangCode(langCode))
        query.setLang(langCode);

    // Get date strings
    String sinceString = (String) data.getParameter("since");
    String untilString = (String) data.getParameter("until");

    // Verify the format of the date strings and set the parameters to query if correctly given
    if (validateDateFormat(untilString))
        query.setUntil(untilString);
    if (validateDateFormat(sinceString))
        query.setSince(sinceString);

    // Get GeoLocation
    if (data.getParameter("address") != null) {
        String address = (String) data.getParameter("address");
        double radius = (double) data.getParameter("radius");
        if (radius <= 0)
            radius = 10;
        Query.Unit unit = Query.MILES;
        if (data.getParameter("unit") == "km")
            unit = Query.KILOMETERS;
        GeoLocation geoLocation;
        try {
            double[] coordinates = getGeocode(address);
            geoLocation = new GeoLocation(coordinates[0], coordinates[1]);
        } catch (Exception e) {
            String errorData = generateError(e.getMessage());
            logger.error(errorData);
            return errorData;
        }

        query.geoCode(geoLocation, radius, String.valueOf(unit));

    }

    // Get the number of tweets from count parameter, and set it to default = 15 if not specified
    int numberOfTweets;
    try {
        numberOfTweets = (int) data.getParameter("count");
    } catch (NullPointerException e) {
        numberOfTweets = 15;
    }

    // Generate an ArrayList of the wanted number of tweets, and handle possible errors.
    // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed
    ArrayList<Status> allTweets;
    Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter);
    String tweetsDataDisc = tweetsData.getDiscriminator();
    if (Discriminators.Uri.ERROR.equals(tweetsDataDisc))
        return tweetsData.asPrettyJson();

    else {
        allTweets = (ArrayList<Status>) tweetsData.getPayload();
    }

    // Initialize StringBuilder to hold the final string
    StringBuilder builder = new StringBuilder();

    // Append each Status (each tweet) to the initialized builder
    for (Status status : allTweets) {
        String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : "
                + status.getText() + "\n";
        builder.append(single);
    }

    // Output results
    Container container = new Container();
    container.setText(builder.toString());
    Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container);
    return output.asPrettyJson();
}

From source file:org.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Returns tweets that match a specified query.
 * <p/>//from  ww w. j  a  v a2  s . co  m
 * This method calls http://search.twitter.com/search.json
 * <p/>
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:search}
 *
 * @param query The search query.
 * @param lang Restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
 * @param locale Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific clients and the default should work in the majority of cases.
 * @param maxId If specified, returns tweets with status ids less than the given id
 * @param since If specified, returns tweets since the given date. Date should be formatted as YYYY-MM-DD
 * @param sinceId Returns tweets with status ids greater than the given id.
 * @param geocode A {@link String} containing the latitude and longitude separated by ','. Used to get the tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile
 * @param radius The radius to be used in the geocode -ONLY VALID IF A GEOCODE IS GIVEN-
 * @param unit The unit of measurement of the given radius. Can be 'mi' or 'km'. Miles by default.
 * @param until If specified, returns tweets with generated before the given date. Date should be formatted as YYYY-MM-DD
 * @param resultType If specified, returns tweets included popular or real time or both in the responce. Both by default. Can be 'mixed', 'popular' or 'recent'.
 * @return the {@link QueryResult}
 * @throws TwitterException when Twitter service or network is unavailable
 */
@Processor
public QueryResult search(String query, @Optional String lang, @Optional String locale, @Optional Long maxId,
        @Optional String since, @Optional Long sinceId, @Optional String geocode, @Optional String radius,
        @Default(value = Query.MILES) @Optional String unit, @Optional String until,
        @Optional String resultType) throws TwitterException {
    final Query q = new Query(query);

    if (lang != null) {
        q.setLang(lang);
    }
    if (locale != null) {
        q.setLocale(locale);
    }
    if (maxId != null && maxId.longValue() != 0) {
        q.setMaxId(maxId.longValue());
    }

    if (since != null) {
        q.setSince(since);
    }
    if (sinceId != null && sinceId.longValue() != 0) {
        q.setSinceId(sinceId.longValue());
    }
    if (geocode != null) {
        final String[] geocodeSplit = StringUtils.split(geocode, ',');
        final double latitude = Double.parseDouble(StringUtils.replace(geocodeSplit[0], " ", ""));
        final double longitude = Double.parseDouble(StringUtils.replace(geocodeSplit[1], " ", ""));
        q.setGeoCode(new GeoLocation(latitude, longitude), Double.parseDouble(radius), unit);
    }
    if (until != null) {
        q.setUntil(until);
    }
    if (resultType != null) {
        q.setResultType(resultType);
    }
    return twitter.search(q);
}