All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sap.cloud.sdk.cloudplatform.connectivity.DestinationService Maven / Gradle / Ivy

Go to download

Implementation of the Cloud platform abstraction for general-purpose connectivity on the SAP Cloud Platform (Cloud Foundry).

The newest version!
/*
 * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
 */

package com.sap.cloud.sdk.cloudplatform.connectivity;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sap.cloud.sdk.cloudplatform.CloudPlatform;
import com.sap.cloud.sdk.cloudplatform.CloudPlatformAccessor;
import com.sap.cloud.sdk.cloudplatform.ScpCfCloudPlatform;
import com.sap.cloud.sdk.cloudplatform.connectivity.exception.DestinationAccessException;
import com.sap.cloud.sdk.cloudplatform.exception.CloudPlatformException;
import com.sap.cloud.sdk.cloudplatform.exception.ShouldNotHappenException;
import com.sap.cloud.sdk.cloudplatform.logging.CloudLoggerFactory;

class DestinationService
{
    private static final Logger logger = CloudLoggerFactory.getSanitizedLogger(DestinationService.class);

    static final String SERVICE_NAME = "destination";

    private static final String SERVICE_URI = "uri";
    private static final String SERVICE_PATH = "destination-configuration/v1";

    private static final String BEARER_PREFIX = "Bearer ";

    private ScpCfCloudPlatform getCloudPlatform()
    {
        final CloudPlatform cloudPlatform = CloudPlatformAccessor.getCloudPlatform();

        if( !(cloudPlatform instanceof ScpCfCloudPlatform) ) {
            throw new ShouldNotHappenException(
                "The current Cloud platform is not an instance of "
                    + ScpCfCloudPlatform.class.getSimpleName()
                    + ". Please make sure to specify a dependency to com.sap.cloud.s4hana.cloudplatform:core-scp-cf.");
        }

        return (ScpCfCloudPlatform) cloudPlatform;
    }

    private URI getDestinationServiceUri()
        throws DestinationAccessException
    {
        final JsonObject destinationServiceCredentials;
        try {
            destinationServiceCredentials = getCloudPlatform().getDestinationServiceCredentials();
        }
        catch( final CloudPlatformException e ) {
            throw new DestinationAccessException(e);
        }

        @Nullable
        final JsonElement uri = destinationServiceCredentials.get(SERVICE_URI);

        if( uri == null || !uri.isJsonPrimitive() ) {
            throw new DestinationAccessException(
                "Failed to get '"
                    + SERVICE_URI
                    + "' from "
                    + SERVICE_NAME
                    + " service credentials."
                    + "Please make sure to correctly bind your application to a service instance.");
        }

        try {
            final String uriAsString = uri.getAsString();
            return new URI((uriAsString.endsWith("/") ? uriAsString : uriAsString + "/") + SERVICE_PATH);
        }
        catch( final URISyntaxException e ) {
            throw new DestinationAccessException(e);
        }
    }

    @Nonnull
    String executeRequest( final String servicePath, final AccessToken accessToken )
        throws DestinationAccessException
    {
        final String requestPath = servicePath.startsWith("/") ? servicePath : "/" + servicePath;
        final URI requestUri;
        try {
            requestUri = new URI(getDestinationServiceUri() + requestPath);
        }
        catch( final URISyntaxException e ) {
            throw new DestinationAccessException(e);
        }

        if( logger.isDebugEnabled() ) {
            logger.debug("Executing request: " + requestUri + ".");
        }

        final HttpUriRequest request = new HttpGet(requestUri);
        request.setHeader(HttpHeaders.AUTHORIZATION, BEARER_PREFIX + accessToken.getValue());

        final HttpResponse response;
        try {
            response = HttpClientAccessor.getHttpClient().execute(request);
        }
        catch( final IOException e ) {
            throw new DestinationAccessException(e);
        }

        if( logger.isDebugEnabled() ) {
            final StatusLine statusLine = response.getStatusLine();
            logger.debug(
                "Destination service returned HTTP status "
                    + statusLine.getStatusCode()
                    + " ("
                    + statusLine.getReasonPhrase()
                    + ").");
        }

        final StatusLine status = response.getStatusLine();
        final int statusCode = status.getStatusCode();
        final String reasonPhrase = status.getReasonPhrase();

        if( statusCode != HttpStatus.SC_OK ) {
            throw new DestinationAccessException(
                "Failed to get destinations:"
                    + " destination service returned HTTP status "
                    + statusCode
                    + " ("
                    + reasonPhrase
                    + ") at '"
                    + requestUri
                    + "'.");
        }

        try {
            final String responseBody = HttpEntityUtil.getResponseBody(response);

            if( responseBody == null ) {
                throw new DestinationAccessException("Failed to get destinations: no body returned in response.");
            }

            return responseBody;
        }
        catch( final IOException e ) {
            throw new DestinationAccessException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy