下面列出了怎么用com.google.api.client.http.HttpTransport的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Constructor that will automatically instantiate a Google Cloud Pub/Sub instance.
*
* @throws IOException when the initialization of the Google Cloud Pub/Sub client fails.
*/
public GcloudPubsub() throws IOException {
if (CLOUD_PUBSUB_PROJECT_ID == null) {
throw new IllegalStateException(GCLOUD_PUBSUB_PROJECT_ID_NOT_SET_ERROR);
}
try {
serverName = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
throw new IllegalStateException("Unable to retrieve the hostname of the system");
}
HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
GoogleCredential credential = GoogleCredential.getApplicationDefault(
httpTransport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(PubsubScopes.all());
}
HttpRequestInitializer initializer =
new RetryHttpInitializerWrapper(credential);
pubsub = new Pubsub.Builder(httpTransport, jsonFactory, initializer).build();
logger.info("Google Cloud Pub/Sub Initialization SUCCESS");
}
/**
* Gets {@link GoogleCredential} instance constructed for service account.
*/
@Override
public GoogleCredential getCredential(Collection<String> scopes)
throws GeneralSecurityException, IOException {
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpTransport transport = proxy.getHttpTransport();
if (!isJsonKey) {
return credentialHelper.getP12Credential(
serviceAccountId,
serviceAccountKeyFilePath,
transport,
jsonFactory,
proxy.getHttpRequestInitializer(),
scopes);
}
return credentialHelper.getJsonCredential(
serviceAccountKeyFilePath,
transport,
jsonFactory,
proxy.getHttpRequestInitializer(),
scopes);
}
/**
* Create a Storage Transfer client using user-supplied credentials and other settings.
*
* @param httpTransport a user-supplied HttpTransport
* @param jsonFactory a user-supplied JsonFactory
* @param credential a user-supplied Google credential
* @return a Storage Transfer client
*/
public static Storagetransfer createStorageTransferClient(
HttpTransport httpTransport, JsonFactory jsonFactory, GoogleCredentials credential) {
Preconditions.checkNotNull(httpTransport);
Preconditions.checkNotNull(jsonFactory);
Preconditions.checkNotNull(credential);
// In some cases, you need to add the scope explicitly.
if (credential.createScopedRequired()) {
credential = credential.createScoped(StoragetransferScopes.all());
}
// Please use custom HttpRequestInitializer for automatic
// retry upon failures. We provide a simple reference
// implementation in the "Retry Handling" section.
HttpRequestInitializer initializer = new HttpCredentialsAdapter(credential);
return new Storagetransfer.Builder(httpTransport, jsonFactory, initializer)
.setApplicationName("storagetransfer-sample")
.build();
}
@Test
public void testGetCredentialP12() throws Exception {
File tmpfile = temporaryFolder.newFile(SERVICE_ACCOUNT_FILE_P12);
GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
List<String> scopes = Arrays.asList("profile, calendar");
when(mockCredentialHelper.getP12Credential(
eq("ServiceAccount"),
eq(tmpfile.toPath()),
any(HttpTransport.class),
any(JsonFactory.class),
any(HttpRequestInitializer.class),
eq(scopes)))
.thenReturn(mockCredential);
LocalFileCredentialFactory credentialFactory =
new LocalFileCredentialFactory.Builder()
.setServiceAccountKeyFilePath(tmpfile.getAbsolutePath())
.setServiceAccountId("ServiceAccount")
.build();
assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
@Test
public void testfromConfigurationJsonKey() throws Exception {
File tmpfile = temporaryFolder.newFile("testfromConfiguration" + SERVICE_ACCOUNT_FILE_JSON);
createConfig(tmpfile.getAbsolutePath(), "");
GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
List<String> scopes = Arrays.asList("profile");
when(mockCredentialHelper.getJsonCredential(
eq(tmpfile.toPath()),
any(HttpTransport.class),
any(JsonFactory.class),
any(HttpRequestInitializer.class),
eq(scopes)))
.thenReturn(mockCredential);
LocalFileCredentialFactory credentialFactory = LocalFileCredentialFactory.fromConfiguration();
assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
/**
* @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 void initService(Handler handler) throws CloudsyncException
{
if (service != null) return;
final HttpTransport httpTransport = new NetHttpTransport();
final JsonFactory jsonFactory = new JacksonFactory();
service = new Drive.Builder(httpTransport, jsonFactory, null)
.setApplicationName("Backup")
.setHttpRequestInitializer(credential)
.build();
if (StringUtils.isEmpty(credential.getServiceAccountId())) {
credential.setExpiresInSeconds(MIN_TOKEN_REFRESH_TIMEOUT);
}
try
{
refreshCredential();
}
catch (IOException e)
{
throw new CloudsyncException("couldn't refresh google drive token");
}
handler.getRootItem().setRemoteIdentifier(_getBackupFolder().getId());
}
@Test
public void testApiServiceWithPrebuiltClient() throws Exception {
MockLowLevelHttpRequest request = buildRequest(200, new GenericJson());
HttpTransport transport = new TestingHttpTransport(ImmutableList.of(request));
TestApi apiClient =
(TestApi)
new TestApi.Builder(transport, JSON_FACTORY, null)
.setApplicationName("bring your own client")
.build();
TestApiService apiService =
new TestApiService.Builder()
.setService(apiClient)
.setTransport(transport)
.setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
.build();
validateEmptyItem(apiService.get());
assertThat(
request.getHeaderValues("user-agent").get(0), containsString("bring your own client"));
}
public Optional<Credential> load() {
Properties properties = new Properties();
try {
File file = getAuthenticationFile(options);
if(!file.exists() || !file.canRead()) {
LOGGER.log(Level.FINE, "Cannot find or read properties file. Returning empty credentials.");
return Optional.empty();
}
properties.load(new FileReader(file));
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
.setTransport(httpTransport).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build();
credential.setAccessToken(properties.getProperty(PROP_ACCESS_TOKEN));
credential.setRefreshToken(properties.getProperty(PROP_REFRESH_TOKEN));
return Optional.of(credential);
} catch (IOException e) {
throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to load properties file: " + e.getMessage(), e);
}
}
@Before
public void setup() throws Exception {
when(pipelineOptionsHierarchyFactory.forProject(
eq(project), eq(MajorVersion.ONE), any(IProgressMonitor.class)))
.thenReturn(pipelineOptionsHierarchy);
credential = new GoogleCredential.Builder()
.setJsonFactory(mock(JsonFactory.class))
.setTransport(mock(HttpTransport.class))
.setClientSecrets("clientId", "clientSecret").build();
credential.setRefreshToken("fake-refresh-token");
when(loginService.getCredential("[email protected]")).thenReturn(credential);
when(dependencyManager.getProjectMajorVersion(project)).thenReturn(MajorVersion.ONE);
dataflowDelegate = new DataflowPipelineLaunchDelegate(javaDelegate,
pipelineOptionsHierarchyFactory, dependencyManager, workspaceRoot, loginService);
pipelineArguments.put("accountEmail", "");
when(configurationWorkingCopy.getAttribute(
eq(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES), anyMapOf(String.class, String.class)))
.thenReturn(environmentMap);
}
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
throws IOException {
checkNotNull(httpTransport);
checkNotNull(jsonFactory);
GoogleCredential credential =
GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(PubsubScopes.all());
}
if (credential.getClientAuthentication() != null) {
System.out.println(
"\n***Warning! You are not using service account credentials to "
+ "authenticate.\nYou need to use service account credentials for this example,"
+ "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
+ "out of PubSub quota very quickly.\nSee "
+ "https://developers.google.com/identity/protocols/application-default-credentials.");
System.exit(1);
}
HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
.setApplicationName(APP_NAME)
.build();
}
OAuth1DataGenerator(
OAuth1Config config,
AppCredentials appCredentials,
HttpTransport httpTransport,
String datatype,
AuthMode mode,
Monitor monitor) {
this.config = config;
this.monitor = monitor;
validateConfig();
this.clientId = appCredentials.getKey();
this.clientSecret = appCredentials.getSecret();
this.httpTransport = httpTransport;
this.scope =
mode == AuthMode.EXPORT
? config.getExportScopes().get(datatype)
: config.getImportScopes().get(datatype);
}
/**
* @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 void testReturnRawInputStream_True() throws Exception {
HttpTransport transport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(final String method, final String url) {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() {
return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
BaseEncoding.base64()
.decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
}
};
}
};
MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH,
JSON_OBJECT_PARSER, null).setApplicationName(
"Test Application").build();
MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
request.setReturnRawInputStream(true);
InputStream inputStream = request.executeAsInputStream();
// The response will not be wrapped due to setReturnRawInputStream(true)
assertTrue(inputStream instanceof ByteArrayInputStream);
}
private final GoogleCredential getDefaultCredentialUnsynchronized(
HttpTransport transport, JsonFactory jsonFactory) throws IOException {
if (detectedEnvironment == null) {
detectedEnvironment = detectEnvironment(transport);
}
switch (detectedEnvironment) {
case ENVIRONMENT_VARIABLE:
return getCredentialUsingEnvironmentVariable(transport, jsonFactory);
case WELL_KNOWN_FILE:
return getCredentialUsingWellKnownFile(transport, jsonFactory);
case APP_ENGINE:
return getAppEngineCredential(transport, jsonFactory);
case CLOUD_SHELL:
return getCloudShellCredential(jsonFactory);
case COMPUTE_ENGINE:
return getComputeCredential(transport, jsonFactory);
default:
return null;
}
}
/**
* Ensures initialization of Google Application Default Credentials. Any test that depends on
* ADC should consider this as a fixture, and invoke it before hand. Since ADC are initialized
* once per JVM, this makes sure that all dependent tests get the same ADC instance, and
* can reliably reason about the tokens minted using it.
*/
public static synchronized GoogleCredentials getApplicationDefaultCredentials()
throws IOException {
if (defaultCredentials != null) {
return defaultCredentials;
}
final MockTokenServerTransport transport = new MockTokenServerTransport(
"https://accounts.google.com/o/oauth2/token");
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), TEST_ADC_ACCESS_TOKEN);
File serviceAccount = new File("src/test/resources/service_accounts", "editor.json");
Map<String, String> environmentVariables =
ImmutableMap.<String, String>builder()
.put("GOOGLE_APPLICATION_CREDENTIALS", serviceAccount.getAbsolutePath())
.build();
setEnvironmentVariables(environmentVariables);
defaultCredentials = GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
return defaultCredentials;
}
private static SQLAdmin createAdminApiClient(HttpRequestInitializer requestInitializer) {
HttpTransport httpTransport;
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException err) {
throw new RuntimeException("Unable to initialize HTTP transport", err);
}
String rootUrl = System.getProperty(API_ROOT_URL_PROPERTY);
String servicePath = System.getProperty(API_SERVICE_PATH_PROPERTY);
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
SQLAdmin.Builder adminApiBuilder =
new Builder(httpTransport, jsonFactory, requestInitializer)
.setApplicationName(getUserAgents());
if (rootUrl != null) {
logTestPropertyWarning(API_ROOT_URL_PROPERTY);
adminApiBuilder.setRootUrl(rootUrl);
}
if (servicePath != null) {
logTestPropertyWarning(API_SERVICE_PATH_PROPERTY);
adminApiBuilder.setServicePath(servicePath);
}
return adminApiBuilder.build();
}
@GET
public Response getGoogleCallbackURL(@Context HttpServletRequest request) {
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport httpTransport = new NetHttpTransport();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(httpTransport, jsonFactory, config.google_key, config.google_secret, Arrays
.asList("https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"));
try {
// google will tell the users browser to go to this address once
// they are done authing.
String callbackURL = config.authUrl + "/GoogleCallback";
request.getSession().setAttribute("google", flow);
String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(callbackURL).build();
// send the user to google to be authenticated.
return Response.temporaryRedirect(new URI(authorizationUrl)).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(500).build();
}
}
public HttpResponse getTimeEntryForHttpResponse(String accessToken, String xeroTenantId, UUID projectId, UUID timeEntryId) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTimeEntry");
}// verify the required parameter 'projectId' is set
if (projectId == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTimeEntry");
}// verify the required parameter 'timeEntryId' is set
if (timeEntryId == null) {
throw new IllegalArgumentException("Missing the required parameter 'timeEntryId' when calling getTimeEntry");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTimeEntry");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("projectId", projectId);
uriVariables.put("timeEntryId", timeEntryId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time/{timeEntryId}");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("GET " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
private HttpTransport createTransport(final LowLevelHttpRequest request) {
return new HttpTransport() {
@Override
protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return request;
}
};
}
public HttpResponse createAssetTypeForHttpResponse(String accessToken, String xeroTenantId, AssetType assetType) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createAssetType");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createAssetType");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/AssetTypes");
String url = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("POST " + genericUrl.toString());
}
HttpContent content = null;
content = apiClient.new JacksonJsonHttpContent(assetType);
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
/**
* Create an OAuthThreeLeggedFlow instance from the required information.
*
* @param userId Key that can be used to associate this flow with an end user.
* @param consumerKey Key that identifies the server to the service provider.
* @param consumerSecret Secret that is shared between the server and the service provider.
* @param authorizationServerUrl Url with which we communicate to authorize tis application.
* @param temporaryTokenUrl Url which we will use to obtain a temporary token.
* @param callbackUrl Url which the server should redirect the user to after obtaining
* authorization.
*
* @throws IOException Exception thrown when the flow is unable to communicate with the service
* provider.
*/
public OAuthHmacThreeLeggedFlow(String userId,
String consumerKey,
String consumerSecret,
String authorizationServerUrl,
String temporaryTokenUrl,
String callbackUrl,
HttpTransport transport) throws IOException {
this.userId = userId;
this.consumerSecret = consumerSecret;
this.consumerKey = consumerKey;
this.transport = transport;
this.authorizationServerUrl = authorizationServerUrl;
OAuthGetTemporaryToken temporaryToken = new OAuthGetTemporaryToken(callbackUrl);
OAuthHmacSigner signer = new OAuthHmacSigner();
signer.clientSharedSecret = consumerSecret;
temporaryToken.signer = signer;
temporaryToken.consumerKey = consumerKey;
temporaryToken.callback = callbackUrl;
temporaryToken.transport = this.transport;
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
tempToken = tempCredentials.token;
tempTokenSecret = tempCredentials.tokenSecret;
OAuthAuthorizeTemporaryTokenUrl authorizeUrl =
new OAuthAuthorizeTemporaryTokenUrl(temporaryTokenUrl);
authorizeUrl.temporaryToken = tempCredentials.token;
this.authorizationUrl = authorizeUrl.build();
}
@Override
public Apps newAppsApi(Credential credential) {
Preconditions.checkNotNull(transportCache, "transportCache is null");
HttpTransport transport = transportCache.getUnchecked(GoogleApi.APPENGINE_ADMIN_API);
Preconditions.checkNotNull(transport, "transport is null");
Preconditions.checkNotNull(jsonFactory, "jsonFactory is null");
Appengine appengine =
new Appengine.Builder(transport, jsonFactory, credential)
.setApplicationName(CloudToolsInfo.USER_AGENT).build();
return appengine.apps();
}
@Override
public TestApi.Builder getServiceBuilder(
HttpTransport transport,
JsonFactory jsonFactory,
HttpRequestInitializer requestInitializer) {
return new TestApi.Builder(transport, jsonFactory, requestInitializer);
}
public void testFrom_noDetails() throws Exception {
HttpTransport transport = new MockHttpTransport();
HttpRequest request =
transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.setThrowExceptionOnExecuteError(false);
HttpResponse response = request.execute();
GoogleJsonResponseException ge =
GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
assertNull(ge.getDetails());
assertEquals("200", ge.getMessage());
}
@Test
public void testRequestWithNonRetryableError() throws Exception {
HttpTransport transport =
new TestingHttpTransport(ImmutableList.of(buildRequest(400, new GenericJson())));
TestApiService apiService =
new TestApiService.Builder()
.setTransport(transport)
.setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
.build();
thrown.expect(GoogleJsonResponseException.class);
apiService.get();
}
public HttpResponse getTaskForHttpResponse(String accessToken, String xeroTenantId, UUID projectId, UUID taskId) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTask");
}// verify the required parameter 'projectId' is set
if (projectId == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTask");
}// verify the required parameter 'taskId' is set
if (taskId == null) {
throw new IllegalArgumentException("Missing the required parameter 'taskId' when calling getTask");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTask");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("projectId", projectId);
uriVariables.put("taskId", taskId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/tasks/{taskId}");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("GET " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
public void testDefaultCredentialCaches() throws IOException {
HttpTransport transport = new MockHttpTransport();
TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider();
testProvider.addType(DefaultCredentialProvider.APP_ENGINE_CREDENTIAL_CLASS,
MockAppEngineCredential.class);
testProvider.addType(GAE_SIGNAL_CLASS, MockAppEngineSystemProperty.class);
Credential firstCall = testProvider.getDefaultCredential(transport, JSON_FACTORY);
assertNotNull(firstCall);
Credential secondCall = testProvider.getDefaultCredential(transport, JSON_FACTORY);
assertSame(firstCall, secondCall);
}
protected GerritOptions mockGerritOptions(GitRepository credentialsRepo) {
return new GerritOptions(optionsBuilder.general, optionsBuilder.git) {
@Override
protected HttpTransport getHttpTransport() {
return mockHttpTransport;
}
@Override
protected GitRepository getCredentialsRepo() throws RepoException {
return credentialsRepo != null ? credentialsRepo : super.getCredentialsRepo();
}
};
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
HttpTransport httpTransport = new UrlFetchTransport();
JacksonFactory jsonFactory = new JacksonFactory();
AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL));
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory).build();
credential.setAccessToken(accessToken.getAccessToken());
Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("oauth client").build();
Userinfoplus ui = service.userinfo().get().execute();
resp.getWriter().println(ui.getEmail());
// Using Google Cloud APIs
Storage storage_service = StorageOptions.newBuilder()
.build()
.getService();
for (Bucket b : storage_service.list().iterateAll()){
System.out.println(b);
}
}