Search in sources :

Example 1 with HttpTransport

use of com.google.api.client.http.HttpTransport in project beam by apache.

the class GcsUtilTest method googleJsonResponseException.

/**
   * Builds a fake GoogleJsonResponseException for testing API error handling.
   */
private static GoogleJsonResponseException googleJsonResponseException(final int status, final String reason, final String message) throws IOException {
    final JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.setReason(reason);
            errorInfo.setMessage(message);
            errorInfo.setFactory(jsonFactory);
            GenericJson error = new GenericJson();
            error.set("code", status);
            error.set("errors", Arrays.asList(errorInfo));
            error.setFactory(jsonFactory);
            GenericJson errorResponse = new GenericJson();
            errorResponse.set("error", error);
            errorResponse.setFactory(jsonFactory);
            return new MockLowLevelHttpRequest().setResponse(new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString()).setContentType(Json.MEDIA_TYPE).setStatusCode(status));
        }
    };
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    return GoogleJsonResponseException.from(jsonFactory, response);
}
Also used : GenericJson(com.google.api.client.json.GenericJson) LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) HttpTransport(com.google.api.client.http.HttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) ErrorInfo(com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo) JsonFactory(com.google.api.client.json.JsonFactory) HttpResponse(com.google.api.client.http.HttpResponse) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 2 with HttpTransport

use of com.google.api.client.http.HttpTransport in project camel by apache.

the class BatchGoogleCalendarClientFactory method authorizeServiceAccount.

private Credential authorizeServiceAccount(String emailAddress, String p12FileName, Collection<String> scopes, String user) throws Exception {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    // set the service account user when provided
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(emailAddress).setServiceAccountPrivateKeyFromP12File(new File(p12FileName)).setServiceAccountScopes(scopes).setServiceAccountUser(user).build();
    return credential;
}
Also used : NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) File(java.io.File)

Example 3 with HttpTransport

use of com.google.api.client.http.HttpTransport in project nifi by apache.

the class AbstractGCSProcessor method getServiceOptions.

@Override
protected StorageOptions getServiceOptions(ProcessContext context, GoogleCredentials credentials) {
    final String projectId = context.getProperty(PROJECT_ID).getValue();
    final Integer retryCount = context.getProperty(RETRY_COUNT).asInteger();
    final String proxyHost = context.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = context.getProperty(PROXY_PORT).asInteger();
    StorageOptions.Builder storageOptionsBuilder = StorageOptions.newBuilder().setCredentials(credentials).setProjectId(projectId).setRetryParams(RetryParams.newBuilder().setRetryMaxAttempts(retryCount).setRetryMinAttempts(retryCount).build());
    if (!StringUtils.isBlank(proxyHost) && proxyPort > 0) {
        storageOptionsBuilder.setHttpTransportFactory(new HttpTransportFactory() {

            @Override
            public HttpTransport create() {
                final HttpTransport transport = new NetHttpTransport.Builder().setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort))).build();
                return transport;
            }
        });
    }
    return storageOptionsBuilder.build();
}
Also used : NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) Proxy(java.net.Proxy) StorageOptions(com.google.cloud.storage.StorageOptions) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) InetSocketAddress(java.net.InetSocketAddress) HttpTransportFactory(com.google.auth.http.HttpTransportFactory)

Example 4 with HttpTransport

use of com.google.api.client.http.HttpTransport in project ddf by codice.

the class MetadataConfigurationParser method buildEntityDescriptor.

