Java Code Examples for com.google.appengine.api.urlfetch.HTTPHeader

The following examples show how to use com.google.appengine.api.urlfetch.HTTPHeader. 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: nomulus   Author: google   File: UrlFetchException.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getMessage() {
  StringBuilder res =
      new StringBuilder(2048 + rsp.getContent().length)
          .append(
              String.format(
                  "%s: %s (HTTP Status %d)\nX-Fetch-URL: %s\nX-Final-URL: %s\n",
                  getClass().getSimpleName(),
                  super.getMessage(),
                  rsp.getResponseCode(),
                  req.getURL().toString(),
                  rsp.getFinalUrl()));
  for (HTTPHeader header : rsp.getHeadersUncombined()) {
    res.append(header.getName());
    res.append(": ");
    res.append(header.getValue());
    res.append('\n');
  }
  res.append(">>>\n");
  res.append(new String(rsp.getContent(), UTF_8));
  res.append("\n<<<");
  return res.toString();
}
 
Example #2
Source Project: nomulus   Author: google   File: NordnUploadActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  inject.setStaticField(Ofy.class, "clock", clock);
  when(fetchService.fetch(any(HTTPRequest.class))).thenReturn(httpResponse);
  when(httpResponse.getContent()).thenReturn("Success".getBytes(US_ASCII));
  when(httpResponse.getResponseCode()).thenReturn(SC_ACCEPTED);
  when(httpResponse.getHeadersUncombined())
      .thenReturn(ImmutableList.of(new HTTPHeader(LOCATION, "http://trololol")));
  persistResource(loadRegistrar("TheRegistrar").asBuilder().setIanaIdentifier(99999L).build());
  createTld("tld");
  persistResource(Registry.get("tld").asBuilder().setLordnUsername("lolcat").build());
  action.clock = clock;
  action.fetchService = fetchService;
  action.lordnRequestInitializer = lordnRequestInitializer;
  action.phase = "claims";
  action.taskQueueUtils = new TaskQueueUtils(new Retrier(new FakeSleeper(clock), 3));
  action.tld = "tld";
  action.tmchMarksdbUrl = "http://127.0.0.1";
  action.random = new SecureRandom();
  action.retrier = new Retrier(new FakeSleeper(clock), 3);
}
 
Example #3
Source Project: openid4java   Author: jbufu   File: AppEngineHttpFetcher.java    License: Apache License 2.0 6 votes vote down vote up
private static void addHeaders(HTTPRequest httpRequest,
    HttpRequestOptions requestOptions) {

  String contentType = requestOptions.getContentType();

  if (contentType != null) {
    httpRequest.addHeader(new HTTPHeader("Content-Type", contentType));
  }

  Map<String, String> headers = getRequestHeaders(requestOptions);

  if (headers != null) {
    for (Map.Entry<String, String> header : headers.entrySet()) {
      httpRequest.addHeader(new HTTPHeader(header.getKey(), header.getValue()));
    }
  }
}
 
Example #4
Source Project: google-http-java-client   Author: googleapis   File: UrlFetchResponse.java    License: Apache License 2.0 6 votes vote down vote up
UrlFetchResponse(HTTPResponse fetchResponse) {
  this.fetchResponse = fetchResponse;
  for (HTTPHeader header : fetchResponse.getHeadersUncombined()) {
    String name = header.getName();
    String value = header.getValue();
    if (name != null && value != null) {
      headerNames.add(name);
      headerValues.add(value);
      if ("content-type".equalsIgnoreCase(name)) {
        contentType = value;
      } else if ("content-encoding".equalsIgnoreCase(name)) {
        contentEncoding = value;
      } else if ("content-length".equalsIgnoreCase(name)) {
        try {
          contentLength = Long.parseLong(value);
        } catch (NumberFormatException e) {
          // ignore
        }
      }
    }
  }
}
 
Example #5
Source Project: appengine-java-vm-runtime   Author: GoogleCloudPlatform   File: CurlServlet.java    License: Apache License 2.0 6 votes vote down vote up
public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException {
  String url = req.getParameter("url");
  String deadlineSecs = req.getParameter("deadline");
  URLFetchService service = URLFetchServiceFactory.getURLFetchService();
  HTTPRequest fetchReq = new HTTPRequest(new URL(url));
  if (deadlineSecs != null) {
    fetchReq.getFetchOptions().setDeadline(Double.valueOf(deadlineSecs));
  }
  HTTPResponse fetchRes = service.fetch(fetchReq);
  for (HTTPHeader header : fetchRes.getHeaders()) {
    res.addHeader(header.getName(), header.getValue());
  }
  if (fetchRes.getResponseCode() == 200) {
    res.getOutputStream().write(fetchRes.getContent());
  } else {
    res.sendError(fetchRes.getResponseCode(), "Error while fetching");
  }
}
 
