Example usage for twitter4j Twitter showUser

List of usage examples for twitter4j Twitter showUser

Introduction

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

Prototype

User showUser(long userId) throws TwitterException;

Source Link

Document

Returns extended information of a given user, specified by ID or screen name as per the required id parameter.

Usage

From source file:org.kawalpemilukada.login.login.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w w  .  ja va2  s .  c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String form_action = request.getParameter("form_action");
    if (form_action == null) {
        form_action = "";
    }
    PrintWriter out = response.getWriter();
    if (form_action.equalsIgnoreCase("loginfb")) {
        String tahun = request.getParameter("tahun");
        if (tahun == null) {
            tahun = "";
        }
        Facebook facebook = new FacebookFactory().getInstance();
        request.getSession().setAttribute("facebook", facebook);
        request.getSession().setAttribute("tahun", tahun);
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callbackfb");
        response.sendRedirect(facebook.getOAuthAuthorizationURL(callbackURL.toString()) + "&display=popup");
    }
    if (form_action.equalsIgnoreCase("logintwit")) {
        String tahun = request.getParameter("tahun");
        if (tahun == null) {
            tahun = "";
        }
        Twitter twitter = new TwitterFactory().getInstance();
        request.getSession().setAttribute("twitter", twitter);
        request.getSession().setAttribute("tahun", tahun);
        String rurl = request.getParameter("rurl");
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callbackTwit?rurl=" + rurl);
        try {
            RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
            request.getSession().setAttribute("requestToken", requestToken);
            response.sendRedirect(requestToken.getAuthenticationURL());
        } catch (TwitterException e) {
            request.getSession().removeAttribute("twitter");
            request.getSession().removeAttribute("tahun");
        }
    }

    if (form_action.equalsIgnoreCase("loginmobiletwit")) {
        String t = "twit";
        UserData user = CommonServices.getUser(request);
        LinkedHashMap record = new LinkedHashMap();
        Gson gson = new Gson();
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject input = (JSONObject) JSONValue.parse(sb.toString());
        if (user == null) {
            try {
                JSONObject twit = (JSONObject) input.get("user");
                String id = CommonServices.getVal(twit.get("id"));
                id = id.replaceAll(t, "");
                user = ofy().load().type(UserData.class).id(t + id).now();
                if (user == null) {
                    String accessToken = CommonServices.getVal(twit.get("token"));
                    String accessTokenSecret = CommonServices.getVal(twit.get("secret"));
                    String consumerKey = new CommonServices().getPropValues("kpu.properties", "consumerKey",
                            request);
                    String consumerSecret = new CommonServices().getPropValues("kpu.properties",
                            "consumerSecret", request);
                    ConfigurationBuilder cb = new ConfigurationBuilder();
                    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey)
                            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
                            .setOAuthAccessTokenSecret(accessTokenSecret);
                    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
                    User u = twitter.showUser(twitter.getId());
                    user = new UserData("twit" + CommonServices.getVal(twitter.getId()));
                    user.imgurl = u.getBiggerProfileImageURLHttps().replace("http://", "https://");
                    user.nama = CommonServices.getVal(u.getName());
                    user.link = "https://twitter.com/" + CommonServices.getVal(twitter.getScreenName());
                    user.email = "";
                    user.uuid = CommonServices.getVal(twit.get("uuid"));
                    user.type = t;
                    ofy().save().entity(user).now();
                    Dashboard dashboard = CommonServices.getDashboard(CommonServices.setParentId("2015", "0"));
                    Dashboard dashboard2014 = CommonServices
                            .getDashboard(CommonServices.setParentId("2014", "0"));
                    dashboard.users = CommonServices.getuserSize() + "";
                    ofy().save().entity(dashboard).now();
                    dashboard2014.users = dashboard.users + "";
                    ofy().save().entity(dashboard2014).now();
                } else {
                    user.lastlogin = CommonServices.JakartaTime();
                    user.uuid = CommonServices.getVal(twit.get("uuid"));
                    if (user.link.equalsIgnoreCase("https://twitter.com/kawalpemilukada")
                            || user.link.equalsIgnoreCase(
                                    "https://www.facebook.com/app_scoped_user_id/10153164750839760/")) {
                        user.userlevel = 100000000;
                    }
                    ofy().save().entity(user).now();
                }
                request.getSession().setAttribute("UserData", JSONValue.parse(gson.toJson(user)));
                MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid);
                JSONObject device = (JSONObject) input.get("device");
                mobileSession.platform = CommonServices.getVal(device.get("platform"));
                mobileSession.version = CommonServices.getVal(device.get("version"));
                mobileSession.cordova = CommonServices.getVal(device.get("cordova"));
                mobileSession.model = CommonServices.getVal(device.get("model"));
                mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer"));
                mobileSession.appversion = CommonServices.getVal(device.get("appversion"));
                ofy().save().entity(mobileSession).now();
                record.put("sessionid", mobileSession.uuid);
            } catch (Exception e) {
            }
            record.put("sumber", "bukan dari session");
        } else {
            MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid);
            JSONObject device = (JSONObject) input.get("device");
            mobileSession.platform = CommonServices.getVal(device.get("platform"));
            mobileSession.version = CommonServices.getVal(device.get("version"));
            mobileSession.cordova = CommonServices.getVal(device.get("cordova"));
            mobileSession.model = CommonServices.getVal(device.get("model"));
            mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer"));
            mobileSession.appversion = CommonServices.getVal(device.get("appversion"));
            ofy().save().entity(mobileSession).now();
            record.put("sessionid", mobileSession.uuid);
            record.put("sumber", "dari session");
        }
        record.put("user", JSONValue.parse(gson.toJson(user)));
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("loginmobilefb")) {
        UserData user = CommonServices.getUser(request);
        LinkedHashMap record = new LinkedHashMap();
        Gson gson = new Gson();
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject input = (JSONObject) JSONValue.parse(sb.toString());
        if (user == null) {
            String t = "fb";
            JSONObject fb = (JSONObject) input.get("user");
            String id = CommonServices.getVal(fb.get("id"));
            id = id.replaceAll(t, "");
            try {
                user = ofy().load().type(UserData.class).id(t + id).now();
                if (user == null) {
                    user = new UserData("fb" + CommonServices.getVal(fb.get("id")));
                    user.imgurl = "https://graph.facebook.com/" + fb.get("id") + "/picture";
                    user.nama = CommonServices.getVal(fb.get("name"));
                    user.link = CommonServices.getVal(fb.get("link"));
                    user.email = CommonServices.getVal(fb.get("email"));
                    user.type = t;
                    user.uuid = CommonServices.getVal(fb.get("uuid"));
                    ofy().save().entity(user).now();
                    Dashboard dashboard = CommonServices.getDashboard(CommonServices.setParentId("2015", "0"));
                    Dashboard dashboard2014 = CommonServices
                            .getDashboard(CommonServices.setParentId("2014", "0"));
                    dashboard.users = CommonServices.getuserSize() + "";
                    ofy().save().entity(dashboard).now();
                    dashboard2014.users = dashboard.users + "";
                    ofy().save().entity(dashboard2014).now();
                } else {
                    user.lastlogin = CommonServices.JakartaTime();
                    user.uuid = CommonServices.getVal(fb.get("uuid"));
                    if (user.link.equalsIgnoreCase("https://twitter.com/kawalpemilukada")
                            || user.link.equalsIgnoreCase(
                                    "https://www.facebook.com/app_scoped_user_id/10153164750839760/")) {
                        user.userlevel = 100000000;
                    }
                    ofy().save().entity(user).now();
                }
                request.getSession().setAttribute("UserData", JSONValue.parse(gson.toJson(user)));
                MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid);
                JSONObject device = (JSONObject) input.get("device");
                mobileSession.platform = CommonServices.getVal(device.get("platform"));
                mobileSession.version = CommonServices.getVal(device.get("version"));
                mobileSession.cordova = CommonServices.getVal(device.get("cordova"));
                mobileSession.model = CommonServices.getVal(device.get("model"));
                mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer"));
                mobileSession.appversion = CommonServices.getVal(device.get("appversion"));
                ofy().save().entity(mobileSession).now();
                record.put("sessionid", mobileSession.uuid);
            } catch (Exception e) {
            }
            record.put("sumber", "bukan dari session");
        } else {
            record.put("sumber", "dari session");
            MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid);
            JSONObject device = (JSONObject) input.get("device");
            mobileSession.platform = CommonServices.getVal(device.get("platform"));
            mobileSession.version = CommonServices.getVal(device.get("version"));
            mobileSession.cordova = CommonServices.getVal(device.get("cordova"));
            mobileSession.model = CommonServices.getVal(device.get("model"));
            mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer"));
            mobileSession.appversion = CommonServices.getVal(device.get("appversion"));
            ofy().save().entity(mobileSession).now();
            record.put("sessionid", mobileSession.uuid);
        }
        record.put("user", JSONValue.parse(gson.toJson(user)));
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("cekauth")) {
        UserData user = CommonServices.getUser(request);
        LinkedHashMap record = new LinkedHashMap();
        Gson gson = new Gson();
        if (user == null) {
            record.put("status", "belum login");
        } else {
            record.put("user", JSONValue.parse(gson.toJson(user)));
            if (user.terverifikasi.equalsIgnoreCase("Y")) {
                record.put("status", "terverifikasi");
            } else {
                record.put("status", "Data Anda belum terverifikasi.");
            }
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("verifikasi")) {
        LinkedHashMap record = new LinkedHashMap();
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONArray input = (JSONArray) JSONValue.parse(sb.toString());
        String nama = "";
        String jenis_kelamin = "";
        String no_tps = "";
        try {
            String url = new CommonServices().getPropValues("kpu.properties", "verifikasiURL", request);
            String inputx = getWeb(url + input.get(0).toString());
            JSONObject data = (JSONObject) JSONValue.parse(inputx);
            nama = data.get("nama").toString();
            jenis_kelamin = data.get("jenis_kelamin").toString();
        } catch (Exception e) {
            nama = "";
        }
        if (nama == null || nama.equalsIgnoreCase("")) {
            try {
                String url = new CommonServices().getPropValues("kpu.properties", "verifikasiURL2015", request);
                String inputx = getWeb(url + input.get(0).toString());
                LinkedHashMap data = getJsonNik(inputx);
                nama = data.get("nama").toString();
                jenis_kelamin = data.get("jenis kelamin").toString();
                no_tps = data.get("no_tps").toString();
            } catch (Exception e) {
                nama = "";
            }
        }
        JSONArray matchs = new JSONArray();
        if (nama.equalsIgnoreCase(input.get(1).toString())) {
            UserData user = CommonServices.getUser(request);
            double match = 0;
            //if (data.get("nama").toString().equalsIgnoreCase(user.nama)) {
            //match = 100;
            //} else {
            String[] sosialnamaParts = user.nama.toString().split(" ");
            String[] namaParts = nama.toString().split(" ");
            int dibagi = sosialnamaParts.length;
            if (namaParts.length > dibagi) {
                dibagi = namaParts.length;
            }
            double increase = 100 / dibagi;
            String iiString = "";
            for (int i = 0; i < namaParts.length; i++) {
                String namaPart = namaParts[i];
                for (int ii = 0; ii < sosialnamaParts.length; ii++) {
                    String fbnamaPart = sosialnamaParts[ii];
                    if (namaPart.equalsIgnoreCase(fbnamaPart) && (!iiString.contains(ii + ""))) {
                        match = match + increase;
                        matchs.add(namaPart + " sesuai dengan " + fbnamaPart);
                        iiString = iiString + "[" + ii + "]";
                        break;
                    }
                }
            }
            // }
            if (match > 100) {
                match = 100;
            }
            if (match >= 60) {
                user.terverifikasi = "Y";
                user.notps = no_tps;
                ObjectifyService.ofy().save().entity(user).now();
                Gson gson = new Gson();
                record.put("user", JSONValue.parse(gson.toJson(user)));
            }
            record.put("status", match + "");
            record.put("matchs", matchs);
        } else {
            record.put("status", "Data NIK: " + input.get(0).toString() + " dan Nama: "
                    + input.get(1).toString() + " tidak ditemukan.");
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
}

From source file:org.loklak.harvester.TwitterAPI.java

License:Open Source License

public static JSONObject getUser(String screen_name, boolean forceReload) throws TwitterException, IOException {
    if (!forceReload) {
        JsonFactory mapcapsule = DAO.user_dump.get("screen_name", screen_name);
        if (mapcapsule == null)
            mapcapsule = DAO.user_dump.get("id_str", screen_name);
        if (mapcapsule != null) {
            JSONObject json = mapcapsule.getJSON();
            if (json.length() > 0) {
                // check if the entry is maybe outdated, i.e. if it is empty or too old
                try {
                    Date d = DAO.user_dump.parseDate(json);
                    if (d.getTime() + DateParser.DAY_MILLIS > System.currentTimeMillis())
                        return json;
                } catch (ParseException e) {
                    return json;
                }/*w w w.  j  a  va 2  s .  c  o m*/
            }
        }
    }
    TwitterFactory tf = getUserTwitterFactory(screen_name);
    if (tf == null)
        tf = getAppTwitterFactory();
    if (tf == null)
        return new JSONObject();
    Twitter twitter = tf.getInstance();
    User user = twitter.showUser(screen_name);
    RateLimitStatus rateLimitStatus = user.getRateLimitStatus();
    getUserResetTime = System.currentTimeMillis() + rateLimitStatus.getSecondsUntilReset() * 1000;
    getUserRemaining = rateLimitStatus.getRemaining();
    JSONObject json = user2json(user);
    enrichLocation(json);
    DAO.user_dump.putUnique(json);
    return json;
}

From source file:org.mariotaku.twidere.loader.ParcelableUserLoader.java

License:Open Source License

@Override
public SingleResponse<ParcelableUser> loadInBackground() {
    if (!omit_intent_extra && extras != null) {
        final ParcelableUser user = extras.getParcelable(EXTRA_USER);
        if (user != null) {
            final ContentValues values = ParcelableUser.makeCachedUserContentValues(user);
            resolver.delete(CachedUsers.CONTENT_URI, CachedUsers.USER_ID + " = " + user.id, null);
            resolver.insert(CachedUsers.CONTENT_URI, values);
            return new SingleResponse<ParcelableUser>(user, null);
        }//ww  w  .  j a  v a  2  s  .c  om
    }
    final Twitter twitter = getTwitterInstance(getContext(), account_id, true);
    if (twitter == null)
        return new SingleResponse<ParcelableUser>(null, null);
    if (load_from_cache) {
        final String where = CachedUsers.USER_ID + " = " + user_id + " OR " + CachedUsers.SCREEN_NAME + " = '"
                + screen_name + "'";
        final Cursor cur = resolver.query(CachedUsers.CONTENT_URI, CachedUsers.COLUMNS, where, null, null);
        final int count = cur.getCount();
        try {
            if (count > 0) {
                cur.moveToFirst();
                return new SingleResponse<ParcelableUser>(new ParcelableUser(cur, account_id), null);
            }
        } finally {
            cur.close();
        }
    }
    try {
        final User user;
        if (user_id != -1) {
            user = twitter.showUser(user_id);
        } else if (screen_name != null) {
            user = twitter.showUser(screen_name);
        } else
            return new SingleResponse<ParcelableUser>(null, null);
        final ContentValues values = makeCachedUserContentValues(user, hires_profile_image);
        final String where = CachedUsers.USER_ID + " = " + user.getId() + " OR " + CachedUsers.SCREEN_NAME
                + " = ?";
        resolver.delete(CachedUsers.CONTENT_URI, where, new String[] { user.getScreenName() });
        resolver.insert(CachedUsers.CONTENT_URI, values);
        return new SingleResponse<ParcelableUser>(new ParcelableUser(user, account_id, hires_profile_image),
                null);
    } catch (final TwitterException e) {
        return new SingleResponse<ParcelableUser>(null, e);
    }
}

From source file:org.opencredo.twitter.si.FilterTwitterStreamInboundChannelAdapter.java

License:Apache License

private int[] getUserIds(TwitterCredentials credentials, String[] screenNames) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance(credentials.getScreenName(),
            credentials.getScreenName());
    int[] userIds = new int[screenNames.length];
    for (int ix = 0; ix < screenNames.length; ix++) {
        userIds[ix] = twitter.showUser(screenNames[ix]).getId();
    }//  w w w.  j  a  v  a2 s  .co m
    return userIds;
}

From source file:org.sakaiproject.myshowcase.tool.MyShowcaseSaveArtefactTwitterController.java

License:Open Source License

/**
  * Implementation of AbstractController.handleRequestInternal
  * @param HttpServletRequest request/*w  ww .j a v a  2s.  c o  m*/
  * @param HttpServletResponse response
  * @return ModelAndView
  * @throws Exception
  */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    readRequest(request);

    Owner owner = myshowcaseService.getOwnerById(new Long(ownerId));

    StatusMessage sm = new StatusMessage();

    List<StatusMessage> sms = new ArrayList<StatusMessage>();

    boolean tweetsFound = true;

    int totalTweets = 0;

    int artefactsCount = 0;

    List<Artefact> artefacts = new ArrayList<Artefact>();

    try {

        Twitter twitter = new TwitterFactory().getInstance();

        User user;

        user = twitter.showUser(aDataValue);

        int pageNo = 1;

        int pageSize = 200;

        int totalMatches = 0;

        String matchString = aSearchFilter;

        while (tweetsFound) {

            Paging paging = new Paging(pageNo, pageSize);

            ResponseList<Status> statuses = twitter.getUserTimeline(user.getId(), paging);

            for (Status status : statuses) {

                if ((matchString.length() == 0) || (status.getText().contains(matchString))) {

                    totalMatches++;

                    Artefact artefact = new Artefact();

                    ArtefactDetail artefactDetail = new ArtefactDetail();

                    ArtefactType artefactType = myshowcaseService.getArtefactTypeByName(aType);

                    artefact.setOwner(owner);

                    artefact.setDescription(aDescription);

                    artefact.setName(aTitle);

                    artefact.setShortDesc(aTitle);

                    artefact.setType(artefactType);

                    artefactDetail.setTwitterUserName(aDataValue);

                    artefactDetail.setDetail(status.getText());

                    artefact.setArtefactDetail(artefactDetail);

                    artefacts.add(artefact);

                    //                      myshowcaseService.saveArtefact(artefact) ;

                    //                      artefactsCount++;
                }
            }

            totalTweets += statuses.size();

            pageNo++;

            tweetsFound = (statuses.size() > 0);

        }

    } catch (Exception e) {

        System.out.println("Exception: MyShowcaseSaveArtefactTwitter: " + e.toString());
    }

    if (artefacts.size() > 0) {

        sm = new StatusMessage("OK",
                "A total of " + artefacts.size() + " tweets have been added to your evidence stream.");

        for (Artefact artefact : artefacts) {

            myshowcaseService.saveArtefact(artefact);
        }

    } else {

        sm = new StatusMessage("ERROR",
                "MyShowcase has been unable to collect any tweets for your request. No evidence has been added to your evidence stream.");
    }
    ;

    sms.add(sm);

    response.setContentType("application/json");

    response.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();

    out.write(new Gson().toJson(sms));

    out.flush();

    out.close();

    return null;
}

