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

The following examples show how to use com.google.appengine.api.urlfetch.HTTPHeader. 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: OauthRawGcsService.java    From appengine-gcs-client with 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 #2
Source File: GceApiUtils.java    From solutions-google-compute-engine-orchestrator with 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 #3
Source File: URLFetchUtilsTest.java    From appengine-gcs-client with 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 #4
Source File: OauthRawGcsService.java    From appengine-gcs-client with 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 #5
Source File: GcsServiceFactory.java    From appengine-gcs-client with 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 #6
Source File: CurlServlet.java    From appengine-java-vm-runtime with 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 #7
Source File: UrlFetchResponse.java    From google-http-java-client with 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 #8
Source File: AppEngineHttpFetcher.java    From openid4java with 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 #9
Source File: NordnUploadActionTest.java    From nomulus with 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 #10
Source File: UrlFetchException.java    From nomulus with 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 #11
Source File: UrlFetchUtils.java    From nomulus with 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 #12
Source File: UrlFetchUtils.java    From nomulus with 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 File: HttpClientGAE.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
public static String getResponseGET(String url, Map<String, String> params, Map<String, String> headers) {
	int retry = 0;
	while (retry < 3) {
		long start = System.currentTimeMillis();
		try {
			URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
			String urlStr = ToolString.toUrl(url.trim(), params);
			HTTPRequest httpRequest = new HTTPRequest(new URL(urlStr), HTTPMethod.GET, FetchOptions.Builder.withDeadline(deadline));
			if (headers != null) {
				for (String name : headers.keySet()) {
					httpRequest.addHeader(new HTTPHeader(name, headers.get(name)));
				}
			}
			return processResponse(fetcher.fetch(httpRequest));
		} catch (Throwable e) {
			retry++;
			if (e instanceof RuntimeException) {
				throw (RuntimeException) e;
			} else if (retry < 3) {
				logger.warn("retrying after " + (System.currentTimeMillis() - start) + " and " + retry + " retries\n" + e.getClass() + e.getMessage());
			} else {
				logger.error(e.getClass() + "\n" + ToolString.stack2string(e));
			}
		}
	}
	return null;
}
 
Example #14
Source File: HttpClientGAE.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
public static String getResponsePUT(String url, Map<String, String> params, String json, Map<String, String> headers) {
	int retry = 0;
	while (retry < 3) {
		long start = System.currentTimeMillis();
		try {
			URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
			String urlStr = ToolString.toUrl(url.trim(), params);
			logger.debug("PUT : " + urlStr);
			HTTPRequest httpRequest = new HTTPRequest(new URL(urlStr), HTTPMethod.PUT, FetchOptions.Builder.withDeadline(deadline));
			if (headers != null) {
				for (String header : headers.keySet()) {
					httpRequest.addHeader(new HTTPHeader(header, headers.get(header)));
				}
			}
			httpRequest.setPayload(json.getBytes());
			HTTPResponse response = fetcher.fetch(httpRequest);
			return processResponse(response);
		} catch (Throwable e) {
			retry++;
			if (e instanceof RuntimeException) {
				throw (RuntimeException) e;
			} else if (retry < 3) {
				logger.warn("retrying after " + (System.currentTimeMillis() - start) + " and " + retry + " retries\n" + e.getClass() + e.getMessage());
			} else {
				logger.error(e.getClass() + "\n" + ToolString.stack2string(e));
			}
		}
	}
	return null;
}
 
Example #15
Source File: GoogleAppEngineRequestor.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private static Response toRequestorResponse(HTTPResponse response) {
    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    for (HTTPHeader header : response.getHeadersUncombined()) {
        List<String> existing = headers.get(header.getName());
        if (existing == null) {
            existing = new ArrayList<String>();
            headers.put(header.getName(), existing);
        }
        existing.add(header.getValue());
    }

    return new Response(response.getResponseCode(),
                        new ByteArrayInputStream(response.getContent()),
                        headers);
}
 
Example #16
Source File: GoogleAppEngineRequestor.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private HTTPRequest newRequest(String url, HTTPMethod method, Iterable<Header> headers) throws IOException {
    HTTPRequest request = new HTTPRequest(new URL(url), method, options);
    for (Header header : headers) {
        request.addHeader(new HTTPHeader(header.getKey(), header.getValue()));
    }
    return request;
}
 
Example #17
Source File: URLFetchTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPayload() throws Exception {
    URLFetchService service = URLFetchServiceFactory.getURLFetchService();

    URL url = getFetchUrl();

    HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST);
    req.setHeader(new HTTPHeader("Content-Type", "application/octet-stream"));
    req.setPayload("Tralala".getBytes(UTF_8));

    HTTPResponse response = service.fetch(req);
    String content = new String(response.getContent());
    Assert.assertEquals("Hopsasa", content);
}
 
Example #18
Source File: HttpRequestTest.java    From appengine-tck with 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());
}
 
Example #19
Source File: SerializationTest.java    From appengine-gcs-client with 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 #20
Source File: OauthRawGcsServiceTest.java    From appengine-gcs-client with 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 #21
Source File: OauthRawGcsServiceTest.java    From appengine-gcs-client with 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 #22
Source File: OauthRawGcsServiceTest.java    From appengine-gcs-client with 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 #23
Source File: URLFetchUtilsTest.java    From appengine-gcs-client with 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 #24
Source File: UrlFetchUtilsTest.java    From nomulus with 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 #25
Source File: OauthRawGcsService.java    From appengine-gcs-client with 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 #26
Source File: AppEngineHttpFetcher.java    From openid4java with 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 #27
Source File: RdeReportActionTest.java    From nomulus with 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 #28
Source File: RdeReporter.java    From nomulus with 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 #29
Source File: AbstractOAuthURLFetchService.java    From appengine-gcs-client with 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 #30
Source File: OauthRawGcsService.java    From appengine-gcs-client with 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();
}