Example #6
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: GcsServiceFactory.java    License: Apache License 2.0 6 votes vote down vote up
static RawGcsService createRawGcsService(Map<String, String> headers) {
  ImmutableSet.Builder<HTTPHeader> builder = ImmutableSet.builder();
  if (headers != null) {
    for (Map.Entry<String, String> header : headers.entrySet()) {
      builder.add(new HTTPHeader(header.getKey(), header.getValue()));
    }
  }

  RawGcsService rawGcsService;
  Value location = SystemProperty.environment.value();
  if (location == SystemProperty.Environment.Value.Production || hasCustomAccessTokenProvider()) {
    rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build());
  } else if (location == SystemProperty.Environment.Value.Development) {
    rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService();
  } else {
    Delegate<?> delegate = ApiProxy.getDelegate();
    if (delegate == null
        || delegate.getClass().getName().startsWith("com.google.appengine.tools.development")) {
      rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService();
    } else {
      rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build());
    }
  }
  return rawGcsService;
}
 
Example #7
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsService.java    License: Apache License 2.0 6 votes vote down vote up
private void addOptionsHeaders(HTTPRequest req, GcsFileOptions options) {
  if (options == null) {
    return;
  }
  if (options.getMimeType() != null) {
    req.setHeader(new HTTPHeader(CONTENT_TYPE, options.getMimeType()));
  }
  if (options.getAcl() != null) {
    req.setHeader(new HTTPHeader(ACL, options.getAcl()));
  }
  if (options.getCacheControl() != null) {
    req.setHeader(new HTTPHeader(CACHE_CONTROL, options.getCacheControl()));
  }
  if (options.getContentDisposition() != null) {
    req.setHeader(new HTTPHeader(CONTENT_DISPOSITION, options.getContentDisposition()));
  }
  if (options.getContentEncoding() != null) {
    req.setHeader(new HTTPHeader(CONTENT_ENCODING, options.getContentEncoding()));
  }
  for (Entry<String, String> entry : options.getUserMetadata().entrySet()) {
    req.setHeader(new HTTPHeader(X_GOOG_META + entry.getKey(), entry.getValue()));
  }
}
 
Example #8
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void copyObject(GcsFilename source, GcsFilename dest, GcsFileOptions fileOptions,
    long timeoutMillis) throws IOException {
  HTTPRequest req = makeRequest(dest, null, PUT, timeoutMillis);
  req.setHeader(new HTTPHeader(X_GOOG_COPY_SOURCE, makePath(source)));
  if (fileOptions != null) {
    req.setHeader(REPLACE_METADATA_HEADER);
    addOptionsHeaders(req, fileOptions);
  }
  HTTPResponse resp;
  try {
    resp = urlfetch.fetch(req);
  } catch (IOException e) {
    throw createIOException(new HTTPRequestInfo(req), e);
  }
  if (resp.getResponseCode() != 200) {
    throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);
  }
}
 
Example #9
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: URLFetchUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDescribeRequestAndResponseF() throws Exception {
  HTTPRequest request = new HTTPRequest(new URL("http://ping/pong"));
  request.setPayload("hello".getBytes());
  request.addHeader(new HTTPHeader("k1", "v1"));
  request.addHeader(new HTTPHeader("k2", "v2"));
  HTTPResponse response = mock(HTTPResponse.class);
  when(response.getHeadersUncombined()).thenReturn(ImmutableList.of(new HTTPHeader("k3", "v3")));
  when(response.getResponseCode()).thenReturn(500);
  when(response.getContent()).thenReturn("bla".getBytes());
  String expected = "Request: GET http://ping/pong\nk1: v1\nk2: v2\n\n"
      + "5 bytes of content\n\nResponse: 500 with 3 bytes of content\nk3: v3\nbla\n";
  String result =
      URLFetchUtils.describeRequestAndResponse(new HTTPRequestInfo(request), response);
  assertEquals(expected, result);
}
 
Example #10
Source Project: solutions-google-compute-engine-orchestrator   Author: GoogleCloudPlatform   File: GceApiUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an HTTPRequest with the information passed in.
 *
 * @param accessToken the access token necessary to authorize the request.
 * @param url the url to query.
 * @param payload the payload for the request.
 * @return the created HTTP request.
 * @throws IOException
 */