From source file:org.smarttechie.servlet.SimpleStream.java

public void getStream(TwitterStream twitterStream, String[] parametros, final Session session)//,PrintStream out)
{

    listener = new StatusListener() {

        @Override/* w w  w  .j av  a2s . co  m*/
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {
            Twitter twitter = new TwitterFactory().getInstance();
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();
            System.out.println("");
            String profileLocation = user.getLocation();
            System.out.println(profileLocation);
            long tweetId = status.getId();
            System.out.println(tweetId);
            String content = status.getText();
            System.out.println(content + "\n");

            JSONObject obj = new JSONObject();
            obj.put("User", status.getUser().getScreenName());
            obj.put("ProfileLocation", user.getLocation().replaceAll("'", "''"));
            obj.put("Id", status.getId());
            obj.put("UserId", status.getUser().getId());
            //obj.put("User", status.getUser());
            obj.put("Message", status.getText().replaceAll("'", "''"));
            obj.put("CreatedAt", status.getCreatedAt().toString());
            obj.put("CurrentUserRetweetId", status.getCurrentUserRetweetId());
            //Get user retweeteed
            String otheruser;
            try {
                if (status.getCurrentUserRetweetId() != -1) {
                    User user2 = twitter.showUser(status.getCurrentUserRetweetId());
                    otheruser = user2.getScreenName();
                    System.out.println("Other user: " + otheruser);
                }
            } catch (Exception ex) {
                System.out.println("ERROR: " + ex.getMessage().toString());
            }
            obj.put("IsRetweet", status.isRetweet());
            obj.put("IsRetweeted", status.isRetweeted());
            obj.put("IsFavorited", status.isFavorited());

            obj.put("InReplyToUserId", status.getInReplyToUserId());
            //In reply to
            obj.put("InReplyToScreenName", status.getInReplyToScreenName());

            obj.put("RetweetCount", status.getRetweetCount());
            if (status.getGeoLocation() != null) {
                obj.put("GeoLocationLatitude", status.getGeoLocation().getLatitude());
                obj.put("GeoLocationLongitude", status.getGeoLocation().getLongitude());
            }

            JSONArray listHashtags = new JSONArray();
            String hashtags = "";
            for (HashtagEntity entity : status.getHashtagEntities()) {
                listHashtags.add(entity.getText());
                hashtags += entity.getText() + ",";
            }

            if (!hashtags.isEmpty())
                obj.put("HashtagEntities", hashtags.substring(0, hashtags.length() - 1));

            if (status.getPlace() != null) {
                obj.put("PlaceCountry", status.getPlace().getCountry());
                obj.put("PlaceFullName", status.getPlace().getFullName());
            }

            obj.put("Source", status.getSource());
            obj.put("IsPossiblySensitive", status.isPossiblySensitive());
            obj.put("IsTruncated", status.isTruncated());

            if (status.getScopes() != null) {
                JSONArray listScopes = new JSONArray();
                String scopes = "";
                for (String scope : status.getScopes().getPlaceIds()) {
                    listScopes.add(scope);
                    scopes += scope + ",";
                }

                if (!scopes.isEmpty())
                    obj.put("Scopes", scopes.substring(0, scopes.length() - 1));
            }

            obj.put("QuotedStatusId", status.getQuotedStatusId());

            JSONArray list = new JSONArray();
            String contributors = "";
            for (long id : status.getContributors()) {
                list.add(id);
                contributors += id + ",";
            }

            if (!contributors.isEmpty())
                obj.put("Contributors", contributors.substring(0, contributors.length() - 1));

            System.out.println("" + obj.toJSONString());

            insertNodeNeo4j(obj);

            //out.println(obj.toJSONString());
            String statement = "INSERT INTO TweetsClassification JSON '" + obj.toJSONString() + "';";
            executeQuery(session, statement);
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };
    FilterQuery fq = new FilterQuery();

    fq.track(parametros);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
}

From source file:Principal.Tracker_Twitter.java

License:Minecraft Mod Public

public void guardarResultados_Twitter(List<ObjetoBuscar> lista, BD base, int contadorBase, int TokenIndice)
        throws NoSuchAlgorithmException, KeyManagementException {
    int nuevoContadorBase = 0;
    if (contadorBase >= lista.size()) {
        System.out.println("Termino en:" + contadorBase);
    } else {//www .  j  a va 2s.co m
        System.out.println("---------------------------------------------------------------------:P");

        TrustManager[] trustAllCerts = { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        System.out.println("Token : " + TokenIndice);
        System.out.println(consumerKey[TokenIndice]);
        try {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setOAuthConsumerKey(consumerKey[TokenIndice]);
            cb.setOAuthConsumerSecret(this.consumerSecret[TokenIndice]);
            cb.setOAuthAccessToken(this.token[TokenIndice]);
            cb.setOAuthAccessTokenSecret(this.tokenSecret[TokenIndice]);
            Twitter unauthenticatedTwitter = new TwitterFactory(cb.build()).getInstance();

            for (int numtTweets = contadorBase; numtTweets < contadorBase + 5; numtTweets++) {

                if (((ObjetoBuscar) lista.get(numtTweets)).getUrl().equals("")
                        || ((ObjetoBuscar) lista.get(numtTweets)).getUrl() == null) {

                } else {

                    System.out.println("Usuario:  " + ((ObjetoBuscar) lista.get(numtTweets)).getUrl());

                    String usuariosinArroba = ((ObjetoBuscar) lista.get(numtTweets)).getUrl().replace("@", "");

                    System.out.println("" + usuariosinArroba);

                    try {

                        User usuario = unauthenticatedTwitter.showUser(usuariosinArroba);
                        List<Status> ret = unauthenticatedTwitter.getRetweetsOfMe();
                        List<Status> favoritos = unauthenticatedTwitter.getFavorites();
                        Paging paging = new Paging(1, 1000);
                        ResponseList<Status> statuses = unauthenticatedTwitter.getUserTimeline(usuario.getId(),
                                paging);
                        System.out.println("Followers: " + usuario.getFollowersCount());
                        System.out.println("Yo sigo: " + usuario.getFriendsCount());
                        List<String> listaTweets = new ArrayList();
                        List<Long> ListaRettewts = new ArrayList();
                        List<Integer> ListaFavoritos = new ArrayList();
                        List<Integer> ListaMenciones = new ArrayList();
                        List<Date> ListaFecha = new ArrayList();
                        List<Long> ListaIds = new ArrayList();
                        for (Status sta : statuses) {
                            ListaIds.add(Long.valueOf(sta.getId()));
                            listaTweets.add(sta.getText());
                            ListaRettewts.add(Long.valueOf(Long.parseLong(sta.getRetweetCount() + "")));
                            ListaMenciones.add(Integer.valueOf(sta.getUserMentionEntities().length));
                            ListaFecha.add(sta.getCreatedAt());
                            ListaFavoritos.add(Integer.valueOf(sta.getFavoriteCount()));
                        }
                        for (int i = 0; i < listaTweets.size(); i++) {
                            base.guardarTrackTwitter_Log((Long) ListaIds.get(i),
                                    ((ObjetoBuscar) lista.get(numtTweets)).getUrl(),
                                    (String) listaTweets.get(i), (Date) ListaFecha.get(i),
                                    (Long) ListaRettewts.get(i), ((Integer) ListaFavoritos.get(i)).intValue(),
                                    ((Integer) ListaMenciones.get(i)).intValue());
                        }

                    } catch (Exception e) {
                        System.err.println("Entro al Try por :" + e);
                    }

                    nuevoContadorBase = numtTweets;
                }
            }
            System.out.println("Numero de Contador Base:" + nuevoContadorBase);
            guardarResultados_Twitter(lista, base, nuevoContadorBase + 1, TokenIndice + 1);
        } catch (NumberFormatException e) {
            System.err.println("Fallo por :" + e);
        }
    }
}

From source file:Servlet.CallbackServlet.java

License:Apache License

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from   w  ww  . jav  a  2  s. c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");

    try {
        twitter.getOAuthAccessToken(requestToken, verifier);
        request.getSession().removeAttribute("requestToken");

        String twitterIDString = Long.toString(twitter.getId());
        twitter4j.User user = twitter.showUser(twitter.getId());

        Model.User loggedUser = DBAdmin.getTwitterUser(twitterIDString);

        if (loggedUser == null) {
            String username = user.getName().replaceAll(" ", "");

            if (DBAdmin.isUsernameTaken(username)) {
                int i = 1;
                while (DBAdmin.isUsernameTaken(username + i)) {
                    i++;
                }
                username += i;
            }

            DBAdmin.registerTwitter(twitterIDString, username, "null", "", "player", user.getName(),
                    "unaffliated");
            DirectoryAdmin.prepNewUserDirectory(request, username);

            loggedUser = DBAdmin.getTwitterUser(twitterIDString);
        }

        request.getSession().setAttribute("loggedUser", loggedUser);
    } catch (IllegalStateException | TwitterException ex) {
        throw new ServletException(ex);
    }

    response.sendRedirect("main");
}

From source file:twitfeedbot.BotherSomeoneServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Twitter twit;
    StringBuilder builder = new StringBuilder();
    User victim = null;//from w  ww.j  ava2s.c  o  m
    long cursor = -1;
    long[] friendIDs, victimIDs;
    Random r = new Random();

    resp.setContentType("text/html");
    resp.getWriter().println("<html>");
    resp.getWriter().println("<body>");
    try {
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();

        Trends t = twit.getPlaceTrends(1); //global trends
        friendIDs = twit.getFollowersIDs(twit.getId(), cursor).getIDs();
        if (friendIDs.length == 0)
            resp.getWriter().println("Cannot find any followers to bother");
        else {
            victimIDs = twit.getFollowersIDs(friendIDs[r.nextInt(friendIDs.length)], cursor).getIDs();
            if (victimIDs.length == 0)
                resp.getWriter().println("Cannot find any followers to bother");
            else {
                victim = twit.showUser(victimIDs[r.nextInt(victimIDs.length)]);
                builder.append("@" + victim.getScreenName()).append(" ");
                //Append Wordnik example sentence
                builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                if (builder.length() > 140) //Tweets are maximum 140 characters
                {
                    if (builder.lastIndexOf(";", 110) > 0)
                        builder.setLength(builder.lastIndexOf(";", 110));
                    else if (builder.lastIndexOf(":", 110) > 0)
                        builder.setLength(builder.lastIndexOf(":", 110));
                    else if (builder.lastIndexOf(",", 110) > 0)
                        builder.setLength(builder.lastIndexOf(",", 110));
                    else
                        builder.setLength(110);
                }
                builder.append(" " + t.getTrends()[r.nextInt(t.getTrends().length)].getName());

                if (builder.length() > 140)
                    builder.setLength(140); //Tweets are limited to 140 characters

                twit.updateStatus(builder.toString());
                resp.getWriter().println("Tweet posted: " + builder.toString() + "<br>");
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}

From source file:twitter.metrics.TwitterMetrics.java

/**
 * @param args the command line arguments
 *///from   w w w . j a  v  a 2s .c  o m
public static void main(String[] args) {

    try {

        /*Parte que guarda en un archivo*/
        // Se crea el libro
        HSSFWorkbook libro = new HSSFWorkbook();

        // Se crea una hoja dentro del libro
        HSSFSheet hoja = libro.createSheet();

        // Se crea una fila dentro de la hoja
        HSSFRow fila = hoja.createRow(0);

        // Se crea una celda dentro de la fila
        HSSFCell celda = fila.createCell(1);

        // Se crea el contenido de la celda y se mete en ella.
        HSSFRichTextString texto = new HSSFRichTextString("Metricas de Twitter");
        celda.setCellValue(texto);
        /************************************/

        /*Conexion con Mongo DB*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("JavaMongoTwitter");

        DBCollection datos = db.getCollection("Datos");

        /***********************/

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);

        cb.setOAuthConsumerKey("TobUISZXWUhDda04ZBtFGQ");
        cb.setOAuthConsumerSecret("7xurVN3iP6VDcBfKdFJxVuNsJjExERFYNmQIDgtg");

        cb.setOAuthAccessToken("849956971-GJBiORhLIuWK4i3MJ2YCd4vidh65N1GzPIb6duXk");
        cb.setOAuthAccessTokenSecret("4MJgPS9grxVuKbczrPCdSjNnumhcWs7t7OLy2F4kkpOdu");

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

        User u = twitter.showUser("Pringles");

        System.out.println("Nombre: " + u.getName());
        System.out.println("Seguidores: " + u.getFollowersCount());
        System.out.println("Favoritos: " + u.getFavouritesCount());
        System.out.println("Seguidos: " + u.getFriendsCount());
        System.out.println("Ubicacion: " + u.getLocation());
        System.out.println("Descripcin: " + u.getDescription());
        System.out.println("");

        fila = hoja.createRow(1);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Nombre:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getName()));

        fila = hoja.createRow(2);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidores:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFollowersCount() + ""));

        fila = hoja.createRow(3);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Favoritos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFavouritesCount() + ""));

        fila = hoja.createRow(4);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFriendsCount() + ""));

        fila = hoja.createRow(5);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Ubicacin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getLocation() + ""));

        fila = hoja.createRow(6);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Descripcin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getDescription() + ""));

        fila = hoja.createRow(7);
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweets!!!"));

        fila = hoja.createRow(9);
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString("IdTweet"));
        celda = fila.createCell(2);
        celda.setCellValue(new HSSFRichTextString("Cuenta"));
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweet"));
        celda = fila.createCell(4);
        celda.setCellValue(new HSSFRichTextString("Geolocation"));
        celda = fila.createCell(5);
        celda.setCellValue(new HSSFRichTextString("Place"));
        celda = fila.createCell(6);
        celda.setCellValue(new HSSFRichTextString("Retweets"));
        celda = fila.createCell(7);
        celda.setCellValue(new HSSFRichTextString("Favoritos"));

        Paging paging = new Paging(1, 1000);
        ResponseList<Status> s = twitter.getUserTimeline(u.getId(), paging);
        int i = 0;
        int filaNum = 10;
        for (Status st : s) {

            BasicDBObject obj = new BasicDBObject();

            obj.append("idTweet", s.get(i).getId() + "");
            obj.append("Cuenta", u.getName());
            obj.append("Tweet", s.get(i).getText());
            obj.append("Geolocation", s.get(i).getGeoLocation());
            obj.append("Place", s.get(i).getPlace());
            obj.append("Reteews", s.get(i).getRetweetCount());
            obj.append("Favoritos", s.get(i).getFavoriteCount());

            fila = hoja.createRow(filaNum);
            celda = fila.createCell(1);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getId() + ""));
            celda = fila.createCell(2);
            celda.setCellValue(new HSSFRichTextString(u.getName()));
            celda = fila.createCell(3);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getText()));
            celda = fila.createCell(4);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getGeoLocation() + ""));
            celda = fila.createCell(5);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getPlace() + ""));
            celda = fila.createCell(6);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getRetweetCount() + ""));
            celda = fila.createCell(7);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getFavoriteCount() + ""));

            i++;
            filaNum++;

            datos.insert(obj);
        }

        FileOutputStream elFichero = new FileOutputStream("Metricas_Twitter.xls");
        libro.write(elFichero);
        elFichero.close();

        /********************************/

        System.out.println(i);

        //User usuario = twitter.showUser("@aaron21007");
        //    List<Status> statuses = twitter.getHomeTimeline();
        //    System.out.println("Showing home timeline.");
        //    for (Status status : statuses) {
        //        System.out.println(status.getUser().getName() + ":" +
        //                           status.getText());
        //    }

        //        Twitter unauthenticatedTwitter = new TwitterFactory(cb.build()).getInstance();
        //        
        //          List<String> listaTweets = new ArrayList();
        //          List<Long> ListaRettewts = new ArrayList();
        //          List<Integer> ListaFavoritos = new ArrayList();
        //          List<Integer> ListaMenciones = new ArrayList();
        //          List<Date> ListaFecha = new ArrayList();
        //          List<Long> ListaIds = new ArrayList();
        ////
        //          User usuario = unauthenticatedTwitter.showUser("@aaron21007");
        //          List<Status> ret = unauthenticatedTwitter.getRetweetsOfMe();
        //          List<Status> favoritos = unauthenticatedTwitter.getFavorites();
        //          Paging paging = new Paging(1, 1000);
        //          ResponseList<Status> statuses = unauthenticatedTwitter.getUserTimeline(usuario.getId(), paging);
        //          
        //          
        //          for (Status sta : statuses) {
        //              
        //            ListaIds.add(Long.valueOf(sta.getId()));
        //            listaTweets.add(sta.getText());
        //            ListaRettewts.add(Long.valueOf(Long.parseLong(sta.getRetweetCount() + "")));
        //            ListaMenciones.add(Integer.valueOf(sta.getUserMentionEntities().length));
        //            ListaFecha.add(sta.getCreatedAt());
        //            ListaFavoritos.add(Integer.valueOf(sta.getFavoriteCount()));
        //              System.out.println(sta.getText());
        //              
        //          }
        //          
        //          
        //        
        //       
        //        
    } catch (Exception e) {
        System.err.println("Fallo................." + e);
    }
}