Search in sources :

Example 1 with RestCallFailedException

use of org.openkilda.exception.RestCallFailedException in project open-kilda by telstra.

the class OAuthService method getResponse.

@Override
public <T> T getResponse(UrlDto request, AuthConfigDto authDto, Class<T> responseClass) {
    T obj = null;
    try {
        HttpResponse response = getHttpResponse(request, authDto);
        obj = restClientManager.getResponse(response, responseClass);
    } catch (RestCallFailedException e) {
        e.printStackTrace();
    }
    return obj;
}
Also used : RestCallFailedException(org.openkilda.exception.RestCallFailedException) HttpResponse(org.apache.http.HttpResponse)

Example 2 with RestCallFailedException

use of org.openkilda.exception.RestCallFailedException in project open-kilda by telstra.

the class RestClientManager method getResponse.

/**
 * Gets the response.
 *
 * @param <T> the generic type
 * @param <E> the element type
 * @param response the response
 * @param responseClass the response class
 * @param dependentClass the dependent class
 * @return the response
 */
private <T, E> T getResponse(final HttpResponse response, final Class<T> responseClass, final Class<E> dependentClass) {
    T obj = null;
    try {
        LOGGER.info("[getResponse]  : StatusCode " + response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() != HttpStatus.NO_CONTENT.value()) {
            String responseEntity = IoUtil.toString(response.getEntity().getContent());
            LOGGER.debug("[getResponse]  : response object " + responseEntity);
            if (!(HttpStatus.valueOf(response.getStatusLine().getStatusCode()).is2xxSuccessful() && response.getEntity() != null)) {
                String errorMessage = null;
                try {
                    if (responseEntity.startsWith("[")) {
                        responseEntity = responseEntity.replaceFirst("]", "").trim();
                    }
                    if (responseEntity.endsWith("]")) {
                        responseEntity = responseEntity.replace("]", "").trim();
                    }
                    errorMessage = mapper.readValue(responseEntity, ErrorMessage.class).getMessage();
                } catch (Exception e) {
                    if (response.getStatusLine().getStatusCode() == HttpStatus.UNAUTHORIZED.value()) {
                        throw new UnauthorizedException(HttpError.UNAUTHORIZED.getMessage());
                    }
                    LOGGER.error("Error occurred while retriving response from third party service provider", e);
                    errorMessage = authPropertyService.getError(IAuthConstants.Code.RESPONSE_PARSING_FAIL_ERROR).getMessage();
                    throw new RestCallFailedException(errorMessage);
                }
                LOGGER.error("Error occurred while retriving response from third party service provider:" + responseEntity);
                throw new ExternalSystemException(response.getStatusLine().getStatusCode(), errorMessage);
            } else {
                if (dependentClass == null) {
                    if (responseClass != null) {
                        obj = mapper.readValue(responseEntity, responseClass);
                    }
                } else {
                    obj = mapper.readValue(responseEntity, TypeFactory.defaultInstance().constructCollectionLikeType(responseClass, dependentClass));
                }
            }
        }
    } catch (IOException e) {
        throw new RestCallFailedException(e.getMessage());
    }
    return obj;
}
Also used : ExternalSystemException(org.openkilda.exception.ExternalSystemException) RestCallFailedException(org.openkilda.exception.RestCallFailedException) UnauthorizedException(org.openkilda.exception.UnauthorizedException) IOException(java.io.IOException) ExternalSystemException(org.openkilda.exception.ExternalSystemException) RestCallFailedException(org.openkilda.exception.RestCallFailedException) InvalidResponseException(org.openkilda.integration.exception.InvalidResponseException) UnauthorizedException(org.openkilda.exception.UnauthorizedException) IOException(java.io.IOException)

Example 3 with RestCallFailedException

use of org.openkilda.exception.RestCallFailedException in project open-kilda by telstra.

the class RestClientManager method invoke.

/**
 * Invoke.
 *
 * @param apiUrl the api url
 * @param httpMethod the http method
 * @param payload the payload
 * @param contentType the content type
 * @param basicAuth the basic auth
 * @return the http response
 */