private void buildEntityDescriptor(String entityDescription) throws IOException {
    EntityDescriptor entityDescriptor = null;
    entityDescription = entityDescription.trim();
    if (entityDescription.startsWith(HTTPS) || entityDescription.startsWith(HTTP)) {
        if (entityDescription.startsWith(HTTP)) {
            LOGGER.warn("Retrieving metadata via HTTP instead of HTTPS. The metadata configuration is unsafe!!!");
        }
        PropertyResolver propertyResolver = new PropertyResolver(entityDescription);
        HttpTransport httpTransport = new NetHttpTransport();
        HttpRequest httpRequest = httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(propertyResolver.getResolvedString()));
        httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setBackOffRequired(HttpBackOffUnsuccessfulResponseHandler.BackOffRequired.ALWAYS));
        httpRequest.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
        ListenableFuture<HttpResponse> httpResponseFuture = service.submit(httpRequest::execute);
        Futures.addCallback(httpResponseFuture, new FutureCallback<HttpResponse>() {

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse != null) {
                    try {
                        String parsedResponse = httpResponse.parseAsString();
                        buildEntityDescriptor(parsedResponse);
                    } catch (IOException e) {
                        LOGGER.info("Unable to parse metadata from: {}", httpResponse.getRequest().getUrl().toString(), e);
                    }
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                LOGGER.info("Unable to retrieve metadata.", throwable);
            }
        });
        service.shutdown();
    } else if (entityDescription.startsWith(FILE + System.getProperty("ddf.home"))) {
        String pathStr = StringUtils.substringAfter(entityDescription, FILE);
        Path path = Paths.get(pathStr);
        if (Files.isReadable(path)) {
            try (InputStream fileInputStream = Files.newInputStream(path)) {
                entityDescriptor = readEntityDescriptor(new InputStreamReader(fileInputStream, "UTF-8"));
            }
        }
    } else if (entityDescription.startsWith("<") && entityDescription.endsWith(">")) {
        entityDescriptor = readEntityDescriptor(new StringReader(entityDescription));
    } else {
        LOGGER.info("Skipping unknown metadata configuration value: {}", entityDescription);
    }
    if (entityDescriptor != null) {
        entityDescriptorMap.put(entityDescriptor.getEntityID(), entityDescriptor);
        if (updateCallback != null) {
            updateCallback.accept(entityDescriptor);
        }
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Path(java.nio.file.Path) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) PropertyResolver(org.codice.ddf.configuration.PropertyResolver) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) StringReader(java.io.StringReader) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService)

Example 5 with HttpTransport

use of com.google.api.client.http.HttpTransport in project ddf by codice.

the class PaosInInterceptor method getHttpResponse.

