Java源码示例:com.restfb.FacebookClient

示例1
/**
 * Creates a {@code DefaultMessenger} instance.
 *
 * If the app secret is not provided ({@code null} the callback signature verification will be disabled.
 *
 * The access token and api version need to be configured on the provided facebook client.
 *
 * @param verifyToken     the verify token
 * @param appSecret       the app secret
 * @param callbackHandler the callback handler
 * @param facebookClient  the facebook client
 */
public DefaultMessenger(String verifyToken, String appSecret, CallbackHandler callbackHandler, FacebookClient facebookClient) {
    this.verifyToken = verifyToken;
    this.appSecret = appSecret;
    this.callbackHandler = callbackHandler;
    this.facebookClient = facebookClient;
    this.sendOperations = new DefaultSendOperations(facebookClient);
    if (appSecret == null) {
        if (logger.isLoggable(WARNING)) {
            logger.warning("App secret not configured; webhook signature will not be verified");
        }
    }
    if (callbackHandler == null) {
        if (logger.isLoggable(WARNING)) {
            logger.warning("Webhook handler not configured; webhook callbacks will not be handled");
        }
    }
}
 
示例2
@Test
public void testDefaultAutoConfiguration() {
    load(new Class[] {CallbackHandlerConfig.class, MessengerAutoConfiguration.class},
            "restfbmessenger.verify-token: the_verify_token",
            "restfbmessenger.access-token: the_access_token",
            "restfbmessenger.app-secret: the_app_secret");

    Messenger messenger = this.context.getBean(Messenger.class);
    DefaultMessenger defaultMessenger = (DefaultMessenger) messenger;
    FacebookClient facebookClient =
            (FacebookClient) getFieldValue(defaultMessenger, "facebookClient");
    DefaultFacebookClient defaultFacebookClient = (DefaultFacebookClient) facebookClient;
    CallbackHandler callbackHandler =
            (CallbackHandler) getFieldValue(defaultMessenger, "callbackHandler");

    assertThat((String) getFieldValue(defaultMessenger, "verifyToken"), is("the_verify_token"));
    assertThat((String) getFieldValue(defaultMessenger, "appSecret"), is("the_app_secret"));
    assertThat((String) getFieldValue(defaultFacebookClient, "accessToken"),
            is("the_access_token"));
    assertThat((String) getFieldValue(defaultFacebookClient, "appSecret"),
            is("the_app_secret"));
    assertThat(callbackHandler, is(notNullValue()));
    assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings(),
            hasItem("/webhook/*"));
}
 
示例3
void importSingleVideo(FacebookClient client, VideoObject video) {
  ArrayList<Parameter> params = new ArrayList<>();
  params.add(Parameter.with("file_url", video.getContentUrl().toString()));
  if (video.getDescription() != null)
    params.add(Parameter.with("description", video.getDescription()));

  String endpoint = "me/videos";
  client.publish(endpoint, GraphResponse.class, params.toArray(new Parameter[0]));
}
 
示例4
@Override
protected void notify(Parameters parameters) throws NotificationException {
    try {
        FacebookClient facebookClient =
                createFacebookClient(getConfiguration().getString(KEY_ACCESS_TOKEN));

        FacebookType publishResponse;

        if (hasMovie()) {
            publishResponse = facebookClient.publish("me/videos", FacebookType.class,
                    BinaryAttachment.with(movie.getFileName().toString(),
                            Files.readAllBytes(movie),
                            Files.probeContentType(movie)),
                    com.restfb.Parameter.with("description", message));
        } else if (hasPhoto()) {
            publishResponse = facebookClient.publish("me/photos", FacebookType.class,
                    BinaryAttachment.with(
                            photo.getFileName().toString(),
                            Files.readAllBytes(photo),
                            Files.probeContentType(photo)),
                    com.restfb.Parameter.with("message", message));
        } else {
            publishResponse =
                    facebookClient.publish("me/feed", FacebookType.class,
                            com.restfb.Parameter.with("message", message));
        }

        log.debug("Published content has ID {}", publishResponse.getId());
    } catch (FacebookException | IOException e) {
        throw new NotificationException(e);
    }
}
 
