Search in sources :

Example 1 with HttpParameterImpl

use of com.bluenimble.platform.http.impls.HttpParameterImpl 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 HttpParameterImpl

use of com.bluenimble.platform.http.impls.HttpParameterImpl in project serverless by bluenimble.

the class SimpleGetRequest method main.

public static void main(String[] args) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    GetRequest request = new GetRequest(HttpUtils.createEndpoint(new URI("https://api.indix.com/v2/summary/products?countryCode=US&app_id=2a4049dd&app_key=444978937e94a8adebdcd701660da344")));
    request.getParameters().add(new HttpParameterImpl("q", "hello kitty"));
    HttpResponse response = client.send(request);
    response.getBody().dump(System.out, "utf-8", null);
}
Also used : HttpParameterImpl(com.bluenimble.platform.http.impls.HttpParameterImpl) GetRequest(com.bluenimble.platform.http.request.impls.GetRequest) HttpResponse(com.bluenimble.platform.http.response.HttpResponse) URI(java.net.URI) DefaultHttpClient(com.bluenimble.platform.http.impls.DefaultHttpClient)

Example 3 with HttpParameterImpl

use of com.bluenimble.platform.http.impls.HttpParameterImpl in project serverless by bluenimble.

the class RemoteUtils method request.

@SuppressWarnings("unchecked")
private static HttpRequest request(JsonObject oKeys, JsonObject spec, Tool tool, JsonObject config, Map<String, String> options, List<Object> streams) throws Exception {
    Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
    String service = (String) eval(Json.getString(spec, Spec.request.Service), vars, config, options, oKeys);
    HttpRequest request = HttpRequests.get(Json.getString(spec, Spec.request.Method, HttpMethods.GET).toUpperCase()).getConstructor(new Class[] { HttpEndpoint.class }).newInstance(HttpUtils.createEndpoint(new URI(service)));
    String contentType = Json.getString(spec, Spec.request.ContentType);
    // set headers
    List<HttpHeader> headers = request.getHeaders();
    if (headers == null) {
        headers = new ArrayList<HttpHeader>();
        request.setHeaders(headers);
    }
    JsonObject oHeaders = Json.getObject(spec, Spec.request.Headers);
    // add default Accept header application/json
    if (oHeaders == null || !oHeaders.containsKey(ApiHeaders.Accept)) {
        String accept = (String) vars.get(DefaultVars.RemoteHeadersAccept);
        if (Lang.isNullOrEmpty(accept)) {
            accept = ApiContentTypes.Json;
        }
        headers.add(new HttpHeaderImpl(ApiHeaders.Accept, accept));
    }
    if (oHeaders != null && !oHeaders.isEmpty()) {
        Iterator<String> hNames = oHeaders.keys();
        while (hNames.hasNext()) {
            String hName = hNames.next();
            headers.add(new HttpHeaderImpl(hName, String.valueOf(eval(Json.getString(oHeaders, hName), vars, config, options, oKeys))));
        }
    }
    // set parameters
    JsonObject oParameters = Json.getObject(spec, Spec.request.Parameters);
    if (oParameters != null && !oParameters.isEmpty()) {
        List<HttpParameter> parameters = request.getParameters();
        if (parameters == null) {
            parameters = new ArrayList<HttpParameter>();
            request.setParameters(parameters);
        }
        Iterator<String> pNames = oParameters.keys();
        while (pNames.hasNext()) {
            String pName = pNames.next();
            parameters.add(new HttpParameterImpl(pName, String.valueOf(eval(Json.getString(oParameters, pName), vars, config, options, oKeys))));
        }
    }
    // set body
    JsonObject oBody = Json.getObject(spec, Spec.request.Body);
    if (oBody != null && !oBody.isEmpty()) {
        HttpMessageBody body = new HttpMessageBodyImpl();
        request.setBody(body);
        Iterator<String> bNames = oBody.keys();
        while (bNames.hasNext()) {
            String bName = bNames.next();
            Object value = eval(Json.getString(oBody, bName), vars, config, options, oKeys);
            if (value == null) {
                continue;
            }
            if (ContentTypes.Json.equals(contentType)) {
                Object ov = null;
                String varName = String.valueOf(value);
                if (EmptyPayload.equals(varName)) {
                    ov = JsonObject.Blank;
                } else {
                    ov = ((Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS)).get(varName);
                    if (ov == null) {
                        throw new Exception("variable " + value + " not found");
                    }
                    if (!(ov instanceof JsonObject)) {
                        throw new Exception(value + " isn't a valid json object");
                    }
                }
                body.add(new StringHttpMessageBodyPart(ov.toString()));
                continue;
            }
            String fileName = null;
            InputStream stream = null;
            if (value instanceof File) {
                File file = (File) value;
                fileName = file.getName();
                stream = new FileInputStream(file);
                streams.add(stream);
            } else if (value instanceof StreamPointer) {
                StreamPointer sp = (StreamPointer) value;
                fileName = sp.getPointer().getName();
                stream = sp.getStream();
                streams.add(sp);
            } else if (value instanceof String) {
                tool.printer().info("Api File/Folder ==> " + value);
                File file = new File((String) value);
                if (!file.exists()) {
                    continue;
                // throw new Exception ("file or folder '" + value + "' doesn't exist");
                }
                fileName = file.getName();
                if (file.isFile()) {
                    stream = new FileInputStream(file);
                    streams.add(stream);
                } else if (file.isDirectory()) {
                    fileName += ".api";
                    File zipFile = new File(BlueNimble.Work, Lang.UUID(20) + ".api");
                    ArchiveUtils.compress(file, zipFile, true, new ArchiveUtils.CompressVisitor() {

                        @Override
                        public boolean onAdd(File file) {
                            if (file.getName().startsWith(Lang.DOT)) {
                                return false;
                            }
                            return true;
                        }
                    });
                    StreamPointer sp = new StreamPointer(zipFile, true);
                    streams.add(sp);
                    stream = sp.getStream();
                }
            }
            body.add(new InputStreamHttpMessageBodyPart(bName, fileName, stream));
        }
    }
    if (request.getBody() != null && request.getBody().count() == 0) {
        request.setBody(null);
    }
    // set content type
    if (!Lang.isNullOrEmpty(contentType)) {
        if (ApiContentTypes.Multipart.equals(contentType)) {
            if (request.getBody() != null) {
                request.setContentType(contentType);
            }
        } else {
            request.setContentType(contentType);
        }
    }
    // sign request
    boolean sign = Json.getBoolean(spec, Spec.request.Sign, true);
    if (sign) {
        String space = Json.getString(oKeys, Keys.Spec.Space);
        String accessKey = Json.getString(oKeys, KeyPair.Fields.AccessKey);
        String secretKey = Json.getString(oKeys, KeyPair.Fields.SecretKey);
        AccessSecretKeysBasedHttpRequestSigner signer = new AccessSecretKeysBasedHttpRequestSigner("m>h>p>d>k>t", "Bearer", space == null ? accessKey : space + Lang.DOT + accessKey, secretKey);
        String timestamp = Lang.utc();
        headers.add(new HttpHeaderImpl(ApiHeaders.Timestamp, timestamp));
        signer.getData().put('t', timestamp);
        signer.sign(request);
    }
    if (Lang.isDebugMode()) {
        tool.printer().content("Http Request", request.toString());
    }
    return request;
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) StreamPointer(com.bluenimble.platform.cli.command.parser.converters.StreamPointer) URI(java.net.URI) HttpHeader(com.bluenimble.platform.http.HttpHeader) InputStreamHttpMessageBodyPart(com.bluenimble.platform.http.impls.InputStreamHttpMessageBodyPart) AccessSecretKeysBasedHttpRequestSigner(com.bluenimble.platform.http.auth.impls.AccessSecretKeysBasedHttpRequestSigner) HttpRequest(com.bluenimble.platform.http.request.HttpRequest) HttpMessageBody(com.bluenimble.platform.http.HttpMessageBody) StringHttpMessageBodyPart(com.bluenimble.platform.http.impls.StringHttpMessageBodyPart) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpEndpoint(com.bluenimble.platform.http.HttpEndpoint) HttpHeaderImpl(com.bluenimble.platform.http.impls.HttpHeaderImpl) HttpParameter(com.bluenimble.platform.http.HttpParameter) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) HttpParameterImpl(com.bluenimble.platform.http.impls.HttpParameterImpl) YamlObject(com.bluenimble.platform.cli.impls.YamlObject) JsonObject(com.bluenimble.platform.json.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) HttpMessageBodyImpl(com.bluenimble.platform.http.impls.HttpMessageBodyImpl)

