Search in sources :

Example 46 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project halyard by spinnaker.

the class GoogleBaseImageValidator method validate.

@Override
public void validate(ConfigProblemSetBuilder p, GoogleBaseImage n) {
    String sourceImage = n.getVirtualizationSettings().getSourceImage();
    String sourceImageFamily = n.getVirtualizationSettings().getSourceImageFamily();
    if (StringUtils.isEmpty(sourceImage) && StringUtils.isEmpty(sourceImageFamily)) {
        p.addProblem(Problem.Severity.ERROR, "Either source image or source image family must be specified for " + n.getBaseImage().getId() + ".");
    }
    if (!StringUtils.isEmpty(sourceImage)) {
        int i = 0;
        boolean[] foundSourceImageHolder = new boolean[1];
        while (!foundSourceImageHolder[0] && i < credentialsList.size()) {
            GoogleNamedAccountCredentials credentials = credentialsList.get(i);
            List<String> imageProjects = Lists.newArrayList(credentials.getProject());
            imageProjects.addAll(credentials.getImageProjects());
            imageProjects.addAll(baseImageProjects);
            Compute compute = credentials.getCompute();
            BatchRequest imageListBatch = buildBatchRequest(compute);
            JsonBatchCallback<ImageList> imageListCallback = new JsonBatchCallback<ImageList>() {

                @Override
                public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
                    p.addProblem(Problem.Severity.ERROR, "Error locating " + sourceImage + " in these projects: " + imageProjects + ": " + e.getMessage() + ".");
                }

                @Override
                public void onSuccess(ImageList imageList, HttpHeaders responseHeaders) throws IOException {
                    // No need to look through these images if the requested image was already found.
                    if (!foundSourceImageHolder[0]) {
                        if (imageList.getItems() != null) {
                            foundSourceImageHolder[0] = imageList.getItems().stream().filter(image -> image.getName().equals(sourceImage)).findFirst().isPresent();
                        }
                    }
                }
            };
            try {
                for (String imageProject : imageProjects) {
                    compute.images().list(imageProject).queue(imageListBatch, imageListCallback);
                }
                imageListBatch.execute();
            } catch (IOException e) {
                p.addProblem(Problem.Severity.ERROR, "Error locating " + sourceImage + " in these projects: " + imageProjects + ": " + e.getMessage() + ".");
            }
            i++;
        }
        if (!foundSourceImageHolder[0]) {
            p.addProblem(Problem.Severity.ERROR, "Image " + sourceImage + " not found via any configured google account.");
        }
    }
    if (!StringUtils.isEmpty(sourceImageFamily)) {
        int i = 0;
        boolean[] foundSourceImageFamilyHolder = new boolean[1];
        while (!foundSourceImageFamilyHolder[0] && i < credentialsList.size()) {
            GoogleNamedAccountCredentials credentials = credentialsList.get(i);
            List<String> imageProjects = Lists.newArrayList(credentials.getProject());
            imageProjects.addAll(credentials.getImageProjects());
            imageProjects.addAll(baseImageProjects);
            Compute compute = credentials.getCompute();
            BatchRequest imageListBatch = buildBatchRequest(compute);
            JsonBatchCallback<ImageList> imageListCallback = new JsonBatchCallback<ImageList>() {

                @Override
                public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
                    p.addProblem(Problem.Severity.ERROR, "Error locating " + sourceImageFamily + " in these projects: " + imageProjects + ": " + e.getMessage() + ".");
                }

                @Override
                public void onSuccess(ImageList imageList, HttpHeaders responseHeaders) throws IOException {
                    // No need to look through these images if the requested image family was already found.
                    if (!foundSourceImageFamilyHolder[0]) {
                        if (imageList.getItems() != null) {
                            foundSourceImageFamilyHolder[0] = imageList.getItems().stream().filter(image -> sourceImageFamily.equals(image.getFamily())).findFirst().isPresent();
                        }
                    }
                }
            };
            try {
                for (String imageProject : imageProjects) {
                    compute.images().list(imageProject).queue(imageListBatch, imageListCallback);
                }
                imageListBatch.execute();
            } catch (IOException e) {
                p.addProblem(Problem.Severity.ERROR, "Error locating " + sourceImageFamily + " in these projects: " + imageProjects + ": " + e.getMessage() + ".");
            }
            i++;
        }
        if (!foundSourceImageFamilyHolder[0]) {
            p.addProblem(Problem.Severity.ERROR, "Image family " + sourceImageFamily + " not found via any configured google account.");
        }
    }
    if (StringUtils.isEmpty(n.getBaseImage().getPackageType())) {
        p.addProblem(Problem.Severity.ERROR, "Package type must be specified for " + n.getBaseImage().getId() + ".");
    }
}
Also used : GoogleNamedAccountCredentials(com.netflix.spinnaker.clouddriver.google.security.GoogleNamedAccountCredentials) HttpHeaders(com.google.api.client.http.HttpHeaders) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError) GoogleBaseImage(com.netflix.spinnaker.halyard.config.model.v1.providers.google.GoogleBaseImage) IOException(java.io.IOException) HttpRequest(com.google.api.client.http.HttpRequest) ImageList(com.google.api.services.compute.model.ImageList) EqualsAndHashCode(lombok.EqualsAndHashCode) ConfigProblemSetBuilder(com.netflix.spinnaker.halyard.config.problem.v1.ConfigProblemSetBuilder) List(java.util.List) Lists(com.google.common.collect.Lists) Validator(com.netflix.spinnaker.halyard.config.model.v1.node.Validator) Data(lombok.Data) Problem(com.netflix.spinnaker.halyard.core.problem.v1.Problem) JsonBatchCallback(com.google.api.client.googleapis.batch.json.JsonBatchCallback) BatchRequest(com.google.api.client.googleapis.batch.BatchRequest) Compute(com.google.api.services.compute.Compute) StringUtils(org.springframework.util.StringUtils) BatchRequest(com.google.api.client.googleapis.batch.BatchRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) JsonBatchCallback(com.google.api.client.googleapis.batch.json.JsonBatchCallback) IOException(java.io.IOException) GoogleNamedAccountCredentials(com.netflix.spinnaker.clouddriver.google.security.GoogleNamedAccountCredentials) ImageList(com.google.api.services.compute.model.ImageList) Compute(com.google.api.services.compute.Compute) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError)

