Search in sources :

Example 1 with HttpClientException

use of com.bluenimble.platform.http.HttpClientException in project serverless by bluenimble.

the class Http method request.

private static HttpRequest request(String verb, JsonObject spec, HttpRequestVisitor visitor) throws HttpClientException {
    verb = verb.toUpperCase();
    Class<? extends AbstractHttpRequest> requestClass = Requests.get(verb);
    if (requestClass == null) {
        throw new HttpClientException("unsupported http method " + verb);
    }
    String url = Json.getString(spec, Spec.Url);
    AbstractHttpRequest request;
    try {
        request = requestClass.getConstructor(new Class[] { HttpEndpoint.class }).newInstance(HttpUtils.createEndpoint(new URI(url)));
    } catch (Exception ex) {
        throw new HttpClientException(ex.getMessage(), ex);
    }
    request.setVisitor(visitor);
    // add timeouts
    JsonObject oTimeouts = Json.getObject(spec, Spec.timeouts.class.getSimpleName());
    if (oTimeouts != null && !oTimeouts.isEmpty()) {
        int connectTimeout = Json.getInteger(oTimeouts, Spec.timeouts.Connect, 0);
        if (connectTimeout > 100) {
            request.setConnectTimeout(connectTimeout);
        }
        int readTimeout = Json.getInteger(oTimeouts, Spec.timeouts.Read, 0);
        if (readTimeout > 100) {
            request.setReadTimeout(readTimeout);
        }
    }
    // add proxy
    JsonObject oProxy = Json.getObject(spec, Spec.proxy.class.getSimpleName());
    if (oProxy != null && !oProxy.isEmpty()) {
        Proxy.Type proxyType = Proxy.Type.valueOf(Json.getString(oProxy, Spec.proxy.Type, Proxy.Type.HTTP.name()).toUpperCase());
        int proxyPort = Json.getInteger(oProxy, Spec.proxy.Port, 8080);
        Proxy proxy = new Proxy(proxyType, new InetSocketAddress(Json.getString(oProxy, Spec.proxy.Endpoint), proxyPort));
        request.setProxy(proxy);
    }
    String contentType = null;
    // add headers
    JsonObject headers = Json.getObject(spec, Spec.Headers);
    if (headers != null && !headers.isEmpty()) {
        List<HttpHeader> hHeaders = new ArrayList<HttpHeader>();
        request.setHeaders(hHeaders);
        Iterator<String> keys = headers.keys();
        while (keys.hasNext()) {
            String h = keys.next();
            String hv = String.valueOf(headers.get(h));
            if (HttpHeaders.CONTENT_TYPE.toUpperCase().equals(h.toUpperCase())) {
                contentType = hv;
            } else {
                hHeaders.add(new HttpHeaderImpl(h, hv));
            }
        }
        headers.remove(HttpHeaders.CONTENT_TYPE);
    }
    request.setContentType(contentType);
    // add params
    JsonObject data = Json.getObject(spec, Spec.Data);
    if (data != null && !data.isEmpty()) {
        if (ContentTypes.Json.equals(contentType)) {
            HttpMessageBody body = new HttpMessageBodyImpl();
            request.setBody(body);
            body.add(new StringHttpMessageBodyPart(data.toString()));
        } else {
            List<HttpParameter> hParams = new ArrayList<HttpParameter>();
            request.setParameters(hParams);
            Iterator<String> keys = data.keys();
            while (keys.hasNext()) {
                String p = keys.next();
                hParams.add(new HttpParameterImpl(p, data.get(p)));
            }
        }
    }
    return request;
}
Also used : HttpMessageBody(com.bluenimble.platform.http.HttpMessageBody) InetSocketAddress(java.net.InetSocketAddress) StringHttpMessageBodyPart(com.bluenimble.platform.http.impls.StringHttpMessageBodyPart) ArrayList(java.util.ArrayList) JsonObject(com.bluenimble.platform.json.JsonObject) URI(java.net.URI) HttpHeaderImpl(com.bluenimble.platform.http.impls.HttpHeaderImpl) HttpParameter(com.bluenimble.platform.http.HttpParameter) HttpClientException(com.bluenimble.platform.http.HttpClientException) HttpEndpoint(com.bluenimble.platform.http.HttpEndpoint) HttpParameterImpl(com.bluenimble.platform.http.impls.HttpParameterImpl) Proxy(java.net.Proxy) HttpClientException(com.bluenimble.platform.http.HttpClientException) HttpHeader(com.bluenimble.platform.http.HttpHeader) AbstractHttpRequest(com.bluenimble.platform.http.request.impls.AbstractHttpRequest) HttpMessageBodyImpl(com.bluenimble.platform.http.impls.HttpMessageBodyImpl)

