Java Code Examples for com.google.api.client.http.GenericUrl

The following examples show how to use com.google.api.client.http.GenericUrl. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: slr-toolkit   Author: sebastiangoetz   File: MendeleyClient.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
   * This methods is adds a document that exists in Mendeley to a specific folder
   * via the POST https://api.mendeley.com/folders/{id}/documents endpoint.
   * @param document This methods needs a dkocument to add
   * @param folder_id This passes the folder where to document is added to
   */
  public void addDocumentToFolder(MendeleyDocument document, String folder_id){
  	refreshTokenIfNecessary();
  	
  	HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  	HttpRequest request;
  	HttpRequest patch_request;
  	
  	Gson gson = new GsonBuilder().create();
  	String json_body = "{\"id\": \""+ document.getId() + "\" }";
  	String resource_url = "https://api.mendeley.com/folders/"+ folder_id + "/documents";
  	GenericUrl gen_url = new GenericUrl(resource_url);
  		
try {
	final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
	patch_request = requestFactory.buildPostRequest(gen_url, content);
	patch_request.getHeaders().setAuthorization("Bearer " + access_token);
	patch_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
	String rawResponse = patch_request.execute().parseAsString();
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
Example #2
Source Project: vpn-over-dns   Author: AlexandreFenyo   File: OAuthServletCallback.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #3
Source Project: openapi-generator   Author: OpenAPITools   File: StoreApi.java    License: Apache License 2.0 6 votes vote down vote up
public HttpResponse deleteOrderForHttpResponse(String orderId) throws IOException {
    // verify the required parameter 'orderId' is set
    if (orderId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling deleteOrder");
    }
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("order_id", orderId);
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}");

    String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = null;
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute();
}
 
Example #4
Source Project: tuxguitar   Author: phiresky   File: TGDriveBrowser.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public void getInputStream(final TGBrowserCallBack<InputStream> cb, TGBrowserElement element) {
	try {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		
	    MediaHttpDownloader downloader = new MediaHttpDownloader(this.httpTransport, this.drive.getRequestFactory().getInitializer());
	    downloader.setDirectDownloadEnabled(true);
	    downloader.download(new GenericUrl(((TGDriveBrowserFile) element).getFile().getDownloadUrl()), outputStream);
	    
		outputStream.flush();
		outputStream.close();
		
		cb.onSuccess(new ByteArrayInputStream(outputStream.toByteArray()));
	} catch (Throwable e) {
		cb.handleError(new TGBrowserException(findActivity().getString(R.string.gdrive_read_file_error), e));
	}
}
 
Example #5
Source Project: google-api-java-client   Author: googleapis   File: BatchRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
public void subTestExecuteWithVoidCallback(boolean testServerError) throws IOException {
  MockTransport transport = new MockTransport(testServerError, false,false, false, false);
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, null, null).setApplicationName("Test Application")
      .build();
  MockGoogleClientRequest<String> jsonHttpRequest1 =
      new MockGoogleClientRequest<String>(client, METHOD1, URI_TEMPLATE1, null, String.class);
  MockGoogleClientRequest<String> jsonHttpRequest2 =
      new MockGoogleClientRequest<String>(client, METHOD2, URI_TEMPLATE2, null, String.class);
  ObjectParser parser = new JsonObjectParser(new JacksonFactory());
  BatchRequest batchRequest =
      new BatchRequest(transport, null).setBatchUrl(new GenericUrl(TEST_BATCH_URL));
  HttpRequest request1 = jsonHttpRequest1.buildHttpRequest();
  request1.setParser(parser);
  HttpRequest request2 = jsonHttpRequest2.buildHttpRequest();
  request2.setParser(parser);
  batchRequest.queue(request1, MockDataClass1.class, GoogleJsonErrorContainer.class, callback1);
  batchRequest.queue(request2, Void.class, Void.class, callback3);
  batchRequest.execute();
  // Assert transport called expected number of times.
  assertEquals(1, transport.actualCalls);
}
 
