下面列出了怎么用com.google.api.client.http.HttpExecuteInterceptor的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testIntercept() throws IOException {
// GIVEN
HttpExecuteInterceptor interceptor1 = mock(HttpExecuteInterceptor.class);
HttpExecuteInterceptor interceptor2 = mock(HttpExecuteInterceptor.class);
List<HttpExecuteInterceptor> interceptors = Arrays.asList(interceptor1, interceptor2);
HttpRequest request = mock(HttpRequest.class);
// WHEN
HttpExecuteInterceptorChain instanceUnderTest = new HttpExecuteInterceptorChain(interceptors);
instanceUnderTest.intercept(request);
// THEN
verify(interceptor1).intercept(request);
verify(interceptor2).intercept(request);
}
/**
* @param method method of presenting the access token to the resource
* server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerUrl token server URL
* @param clientAuthentication client authentication or {@code null} for
* none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}
* )
* @param clientId client identifier
* @param authorizationServerEncodedUrl authorization server encoded URL
*/
public Builder(AccessMethod method,
HttpTransport transport,
JsonFactory jsonFactory,
GenericUrl tokenServerUrl,
HttpExecuteInterceptor clientAuthentication,
String clientId,
String authorizationServerEncodedUrl) {
super(method,
transport,
jsonFactory,
tokenServerUrl,
clientAuthentication,
clientId,
authorizationServerEncodedUrl);
}
public Builder(
Credential.AccessMethod method,
HttpTransport transport,
JsonFactory jsonFactory,
GenericUrl tokenServerUrl,
HttpExecuteInterceptor clientAuthentication,
String clientId,
String authorizationServerEncodedUrl) {
super(
method,
transport,
jsonFactory,
tokenServerUrl,
clientAuthentication,
clientId,
authorizationServerEncodedUrl);
}
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerUrl token server URL
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param clientId client identifier
* @param authorizationServerEncodedUrl authorization server encoded URL
*
* @since 1.14
*/
public AuthorizationCodeFlow(AccessMethod method,
HttpTransport transport,
JsonFactory jsonFactory,
GenericUrl tokenServerUrl,
HttpExecuteInterceptor clientAuthentication,
String clientId,
String authorizationServerEncodedUrl) {
this(new Builder(method,
transport,
jsonFactory,
tokenServerUrl,
clientAuthentication,
clientId,
authorizationServerEncodedUrl));
}
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerUrl token server URL
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param clientId client identifier
* @param authorizationServerEncodedUrl authorization server encoded URL
*/
public Builder(AccessMethod method,
HttpTransport transport,
JsonFactory jsonFactory,
GenericUrl tokenServerUrl,
HttpExecuteInterceptor clientAuthentication,
String clientId,
String authorizationServerEncodedUrl) {
setMethod(method);
setTransport(transport);
setJsonFactory(jsonFactory);
setTokenServerUrl(tokenServerUrl);
setClientAuthentication(clientAuthentication);
setClientId(clientId);
setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl);
}
/**
* @param method method of presenting the access token to the resource
* server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerUrl token server URL
* @param clientAuthentication client authentication or {@code null} for
* none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}
* )
* @param clientId client identifier
* @param authorizationServerEncodedUrl authorization server encoded URL
*/
public Builder(AccessMethod method,
HttpTransport transport,
JsonFactory jsonFactory,
GenericUrl tokenServerUrl,
HttpExecuteInterceptor clientAuthentication,
String clientId,
String authorizationServerEncodedUrl) {
super(method,
transport,
jsonFactory,
tokenServerUrl,
clientAuthentication,
clientId,
authorizationServerEncodedUrl);
}
@Override
public MicrosoftAuthorizationCodeTokenRequest setClientAuthentication(
HttpExecuteInterceptor clientAuthentication) {
Preconditions.checkNotNull(clientAuthentication);
return (MicrosoftAuthorizationCodeTokenRequest)
super.setClientAuthentication(clientAuthentication);
}
private static HttpRequestInitializer newFailingRequestInitializer(
Predicate<HttpRequest> failurePredicate) {
return request -> {
httpRequestInitializer.initialize(request);
HttpExecuteInterceptor executeInterceptor = checkNotNull(request.getInterceptor());
request.setInterceptor(
interceptedRequest -> {
executeInterceptor.intercept(interceptedRequest);
if (failurePredicate.test(interceptedRequest)) {
throw new RuntimeException("Injected failure");
}
});
};
}
@Override
public void initialize(HttpRequest request) throws IOException {
List<HttpIOExceptionHandler> ioExceptionHandlers = new ArrayList<>();
List<HttpUnsuccessfulResponseHandler> unsuccessfulResponseHandlers = new ArrayList<>();
List<HttpExecuteInterceptor> interceptors = new ArrayList<>();
List<HttpResponseInterceptor> responseInterceptors = new ArrayList<>();
for (HttpRequestInitializer initializer : initializers) {
initializer.initialize(request);
if (request.getIOExceptionHandler() != null) {
ioExceptionHandlers.add(request.getIOExceptionHandler());
request.setIOExceptionHandler(null);
}
if (request.getUnsuccessfulResponseHandler() != null) {
unsuccessfulResponseHandlers.add(request.getUnsuccessfulResponseHandler());
request.setUnsuccessfulResponseHandler(null);
}
if (request.getInterceptor() != null) {
interceptors.add(request.getInterceptor());
request.setInterceptor(null);
}
if (request.getResponseInterceptor() != null) {
responseInterceptors.add(request.getResponseInterceptor());
request.setResponseInterceptor(null);
}
}
request.setIOExceptionHandler(
makeIoExceptionHandler(ioExceptionHandlers));
request.setUnsuccessfulResponseHandler(
makeUnsuccessfulResponseHandler(unsuccessfulResponseHandlers));
request.setInterceptor(
makeInterceptor(interceptors));
request.setResponseInterceptor(
makeResponseInterceptor(responseInterceptors));
}
private HttpExecuteInterceptor makeInterceptor(
final Iterable<HttpExecuteInterceptor> interceptors) {
return new HttpExecuteInterceptor() {
@Override
public void intercept(HttpRequest request) throws IOException {
for (HttpExecuteInterceptor interceptor : interceptors) {
interceptor.intercept(request);
}
}
};
}
private static HttpRequestInitializer interceptingRequestInitializer(
Consumer<HttpRequest> interceptFn) {
return request -> {
httpRequestInitializer.initialize(request);
HttpExecuteInterceptor executeInterceptor = checkNotNull(request.getInterceptor());
request.setInterceptor(
interceptedRequest -> {
executeInterceptor.intercept(interceptedRequest);
interceptFn.accept(interceptedRequest);
});
};
}
@Override
public void initialize(HttpRequest request) throws IOException {
if (delegate != null) {
delegate.initialize(request);
}
HttpExecuteInterceptor executeInterceptor = request.getInterceptor();
request.setInterceptor(
r -> {
if (executeInterceptor != null) {
executeInterceptor.intercept(r);
}
requests.add(r);
});
}
@Override
public GoogleAuthorizationCodeTokenRequest setClientAuthentication(
HttpExecuteInterceptor clientAuthentication) {
Preconditions.checkNotNull(clientAuthentication);
return (GoogleAuthorizationCodeTokenRequest) super.setClientAuthentication(
clientAuthentication);
}
public void intercept(HttpRequest batchRequest) throws IOException {
if (originalInterceptor != null) {
originalInterceptor.intercept(batchRequest);
}
for (RequestInfo<?, ?> requestInfo : requestInfos) {
HttpExecuteInterceptor interceptor = requestInfo.request.getInterceptor();
if (interceptor != null) {
interceptor.intercept(requestInfo.request);
}
}
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
credential =
new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
.setTransport(new NetHttpTransport())
.setJsonFactory(Mockito.mock(JsonFactory.class))
.setClientAuthentication(Mockito.mock(HttpExecuteInterceptor.class))
.setTokenServerUrl(TOKEN_SERVER_URL).build();
oAuth2Helper = spy(new OAuth2Helper(libLogger, REFRESH_WINDOW_SECS));
}
public HttpExecuteInterceptorChain(List<HttpExecuteInterceptor> requestInterceptors) {
this.requestInterceptors = requestInterceptors;
}
@Override
public void intercept(HttpRequest request) throws IOException {
for (HttpExecuteInterceptor interceptor: requestInterceptors) {
interceptor.intercept(request);
}
}
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
return (Builder) super.setClientAuthentication(clientAuthentication);
}
@Test
public void useCustomDataStore() throws Exception {
Credential credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
.setTransport(new MockHttpTransport())
.setJsonFactory(new MockJsonFactory())
.setClientAuthentication(Mockito.mock(HttpExecuteInterceptor.class))
.setTokenServerUrl(new GenericUrl(TOKEN_REQUEST_URL))
.build();
credential.setAccessToken("accessToken2");
credential.setRefreshToken("refreshToken2");
credential.setExpiresInSeconds(1000L);
DataStore mockDataStore = Mockito.mock(DataStore.class);
MockDataStoreFactory mockDataStoreFactory = new MockDataStoreFactory(mockDataStore);
Mockito.when(mockDataStore.get(eq("userId"))).thenReturn(new StoredCredential(credential));
OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder()
.setClientSecrets("CLIENT_ID", "CLIENT_SECRET")
.setRedirectUri("http://redirect")
.setHttpTransport(mockHttpTransport)
.setCredentialDataStoreFactory(mockDataStoreFactory)
.setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST))
.build();
Credential storedCredential = oAuth2Credentials.authenticate("authorizationCode", "userId");
Credential loadedCredential = oAuth2Credentials.loadCredential("userId");
assertEquals("Refresh token does not match.", "refreshToken", storedCredential.getRefreshToken());
assertTrue("Expected expires_in between 0 and 3600. Was actually: " + storedCredential.getExpiresInSeconds(),
storedCredential.getExpiresInSeconds() > 0 && storedCredential.getExpiresInSeconds() <= 3600);
assertEquals("Access token does not match.", "accessToken", storedCredential.getAccessToken());
assertEquals("Access method (Bearer) does not match",
BearerToken.authorizationHeaderAccessMethod().getClass(), storedCredential.getMethod().getClass());
assertEquals("Refresh token does not match.", "refreshToken2", loadedCredential.getRefreshToken());
assertTrue("Expected expires_in between 0 and 1000. Was actually: " + loadedCredential.getExpiresInSeconds(),
loadedCredential.getExpiresInSeconds() > 0 && loadedCredential.getExpiresInSeconds() <= 1000L);
assertEquals("Access token does not match.", "accessToken2", loadedCredential.getAccessToken());
assertEquals("Access method (Bearer) does not match",
BearerToken.authorizationHeaderAccessMethod().getClass(), loadedCredential.getMethod().getClass());
}
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
Preconditions.checkArgument(clientAuthentication == null);
return this;
}
/**
* @since 1.11
*/
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
return (Builder) super.setClientAuthentication(clientAuthentication);
}
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
return (Builder) super.setClientAuthentication(clientAuthentication);
}
@Override
public GoogleRefreshTokenRequest setClientAuthentication(
HttpExecuteInterceptor clientAuthentication) {
return (GoogleRefreshTokenRequest) super.setClientAuthentication(clientAuthentication);
}
/**
* Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.
*
* <p>
* Calling {@link #execute()} executes and clears the queued requests. This means that the
* {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests
* again.
* </p>
*/
public void execute() throws IOException {
boolean retryAllowed;
Preconditions.checkState(!requestInfos.isEmpty());
// Log a warning if the user is using the global batch endpoint. In the future, we can turn this
// into a preconditions check.
if (GLOBAL_BATCH_ENDPOINT.equals(this.batchUrl.toString())) {
LOGGER.log(Level.WARNING, GLOBAL_BATCH_ENDPOINT_WARNING);
}
HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null);
// NOTE: batch does not support gzip encoding
HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor();
batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor));
int retriesRemaining = batchRequest.getNumberOfRetries();
do {
retryAllowed = retriesRemaining > 0;
MultipartContent batchContent = new MultipartContent();
batchContent.getMediaType().setSubType("mixed");
int contentId = 1;
for (RequestInfo<?, ?> requestInfo : requestInfos) {
batchContent.addPart(new MultipartContent.Part(
new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++),
new HttpRequestContent(requestInfo.request)));
}
batchRequest.setContent(batchContent);
HttpResponse response = batchRequest.execute();
BatchUnparsedResponse batchResponse;
try {
// Find the boundary from the Content-Type header.
String boundary = "--" + response.getMediaType().getParameter("boundary");
// Parse the content stream.
InputStream contentStream = response.getContent();
batchResponse =
new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed);
while (batchResponse.hasNext) {
batchResponse.parseNextResponse();
}
} finally {
response.disconnect();
}
List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos;
if (!unsuccessfulRequestInfos.isEmpty()) {
requestInfos = unsuccessfulRequestInfos;
} else {
break;
}
retriesRemaining--;
} while (retryAllowed);
requestInfos.clear();
}
BatchInterceptor(HttpExecuteInterceptor originalInterceptor) {
this.originalInterceptor = originalInterceptor;
}
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
return (MockGoogleCredential.Builder) super.setClientAuthentication(clientAuthentication);
}
@Override
public AuthorizationCodeTokenRequest setClientAuthentication(
HttpExecuteInterceptor clientAuthentication) {
return (AuthorizationCodeTokenRequest) super.setClientAuthentication(clientAuthentication);
}
/** Returns the client authentication or {@code null} for none. */
public final HttpExecuteInterceptor getClientAuthentication() {
return clientAuthentication;
}
/** Returns the client authentication or {@code null} for none. */
public final HttpExecuteInterceptor getClientAuthentication() {
return clientAuthentication;
}
@Override
public PasswordTokenRequest setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
return (PasswordTokenRequest) super.setClientAuthentication(clientAuthentication);
}