public static HTTPResponse makeHttpRequest(
    String accessToken, final String url, String payload, HTTPMethod method) throws IOException {

  // Create HTTPRequest and set headers
  HTTPRequest httpRequest = new HTTPRequest(new URL(url.toString()), method);
  httpRequest.addHeader(new HTTPHeader("Authorization", "OAuth " + accessToken));
  httpRequest.addHeader(new HTTPHeader("Host", "www.googleapis.com"));
  httpRequest.addHeader(new HTTPHeader("Content-Length", Integer.toString(payload.length())));
  httpRequest.addHeader(new HTTPHeader("Content-Type", "application/json"));
  httpRequest.addHeader(new HTTPHeader("User-Agent", "google-api-java-client/1.0"));
  httpRequest.setPayload(payload.getBytes());

  URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
  HTTPResponse httpResponse = fetcher.fetch(httpRequest);
  return httpResponse;
}
 
Example #11
Source Project: nomulus   Author: google   File: UrlFetchUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Optional<String> getHeaderFirstInternal(Iterable<HTTPHeader> hdrs, String name) {
  name = Ascii.toLowerCase(name);
  for (HTTPHeader header : hdrs) {
    if (Ascii.toLowerCase(header.getName()).equals(name)) {
      return Optional.of(header.getValue());
    }
  }
  return Optional.empty();
}
 
Example #12
Source Project: nomulus   Author: google   File: UrlFetchUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets payload on request as a {@code multipart/form-data} request.
 *
 * <p>This is equivalent to running the command: {@code curl -F [email protected] URL}
 *
 * @see <a href="http://www.ietf.org/rfc/rfc2388.txt">RFC2388 - Returning Values from Forms</a>
 */
public static void setPayloadMultipart(
    HTTPRequest request,
    String name,
    String filename,
    MediaType contentType,
    String data,
    Random random) {
  String boundary = createMultipartBoundary(random);
  checkState(
      !data.contains(boundary),
      "Multipart data contains autogenerated boundary: %s", boundary);
  String multipart =
      String.format("--%s\r\n", boundary)
          + String.format(
              "%s: form-data; name=\"%s\"; filename=\"%s\"\r\n",
              CONTENT_DISPOSITION, name, filename)
          + String.format("%s: %s\r\n", CONTENT_TYPE, contentType)
          + "\r\n"
          + data
          + "\r\n"
          + String.format("--%s--\r\n", boundary);
  byte[] payload = multipart.getBytes(UTF_8);
  request.addHeader(
      new HTTPHeader(
          CONTENT_TYPE, String.format("multipart/form-data;" + " boundary=\"%s\"", boundary)));
  request.addHeader(new HTTPHeader(CONTENT_LENGTH, Integer.toString(payload.length)));
  request.setPayload(payload);
}
 
Example #13
Source Project: nomulus   Author: google   File: UrlFetchUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Sets the HTTP Basic Authentication header on an {@link HTTPRequest}. */
public static void setAuthorizationHeader(HTTPRequest req, Optional<String> login) {
  if (login.isPresent()) {
    String token = base64().encode(login.get().getBytes(UTF_8));
    req.addHeader(new HTTPHeader(AUTHORIZATION, "Basic " + token));
  }
}
 
Example #14
Source Project: nomulus   Author: google   File: RdeReporter.java    License: Apache License 2.0 5 votes vote down vote up
/** Uploads {@code reportBytes} to ICANN. */
public void send(byte[] reportBytes) throws XmlException {
  XjcRdeReportReport report = XjcXmlTransformer.unmarshal(
      XjcRdeReportReport.class, new ByteArrayInputStream(reportBytes));
  XjcRdeHeader header = report.getHeader().getValue();

  // Send a PUT request to ICANN's HTTPS server.
  URL url = makeReportUrl(header.getTld(), report.getId());
  String username = header.getTld() + "_ry";
  String token = base64().encode(String.format("%s:%s", username, password).getBytes(UTF_8));
  final HTTPRequest req = new HTTPRequest(url, PUT, validateCertificate().setDeadline(60d));
  req.addHeader(new HTTPHeader(CONTENT_TYPE, REPORT_MIME));
  req.addHeader(new HTTPHeader(AUTHORIZATION, "Basic " + token));
  req.setPayload(reportBytes);
  logger.atInfo().log("Sending report:\n%s", new String(reportBytes, UTF_8));
  HTTPResponse rsp =
      retrier.callWithRetry(
          () -> {
            HTTPResponse rsp1 = urlFetchService.fetch(req);
            switch (rsp1.getResponseCode()) {
              case SC_OK:
              case SC_BAD_REQUEST:
                break;
              default:
                throw new UrlFetchException("PUT failed", req, rsp1);
            }
            return rsp1;
          },
          SocketTimeoutException.class);

  // Ensure the XML response is valid.
  XjcIirdeaResult result = parseResult(rsp);
  if (result.getCode().getValue() != 1000) {
    logger.atWarning().log(
        "PUT rejected: %d %s\n%s",
        result.getCode().getValue(), result.getMsg(), result.getDescription());
    throw new InternalServerErrorException(result.getMsg());
  }
}
 