HttpResponseWrapper getHttpResponse(String responseConsumerURL, String soapResponse, Message message) throws IOException {
    //This used to use the ApacheHttpTransport which appeared to not work with 2 way TLS auth but this one does
    HttpTransport httpTransport = new NetHttpTransport();
    HttpContent httpContent = new InputStreamContent(TEXT_XML, new ByteArrayInputStream(soapResponse.getBytes("UTF-8")));
    //this handles redirects for us
    ((InputStreamContent) httpContent).setRetrySupported(true);
    HttpRequest httpRequest = httpTransport.createRequestFactory().buildPostRequest(new GenericUrl(responseConsumerURL), httpContent);
    HttpUnsuccessfulResponseHandler httpUnsuccessfulResponseHandler = (request, response, supportsRetry) -> {
        String redirectLocation = response.getHeaders().getLocation();
        if (request.getFollowRedirects() && HttpStatusCodes.isRedirect(response.getStatusCode()) && redirectLocation != null) {
            String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
            HttpContent content = null;
            if (!isRedirectable(method)) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                message.setContent(OutputStream.class, byteArrayOutputStream);
                BodyWriter bodyWriter = new BodyWriter();
                bodyWriter.handleMessage(message);
                content = new InputStreamContent((String) message.get(Message.CONTENT_TYPE), new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            }
            // resolve the redirect location relative to the current location
            request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation)));
            request.setRequestMethod(method);
            request.setContent(content);
            // remove Authorization and If-* headers
            request.getHeaders().setAuthorization((String) null);
            request.getHeaders().setIfMatch(null);
            request.getHeaders().setIfNoneMatch(null);
            request.getHeaders().setIfModifiedSince(null);
            request.getHeaders().setIfUnmodifiedSince(null);
            request.getHeaders().setIfRange(null);
            request.getHeaders().setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0));
            return true;
        }
        return false;
    };
    httpRequest.setUnsuccessfulResponseHandler(httpUnsuccessfulResponseHandler);
    httpRequest.getHeaders().put(SOAP_ACTION, HTTP_WWW_OASIS_OPEN_ORG_COMMITTEES_SECURITY);
    //has 20 second timeout by default
    HttpResponse httpResponse = httpRequest.execute();
    HttpResponseWrapper httpResponseWrapper = new HttpResponseWrapper();
    httpResponseWrapper.statusCode = httpResponse.getStatusCode();
    httpResponseWrapper.content = httpResponse.getContent();
    return httpResponseWrapper;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) RestSecurity(org.codice.ddf.security.common.jaxrs.RestSecurity) StringUtils(org.apache.commons.lang.StringUtils) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) DOMUtils(org.apache.cxf.helpers.DOMUtils) ResponseBuilder(ddf.security.liberty.paos.impl.ResponseBuilder) SOAPException(javax.xml.soap.SOAPException) DOM2Writer(org.apache.wss4j.common.util.DOM2Writer) IDPList(org.opensaml.saml.saml2.core.IDPList) LoggerFactory(org.slf4j.LoggerFactory) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) AbstractPhaseInterceptor(org.apache.cxf.phase.AbstractPhaseInterceptor) HttpRequest(com.google.api.client.http.HttpRequest) SamlProtocol(ddf.security.samlp.SamlProtocol) HttpResponse(com.google.api.client.http.HttpResponse) IDPEntry(org.opensaml.saml.saml2.core.IDPEntry) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) Fault(org.apache.cxf.interceptor.Fault) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) Map(java.util.Map) XMLStreamException(javax.xml.stream.XMLStreamException) Node(org.w3c.dom.Node) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) GenericUrl(com.google.api.client.http.GenericUrl) OpenSAMLUtil(org.apache.wss4j.common.saml.OpenSAMLUtil) XMLObject(org.opensaml.core.xml.XMLObject) HttpContent(com.google.api.client.http.HttpContent) OutputStream(java.io.OutputStream) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Response(ddf.security.liberty.paos.Response) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Message(org.apache.cxf.message.Message) HttpTransport(com.google.api.client.http.HttpTransport) IOException(java.io.IOException) AccessDeniedException(org.apache.cxf.interceptor.security.AccessDeniedException) StandardCharsets(java.nio.charset.StandardCharsets) Request(org.opensaml.saml.saml2.ecp.Request) IOUtils(org.apache.commons.io.IOUtils) Base64(java.util.Base64) List(java.util.List) SOAPPart(javax.xml.soap.SOAPPart) Element(org.w3c.dom.Element) HttpStatusCodes(com.google.api.client.http.HttpStatusCodes) InputStreamContent(com.google.api.client.http.InputStreamContent) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) ByteArrayInputStream(java.io.ByteArrayInputStream) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) InputStreamContent(com.google.api.client.http.InputStreamContent) HttpContent(com.google.api.client.http.HttpContent)

Aggregations

HttpTransport (com.google.api.client.http.HttpTransport)89 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)39 HttpRequest (com.google.api.client.http.HttpRequest)28 JsonFactory (com.google.api.client.json.JsonFactory)28 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)27 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)26 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)23 HttpResponse (com.google.api.client.http.HttpResponse)21 GoogleNetHttpTransport (com.google.api.client.googleapis.javanet.GoogleNetHttpTransport)20 IOException (java.io.IOException)18 GenericUrl (com.google.api.client.http.GenericUrl)14 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)11 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)10 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)10 Storage (com.google.api.services.storage.Storage)8 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)7 Before (org.junit.Before)7 Credential (com.google.api.client.auth.oauth2.Credential)6 ErrorTransport (com.google.api.client.googleapis.json.GoogleJsonErrorTest.ErrorTransport)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6