Search in sources :

Example 11 with URLFetchResponse

use of com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse in project appengine-java-standard by GoogleCloudPlatform.

the class LocalURLFetchService method fetch.

@LatencyPercentiles(latency50th = 5)
public URLFetchResponse fetch(Status status, URLFetchRequest request) {
    if (status == null) {
        throw new NullPointerException("status cannot be null.");
    }
    if (request == null) {
        throw new NullPointerException("request cannot be null.");
    }
    if (!hasValidURL(request)) {
        throw new ApplicationException(ErrorCode.INVALID_URL.getNumber(), "Invalid URL: " + request.getUrl());
    }
    MethodFactory methodFactory = METHOD_FACTORY_MAP.get(request.getMethod());
    if (methodFactory == null) {
        throw new ApplicationException(ErrorCode.INVALID_URL.getNumber(), "Unsupported method: " + request.getMethod());
    }
    HttpRequestBase method = methodFactory.buildMethod(request);
    HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(params, request.getFollowRedirects());
    // TODO set these timeouts according to the RPC deadline.
    // see http://b/1488459 for more info
    // how long we'll wait to establish a connection
    HttpConnectionParams.setConnectionTimeout(params, timeoutInMs);
    // how long we'll let the socket stay open
    HttpConnectionParams.setSoTimeout(params, timeoutInMs);
    method.setParams(params);
    boolean sawContentType = false;
    for (URLFetchRequest.Header pbHeader : request.getHeaderList()) {
        // an exception, and this behavior matches production.
        if (pbHeader.getKey().equalsIgnoreCase("Content-Length")) {
            continue;
        }
        method.addHeader(pbHeader.getKey(), pbHeader.getValue());
        if (pbHeader.getKey().equalsIgnoreCase("Content-Type")) {
            sawContentType = true;
        }
    }
    // TODO: Should we check on PUT/PATCH? What would the default be?
    if (!sawContentType && (request.getMethod() == RequestMethod.POST) && request.hasPayload()) {
        method.addHeader("Content-Type", "application/x-www-form-urlencoded");
    }
    URLFetchResponse.Builder response = URLFetchResponse.newBuilder();
    try {
        HttpResponse httpResponse = doPrivilegedExecute(request, method, response);
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode < 100 || responseCode >= 600) {
            // Note, response codes in the range [100, 600) are valid.
            throw new ApplicationException(ErrorCode.FETCH_ERROR.getNumber(), "Status code " + responseCode + " unknown when making " + method.getMethod() + " request to URL: " + request.getUrl());
        }
        HttpEntity responseEntity = httpResponse.getEntity();
        if (responseEntity != null) {
            byte[] responseBuffer = responseToByteArray(responseEntity);
            if (responseBuffer.length > maxResponseLength) {
                responseBuffer = Arrays.copyOf(responseBuffer, maxResponseLength);
                response.setContentWasTruncated(true);
            }
            response.setContent(ByteString.copyFrom(responseBuffer));
        }
        httpclientHeadersToPbHeaders(httpResponse.getAllHeaders(), response);
    } catch (SocketTimeoutException ste) {
        throw new ApplicationException(ErrorCode.DEADLINE_EXCEEDED.getNumber(), "http method " + method.getMethod() + " against URL " + request.getUrl() + " timed out.");
    } catch (SSLException e) {
        throw new ApplicationException(ErrorCode.SSL_CERTIFICATE_ERROR.getNumber(), "Couldn't validate the server's SSL certificate for URL " + request.getUrl() + ": " + e.getMessage());
    } catch (IOException e) {
        if (e.getCause() != null && e.getCause().getMessage().matches("Maximum redirects \\([0-9]+\\) exceeded")) {
            throw new ApplicationException(ErrorCode.TOO_MANY_REDIRECTS.getNumber(), "Received exception executing http method " + method.getMethod() + " against URL " + request.getUrl() + ": " + e.getCause().getMessage());
        } else {
            throw new ApplicationException(ErrorCode.FETCH_ERROR.getNumber(), "Received exception executing http method " + method.getMethod() + " against URL " + request.getUrl() + ": " + e.getMessage());
        }
    }
    return response.build();
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) URLFetchResponse(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse) ApplicationException(com.google.apphosting.api.ApiProxy.ApplicationException) SocketTimeoutException(java.net.SocketTimeoutException) BasicHttpParams(org.apache.http.params.BasicHttpParams) URLFetchRequest(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest) LatencyPercentiles(com.google.appengine.tools.development.LatencyPercentiles)

Example 12 with URLFetchResponse

use of com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse in project appengine-java-standard by GoogleCloudPlatform.

the class URLFetchServiceImplTest method testSync_SimpleHEAD.

@Test
public void testSync_SimpleHEAD() throws Exception {
    URL url = new URL("http://google.com/foo");
    HTTPRequest request = new HTTPRequest(url, HTTPMethod.HEAD);
    URLFetchRequest requestProto = URLFetchRequest.newBuilder().setUrl(url.toString()).setMethod(RequestMethod.HEAD).setFollowRedirects(true).build();
    URLFetchResponse responseProto = URLFetchResponse.newBuilder().setStatusCode(200).build();
    when(delegate.makeSyncCall(same(ApiProxy.getCurrentEnvironment()), eq(URLFetchServiceImpl.PACKAGE), eq("Fetch"), eq(requestProto.toByteArray()))).thenReturn(responseProto.toByteArray());
    HTTPResponse response = new URLFetchServiceImpl().fetch(request);
    assertThat(response.getResponseCode()).isEqualTo(200);
    verify(delegate).makeSyncCall(any(), any(), any(), any());
}
Also used : URLFetchResponse(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse) URLFetchRequest(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest) URL(java.net.URL) Test(org.junit.Test)

