/**
   * Method that performs introspection on an AUTH string, and returns data as a String->String
   * hashmap.
   *
   * @param auth the authstring to query, as built by an auth impl.
   * @return the data from the introspect, in a map.
   * @throws IOException if anything goes wrong.
   */
  private Map<String, String> introspectAuth(String accesstoken) throws IOException {
    Map<String, String> results = new HashMap<String, String>();

    // create a fb client using the supplied access token
    FacebookClient client = new DefaultFacebookClient(accesstoken, Version.VERSION_2_5);

    try {
      // get back just the email, and name for the user, we'll get the id
      // for free.
      // fb only allows us to retrieve the things we asked for back in
      // FacebookAuth when creating the token.
      User userWithMetadata =
          client.fetchObject("me", User.class, Parameter.with("fields", "email,name"));

      results.put("valid", "true");
      results.put("email", userWithMetadata.getEmail());
      results.put("name", userWithMetadata.getName());
      results.put("id", "facebook:" + userWithMetadata.getId());

    } catch (FacebookOAuthException e) {
      results.clear();
      results.put("valid", "false");
    }

    return results;
  }
 public String postFeed(int account_index, String feed) {
   String accountToken = accounts.getData().get(account_index).getAccessToken();
   accountName = accounts.getData().get(account_index).getId();
   FacebookClient account = new DefaultFacebookClient(accountToken, Version.VERSION_2_4);
   FacebookType pubAcctMsg =
       account.publish("me/feed", FacebookType.class, Parameter.with("message", feed));
   return pubAcctMsg.getId().split("_")[1];
 }
 public static void getUserPosts(List<String> ids) {
   FacebookClient fbclient = FacebookUtil.getFBClient();
   for (String id : ids) {
     String query = "select post_id from stream where " + "source_id =" + id + " limit 3000";
     List<FqlPost> fqlPosts = fbclient.executeFqlQuery(query, FqlPost.class);
     for (FqlPost pagePost : fqlPosts) {
       System.out.println(pagePost);
     }
     Connection<Post> myFeed = fbclient.fetchConnection("\"" + id + "/feed", Post.class);
     for (List<Post> myFeedConnectionPage : myFeed)
       for (Post post : myFeedConnectionPage) System.out.println("Post: " + post);
   }
 }
 public String postPhotoFeed(int account_index, String feed, String image) {
   String accountToken = accounts.getData().get(account_index).getAccessToken();
   accountName = accounts.getData().get(account_index).getId();
   FacebookClient account = new DefaultFacebookClient(accountToken, Version.VERSION_2_4);
   FacebookType pubAcctMsg =
       account.publish(
           // F360 FORUM = 1401856530050018
           "me/photos",
           FacebookType.class,
           BinaryAttachment.with("cat.png", PhotoBytes.fetchBytesFromImage(image)),
           Parameter.with("message", feed));
   return pubAcctMsg.getId();
 }
示例#5
0
  private void facebookAuthorise() throws FacebookException {
    // I saved my session key to a .properties file for future use so the user doesn't keep have to
    // authorising my app!
    // auth.getSession returns JSON so we need to decode it just to grab the session key
    // http://wiki.developers.facebook.com/index.php/Auth.getSession
    // Here we pickup the session key and define the authToken we used above in facebookConnect()
    JSONObject json =
        new JSONObject(
            facebookClient.executeQuery(
                "auth.getSession", String.class, Parameter.with("auth_token", facebookAuthToken)));
    facebookSessionKey = json.getString("session_key");

    // An example call, you can literally use anything from the REST API
    Long uid = facebookClient.executeQuery("users.getLoggedInUser", facebookSessionKey);
    System.out.println("FB User ID: " + uid);
  }
示例#6
0
  private void facebookConnect() throws FacebookException {
    // auth.createToken returns a string
    // http://wiki.developers.facebook.com/index.php/Auth.createToken
    facebookAuthToken = facebookClient.executeQuery("auth.createToken", String.class);
    String url =
        "http://www.facebook.com/login.php"
            + "?api_key="
            + FACEBOOK_API_KEY
            + "&fbconnect=true"
            + "&v=1.0"
            + "&connect_display=page"
            + "&session_key_only=true"
            + "&req_perms=read_stream,publish_stream,offline_access"
            + "&auth_token="
            + facebookAuthToken;

    // Here we launch a browser with the above URL so the user can login to Facebook, grant our
    // requested permissions and send our token for pickup later
    if (Desktop.isDesktopSupported()) {
      Desktop desktop = Desktop.getDesktop();

      if (desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
          desktop.browse(new URI(url));
        } catch (IOException ioe) {
          ioe.printStackTrace();
        } catch (URISyntaxException use) {
          use.printStackTrace();
        }
      }
    }
  }