Example 4 with HttpParameterImpl

use of com.bluenimble.platform.http.impls.HttpParameterImpl in project serverless by bluenimble.

the class AccessSecretKeysBasedHttpRequestSigner method sign.

@Override
public void sign(HttpRequest request) throws HttpRequestSignerException {
    List<HttpParameter> params = request.getParameters();
    String signature = null;
    try {
        URI uri = request.getURI();
        signature = generate(params, uri.getScheme() + "://" + uri.getHost(), uri.getPort(), uri.getPath(), request.getName());
    } catch (Throwable th) {
        throw new HttpRequestSignerException(th);
    }
    if (SignaturePlaceHolder.Headers.equals(signatureParameterPlace)) {
        List<HttpHeader> headers = request.getHeaders();
        if (headers == null) {
            headers = new ArrayList<HttpHeader>();
            request.setHeaders(headers);
        }
        headers.add(new HttpHeaderImpl(HttpHeaders.AUTHORIZATION, scheme + " " + accessKey + ":" + signature));
    } else {
        if (signatureParameterName == null) {
            signatureParameterName = "signature";
        }
        params.add(new HttpParameterImpl(signatureParameterName, encode(signature)));
    }
}
Also used : HttpParameterImpl(com.bluenimble.platform.http.impls.HttpParameterImpl) HttpHeader(com.bluenimble.platform.http.HttpHeader) HttpRequestSignerException(com.bluenimble.platform.http.auth.HttpRequestSignerException) HttpParameter(com.bluenimble.platform.http.HttpParameter) URI(java.net.URI) HttpHeaderImpl(com.bluenimble.platform.http.impls.HttpHeaderImpl)

