private static void fetchLikesAndUpdateUsers(Post post, Set<User> users, Page page) {
   PagedList<Reference> likes = facebook.likeOperations().getLikes(post.getId());
   int totalLikes = likes.size();
   for (Reference userLike : likes) {
     User user =
         users
             .stream()
             .filter(f -> f.getId().equals(userLike.getId()))
             .findFirst()
             .orElse(new User(userLike.getId(), userLike.getName(), page));
     user.addLike(post, page.getId());
     users.add(user);
   }
   while (likes.getNextPage() != null) {
     likes = facebook.likeOperations().getLikes(post.getId(), likes.getNextPage());
     totalLikes += likes.size();
     for (Reference userLike : likes) {
       User user =
           users
               .stream()
               .filter(f -> f.getId().equals(userLike.getId()))
               .findFirst()
               .orElse(new User(userLike.getId(), userLike.getName(), page));
       user.addLike(post, page.getId());
       users.add(user);
     }
   }
   post.getExtraData().putIfAbsent("likesCount", totalLikes);
 }
  protected static String getOwnerMail() {
    Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
    String email = "";
    if (currentAuthentication instanceof SocialAuthenticationToken) {
      SocialAuthenticationToken social = (SocialAuthenticationToken) currentAuthentication;

      switch (social.getProviderId()) {
        case ("google"):
          Google google = (Google) social.getConnection().getApi();
          email = google.plusOperations().getGoogleProfile().getAccountEmail();
          break;
        case ("facebook"):
          Facebook facebook = (Facebook) social.getConnection().getApi();
          email = facebook.userOperations().getUserProfile().getEmail();
          break;
      }
    } else if (currentAuthentication instanceof UsernamePasswordAuthenticationToken) {
      UsernamePasswordAuthenticationToken local =
          (UsernamePasswordAuthenticationToken) currentAuthentication;
      email = (String) local.getPrincipal();
    } else if (currentAuthentication instanceof AnonymousAuthenticationToken) {
      return null;
    }
    return email;
  }
  @Override
  public Authentication authenticate(Authentication a) throws AuthenticationException {
    FacebookUserDTO fud = (FacebookUserDTO) a.getPrincipal();
    String credentials = (String) a.getCredentials();

    // fetch user from our DB
    FacebookUser user = usersService.getByFacebookId(fud.getFacebookProfileId());

    // checking according to spring security documentation
    if (user.isDisabled()) {
      logger.info("Account disabled: " + user);
      throw new DisabledException("Konto wyłączone");
    }
    if (user.isLocked()) {
      logger.info("Account locked: " + user);
      throw new LockedException("Konto zablokowane");
    }

    // if user is allowed to access - allow him :)
    List<GrantedAuthority> authorities = usersService.getUsersAuthorities(user);
    logger.info("User granted authorities=" + authorities);

    // fetch profile of logged user and fill information from his profile
    Facebook facebook = new FacebookTemplate(fud.getAccessToken());
    FacebookProfile facebookProfile = facebook.userOperations().getUserProfile();
    fillUserData(user, facebookProfile);
    user.setAccessToken(fud.getAccessToken());

    Authentication auth = new UsernamePasswordAuthenticationToken(user, credentials, authorities);
    logger.info("Authentication completed: " + auth);
    return auth;
  }
  public static void collect(CollectorInfo.Moment moment) {
    List<Page> pages = MongoService.getAllPages();
    for (Page page : pages) {
      try {

        long lastMonth = DateTime.now().minusMonths(1).toDateTime().getMillis() / 1000;
        long now = DateTime.now().toDateTime().getMillis() / 1000;

        PagingParameters pagingParameters = new PagingParameters(25, null, lastMonth, now);
        PagedList<Post> posts;
        switch (moment) {
          case ALL:
            posts = facebook.feedOperations().getPosts(page.getId());
            break;
          case RECENT:
            posts = facebook.feedOperations().getPosts(page.getId(), pagingParameters);
            break;
          default:
            posts = facebook.feedOperations().getPosts(page.getId());
            break;
        }

        boolean firstTime = true;
        do {
          try {
            if (!firstTime)
              posts = facebook.feedOperations().getPosts(page.getId(), posts.getNextPage());
            firstTime = false;
            for (Post post : posts) {
              Set<User> users = new HashSet<>();
              Set<Comment> comments = new HashSet<>();
              fetchCommentAndUpdateUsers(post, comments, users, page);
              fetchLikesAndUpdateUsers(post, users, page);

              MongoService.save(post);

              for (Comment comment : comments) {
                MongoService.save(comment);
              }
              // save or update users iterations
              MongoService.save(users);
            }
          } catch (Exception e) {
            Logger.debug("error on get more  posts: " + e.getMessage());
          }
          Logger.debug("update:" + page.getTitle() + "  ");
        } while (posts.getNextPage() != null);
        Logger.debug("Finished page:" + page.getId());

      } catch (Exception e) {
        Logger.debug("error on page:" + page.getId());
      }
    }
  }
 @RequestMapping(value = "/player/games", method = RequestMethod.GET)
 public String getAvailabilities(Model model) {
   Player player = teamService.getPlayerByFbId(facebook.userOperations().getUserProfile().getId());
   List<Team> teams = player.getTeam();
   List<Game> games = new ArrayList<>();
   teams.forEach((team) -> games.addAll(team.getGames()));
   Collections.sort(games, (x1, x2) -> x1.getDate().compareTo(x2.getDate()));
   model.addAttribute("fbid", facebook.userOperations().getUserProfile().getId());
   model.addAttribute("games", games);
   model.addAttribute("player", player);
   return "showplayergames";
 }
  @RequestMapping(method = RequestMethod.GET)
  public String helloFacebook(Model model) {
    if (!facebook.isAuthorized()) {
      return "redirect:/connect/facebook";
    }

    FacebookProfile facebookProfile = facebook.userOperations().getUserProfile();
    model.addAttribute(facebookProfile);
    // PagedList<Checkin> homeFeed = facebook.placesOperations().getCheckins();
    // model.addAttribute("feed", homeFeed);

    return "hello";
  }
 @RequestMapping(value = "/manager/imanage", method = RequestMethod.GET)
 public String imanage(Model model) {
   String fbId = facebook.userOperations().getUserProfile().getId();
   List<Team> teams = teamService.findTeamsByManager(fbId);
   model.addAttribute("teams", teams);
   return "showteams";
 }
  public UserAccount fillLocationFromFacebook(UserAccount userAccount) {
    Reference fbhome = facebook.userOperations().getUserProfile().getHometown();
    String loca = "";
    // FIXME move to "submit"
    if (fbhome != null) {
      List<YahooPlaceResult> places = yahooPlaceFinderService.searchPlaceResult(fbhome.getName());
      Location location = new Location();
      if (places.size() > 0) {
        YahooPlaceResult place = places.get(0);
        location.setCity(place.getCity());
        location.setLatitude(place.getLatitude().floatValue());
        location.setLongitude(place.getLongitude().floatValue());
        location.setStateInitial(place.getStateCode());
        Zip zip = null;
        try {
          zip = Zip.findZipsByZipCode(place.getUzip().toString()).getSingleResult();
        } catch (NoResultException e) {
          zip = new Zip();
          zip.setZipCode(place.getUzip().toString());
          zip.setLatitude(place.getLatitude().floatValue());
          zip.setLongitude(place.getLongitude().floatValue());
          zip.persist();
        }
        location.setZip(zip);

        // POINT( LON LAT )
        //				userAccount.setWkt("POINT( " + place.getLongitude() + " " + place.getLatitude() + "
        // )");
        userAccount.setWktLocation(place.getLongitude(), place.getLatitude());
      }
      userAccount.setLocation(location);
    }
    return userAccountService.updateUserAccount(userAccount);
  }
  //	@RequestMapping(method=RequestMethod.GET)
  public String facebook(Model model) {
    if (!facebook.isAuthorized()) {
      return "redirect:/connect/facebook";
    }

    return "hello";
  }
 @RequestMapping(value = "/player/games/{id}", method = RequestMethod.GET)
 public String getGameForPlayer(@PathVariable("id") long id, Model model) {
   Game game = teamService.findGameWithAvailability(id);
   Availability availability = new Availability();
   List<String> statuses = new ArrayList<>();
   statuses.add(TeamService.UNDEFINED);
   statuses.add(TeamService.NOTSURE);
   statuses.add(TeamService.THERE);
   statuses.add(TeamService.CANT);
   model.addAttribute("availability", availability);
   model.addAttribute("statuses", statuses);
   model.addAttribute("fbId", facebook.userOperations().getUserProfile().getId());
   model.addAttribute("game", game);
   return "showplayeravailability";
 }
 @RequestMapping(value = "/", method = RequestMethod.POST)
 public String home1(Model model) {
   List<Reference> friends = facebook.friendOperations().getFriends();
   model.addAttribute("friends", friends);
   return "home";
 }
 @RequestMapping(value = "/player/teams/join", method = RequestMethod.POST)
 public String joinTeam(@ModelAttribute("Team") Team myTeam, Model model) {
   FacebookProfile userProfile = facebook.userOperations().getUserProfile();
   Team team = teamService.joinPlayer(userProfile, myTeam);
   return "redirect:/player/games";
 }
 @RequestMapping(value = "/manager/teams/add", method = RequestMethod.POST)
 public String addTeam(@ModelAttribute("Team") Team team) {
   Team savedteam = teamService.save(team, facebook.userOperations().getUserProfile());
   return "redirect:/manager/teams/" + savedteam.getId();
 }
 @RequestMapping(value = "/facebook/feed", method = RequestMethod.POST)
 public String postUpdate(String message) {
   facebook.feedOperations().updateStatus(message);
   return "redirect:/facebook/feed";
 }
 @RequestMapping(value = "/facebook/feed", method = RequestMethod.GET)
 public String showFeed(Model model) {
   model.addAttribute("feed", facebook.feedOperations().getFeed());
   return "facebook/feed";
 }
  private static void fetchCommentAndUpdateUsers(
      Post post, Set<Comment> commentsToSave, Set<User> users, Page page) {
    PagedList<Comment> comments = facebook.commentOperations().getComments(post.getId());
    int totalComments = comments.size();

    for (Comment comment : comments) {

      User user =
          users
              .stream()
              .filter(f -> f.getId().equals(comment.getFrom().getId()))
              .findFirst()
              .orElse(new User(comment.getFrom().getId(), comment.getFrom().getName(), page));
      user.addComment(comment, post, page.getId());
      users.add(user);

      commentsToSave.add(comment);
      if (comment.getCommentCount() != null && comment.getCommentCount() > 0) {
        PagedList<Comment> commentsComments =
            facebook.commentOperations().getComments(comment.getId());
        for (Comment commentsComment : commentsComments) {

          user =
              users
                  .stream()
                  .filter(f -> f.getId().equals(commentsComment.getFrom().getId()))
                  .findFirst()
                  .orElse(new User(comment.getFrom().getId(), comment.getFrom().getName(), page));
          user.addComment(commentsComment, post, page.getId());
          users.add(user);
          commentsToSave.add(comment);
        }
        while (commentsComments.getNextPage() != null) {
          commentsComments =
              facebook.commentOperations().getComments(post.getId(), comments.getNextPage());
          for (Comment commentsComment : commentsComments) {
            user =
                users
                    .stream()
                    .filter(f -> f.getId().equals(commentsComment.getFrom().getId()))
                    .findFirst()
                    .orElse(new User(comment.getFrom().getId(), comment.getFrom().getName(), page));
            user.addComment(commentsComment, post, page.getId());
            users.add(user);
            commentsToSave.add(comment);
          }
        }
      }
    }
    while (comments.getNextPage() != null) {
      comments = facebook.commentOperations().getComments(post.getId(), comments.getNextPage());
      totalComments += comments.size();

      for (Comment comment : comments) {
        User user =
            users
                .stream()
                .filter(f -> f.getId().equals(comment.getFrom().getId()))
                .findFirst()
                .orElse(new User(comment.getFrom().getId(), comment.getFrom().getName(), page));
        user.addComment(comment, post, page.getId());
        users.add(user);
        commentsToSave.add(comment);
        if (comment.getCommentCount() != null && comment.getCommentCount() > 0) {
          PagedList<Comment> commentsComments =
              facebook.commentOperations().getComments(comment.getId());
          for (Comment commentsComment : commentsComments) {

            user =
                users
                    .stream()
                    .filter(f -> f.getId().equals(commentsComment.getFrom().getId()))
                    .findFirst()
                    .orElse(new User(comment.getFrom().getId(), comment.getFrom().getName(), page));
            user.addComment(commentsComment, post, page.getId());
            users.add(user);
            commentsToSave.add(comment);
          }
          while (commentsComments.getNextPage() != null) {
            commentsComments =
                facebook.commentOperations().getComments(post.getId(), comments.getNextPage());
            for (Comment commentsComment : commentsComments) {
              user =
                  users
                      .stream()
                      .filter(f -> f.getId().equals(commentsComment.getFrom().getId()))
                      .findFirst()
                      .orElse(
                          new User(comment.getFrom().getId(), comment.getFrom().getName(), page));
              user.addComment(commentsComment, post, page.getId());
              users.add(user);
              commentsToSave.add(comment);
            }
          }
        }
      }
    }
    post.getExtraData().putIfAbsent("commentsCount", totalComments);
  }