示例#7
0
 /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // TODO Auto-generated method stub
   PrintWriter out = response.getWriter();
   out.println("* Fetching single objects *");
   try {
     User user = fbClient.fetchObject("me", User.class);
     Page page = fbClient.fetchObject("tradesbyjack", Page.class);
     out.println("User name: " + user.getName());
     out.println("User name: " + user.getId());
     out.println("User name: " + user.getGender());
     out.println("Page likes: " + page.getLikes());
   } catch (FacebookOAuthException fbexp) {
     out.println("Cannot find user info. " + fbexp.getErrorMessage());
   }
 }
  public static void getPages() {

    Page page = facebookClient.fetchObject("cocacola", Page.class);

    System.out.println(page.getAbout());
    System.out.println("\n" + page.getDescription());
    System.out.println("\n" + page.getMission());
    System.out.println("\n" + page.getLocation().toString());
    System.out.println("\n" + page.getAccessToken());
  }
示例#9
0
 private void createUserSessionDetails(HttpServletRequest request, AuthToken token) {
   // create client and get facebook user
   log.debug("Creating new Facebook client for token: " + token);
   FacebookClient client = new DefaultFacebookClient(token.getToken());
   FacebookUser fbuser = client.fetchObject("me", FacebookUser.class);
   // get current session and fetch user
   Session session = sessionManager.getSessionByExternalId(fbuser.getId(), operatorId);
   log.debug("Found session for client: " + session);
   User user = userManager.getUser(session.getUserId());
   // update display name
   userManager.setDisplayName(user.getId(), fbuser.getName());
   // fire event
   fbuser.updateKalahDetails(user);
   eventSink.userLoggedIn(user, fbuser);
   // store objects in session
   setSessionAttribute(request, SESSION_ATTR, session);
   setSessionAttribute(request, CLIENT_ATTR, client);
   setSessionAttribute(request, USER_ATTR, user);
 }
示例#10
0
 public static void fbLogin() {
   String token = params.get("token");
   if (null != token && !token.isEmpty()) {
     FacebookClient fb = new DefaultFacebookClient(token);
     User fbUser = fb.fetchObject("me", User.class);
     Logger.info("Facebook User:"******"Such a user does not exists. Create/Register one...");
       // Register a new...
       // Email uniqueness is controlled by Facebook I suppose, so no need to check on our side...
       sesUser = new SUser(fbUser.getName(), fbUser.getEmail());
       sesUser.fbId = fbUser.getId();
       sesUser.save();
     }
     Auth.fbLogin(token, sesUser);
   } else {
     redirect("/");
   }
 }
示例#11
0
  @Override
  public List<Comment> fetchCommentList(Post post) {

    List<Comment> postCommentList = new ArrayList<Comment>();
    Connection<Comment> connection =
        facebookClient.fetchConnection(post.getId() + "/comments", Comment.class);
    for (List<Comment> page : connection) {
      for (Comment comment : page) {
        postCommentList.add(comment);
      }
    }

    return postCommentList;
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<br><h4>we are getting data</h4>");
    String code = request.getParameter("code");
    out.println("<br>code: " + code);
    out.println("<br>");
    try {
      OAuthClientRequest requestOAuth =
          OAuthClientRequest.tokenLocation("https://graph.facebook.com/oauth/access_token")
              .setGrantType(GrantType.AUTHORIZATION_CODE)
              .setClientId(apiKey)
              .setClientSecret(secretKey)
              .setRedirectURI(redirectUri)
              .setCode(code)
              .buildBodyMessage();

      OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

      GitHubTokenResponse oAuthResponse =
          oAuthClient.accessToken(requestOAuth, GitHubTokenResponse.class);
      accessToken = oAuthResponse.getAccessToken();
      expiresIn = oAuthResponse.getExpiresIn();
    } catch (OAuthSystemException ae) {
      ae.printStackTrace();
    } catch (OAuthProblemException pe) {
      pe.printStackTrace();
    }

    // out.println("<br>Access Token: " + accessToken);
    // out.println("<br>Expires In: " + expiresIn);

    try {
      FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
      myFriends = facebookClient.fetchConnection("me/friends", User.class);
      myFeeds = facebookClient.fetchConnection("me/home", Post.class);

      for (User myFriend : myFriends.getData()) {
        f.add(myFriend.getName());
        out.println("<br>id: " + myFriend.getId() + " Name: " + myFriend.getName());
      }
      //	out.println("<br>");
      out.println("<br>f count: " + f.size());
    } catch (FacebookException e) {
      e.printStackTrace();
    }

    facebookDataBean fdb = new facebookDataBean();
    fdb.setName("zishan ali khan");
    HttpSession session = request.getSession();
    if (session != null) {
      session.setAttribute("myfdb", fdb);
      session.setAttribute("yourFriends", f);
      session.setAttribute("feeds", myFeeds);
      RequestDispatcher view = request.getRequestDispatcher("result.jsp");
      view.forward(request, response);
      f.clear();
      // out.println("<br>I am in");
    } else {
      // out.println("<br>Session Over");
    }
  }