Example 5 with HttpParameterImpl

use of com.bluenimble.platform.http.impls.HttpParameterImpl in project serverless by bluenimble.

the class HttpUtils method parseParameters.

public static void parseParameters(String query, List<HttpParameter> parameters) {
    if (Lang.isNullOrEmpty(query)) {
        return;
    }
    String[] aParams = Lang.split(query, Lang.AMP);
    for (String pv : aParams) {
        int indexOfEquals = pv.indexOf(Lang.EQUALS);
        String name = null;
        String value = null;
        if (indexOfEquals > 0) {
            name = pv.substring(0, indexOfEquals);
            value = pv.substring(indexOfEquals + 1);
        } else {
            name = pv;
        }
        parameters.add(new HttpParameterImpl(name, value));
    }
}
Also used : HttpParameterImpl(com.bluenimble.platform.http.impls.HttpParameterImpl) HttpEndpoint(com.bluenimble.platform.http.HttpEndpoint)

Aggregations

HttpParameterImpl (com.bluenimble.platform.http.impls.HttpParameterImpl)5 URI (java.net.URI)4 HttpEndpoint (com.bluenimble.platform.http.HttpEndpoint)3 HttpHeader (com.bluenimble.platform.http.HttpHeader)3 HttpParameter (com.bluenimble.platform.http.HttpParameter)3 HttpHeaderImpl (com.bluenimble.platform.http.impls.HttpHeaderImpl)3 HttpMessageBody (com.bluenimble.platform.http.HttpMessageBody)2 HttpMessageBodyImpl (com.bluenimble.platform.http.impls.HttpMessageBodyImpl)2 StringHttpMessageBodyPart (com.bluenimble.platform.http.impls.StringHttpMessageBodyPart)2 JsonObject (com.bluenimble.platform.json.JsonObject)2 CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)1 StreamPointer (com.bluenimble.platform.cli.command.parser.converters.StreamPointer)1 YamlObject (com.bluenimble.platform.cli.impls.YamlObject)1 HttpClientException (com.bluenimble.platform.http.HttpClientException)1 HttpRequestSignerException (com.bluenimble.platform.http.auth.HttpRequestSignerException)1 AccessSecretKeysBasedHttpRequestSigner (com.bluenimble.platform.http.auth.impls.AccessSecretKeysBasedHttpRequestSigner)1 DefaultHttpClient (com.bluenimble.platform.http.impls.DefaultHttpClient)1 InputStreamHttpMessageBodyPart (com.bluenimble.platform.http.impls.InputStreamHttpMessageBodyPart)1 HttpRequest (com.bluenimble.platform.http.request.HttpRequest)1 AbstractHttpRequest (com.bluenimble.platform.http.request.impls.AbstractHttpRequest)1