Example 47 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-auth-library-java by google.

the class HttpCredentialsAdapterTest method initialize_populatesOAuth2Credentials.

@Test
public void initialize_populatesOAuth2Credentials() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken;
    MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
    transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET);
    transportFactory.transport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).setRefreshToken(REFRESH_TOKEN).setHttpTransportFactory(transportFactory).build();
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpRequestFactory requestFactory = transportFactory.transport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://foo"));
    adapter.initialize(request);
    HttpHeaders requestHeaders = request.getHeaders();
    String authorizationHeader = requestHeaders.getAuthorization();
    assertEquals(authorizationHeader, expectedAuthorization);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) MockTokenServerTransportFactory(com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) GenericUrl(com.google.api.client.http.GenericUrl) Test(org.junit.Test)

Example 48 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project feign by OpenFeign.

the class GoogleHttpClient method convertResponse.

private final Response convertResponse(final Request inputRequest, final HttpResponse inputResponse) throws IOException {
    final HttpHeaders headers = inputResponse.getHeaders();
    Integer contentLength = null;
    if (headers.getContentLength() != null && headers.getContentLength() <= Integer.MAX_VALUE) {
        contentLength = inputResponse.getHeaders().getContentLength().intValue();
    }
    return Response.builder().body(inputResponse.getContent(), contentLength).status(inputResponse.getStatusCode()).reason(inputResponse.getStatusMessage()).headers(toMap(inputResponse.getHeaders())).request(inputRequest).build();
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders)

Example 49 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project feign by OpenFeign.

the class GoogleHttpClient method convertRequest.