Example #6
Source Project: firebase-admin-java   Author: firebase   File: CryptoSigners.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] payload) throws IOException {
  String encodedUrl = String.format(IAM_SIGN_BLOB_URL, serviceAccount);
  HttpResponse response = null;
  String encodedPayload = BaseEncoding.base64().encode(payload);
  Map<String, String> content = ImmutableMap.of("bytesToSign", encodedPayload);
  try {
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(encodedUrl),
        new JsonHttpContent(jsonFactory, content));
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setResponseInterceptor(interceptor);
    response = request.execute();
    SignBlobResponse parsed = response.parseAs(SignBlobResponse.class);
    return BaseEncoding.base64().decode(parsed.signature);
  } finally {
    if (response != null) {
      try {
        response.disconnect();
      } catch (IOException ignored) {
        // Ignored
      }
    }
  }
}
 
Example #7
Source Project: google-api-java-client   Author: googleapis   File: MediaHttpUploader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method sends a POST request with empty content to get the unique upload URL.
 *
 * @param initiationRequestUrl The request URL where the initiation request will be sent
 */
private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException {
  updateStateAndNotifyListener(UploadState.INITIATION_STARTED);

  initiationRequestUrl.put("uploadType", "resumable");
  HttpContent content = metadata == null ? new EmptyContent() : metadata;
  HttpRequest request =
      requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
  initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType());
  if (isMediaLengthKnown()) {
    initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength());
  }
  request.getHeaders().putAll(initiationHeaders);
  HttpResponse response = executeCurrentRequest(request);
  boolean notificationCompleted = false;

  try {
    updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE);
    notificationCompleted = true;
  } finally {
    if (!notificationCompleted) {
      response.disconnect();
    }
  }
  return response;
}
 
Example #8
Source Project: google-api-java-client   Author: googleapis   File: MediaHttpDownloaderTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSetContentRangeWithResumableDownload() throws Exception {
  int contentLength = MediaHttpDownloader.MAXIMUM_CHUNK_SIZE;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.bytesDownloaded = contentLength - 10000;
  fakeTransport.lastBytePos = contentLength;

  MediaHttpDownloader downloader = new MediaHttpDownloader(fakeTransport, null);
  downloader.setContentRange(contentLength - 10000, contentLength);

  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  downloader.download(new GenericUrl(TEST_REQUEST_URL), outputStream);
  assertEquals(10000, outputStream.size());

  // There should be 1 download call made.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #9
Source Project: google-oauth-java-client   Author: googleapis   File: AuthorizationCodeFlow.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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));
}
 
Example #10
Source Project: vpn-over-dns   Author: AlexandreFenyo   File: OAuthServlet.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #11
Source Project: firebase-admin-java   Author: firebase   File: FirebaseAuthIT.java    License: Apache License 2.0 6 votes vote down vote up
private String signInWithCustomToken(String customToken) throws IOException {
  GenericUrl url = new GenericUrl(VERIFY_CUSTOM_TOKEN_URL + "?key="
      + IntegrationTestUtils.getApiKey());
  Map<String, Object> content = ImmutableMap.<String, Object>of(
      "token", customToken, "returnSecureToken", true);
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
      new JsonHttpContent(jsonFactory, content));
  request.setParser(new JsonObjectParser(jsonFactory));
  HttpResponse response = request.execute();
  try {
    GenericJson json = response.parseAs(GenericJson.class);
    return json.get("idToken").toString();
  } finally {
    response.disconnect();
  }
}
 