示例#13
0
 @Override
 public Post get(String postId) {
   return facebookClient.fetchObject(postId, Post.class);
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @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 {
    response.setContentType("text/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      // THIS is for NOKIA application
      Logger.getLogger(FBPlacesServlet.class.getName())
          .log(Level.SEVERE, "Oops !!! Somebody called " + FBPlacesServlet.class.getName());

      if (HttpUtils.isEmptyAny(request, "latitude", "longitude", "distance")) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      } else {
        String latitude = request.getParameter("latitude");
        String longitude = request.getParameter("longitude");
        String distance = request.getParameter("distance");
        int limit = NumberUtils.getInt(request.getParameter("limit"), 30);

        FacebookClient facebookClient =
            FacebookUtils.getFacebookClient(Commons.getProperty(Property.fb_app_token));

        String query = request.getParameter("q");
        JsonObject placesSearch = null;

        if (query != null && query.length() > 0) {
          placesSearch =
              facebookClient.fetchObject(
                  "search",
                  JsonObject.class,
                  Parameter.with("type", "place"),
                  Parameter.with("center", latitude + "," + longitude),
                  Parameter.with("distance", distance),
                  Parameter.with("q", query),
                  Parameter.with("limit", limit));
        } else {
          placesSearch =
              facebookClient.fetchObject(
                  "search",
                  JsonObject.class,
                  Parameter.with("type", "place"),
                  Parameter.with("center", latitude + "," + longitude),
                  Parameter.with("distance", distance),
                  Parameter.with("limit", limit));
        }

        JsonArray data = placesSearch.getJsonArray("data");

        ArrayList<Object> jsonArray = new ArrayList<Object>();
        String output = "";

        if (request.getParameter("version") != null
            && request.getParameter("version").equals("3")) {

          for (int i = 0; i < data.length(); i++) {
            Map<String, Object> jsonObject = new HashMap<String, Object>();
            JsonObject place = (JsonObject) data.get(i);
            jsonObject.put("name", place.getString("name"));
            jsonObject.put("url", place.getString("id"));

            Map<String, String> desc = new HashMap<String, String>();
            if (place.has("category")) {
              desc.put("category", place.getString("category"));
            }
            JsonObject location = place.getJsonObject("location");
            Iterator<?> iter = location.sortedKeys();
            while (iter.hasNext()) {
              String next = (String) iter.next();
              if (!(next.equals("latitude") || next.equals("longitude"))) {
                desc.put(next, location.getString(next));
              }
            }
            jsonObject.put("desc", desc);
            jsonObject.put("lat", MathUtils.normalizeE6(location.getDouble("latitude")));
            jsonObject.put("lng", MathUtils.normalizeE6(location.getDouble("longitude")));
            jsonArray.add(jsonObject);
          }

          JSONObject json = new JSONObject().put("ResultSet", jsonArray);
          output = json.toString();

        } else if (request.getParameter("version") != null
            && request.getParameter("version").equals("2")) {

          for (int i = 0; i < data.length(); i++) {
            Map<String, Object> jsonObject = new HashMap<String, Object>();
            JsonObject place = (JsonObject) data.get(i);
            jsonObject.put("name", place.getString("name"));
            jsonObject.put("desc", place.getString("id"));
            JsonObject location = place.getJsonObject("location");
            jsonObject.put("lat", MathUtils.normalizeE6(location.getDouble("latitude")));
            jsonObject.put("lng", MathUtils.normalizeE6(location.getDouble("longitude")));
            jsonArray.add(jsonObject);
          }

          JSONObject json = new JSONObject().put("ResultSet", jsonArray);
          output = json.toString();

        } else {
          // data
          for (int i = 0; i < data.length(); i++) {
            Map<String, Object> jsonObject = new HashMap<String, Object>();
            JsonObject place = (JsonObject) data.get(i);
            if (place.has("name")) {
              jsonObject.put("name", place.getString("name"));
            } else {
              jsonObject.put("name", place.getString("id"));
            }
            jsonObject.put("id", place.getString("id"));
            JsonObject location = place.getJsonObject("location");
            jsonObject.put("lat", MathUtils.normalizeE6(location.getDouble("latitude")));
            jsonObject.put("lng", MathUtils.normalizeE6(location.getDouble("longitude")));
            jsonArray.add(jsonObject);
          }

          JSONObject json = new JSONObject().put("data", jsonArray);
          output = json.toString();
        }

        out.println(output);
      }
    } catch (Exception ex) {
      Logger.getLogger(FBPlacesServlet.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
      if (ex instanceof FacebookOAuthException) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
    } finally {
      out.close();
    }
  }
 public FacebookAccountPublisher(String token) {
   accessToken = token;
   myFb = new DefaultFacebookClient(accessToken, Version.VERSION_2_4);
   accounts = myFb.fetchConnection("me/accounts", Account.class);
 }