public HttpResponse invoke(final String apiUrl, final HttpMethod httpMethod, final String payload, final String contentType, final String basicAuth) {
    HttpResponse httpResponse = null;
    try {
        RequestContext requestContext = serverContext.getRequestContext();
        HttpClient client = HttpClients.createDefault();
        HttpUriRequest httpUriRequest = null;
        HttpEntityEnclosingRequestBase httpEntityEnclosingRequest = null;
        // Initializing Request
        if (HttpMethod.POST.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPost(apiUrl);
        } else if (HttpMethod.PUT.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPut(apiUrl);
        } else if (HttpMethod.DELETE.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpEntityEnclosingRequestBase() {

                @Override
                public String getMethod() {
                    return "DELETE";
                }
            };
        } else if (HttpMethod.PATCH.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPatch(apiUrl);
        } else {
            httpUriRequest = new HttpGet(apiUrl);
        }
        if (!HttpMethod.POST.equals(httpMethod) && !HttpMethod.PUT.equals(httpMethod) && !HttpMethod.PATCH.equals(httpMethod) && !HttpMethod.DELETE.equals(httpMethod)) {
            // Setting Required Headers
            if (!StringUtil.isNullOrEmpty(basicAuth)) {
                LOGGER.debug("[invoke] Setting authorization in header as " + IAuthConstants.Header.AUTHORIZATION);
                httpUriRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
                httpUriRequest.setHeader(IAuthConstants.Header.CORRELATION_ID, requestContext.getCorrelationId());
            }
        }
        if (HttpMethod.POST.equals(httpMethod) || HttpMethod.PUT.equals(httpMethod) || HttpMethod.PATCH.equals(httpMethod)) {
            LOGGER.info("[invoke] Executing POST/ PUT request : httpEntityEnclosingRequest : " + httpEntityEnclosingRequest + " : payload : " + payload);
            // Setting POST/PUT related headers
            httpEntityEnclosingRequest.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.CORRELATION_ID, requestContext.getCorrelationId());
            // Setting request payload
            httpEntityEnclosingRequest.setEntity(new StringEntity(payload));
            httpResponse = client.execute(httpEntityEnclosingRequest);
            LOGGER.debug("[invoke] Call executed successfully");
        } else if (HttpMethod.DELETE.equals(httpMethod)) {
            httpEntityEnclosingRequest.setURI(URI.create(apiUrl));
            LOGGER.info("[invoke] Executing DELETE request : httpDeleteRequest : " + httpEntityEnclosingRequest + " : payload : " + payload);
            // Setting DELETE related headers
            httpEntityEnclosingRequest.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.EXTRA_AUTH, String.valueOf(System.currentTimeMillis()));
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
            httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.CORRELATION_ID, requestContext.getCorrelationId());
            // Setting request payload
            httpEntityEnclosingRequest.setEntity(new StringEntity(payload));
            httpResponse = client.execute(httpEntityEnclosingRequest);
            LOGGER.debug("[invoke] Call executed successfully");
        } else {
            LOGGER.info("[invoke] Executing : httpUriRequest : " + httpUriRequest);
            httpResponse = client.execute(httpUriRequest);
            LOGGER.info("[invoke] Call executed successfully");
        }
    } catch (Exception e) {
        LOGGER.error("Error occurred while trying to communicate third party service provider", e);
        throw new RestCallFailedException(e);
    }
    return httpResponse;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpGet(org.apache.http.client.methods.HttpGet) RestCallFailedException(org.openkilda.exception.RestCallFailedException) HttpResponse(org.apache.http.HttpResponse) HttpPut(org.apache.http.client.methods.HttpPut) HttpPatch(org.apache.http.client.methods.HttpPatch) ExternalSystemException(org.openkilda.exception.ExternalSystemException) RestCallFailedException(org.openkilda.exception.RestCallFailedException) InvalidResponseException(org.openkilda.integration.exception.InvalidResponseException) UnauthorizedException(org.openkilda.exception.UnauthorizedException) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) HttpClient(org.apache.http.client.HttpClient) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestContext(org.openkilda.auth.model.RequestContext)

Example 4 with RestCallFailedException

use of org.openkilda.exception.RestCallFailedException in project open-kilda by telstra.

the class RestClientManager method invoke.

/**
 * Invoke.
 *
 * @param apiRequestDto the api request dto
 * @return the http response
 */