Example #12
Source Project: datacollector   Author: streamsets   File: VaultEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
protected Secret getSecret(String path, String method, HttpContent content) throws VaultException {
  try {
    HttpRequest request = getRequestFactory().buildRequest(
        method,
        new GenericUrl(getConf().getAddress() + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.parseAs(Secret.class);
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example #13
Source Project: nomulus   Author: google   File: RequestFactoryModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_provideHttpRequestFactory_localhost() throws Exception {
  // Make sure that localhost creates a request factory with an initializer.
  boolean origIsLocal = RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal;
  RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = true;
  try {
    HttpRequestFactory factory =
        RequestFactoryModule.provideHttpRequestFactory(credentialsBundle);
    HttpRequestInitializer initializer = factory.getInitializer();
    assertThat(initializer).isNotNull();
    HttpRequest request = factory.buildGetRequest(new GenericUrl("http://localhost"));
    initializer.initialize(request);
    verifyZeroInteractions(httpRequestInitializer);
  } finally {
    RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = origIsLocal;
  }
}
 
Example #14
Source Project: openapi-generator   Author: OpenAPITools   File: PetApi.java    License: Apache License 2.0 6 votes vote down vote up
public HttpResponse updatePetWithFormForHttpResponse(Long petId, String name, String status) throws IOException {
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'petId' when calling updatePetWithForm");
    }
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}");

    String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = new EmptyContent();
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
 
Example #15
Source Project: android-oauth-client   Author: wuman   File: AuthorizationFlow.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
    return new LenientAuthorizationCodeTokenRequest(getTransport(), getJsonFactory(),
            new GenericUrl(getTokenServerEncodedUrl()), authorizationCode)
            .setClientAuthentication(getClientAuthentication())
            .setScopes(getScopes())
            .setRequestInitializer(
                    new HttpRequestInitializer() {
                        @Override
                        public void initialize(HttpRequest request) throws IOException {
                            HttpRequestInitializer requestInitializer = getRequestInitializer();
                            // If HttpRequestInitializer is set, initialize it as before
                            if (requestInitializer != null) {
                                requestInitializer.initialize(request);
                            }
                            // Also set JSON accept header
                            request.getHeaders().setAccept("application/json");
                        }
                    });
}
 
Example #16
Source Project: openapi-generator   Author: OpenAPITools   File: PetApi.java    License: Apache License 2.0 6 votes vote down vote up
public HttpResponse uploadFileWithRequiredFileForHttpResponse(Long petId, File requiredFile, String additionalMetadata) throws IOException {
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'petId' when calling uploadFileWithRequiredFile");
    }// verify the required parameter 'requiredFile' is set
    if (requiredFile == null) {
        throw new IllegalArgumentException("Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile");
    }
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/{petId}/uploadImageWithRequiredFile");

    String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = new EmptyContent();
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
 
Example #17
Source Project: data-transfer-project   Author: google   File: SolidUtilities.java    License: Apache License 2.0 6 votes vote down vote up
/** Posts an RDF model to a Solid server. **/
public String postContent(
    String url,
    String slug,
    String type,
    Model model)
    throws IOException {
  StringWriter stringWriter = new StringWriter();
  model.write(stringWriter, "TURTLE");
  HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes());

  HttpRequest postRequest = factory.buildPostRequest(
      new GenericUrl(url), content);
  HttpHeaders headers = new HttpHeaders();
  headers.setCookie(authCookie);
  headers.set("Link", "<" + type + ">; rel=\"type\"");
  headers.set("Slug", slug);
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();

  validateResponse(response, 201);
  return response.getHeaders().getLocation();
}
 
Example #18
Source Project: openapi-generator   Author: OpenAPITools   File: FakeApi.java    License: Apache License 2.0 6 votes vote down vote up
public HttpResponse testJsonFormDataForHttpResponse(String param, String param2) throws IOException {
    // verify the required parameter 'param' is set
    if (param == null) {
        throw new IllegalArgumentException("Missing the required parameter 'param' when calling testJsonFormData");
    }// verify the required parameter 'param2' is set
    if (param2 == null) {
        throw new IllegalArgumentException("Missing the required parameter 'param2' when calling testJsonFormData");
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/jsonFormData");

    String localVarUrl = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = null;
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute();
}
 
Example #19
Source Project: google-api-java-client   Author: googleapis   File: MediaHttpUploaderTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testDirectMediaUpload_WithSpecifiedHeader() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.directUploadEnabled = true;
  fakeTransport.assertTestHeaders = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.getInitiationHeaders().set("test-header-name", "test-header-value");
  uploader.setProgressListener(new DirectProgressListener());
  // Enable direct media upload.
  uploader.setDirectUploadEnabled(true);

  HttpResponse response = uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
  assertEquals(200, response.getStatusCode());

  // There should be only 1 call made for direct media upload.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #20
Source Project: Xero-Java   Author: XeroAPI   File: BankFeedsApi.java    License: MIT License 5 votes vote down vote up
public HttpResponse getStatementForHttpResponse(String accessToken,  String xeroTenantId,  UUID statementId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getStatement");
    }// verify the required parameter 'statementId' is set
    if (statementId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'statementId' when calling getStatement");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getStatement");
    }
    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("statementId", statementId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Statements/{statementId}");
    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();  
}
 
Example #21
Source Project: Xero-Java   Author: XeroAPI   File: IdentityApi.java    License: MIT License 5 votes vote down vote up
public HttpResponse getConnectionsForHttpResponse(String accessToken,  UUID authEventId) throws IOException {
    
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getConnections");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/connections");
    if (authEventId != null) {
        String key = "authEventId";
        Object value = authEventId;
        if (value instanceof Collection) {
            uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
        } else if (value instanceof Object[]) {
            uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
        } else {
            uriBuilder = uriBuilder.queryParam(key, value);
        }
    }
    String url = uriBuilder.build().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();  
}
 