示例5
@Before
public void setUp() {
    this.callbackHandler = mock(CallbackHandler.class);
    this.facebookClient = mock(FacebookClient.class);
    this.facebookOAuthException = mock(FacebookOAuthException.class);
    this.jsonMapper = mock(JsonMapper.class);
    this.messenger = new DefaultMessenger(verifyToken, appSecret, callbackHandler, facebookClient);
    when(facebookClient.getJsonMapper()).thenReturn(jsonMapper);
}
 
示例6
@Test
public void testNoAppSecret() {
    load(new Class[] {CallbackHandlerConfig.class, MessengerAutoConfiguration.class},
            "restfbmessenger.verify-token: the_verify_token",
            "restfbmessenger.access-token: the_access_token");

    Messenger messenger = this.context.getBean(Messenger.class);
    DefaultMessenger defaultMessenger = (DefaultMessenger) messenger;
    FacebookClient facebookClient =
            (FacebookClient) getFieldValue(defaultMessenger, "facebookClient");
    DefaultFacebookClient defaultFacebookClient = (DefaultFacebookClient) facebookClient;

    assertThat(getFieldValue(defaultMessenger, "appSecret"), is(nullValue()));
    assertThat(getFieldValue(defaultFacebookClient, "appSecret"), is(nullValue()));
}
 
示例7
@Override
protected void notify(Parameters parameters) throws NotificationException {
    try {
        FacebookClient facebookClient =
                createFacebookClient(getConfiguration().getString(KEY_ACCESS_TOKEN));

        FacebookType publishResponse;

        if (hasMovie()) {
            publishResponse = facebookClient.publish("me/videos", FacebookType.class,
                    BinaryAttachment.with(movie.getFileName().toString(),
                            Files.readAllBytes(movie),
                            Files.probeContentType(movie)),
                    com.restfb.Parameter.with("description", message));
        } else if (hasPhoto()) {
            publishResponse = facebookClient.publish("me/photos", FacebookType.class,
                    BinaryAttachment.with(
                            photo.getFileName().toString(),
                            Files.readAllBytes(photo),
                            Files.probeContentType(photo)),
                    com.restfb.Parameter.with("message", message));
        } else {
            publishResponse =
                    facebookClient.publish("me/feed", FacebookType.class,
                            com.restfb.Parameter.with("message", message));
        }

        log.debug("Published content has ID {}", publishResponse.getId());
    } catch (FacebookException | IOException e) {
        throw new NotificationException(e);
    }
}
 
示例8
@SuppressWarnings("deprecation")
public static boolean isValidated(String accessToken, String userID) {
	try {
		FacebookClient fc = new DefaultFacebookClient(accessToken, Version.VERSION_2_5);
		String id = fc.fetchObject("me", User.class).getId();
		if (!id.equals(userID)) {
			return false;
		}
		return true;
	} catch (FacebookOAuthException e) {
		e.printStackTrace();
		return false;
	}
}
 
示例9
@SuppressWarnings("deprecation")
public static FacebookClient isValidatedFacebookClient(String accessToken, String userID) {
	try {
		FacebookClient fc = new DefaultFacebookClient(accessToken, Version.VERSION_2_5);
		String id = fc.fetchObject("me", User.class).getId();
		if (!id.equals(userID)) {
			return null;
		}
		return fc;
	} catch (FacebookOAuthException e) {
		e.printStackTrace();
		return null;
	}
}
 
示例10
public static boolean isValidated(String accessToken, String userID) {
	try {	
		FacebookClient fc = new DefaultFacebookClient(accessToken, Version.VERSION_2_5);
		String id = fc.fetchObject("me", User.class).getId();
		if (!id.equals(userID)) {
			return false;
		}
		return true;
	} catch (FacebookOAuthException e) {
		e.printStackTrace();
		return false;
	}
}
 