public HttpResponse invoke(final ApiRequestDto apiRequestDto) {
    HttpResponse httpResponse = null;
    String url = apiRequestDto.getUrl();
    String headers = apiRequestDto.getHeader();
    HttpMethod httpMethod = apiRequestDto.getHttpMethod();
    String payload = apiRequestDto.getPayload();
    try {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build();
        CloseableHttpClient client = HttpClientBuilder.create().setSSLContext(sslContext).setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build())).build();
        HttpUriRequest httpUriRequest = null;
        HttpEntityEnclosingRequestBase httpEntityEnclosingRequest = null;
        // Initializing Request
        if (HttpMethod.POST.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPost(url);
        } else if (HttpMethod.PUT.equals(httpMethod)) {
            httpEntityEnclosingRequest = new HttpPut(url);
        } else if (HttpMethod.DELETE.equals(httpMethod)) {
            httpUriRequest = new HttpDelete(url);
        } else if (HttpMethod.PATCH.equals(httpMethod)) {
            httpUriRequest = new HttpPatch(url);
        } else {
            httpUriRequest = new HttpGet(url);
        }
        Map<String, String> headersMap = new HashMap<String, String>();
        if (!HttpMethod.POST.equals(httpMethod) && !HttpMethod.PUT.equals(httpMethod)) {
            if (!StringUtil.isNullOrEmpty(headers)) {
                for (String header : headers.split("\n")) {
                    getHeaders(headersMap, header);
                    for (Entry<String, String> headerEntrySet : headersMap.entrySet()) {
                        httpUriRequest.setHeader(headerEntrySet.getKey(), headerEntrySet.getValue());
                    }
                }
            }
        }
        if (HttpMethod.POST.equals(httpMethod) || HttpMethod.PUT.equals(httpMethod)) {
            LOGGER.info("[invoke] Executing POST/ PUT request : httpEntityEnclosingRequest : " + httpEntityEnclosingRequest);
            if (!StringUtil.isNullOrEmpty(headers)) {
                for (String header : headers.split("\n")) {
                    getHeaders(headersMap, header);
                    for (Entry<String, String> headerEntrySet : headersMap.entrySet()) {
                        httpEntityEnclosingRequest.setHeader(headerEntrySet.getKey(), headerEntrySet.getValue());
                    }
                }
            }
            // Setting request payload
            httpEntityEnclosingRequest.setEntity(new StringEntity(payload));
            httpResponse = client.execute(httpEntityEnclosingRequest);
            LOGGER.debug("[invoke] Call executed successfully");
        } else {
            LOGGER.info("[invoke] Executing : httpUriRequest : " + httpUriRequest);
            httpResponse = client.execute(httpUriRequest);
            LOGGER.info("[invoke] Call executed successfully");
        }
    } catch (Exception e) {
        LOGGER.error("Error occurred while trying to communicate third party service provider", e);
        throw new RestCallFailedException(e);
    }
    return httpResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) SSLContext(javax.net.ssl.SSLContext) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpPatch(org.apache.http.client.methods.HttpPatch) AuthPropertyService(org.openkilda.service.AuthPropertyService) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) Map(java.util.Map) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ExternalSystemException(org.openkilda.exception.ExternalSystemException) IAuthConstants(org.openkilda.constants.IAuthConstants) HttpHeaders(org.springframework.http.HttpHeaders) StringEntity(org.apache.http.entity.StringEntity) List(java.util.List) StringUtil(org.openkilda.utility.StringUtil) HttpGet(org.apache.http.client.methods.HttpGet) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) Entry(java.util.Map.Entry) HttpClients(org.apache.http.impl.client.HttpClients) RequestContext(org.openkilda.auth.model.RequestContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) HashMap(java.util.HashMap) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) RestCallFailedException(org.openkilda.exception.RestCallFailedException) ServerContext(org.openkilda.auth.context.ServerContext) InvalidResponseException(org.openkilda.integration.exception.InvalidResponseException) HttpDelete(org.apache.http.client.methods.HttpDelete) ErrorMessage(org.openkilda.model.response.ErrorMessage) HttpClient(org.apache.http.client.HttpClient) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpMethod(org.springframework.http.HttpMethod) UnauthorizedException(org.openkilda.exception.UnauthorizedException) IOException(java.io.IOException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) HttpError(org.openkilda.constants.HttpError) IoUtil(org.openkilda.utility.IoUtil) HttpStatus(org.springframework.http.HttpStatus) Component(org.springframework.stereotype.Component) HttpPut(org.apache.http.client.methods.HttpPut) ApiRequestDto(org.openkilda.store.common.model.ApiRequestDto) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) RestCallFailedException(org.openkilda.exception.RestCallFailedException) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpPut(org.apache.http.client.methods.HttpPut) HttpPatch(org.apache.http.client.methods.HttpPatch) ExternalSystemException(org.openkilda.exception.ExternalSystemException) RestCallFailedException(org.openkilda.exception.RestCallFailedException) InvalidResponseException(org.openkilda.integration.exception.InvalidResponseException) UnauthorizedException(org.openkilda.exception.UnauthorizedException) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) HttpMethod(org.springframework.http.HttpMethod)

Example 5 with RestCallFailedException

use of org.openkilda.exception.RestCallFailedException in project open-kilda by telstra.

the class OAuthService method getResponseList.

@Override
public <T> List<T> getResponseList(UrlDto request, AuthConfigDto authDto, Class<T> responseClass) {
    List<T> obj = null;
    try {
        HttpResponse response = getHttpResponse(request, authDto);
        obj = restClientManager.getResponseList(response, responseClass);
    } catch (RestCallFailedException e) {
        e.printStackTrace();
    }
    return obj;
}
Also used : RestCallFailedException(org.openkilda.exception.RestCallFailedException) HttpResponse(org.apache.http.HttpResponse)

Aggregations

RestCallFailedException (org.openkilda.exception.RestCallFailedException)6 HttpResponse (org.apache.http.HttpResponse)4 IOException (java.io.IOException)3 ExternalSystemException (org.openkilda.exception.ExternalSystemException)3 UnauthorizedException (org.openkilda.exception.UnauthorizedException)3 InvalidResponseException (org.openkilda.integration.exception.InvalidResponseException)3 HttpClient (org.apache.http.client.HttpClient)2 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)2 HttpGet (org.apache.http.client.methods.HttpGet)2 HttpPatch (org.apache.http.client.methods.HttpPatch)2 HttpPost (org.apache.http.client.methods.HttpPost)2 HttpPut (org.apache.http.client.methods.HttpPut)2 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)2 StringEntity (org.apache.http.entity.StringEntity)2 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)2 RequestContext (org.openkilda.auth.model.RequestContext)2 ApiRequestDto (org.openkilda.store.common.model.ApiRequestDto)2 HttpMethod (org.springframework.http.HttpMethod)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 TypeFactory (com.fasterxml.jackson.databind.type.TypeFactory)1