Example #15
Source Project: nomulus   Author: google   File: RdeReportActionTest.java    License: Apache License 2.0 5 votes vote down vote up
private static ImmutableMap<String, String> mapifyHeaders(Iterable<HTTPHeader> headers) {
  ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
  for (HTTPHeader header : headers) {
    builder.put(Ascii.toUpperCase(header.getName().replace('-', '_')), header.getValue());
  }
  return builder.build();
}
 
Example #16
Source Project: nomulus   Author: google   File: UrlFetchUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetPayloadMultipart() {
  HTTPRequest request = mock(HTTPRequest.class);
  setPayloadMultipart(
      request,
      "lol",
      "cat",
      CSV_UTF_8,
      "The nice people at the store say hello. ヘ(◕。◕ヘ)",
      random);
  ArgumentCaptor<HTTPHeader> headerCaptor = ArgumentCaptor.forClass(HTTPHeader.class);
  verify(request, times(2)).addHeader(headerCaptor.capture());
  List<HTTPHeader> addedHeaders = headerCaptor.getAllValues();
  assertThat(addedHeaders.get(0).getName()).isEqualTo(CONTENT_TYPE);
  assertThat(addedHeaders.get(0).getValue())
      .isEqualTo(
          "multipart/form-data; "
              + "boundary=\"------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"");
  assertThat(addedHeaders.get(1).getName()).isEqualTo(CONTENT_LENGTH);
  assertThat(addedHeaders.get(1).getValue()).isEqualTo("294");
  String payload = "--------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n"
      + "Content-Disposition: form-data; name=\"lol\"; filename=\"cat\"\r\n"
      + "Content-Type: text/csv; charset=utf-8\r\n"
      + "\r\n"
      + "The nice people at the store say hello. ヘ(◕。◕ヘ)\r\n"
      + "--------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA--\r\n";
  verify(request).setPayload(payload.getBytes(UTF_8));
  verifyNoMoreInteractions(request);
}
 
Example #17
Source Project: openid4java   Author: jbufu   File: AppEngineHttpFetcher.java    License: Apache License 2.0 5 votes vote down vote up
private static Header[] getResponseHeaders(HTTPResponse httpResponse, String headerName) {
  List<HTTPHeader> allHeaders = httpResponse.getHeaders();
  List<Header> matchingHeaders = new ArrayList<Header>();
  for (HTTPHeader header : allHeaders) {
    if (header.getName().equalsIgnoreCase(headerName)) {
      matchingHeaders.add(new BasicHeader(header.getName(), header.getValue()));
    }
  }
  return matchingHeaders.toArray(new Header[matchingHeaders.size()]);
}
 
Example #18
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: AbstractOAuthURLFetchService.java    License: Apache License 2.0 5 votes vote down vote up
private HTTPRequest createAuthorizeRequest(final HTTPRequest req) throws RetryHelperException {
  String token = RetryHelper.runWithRetries(new Callable<String>() {
    @Override
    public String call() {
      return getToken();
    }
  }, RETRY_PARAMS, EXCEPTION_HANDLER);
  HTTPRequest request = URLFetchUtils.copyRequest(req);
  request.setHeader(new HTTPHeader("Authorization", "Bearer " + token));
  return request;
}
 
Example #19
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsService.java    License: Apache License 2.0 5 votes vote down vote up
OauthRawGcsService(OAuthURLFetchService urlfetch, ImmutableSet<HTTPHeader> headers) {
  this.urlfetch = checkNotNull(urlfetch, "Null urlfetch");
  this.headers = checkNotNull(headers, "Null headers");
  AppIdentityCredential cred = new AppIdentityCredential(OAUTH_SCOPES);
  storage = new Storage.Builder(new UrlFetchTransport(), new JacksonFactory(), cred)
      .setApplicationName(SystemProperty.applicationId.get()).build();
}
 
Example #20
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsService.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
HTTPRequest makeRequest(GcsFilename filename, @Nullable Map<String, String> queryStrings,
    HTTPMethod method, long timeoutMillis, byte[] payload) {
  HTTPRequest request = new HTTPRequest(makeUrl(filename, queryStrings), method,
      FetchOptions.Builder.disallowTruncate()
          .doNotFollowRedirects()
          .validateCertificate()
          .setDeadline(timeoutMillis / 1000.0));
  for (HTTPHeader header : headers) {
    request.addHeader(header);
  }
  request.addHeader(USER_AGENT);
  if (payload != null && payload.length > 0) {
    request.setHeader(new HTTPHeader(CONTENT_LENGTH, String.valueOf(payload.length)));
    try {
      request.setHeader(new HTTPHeader(CONTENT_MD5,
          BaseEncoding.base64().encode(MessageDigest.getInstance("MD5").digest(payload))));
    } catch (NoSuchAlgorithmException e) {
      log.severe(
          "Unable to get a MessageDigest instance, no Content-MD5 header sent.\n" + e.toString());
    }
    request.setPayload(payload);
  } else {
    request.setHeader(ZERO_CONTENT_LENGTH);
  }
  return request;
}
 
Example #21
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsService.java    License: Apache License 2.0 5 votes vote down vote up
HTTPRequest createPutRequest(final GcsRestCreationToken token, final ByteBuffer chunk,
    final boolean isFinalChunk, long timeoutMillis, final int length) {
  long offset = token.offset;
  Preconditions.checkArgument(offset % CHUNK_ALIGNMENT_BYTES == 0,
      "%s: Offset not aligned; offset=%s, length=%s, token=%s",
      this, offset, length, token);
  Preconditions.checkArgument(isFinalChunk || length % CHUNK_ALIGNMENT_BYTES == 0,
      "%s: Chunk not final and not aligned: offset=%s, length=%s, token=%s",
      this, offset, length, token);
  Preconditions.checkArgument(isFinalChunk || length > 0,
      "%s: Chunk empty and not final: offset=%s, length=%s, token=%s",
      this, offset, length, token);
  if (log.isLoggable(Level.FINEST)) {
    log.finest(this + ": About to write to " + token + " " + String.format("0x%x", length)
        + " bytes at offset " + String.format("0x%x", offset)
        + "; isFinalChunk: " + isFinalChunk + ")");
  }
  long limit = offset + length;
  Map<String, String> queryStrings = Collections.singletonMap(UPLOAD_ID, token.uploadId);
  final HTTPRequest req =
      makeRequest(token.filename, queryStrings, PUT, timeoutMillis, chunk);
  req.setHeader(
      new HTTPHeader(CONTENT_RANGE,
          "bytes " + (length == 0 ? "*" : offset + "-" + (limit - 1))
          + (isFinalChunk ? "/" + limit : "/*")));
  return req;
}
 
Example #22
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: URLFetchUtils.java    License: Apache License 2.0 5 votes vote down vote up
static void appendResponse(HTTPResponse resp, StringBuilder b) {
  byte[] content = resp.getContent();
  b.append(resp.getResponseCode()).append(" with ").append(content == null ? 0 : content.length);
  b.append(" bytes of content");
  for (HTTPHeader h : resp.getHeadersUncombined()) {
    b.append('\n').append(h.getName()).append(": ").append(h.getValue());
  }
  b.append('\n').append(content == null ? "" : new String(content, UTF_8)).append('\n');
}
 
Example #23
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: URLFetchUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Gets all headers with the name {@code headerName}, case-insensitive. */
private static Iterable<HTTPHeader> getHeaders(HTTPResponse resp, String headerName) {
  final String lowercaseHeaderName = headerName.toLowerCase();
  return Iterables.filter(resp.getHeadersUncombined(), new Predicate<HTTPHeader>() {
    @Override public boolean apply(HTTPHeader header) {
      return header.getName().toLowerCase().equals(lowercaseHeaderName);
    }
  });
}
 
Example #24
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: URLFetchUtils.java    License: Apache License 2.0 5 votes vote down vote up
static HTTPRequest copyRequest(HTTPRequest in) {
  HTTPRequest out = new HTTPRequest(in.getURL(), in.getMethod(), in.getFetchOptions());
  for (HTTPHeader h : in.getHeaders()) {
    out.addHeader(h);
  }
  out.setPayload(in.getPayload());
  return out;
}
 
Example #25
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: URLFetchUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCopyRequest() throws Exception {
  HTTPRequest request = new HTTPRequest(new URL("http://h1/v1"), HTTPMethod.HEAD);
  request.setHeader(new HTTPHeader("k3", "v3"));
  HTTPRequest copy = URLFetchUtils.copyRequest(request);
  assertEquals("http://h1/v1", copy.getURL().toString());
  assertEquals(HTTPMethod.HEAD, copy.getMethod());
  assertEquals(1, copy.getHeaders().size());
  assertEquals("k3", copy.getHeaders().get(0).getName());
  assertEquals("v3", copy.getHeaders().get(0).getValue());
}
 
Example #26
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void makeRequestShouldHandleAnAbsentPayload() throws MalformedURLException {
  URL url = new URL("https://storage.googleapis.com/sample-bucket/sample-object");
  HTTPRequest expected = new HTTPRequest(url, PUT, FETCH_OPTIONS);
  expected.addHeader(new HTTPHeader("Content-Length", "0"));
  expected.addHeader(new HTTPHeader("User-Agent", OauthRawGcsService.USER_AGENT_PRODUCT));
  assertHttpRequestEquals(expected, service.makeRequest(GCS_FILENAME, null, PUT, 30000));
}
 
Example #27
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void makeRequestShouldHandleAnEmptyPayload() throws MalformedURLException {
  URL url = new URL("https://storage.googleapis.com/sample-bucket/sample-object");
  HTTPRequest expected = new HTTPRequest(url, PUT, FETCH_OPTIONS);
  expected.addHeader(new HTTPHeader("Content-Length", "0"));
  expected.addHeader(new HTTPHeader("User-Agent", OauthRawGcsService.USER_AGENT_PRODUCT));
  assertHttpRequestEquals(
      expected, service.makeRequest(GCS_FILENAME, null, PUT, 30000, new byte[0]));
}
 
Example #28
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: OauthRawGcsServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void makeRequestShouldHandleAPresentPayload() throws MalformedURLException {
  URL url = new URL("https://storage.googleapis.com/sample-bucket/sample-object");
  byte[] payload = "hello".getBytes(UTF_8);
  HTTPRequest expected = new HTTPRequest(url, PUT, FETCH_OPTIONS);
  expected.addHeader(new HTTPHeader("Content-Length", "5"));
  expected.addHeader(new HTTPHeader("Content-MD5", "XUFAKrxLKna5cZ2REBfFkg=="));
  expected.addHeader(new HTTPHeader("User-Agent", OauthRawGcsService.USER_AGENT_PRODUCT));
  expected.setPayload(payload);
  assertHttpRequestEquals(expected, service.makeRequest(GCS_FILENAME, null, PUT, 30000, payload));
}
 
Example #29
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: SerializationTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
@Test
public void testOauthSerializes() throws IOException, ClassNotFoundException {
  RawGcsService rawGcsService =
      OauthRawGcsServiceFactory.createOauthRawGcsService(ImmutableSet.<HTTPHeader>of());
  GcsService gcsService = new GcsServiceImpl(rawGcsService, GcsServiceOptions.DEFAULT);
  GcsInputChannel readChannel = gcsService.openReadChannel(TestFile.SMALL.filename, 0);
  GcsInputChannel reconstruct = reconstruct(readChannel);
  readChannel.close();
  reconstruct.close();
}
 
Example #30
Source Project: appengine-tck   Author: GoogleCloudPlatform   File: HttpRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetters() throws Exception {
    HTTPRequest request = new HTTPRequest(getFetchUrl(), HTTPMethod.PATCH, FetchOptions.Builder.withDefaults());
    request.addHeader(new HTTPHeader("foo", "bar"));
    request.setPayload("qwerty".getBytes());

    Assert.assertEquals(getFetchUrl(), request.getURL());
    Assert.assertEquals(HTTPMethod.PATCH, request.getMethod());
    Assert.assertNotNull(request.getFetchOptions());
    Assert.assertNotNull(request.getHeaders());
    Assert.assertEquals(1, request.getHeaders().size());
    assertEquals(new HTTPHeader("foo", "bar"), request.getHeaders().get(0));
    Assert.assertArrayEquals("qwerty".getBytes(), request.getPayload());
}