Example 2 with HttpClientException

use of com.bluenimble.platform.http.HttpClientException in project serverless by bluenimble.

the class DefaultHttpClient method send.

public HttpResponse send(final HttpRequest request) throws HttpClientException {
    HttpURLConnection hc = null;
    try {
        if (request == null || request.getURI() == null) {
            throw new HttpClientException("No request to proceed");
        }
        URL url = request.getURI().toURL();
        URLConnection connection = null;
        if (request.getProxy() != null) {
            connection = url.openConnection(request.getProxy());
        } else {
            connection = url.openConnection();
        }
        hc = (HttpURLConnection) connection;
        if (hc instanceof HttpsURLConnection) {
            HttpsURLConnection https = (HttpsURLConnection) hc;
            if (trustAll) {
                https.setSSLSocketFactory(TrustAllSocketFactory);
                https.setHostnameVerifier(TrustAllHostVerifier);
            }
        }
        hc.setConnectTimeout(request.getConnectTimeout());
        hc.setReadTimeout(request.getReadTimeout());
        hc.setRequestMethod(request.getName());
        if (request.getName().equals(HttpMethods.POST) || request.getName().equals(HttpMethods.PUT)) {
            connection.setDoOutput(true);
        }
        if (!(connection instanceof HttpURLConnection)) {
            throw new HttpClientException("Only Http request can be handled");
        }
        setRequestCookie(request);
        request.write(hc);
        InputStream iobody = null;
        int status = hc.getResponseCode();
        HttpResponseImpl response = new HttpResponseImpl(request.getId());
        response.setStatus(status);
        addResponseHeaders(response, hc);
        String charset = request.getCharset();
        HttpHeader cth = response.getHeader(HttpHeaders.CONTENT_TYPE);
        if (cth != null) {
            String[] values = cth.getValues();
            if (values != null && values.length > 0) {
                String contentType = values[0];
                response.setContentType(contentType);
                for (String param : contentType.replace(" ", "").split(";")) {
                    if (param.startsWith("charset=")) {
                        charset = param.split("=", 2)[1];
                        break;
                    }
                }
            }
        }
        response.setCharset(charset);
        if (request.getSuccessCodes().contains(String.valueOf(status))) {
            iobody = hc.getInputStream();
        } else {
            iobody = hc.getErrorStream();
        }
        if (GZip.equals(hc.getContentEncoding())) {
            iobody = new GZIPInputStream(iobody);
        }
        response.setBody(new HttpMessageBodyImpl(new InputStreamHttpMessageBodyPart(iobody)));
        updateCookies(response);
        return response;
    } catch (Throwable th) {
        throw new HttpClientException(th);
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) GZIPInputStream(java.util.zip.GZIPInputStream) HttpURLConnection(java.net.HttpURLConnection) HttpClientException(com.bluenimble.platform.http.HttpClientException) HttpHeader(com.bluenimble.platform.http.HttpHeader) HttpResponseImpl(com.bluenimble.platform.http.response.impls.HttpResponseImpl) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 3 with HttpClientException

use of com.bluenimble.platform.http.HttpClientException in project serverless by bluenimble.

the class OAuthServiceSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    JsonObject config = request.getService().getCustom();
    JsonObject providers = Json.getObject(config, Providers);
    JsonObject provider = Json.getObject(providers, (String) request.get(Spec.Provider));
    if (provider == null || provider.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + " not supported").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject oAuthKeys = Json.getObject(provider, OAuth.Keys);
    if (oAuthKeys == null || oAuthKeys.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". client_id and client_secret not found").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject oAuthEndpoints = Json.getObject(provider, OAuth.Endpoints);
    if (oAuthEndpoints == null || oAuthEndpoints.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". oAuth endpoints authorize and profile not configured").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Authorize);
    if (endpoint == null || endpoint.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". oAuth authorize endpoint not configured").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject data = (JsonObject) new JsonObject().set(OAuth.Code, request.get(Spec.AuthCode)).set(OAuth.ClientId, Json.getString(oAuthKeys, OAuth.ClientId)).set(OAuth.ClientSecret, Json.getString(oAuthKeys, OAuth.ClientSecret));
    if (provider.containsKey(OAuth.Redirect)) {
        data.set(OAuth.RedirectUri, Json.getString(provider, OAuth.Redirect));
    }
    JsonObject params = Json.getObject(endpoint, OAuth.Endpoint.Parameters);
    if (params != null && !params.isEmpty()) {
        Iterator<String> keys = params.keys();
        while (keys.hasNext()) {
            String p = keys.next();
            data.set(p, params.get(p));
        }
    }
    JsonObject hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
    HttpResponse hResponse = null;
    try {
        hResponse = Http.post(hRequest, null);
    } catch (HttpClientException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    if (hResponse.getStatus() != 200) {
        throw new ApiServiceExecutionException("invalid authorization code");
    }
    InputStream out = hResponse.getBody().get(0).toInputStream();
    JsonObject oAuthResult = null;
    try {
        oAuthResult = new JsonObject(out);
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    // get profile
    endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Profile);
    if (endpoint == null || endpoint.isEmpty()) {
        return new JsonApiOutput(oAuthResult);
    }
    String accessToken = Json.getString(oAuthResult, OAuth.AccessToken);
    data.clear();
    data.set(OAuth.AccessToken, accessToken);
    hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
    try {
        hResponse = Http.post(hRequest, null);
    } catch (HttpClientException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    if (hResponse.getStatus() != 200) {
        throw new ApiServiceExecutionException("invalid access token");
    }
    out = hResponse.getBody().get(0).toInputStream();
    try {
        oAuthResult = new JsonObject(out);
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    // email endpoint
    endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Email);
    if (endpoint == null || endpoint.isEmpty()) {
        return new JsonApiOutput(oAuthResult);
    }
    hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
    try {
        hResponse = Http.post(hRequest, null);
    } catch (HttpClientException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    if (hResponse.getStatus() != 200) {
        throw new ApiServiceExecutionException("invalid access token");
    }
    out = hResponse.getBody().get(0).toInputStream();
    JsonObject oEmail = null;
    try {
        oEmail = new JsonObject(out);
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    Iterator<String> keys = oEmail.keys();
    while (keys.hasNext()) {
        String k = keys.next();
        oAuthResult.set(k, oEmail.get(k));
    }
    // call extend if any
    JsonObject onFinish = Json.getObject(config, Config.onFinish.class.getSimpleName());
    ApiOutput onFinishOutput = SecurityUtils.onFinish(api, consumer, request, onFinish, oAuthResult);
    if (onFinishOutput != null) {
        oAuthResult.set(Json.getString(onFinish, Config.onFinish.ResultProperty, Config.onFinish.class.getSimpleName()), onFinishOutput.data());
    }
    return new JsonApiOutput(oAuthResult);
}
Also used : HttpClientException(com.bluenimble.platform.http.HttpClientException) ApiOutput(com.bluenimble.platform.api.ApiOutput) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) InputStream(java.io.InputStream) Config(com.bluenimble.platform.api.impls.im.LoginServiceSpi.Config) JsonObject(com.bluenimble.platform.json.JsonObject) HttpResponse(com.bluenimble.platform.http.response.HttpResponse) HttpClientException(com.bluenimble.platform.http.HttpClientException) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Aggregations

HttpClientException (com.bluenimble.platform.http.HttpClientException)3 HttpHeader (com.bluenimble.platform.http.HttpHeader)2 JsonObject (com.bluenimble.platform.json.JsonObject)2 InputStream (java.io.InputStream)2 ApiOutput (com.bluenimble.platform.api.ApiOutput)1 ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)1 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)1 Config (com.bluenimble.platform.api.impls.im.LoginServiceSpi.Config)1 HttpEndpoint (com.bluenimble.platform.http.HttpEndpoint)1 HttpMessageBody (com.bluenimble.platform.http.HttpMessageBody)1 HttpParameter (com.bluenimble.platform.http.HttpParameter)1 HttpHeaderImpl (com.bluenimble.platform.http.impls.HttpHeaderImpl)1 HttpMessageBodyImpl (com.bluenimble.platform.http.impls.HttpMessageBodyImpl)1 HttpParameterImpl (com.bluenimble.platform.http.impls.HttpParameterImpl)1 StringHttpMessageBodyPart (com.bluenimble.platform.http.impls.StringHttpMessageBodyPart)1 AbstractHttpRequest (com.bluenimble.platform.http.request.impls.AbstractHttpRequest)1 HttpResponse (com.bluenimble.platform.http.response.HttpResponse)1 HttpResponseImpl (com.bluenimble.platform.http.response.impls.HttpResponseImpl)1 HttpURLConnection (java.net.HttpURLConnection)1 InetSocketAddress (java.net.InetSocketAddress)1