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

The following examples show how to use com.google.api.client.http.GenericUrl. 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 File: FirebaseAuthIT.java    From firebase-admin-java with 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 #2
Source File: PetApi.java    From openapi-generator with 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 #3
Source File: SolidUtilities.java    From data-transfer-project with 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 #4
Source File: AuthorizationFlow.java    From android-oauth-client with 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 #5
Source File: MediaHttpUploader.java    From google-api-java-client with 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 #6
Source File: PetApi.java    From openapi-generator with 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 #7
Source File: RequestFactoryModuleTest.java    From nomulus with 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 #8
Source File: BatchRequestTest.java    From google-api-java-client with 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 #9
Source File: VaultEndpoint.java    From datacollector with 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 #10
Source File: MediaHttpDownloaderTest.java    From google-api-java-client with 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 #11
Source File: TGDriveBrowser.java    From tuxguitar with 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 #12
Source File: FakeApi.java    From openapi-generator with 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 #13
Source File: AuthorizationCodeFlow.java    From google-oauth-java-client with 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 #14
Source File: MediaHttpUploaderTest.java    From google-api-java-client with 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 #15
Source File: StoreApi.java    From openapi-generator with 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 #16
Source File: CryptoSigners.java    From firebase-admin-java with 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 #17
Source File: OAuthServlet.java    From vpn-over-dns with 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 #18
Source File: OAuthServletCallback.java    From vpn-over-dns with 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 #19
Source File: MendeleyClient.java    From slr-toolkit with 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 #20
Source File: GoogleJsonResponseExceptionHelper.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public static HttpResponse createHttpResponse(int statusCode, InputStream content)
    throws IOException {
  FakeHttpTransport transport = new FakeHttpTransport(statusCode, content);
  HttpRequestFactory factory = transport.createRequestFactory();
  HttpRequest request =
      factory.buildRequest(
          "foo", new GenericUrl("http://example.com/bar"), new EmptyHttpContent());
  request.setThrowExceptionOnExecuteError(false);
  return request.execute();
}
 
Example #21
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testResumableMediaUploadWithoutContentClose() throws Exception {
  int contentLength = 0;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  TestableByteArrayInputStream inputStream =
      new TestableByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(
      TEST_CONTENT_TYPE, inputStream).setLength(contentLength).setCloseInputStream(false);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
  assertFalse(inputStream.isClosed());
}
 
Example #22
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createLeaveApplicationForHttpResponse(String accessToken,  String xeroTenantId,  List<LeaveApplication> leaveApplication) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createLeaveApplication");
    }// verify the required parameter 'leaveApplication' is set
    if (leaveApplication == null) {
        throw new IllegalArgumentException("Missing the required parameter 'leaveApplication' when calling createLeaveApplication");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createLeaveApplication");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/LeaveApplications");
    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(leaveApplication);
    
    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 #23
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public HttpResponse fakeOuterNumberSerializeForHttpResponse(BigDecimal body, Map<String, Object> params) throws IOException {
    
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/number");

    // 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.POST, genericUrl, content).execute();
}
 
Example #24
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public HttpResponse testBodyWithQueryParamsForHttpResponse(String query, User body) throws IOException {
    // verify the required parameter 'query' is set
    if (query == null) {
        throw new IllegalArgumentException("Missing the required parameter 'query' when calling testBodyWithQueryParams");
    }// verify the required parameter 'body' is set
    if (body == null) {
        throw new IllegalArgumentException("Missing the required parameter 'body' when calling testBodyWithQueryParams");
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/body-with-query-params");
    if (query != null) {
        String key = "query";
        Object value = query;
        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.PUT, genericUrl, content).execute();
}
 
Example #25
Source File: BankFeedsApi.java    From Xero-Java with 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 #26
Source File: MediaHttpDownloader.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the current request.
 *
 * @param currentRequestLastBytePos last byte position for current request
 * @param requestUrl request URL where the download requests will be sent
 * @param requestHeaders request headers or {@code null} to ignore
 * @param outputStream destination output stream
 * @return HTTP response
 */
private HttpResponse executeCurrentRequest(long currentRequestLastBytePos, GenericUrl requestUrl,
    HttpHeaders requestHeaders, OutputStream outputStream) throws IOException {
  // prepare the GET request
  HttpRequest request = requestFactory.buildGetRequest(requestUrl);
  // add request headers
  if (requestHeaders != null) {
    request.getHeaders().putAll(requestHeaders);
  }
  // set Range header (if necessary)
  if (bytesDownloaded != 0 || currentRequestLastBytePos != -1) {
    StringBuilder rangeHeader = new StringBuilder();
    rangeHeader.append("bytes=").append(bytesDownloaded).append("-");
    if (currentRequestLastBytePos != -1) {
      rangeHeader.append(currentRequestLastBytePos);
    }
    request.getHeaders().setRange(rangeHeader.toString());
  }
  // execute the request and copy into the output stream
  HttpResponse response = request.execute();
  try {
    ByteStreams.copy(response.getContent(), outputStream);
  } finally {
    response.disconnect();
  }
  return response;
}
 
Example #27
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testDirectMediaUploadWithZeroContent() throws Exception {
  int contentLength = 0;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.directUploadEnabled = true;
  ByteArrayContent mediaContent =
      new ByteArrayContent(TEST_CONTENT_TYPE, new byte[contentLength]);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.setDirectUploadEnabled(true);
  uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));

  // There should be only 1 call made for direct media upload.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #28
Source File: GoogleHttpClientEdgeGridInterceptorTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptor() throws URISyntaxException, IOException, RequestSigningException {
    HttpRequestFactory requestFactory = createSigningRequestFactory();

    URI uri = URI.create("https://endpoint.net/billing-usage/v1/reportSources");
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri));
    // Mimic what the library does to process the interceptor.
    request.getInterceptor().intercept(request);

    assertThat(request.getHeaders().containsKey("host"), is(false));
    assertThat(request.getUrl().getHost(), equalTo("endpoint.net"));
    assertThat(request.getHeaders().getAuthorization(), not(isEmptyOrNullString()));
}
 
Example #29
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public HttpResponse deletePetForHttpResponse(Long petId, Map<String, Object> params) throws IOException {
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'petId' when calling deletePet");
    }
    // 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}");

    // 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.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = null;
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute();
}
 
Example #30
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public HttpResponse addPetForHttpResponse(Pet 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 addPet");
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet");

    // 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.POST, genericUrl, content).execute();
}