Example #22
Source Project: openapi-generator   Author: OpenAPITools   File: FakeApi.java    License: Apache License 2.0 5 votes vote down vote up
public HttpResponse testClientModelForHttpResponse(Client body, Map<String, Object> params) throws IOException {
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new IllegalArgumentException("Missing the required parameter 'body' when calling testClientModel");
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake");

    // Copy the params argument if present, to allow passing in immutable maps
    Map<String, Object> allParams = params == null ? new HashMap<String, Object>() : new HashMap<String, Object>(params);

    for (Map.Entry<String, Object> entry: allParams.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (key != null && value != null) {
            if (value instanceof Collection) {
                uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
            } else if (value instanceof Object[]) {
                uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
            } else {
                uriBuilder = uriBuilder.queryParam(key, value);
            }
        }
    }

    String localVarUrl = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = apiClient.new JacksonJsonHttpContent(body);
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute();
}
 
Example #23
Source Project: firebase-admin-java   Author: firebase   File: CryptoSigners.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a {@link CryptoSigner} instance for the given Firebase app. Follows the protocol
 * documented at go/firebase-admin-sign.
 */
public static CryptoSigner getCryptoSigner(FirebaseApp firebaseApp) throws IOException {
  GoogleCredentials credentials = ImplFirebaseTrampolines.getCredentials(firebaseApp);

  // If the SDK was initialized with a service account, use it to sign bytes.
  if (credentials instanceof ServiceAccountCredentials) {
    return new ServiceAccountCryptoSigner((ServiceAccountCredentials) credentials);
  }

  FirebaseOptions options = firebaseApp.getOptions();
  HttpRequestFactory requestFactory = options.getHttpTransport().createRequestFactory(
      new FirebaseRequestInitializer(firebaseApp));
  JsonFactory jsonFactory = options.getJsonFactory();

  // If the SDK was initialized with a service account email, use it with the IAM service
  // to sign bytes.
  String serviceAccountId = options.getServiceAccountId();
  if (!Strings.isNullOrEmpty(serviceAccountId)) {
    return new IAMCryptoSigner(requestFactory, jsonFactory, serviceAccountId);
  }

  // If the SDK was initialized with some other credential type that supports signing
  // (e.g. GAE credentials), use it to sign bytes.
  if (credentials instanceof ServiceAccountSigner) {
    return new ServiceAccountCryptoSigner((ServiceAccountSigner) credentials);
  }

  // Attempt to discover a service account email from the local Metadata service. Use it
  // with the IAM service to sign bytes.
  HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(METADATA_SERVICE_URL));
  request.getHeaders().set("Metadata-Flavor", "Google");
  HttpResponse response = request.execute();
  try {
    byte[] output = ByteStreams.toByteArray(response.getContent());
    serviceAccountId = StringUtils.newStringUtf8(output).trim();
    return new IAMCryptoSigner(requestFactory, jsonFactory, serviceAccountId);
  } finally {
    response.disconnect();
  }
}
 