Example 13 with URLFetchResponse

use of com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse in project appengine-java-standard by GoogleCloudPlatform.

the class URLFetchServiceImplTest method testSync_Redirects_followRedirects.

@Test
public void testSync_Redirects_followRedirects() throws Exception {
    URL url = new URL("http://non-existent-domain.com/foo");
    HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, followRedirects());
    URLFetchRequest requestProto = URLFetchRequest.newBuilder().setUrl(url.toString()).setMethod(RequestMethod.GET).setFollowRedirects(true).build();
    URLFetchResponse responseProto = URLFetchResponse.newBuilder().setStatusCode(200).setFinalUrl("http://fancytown.example.com").build();
    when(delegate.makeSyncCall(same(ApiProxy.getCurrentEnvironment()), eq(URLFetchServiceImpl.PACKAGE), eq("Fetch"), eq(requestProto.toByteArray()))).thenReturn(responseProto.toByteArray());
    HTTPResponse response = new URLFetchServiceImpl().fetch(request);
    assertThat(response.getResponseCode()).isEqualTo(200);
    // Avoid URL.equals, which will try to resolve the hostname in the URL.
    assertThat(response.getFinalUrl().toString()).isEqualTo(new URL("http://fancytown.example.com").toString());
}
Also used : URLFetchResponse(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse) URLFetchRequest(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest) URL(java.net.URL) Test(org.junit.Test)

Example 14 with URLFetchResponse

use of com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse in project appengine-java-standard by GoogleCloudPlatform.

the class URLFetchServiceImplTest method testSync_RequestHeaders.

@Test
public void testSync_RequestHeaders() throws Exception {
    URL url = new URL("http://google.com/foo");
    HTTPRequest request = new HTTPRequest(url);
    request.addHeader(new HTTPHeader("Test-Header", "Request"));
    String responseContent = "<p>This is the desired response.</p>";
    URLFetchRequest requestProto = URLFetchRequest.newBuilder().setUrl(url.toString()).setMethod(RequestMethod.GET).setFollowRedirects(true).addHeader(URLFetchRequest.Header.newBuilder().setKey("Test-Header").setValue("Request")).build();
    URLFetchResponse responseProto = URLFetchResponse.newBuilder().setStatusCode(200).setContent(ByteString.copyFromUtf8(responseContent)).build();
    when(delegate.makeSyncCall(same(ApiProxy.getCurrentEnvironment()), eq(URLFetchServiceImpl.PACKAGE), eq("Fetch"), eq(requestProto.toByteArray()))).thenReturn(responseProto.toByteArray());
    HTTPResponse response = new URLFetchServiceImpl().fetch(request);
    assertThat(response.getResponseCode()).isEqualTo(200);
    assertThat(new String(response.getContent(), UTF_8)).isEqualTo(responseContent);
}
Also used : URLFetchResponse(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse) ByteString(com.google.protobuf.ByteString) URLFetchRequest(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest) URL(java.net.URL) Test(org.junit.Test)

Example 15 with URLFetchResponse

use of com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse in project appengine-java-standard by GoogleCloudPlatform.

the class URLFetchServiceImplTest method testSync_URLOnly.

@Test
public void testSync_URLOnly() throws Exception {
    URL url = new URL("http://google.com/foo");
    String responseContent = "<p>This is the desired response.</p>";
    URLFetchRequest requestProto = URLFetchRequest.newBuilder().setUrl(url.toString()).setMethod(RequestMethod.GET).setFollowRedirects(true).build();
    URLFetchResponse responseProto = URLFetchResponse.newBuilder().setStatusCode(200).setContent(ByteString.copyFromUtf8(responseContent)).build();
    when(delegate.makeSyncCall(same(ApiProxy.getCurrentEnvironment()), eq(URLFetchServiceImpl.PACKAGE), eq("Fetch"), eq(requestProto.toByteArray()))).thenReturn(responseProto.toByteArray());
    HTTPResponse response = new URLFetchServiceImpl().fetch(url);
    assertThat(response.getResponseCode()).isEqualTo(200);
    assertThat(new String(response.getContent(), UTF_8)).isEqualTo(responseContent);
}
Also used : URLFetchResponse(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse) ByteString(com.google.protobuf.ByteString) URLFetchRequest(com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest) URL(java.net.URL) Test(org.junit.Test)

Aggregations

URLFetchResponse (com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse)21 URLFetchRequest (com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest)19 URL (java.net.URL)18 Test (org.junit.Test)16 ByteString (com.google.protobuf.ByteString)11 SocketTimeoutException (java.net.SocketTimeoutException)3 ApiProxy (com.google.apphosting.api.ApiProxy)2 IOException (java.io.IOException)2 FutureWrapper (com.google.appengine.api.utils.FutureWrapper)1 LatencyPercentiles (com.google.appengine.tools.development.LatencyPercentiles)1 LocalRpcService (com.google.appengine.tools.development.LocalRpcService)1 ApplicationException (com.google.apphosting.api.ApiProxy.ApplicationException)1 SSLException (javax.net.ssl.SSLException)1 HttpEntity (org.apache.http.HttpEntity)1 HttpResponse (org.apache.http.HttpResponse)1 HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)1 BasicHttpParams (org.apache.http.params.BasicHttpParams)1 HttpParams (org.apache.http.params.HttpParams)1