private final HttpRequest convertRequest(final Request inputRequest, final Request.Options options) throws IOException {
    // Setup the request body
    HttpContent content = null;
    if (inputRequest.length() > 0) {
        final Collection<String> contentTypeValues = inputRequest.headers().get("Content-Type");
        String contentType = null;
        if (contentTypeValues != null && contentTypeValues.size() > 0) {
            contentType = contentTypeValues.iterator().next();
        } else {
            contentType = "application/octet-stream";
        }
        content = new ByteArrayContent(contentType, inputRequest.body());
    }
    // Build the request
    final HttpRequest request = requestFactory.buildRequest(inputRequest.httpMethod().name(), new GenericUrl(inputRequest.url()), content);
    // Setup headers
    final HttpHeaders headers = new HttpHeaders();
    for (final Map.Entry<String, Collection<String>> header : inputRequest.headers().entrySet()) {
        headers.set(header.getKey(), header.getValue());
    }
    // Some servers don't do well with no Accept header
    if (inputRequest.headers().get("Accept") == null) {
        headers.setAccept("*/*");
    }
    request.setHeaders(headers);
    // Setup request options
    request.setReadTimeout(options.readTimeoutMillis()).setConnectTimeout(options.connectTimeoutMillis()).setFollowRedirects(options.isFollowRedirects()).setThrowExceptionOnExecuteError(false);
    return request;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Collection(java.util.Collection) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent) HashMap(java.util.HashMap) Map(java.util.Map) HttpContent(com.google.api.client.http.HttpContent)

Example 50 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project scout.rt by eclipse.

the class HttpServiceTunnel method executeRequest.

/**
 * Execute a {@link ServiceTunnelRequest}, returns the plain {@link HttpResponse} - (executed and) ready to be
 * processed to create a {@link ServiceTunnelResponse}.
 *
 * @param call
 *          the original call
 * @param callData
 *          the data created by the {@link IServiceTunnelContentHandler} used by this tunnel Create url connection and
 *          write post data (if required)
 * @throws IOException
 *           override this method to customize the creation of the {@link HttpResponse} see
 *           {@link #addCustomHeaders(HttpRequest, ServiceTunnelRequest, byte[])}
 */
protected HttpResponse executeRequest(ServiceTunnelRequest call, byte[] callData) throws IOException {
    // fast check of wrong URL's for this tunnel
    if (!"http".equalsIgnoreCase(getServerUrl().getProtocol()) && !"https".equalsIgnoreCase(getServerUrl().getProtocol())) {
        throw new IOException("URL '" + getServerUrl().toString() + "' is not supported by this tunnel ('" + getClass().getName() + "').");
    }
    if (!isActive()) {
        String key = BEANS.get(ServiceTunnelTargetUrlProperty.class).getKey();
        throw new IllegalArgumentException("No target URL configured. Please specify a target URL in the config.properties using property '" + key + "'.");
    }
    HttpRequestFactory requestFactory = getHttpTransportManager().getHttpRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(getGenericUrl(), new ByteArrayContent(null, callData));
    HttpHeaders headers = request.getHeaders();
    headers.setCacheControl("no-cache");
    headers.setContentType("text/xml");
    headers.put("Pragma", "no-cache");
    addCustomHeaders(request, call, callData);
    return request.execute();
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) ServiceTunnelTargetUrlProperty(org.eclipse.scout.rt.shared.SharedConfigProperties.ServiceTunnelTargetUrlProperty) IOException(java.io.IOException) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Aggregations

HttpHeaders (com.google.api.client.http.HttpHeaders)63 HttpRequest (com.google.api.client.http.HttpRequest)32 IOException (java.io.IOException)26 GenericUrl (com.google.api.client.http.GenericUrl)22 HttpResponse (com.google.api.client.http.HttpResponse)21 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)15 Test (org.junit.Test)8 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)7 ByteArrayContent (com.google.api.client.http.ByteArrayContent)6 HttpContent (com.google.api.client.http.HttpContent)6 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)6 HttpResponseException (com.google.api.client.http.HttpResponseException)6 JsonObjectParser (com.google.api.client.json.JsonObjectParser)5 Map (java.util.Map)5 HttpTransport (com.google.api.client.http.HttpTransport)4 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 Objects (com.google.api.services.storage.model.Objects)4 SocketTimeoutException (java.net.SocketTimeoutException)4 URI (java.net.URI)4