Example #24
Source Project: google-oauth-java-client   Author: googleapis   File: OAuthParametersTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testSignature() throws GeneralSecurityException {
  OAuthParameters parameters = new OAuthParameters();
  parameters.signer = new MockSigner();

  GenericUrl url = new GenericUrl("https://example.local?foo=bar");
  parameters.computeSignature("GET", url);
  assertEquals("GET&https%3A%2F%2Fexample.local&foo%3Dbar%26oauth_signature_method%3Dmock", parameters.signature);
}
 
Example #25
Source Project: openapi-generator   Author: OpenAPITools   File: StoreApi.java    License: Apache License 2.0 5 votes vote down vote up
public HttpResponse placeOrderForHttpResponse(Order body) throws IOException {
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new IllegalArgumentException("Missing the required parameter 'body' when calling placeOrder");
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order");

    String localVarUrl = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = apiClient.new JacksonJsonHttpContent(body);
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
 
Example #26
Source Project: datacollector   Author: streamsets   File: Auth.java    License: Apache License 2.0 5 votes vote down vote up
public boolean enable(String path, String type, String description) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/auth/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example #27
Source Project: Xero-Java   Author: XeroAPI   File: ProjectApi.java    License: MIT License 5 votes vote down vote up
public HttpResponse createProjectForHttpResponse(String accessToken,  String xeroTenantId,  ProjectCreateOrUpdate projectCreateOrUpdate) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createProject");
    }// verify the required parameter 'projectCreateOrUpdate' is set
    if (projectCreateOrUpdate == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectCreateOrUpdate' when calling createProject");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createProject");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects");
    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(projectCreateOrUpdate);
    
    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();  
}
 
Example #28
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: FirebaseChannel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * firebaseGet.
 *
 * @param path .
 * @return .
 * @throws IOException .
 */
public HttpResponse firebaseGet(String path) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));

  GenericUrl url = new GenericUrl(path);

  return requestFactory.buildGetRequest(url).execute();
}
 
Example #29
Source Project: googleads-java-lib   Author: googleads   File: BatchJobUploader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initiates the resumable upload by sending a request to Google Cloud Storage.
 *
 * @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob}
 * @return the URI for the initiated resumable upload
 */
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException {
  // This follows the Google Cloud Storage guidelines for initiating resumable uploads:
  // https://cloud.google.com/storage/docs/resumable-uploads-xml
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(
          req -> {
            HttpHeaders headers = createHttpHeaders();
            headers.setContentLength(0L);
            headers.set("x-goog-resumable", "start");
            req.setHeaders(headers);
            req.setLoggingEnabled(true);
          });

  try {
    HttpRequest httpRequest =
        requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent());
    HttpResponse response = httpRequest.execute();
    if (response.getHeaders() == null || response.getHeaders().getLocation() == null) {
      throw new BatchJobException(
          "Initiate upload failed. Resumable upload URI was not in the response.");
    }
    return URI.create(response.getHeaders().getLocation());
  } catch (IOException e) {
    throw new BatchJobException("Failed to initiate upload", e);
  }
}
 
Example #30
Source Project: datacollector   Author: streamsets   File: Mounts.java    License: Apache License 2.0 5 votes vote down vote up
public boolean mount(String path, String type, String description, Map<String, String> config) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  if (config != null) {
    data.put("config", config);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/mounts/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}