示例11
public static FacebookClient isValidatedFacebookClient(String accessToken, String userID) {
	try {
		FacebookClient fc = new DefaultFacebookClient(accessToken, Version.VERSION_2_5);
		String id = fc.fetchObject("me", User.class).getId();
		if (!id.equals(userID)) {
			return null;
		}
		return fc;
	} catch (FacebookOAuthException e) {
		e.printStackTrace();
		return null;
	}
}
 
示例12
@Before
public void setUp() {
    this.facebookClient = mock(FacebookClient.class);
    this.sendOperations = new DefaultSendOperations(facebookClient);
}
 
示例13
/**
 * Removes a previously registered subscription having the specified
 * subscriptionID.
 */
@RequestMapping(value = "/Admin/ResetDB", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> resetDB(@RequestParam String userID, @RequestParam String accessToken) {
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.add("Content-Type", "text/html; charset=utf-8");

	// Access Control is not mandatory
	// However, if fid and accessToken provided, more information provided
	FacebookClient fc = null;
	List<String> friendList = null;
	if (userID != null) {
		// Check accessToken
		fc = OAuthUtil.isValidatedFacebookClient(accessToken, userID);
		if (fc == null) {
			return new ResponseEntity<>(new String("Unauthorized Token"), responseHeaders, HttpStatus.UNAUTHORIZED);
		}
		friendList = new ArrayList<String>();

		Connection<User> friendConnection = fc.fetchConnection("me/friends", User.class);
		for (User friend : friendConnection.getData()) {
			friendList.add(friend.getId());
		}
	}

	// OAuth Fails
	if (!OAuthUtil.isAdministratable(userID, friendList)) {
		Configuration.logger.log(Level.INFO, " No right to administration ");
		return new ResponseEntity<>(new String("No right to administration"), responseHeaders,
				HttpStatus.BAD_REQUEST);

	}
	if (Configuration.mongoDatabase.getCollection("EventData") != null) {
		Configuration.mongoDatabase.getCollection("EventData").drop();
	}
	if (Configuration.mongoDatabase.getCollection("MasterData") != null) {
		Configuration.mongoDatabase.getCollection("MasterData").drop();
	}
	Configuration.logger.log(Level.INFO, " Repository Initialized ");
	return new ResponseEntity<>(new String("All Event/Master Data removed"), responseHeaders, HttpStatus.OK);
}
 
示例14
/**
 * Provide existing Named Event Queries
 */
@RequestMapping(value = "/Admin/NamedEventQuery/{name}", method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<?> deleteNamedEventQuery(@PathVariable String name, @RequestParam String userID,
		@RequestParam String accessToken) {
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.add("Content-Type", "text/html; charset=utf-8");

	// Access Control is not mandatory
	// However, if fid and accessToken provided, more information provided
	FacebookClient fc = null;
	List<String> friendList = null;
	if (userID != null) {
		// Check accessToken
		fc = OAuthUtil.isValidatedFacebookClient(accessToken, userID);
		if (fc == null) {
			return new ResponseEntity<>(new String("Unauthorized Token"), responseHeaders, HttpStatus.UNAUTHORIZED);
		}
		friendList = new ArrayList<String>();

		Connection<User> friendConnection = fc.fetchConnection("me/friends", User.class);
		for (User friend : friendConnection.getData()) {
			friendList.add(friend.getId());
		}
	}

	// OAuth Fails
	if (!OAuthUtil.isAdministratable(userID, friendList)) {
		Configuration.logger.log(Level.INFO, " No right to administration ");
		return new ResponseEntity<>(new String("No right to administration"), responseHeaders,
				HttpStatus.BAD_REQUEST);

	}

	if (deleteNamedEventQueryFromDB(name)) {
		Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is removed");
		return new ResponseEntity<>(new String("NamedEventQuery: " + name + " is removed"), responseHeaders,
				HttpStatus.OK);
	} else {
		Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " does not exist");
		return new ResponseEntity<>(new String("NamedEventQuery: " + name + " does not exist"), responseHeaders,
				HttpStatus.OK);
	}
}
 
示例15
@RequestMapping(value = "/Poll/NamedEventQuery/{name}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> poll(@PathVariable String name, @RequestParam(required = false) String userID,
		@RequestParam(required = false) String accessToken)
		throws QueryParameterException, QueryTooLargeException, QueryTooComplexException, NoSuchNameException,
		SecurityException, ValidationException, ImplementationException {

	HttpHeaders responseHeaders = new HttpHeaders();

	MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("NamedEventQuery",
			BsonDocument.class);
	BsonDocument namedEventQuery = collection.find(new BsonDocument("name", new BsonString(name))).first();
	PollParameters pollParams = new PollParameters(namedEventQuery);

	if (pollParams.getFormat() != null && pollParams.getFormat().equals("JSON")) {
		responseHeaders.add("Content-Type", "application/json; charset=utf-8");
	} else {
		responseHeaders.add("Content-Type", "application/xml; charset=utf-8");
	}

	// Access Control is not mandatory
	// However, if fid and accessToken provided, more information provided
	FacebookClient fc = null;
	List<String> friendList = null;

	if (userID != null) {
		// Check accessToken
		fc = OAuthUtil.isValidatedFacebookClient(accessToken, userID);
		if (fc == null) {
			return new ResponseEntity<>(new String("Unauthorized Token"), responseHeaders, HttpStatus.UNAUTHORIZED);
		}
		friendList = new ArrayList<String>();

		Connection<User> friendConnection = fc.fetchConnection("me/friends", User.class);
		for (List<User> friends : friendConnection) {
			for (User friend : friends) {
				friendList.add(friend.getId());
			}
		}
	}

	MongoQueryService mongoQueryService = new MongoQueryService();
	String result = mongoQueryService.poll(pollParams, userID, friendList, null);
	return new ResponseEntity<>(result, responseHeaders, HttpStatus.OK);
}
 
示例16
/**
 * Removes a previously registered subscription having the specified
 * subscriptionID.
 */
@RequestMapping(value = "/Admin/ResetDB", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> resetDB(@RequestParam String userID, @RequestParam String accessToken) {
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.add("Content-Type", "text/html; charset=utf-8");

	// Access Control is not mandatory
	// However, if fid and accessToken provided, more information provided
	FacebookClient fc = null;
	List<String> friendList = null;
	if (userID != null) {
		// Check accessToken
		fc = OAuthUtil.isValidatedFacebookClient(accessToken, userID);
		if (fc == null) {
			return new ResponseEntity<>(new String("Unauthorized Token"), responseHeaders, HttpStatus.UNAUTHORIZED);
		}
		friendList = new ArrayList<String>();

		Connection<User> friendConnection = fc.fetchConnection("me/friends", User.class);
		for (User friend : friendConnection.getData()) {
			friendList.add(friend.getId());
		}
	}

	// OAuth Fails
	if (!OAuthUtil.isAdministratable(userID, friendList)) {
		Configuration.logger.log(Level.INFO, " No right to administration ");
		return new ResponseEntity<>(new String("No right to administration"), responseHeaders,
				HttpStatus.BAD_REQUEST);

	}
	if (Configuration.mongoDatabase.getCollection("EventData") != null) {
		Configuration.mongoDatabase.getCollection("EventData").drop();
	}
	if (Configuration.mongoDatabase.getCollection("MasterData") != null) {
		Configuration.mongoDatabase.getCollection("MasterData").drop();
	}
	Configuration.logger.log(Level.INFO, " Repository Initialized ");
	return new ResponseEntity<>(new String("All Event/Master Data removed"), responseHeaders, HttpStatus.OK);
}
 
示例17
/**
 * Provide existing Named Event Queries
 */
@RequestMapping(value = "/Admin/NamedEventQuery/{name}", method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<?> deleteNamedEventQuery(@PathVariable String name, @RequestParam String userID,
		@RequestParam String accessToken) {
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.add("Content-Type", "text/html; charset=utf-8");

	// Access Control is not mandatory
	// However, if fid and accessToken provided, more information provided
	FacebookClient fc = null;
	List<String> friendList = null;
	if (userID != null) {
		// Check accessToken
		fc = OAuthUtil.isValidatedFacebookClient(accessToken, userID);
		if (fc == null) {
			return new ResponseEntity<>(new String("Unauthorized Token"), responseHeaders, HttpStatus.UNAUTHORIZED);
		}
		friendList = new ArrayList<String>();

		Connection<User> friendConnection = fc.fetchConnection("me/friends", User.class);
		for (User friend : friendConnection.getData()) {
			friendList.add(friend.getId());
		}
	}

	// OAuth Fails
	if (!OAuthUtil.isAdministratable(userID, friendList)) {
		Configuration.logger.log(Level.INFO, " No right to administration ");
		return new ResponseEntity<>(new String("No right to administration"), responseHeaders,
				HttpStatus.BAD_REQUEST);

	}

	if (deleteNamedEventQueryFromDB(name)) {
		Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is removed");
		return new ResponseEntity<>(new String("NamedEventQuery: " + name + " is removed"), responseHeaders,
				HttpStatus.OK);
	} else {
		Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " does not exist");
		return new ResponseEntity<>(new String("NamedEventQuery: " + name + " does not exist"), responseHeaders,
				HttpStatus.OK);
	}
}
 
示例18
@RequestMapping(value = "/Poll/NamedEventQuery/{name}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> poll(@PathVariable String name, @RequestParam(required = false) String userID,
		@RequestParam(required = false) String accessToken)
		throws QueryParameterException, QueryTooLargeException, QueryTooComplexException, NoSuchNameException,
		SecurityException, ValidationException, ImplementationException {

	HttpHeaders responseHeaders = new HttpHeaders();

	MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("NamedEventQuery",
			BsonDocument.class);
	BsonDocument namedEventQuery = collection.find(new BsonDocument("name", new BsonString(name))).first();
	PollParameters pollParams = new PollParameters(namedEventQuery);

	if (pollParams.getFormat() != null && pollParams.getFormat().equals("JSON")) {
		responseHeaders.add("Content-Type", "application/json; charset=utf-8");
	} else {
		responseHeaders.add("Content-Type", "application/xml; charset=utf-8");
	}

	// Access Control is not mandatory
	// However, if fid and accessToken provided, more information provided
	FacebookClient fc = null;
	List<String> friendList = null;

	if (userID != null) {
		// Check accessToken
		fc = OAuthUtil.isValidatedFacebookClient(accessToken, userID);
		if (fc == null) {
			return new ResponseEntity<>(new String("Unauthorized Token"), responseHeaders, HttpStatus.UNAUTHORIZED);
		}
		friendList = new ArrayList<String>();

		Connection<User> friendConnection = fc.fetchConnection("me/friends", User.class);
		for (List<User> friends : friendConnection) {
			for (User friend : friends) {
				friendList.add(friend.getId());
			}
		}
	}

	MongoQueryService mongoQueryService = new MongoQueryService();
	String result = mongoQueryService.poll(pollParams, userID, friendList, null);
	return new ResponseEntity<>(result, responseHeaders, HttpStatus.OK);
}
 
示例19
/**
 * Creates a {@code DefaultSendOperations} instance.
 *
 * @param facebookClient the facebook client, not null
 */
public DefaultSendOperations(FacebookClient facebookClient) {
    this.facebookClient = requireNonNull(facebookClient, "'facebookClient' must not be null");
}