Search in sources :

Example 1 with HttpParameter

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

the class OAuthHttpRequestVisitor method visit.

@Override
public void visit(HttpRequest request, HttpURLConnection connection) throws HttpRequestWriteException {
    HttpEndpoint endpoint = ((AbstractHttpRequest) request).getEndpoint();
    OAuthConsumer consumer = new DefaultOAuthConsumer(key, secret);
    HttpParameters encodedParams = new HttpParameters();
    List<HttpParameter> params = request.getParameters();
    if (params != null && !params.isEmpty()) {
        for (HttpParameter p : params) {
            if (p.getValue() != null) {
                encodedParams.put(p.getName(), OAuth.percentEncode(String.valueOf(p.getValue())));
            }
        }
    }
    encodedParams.put("realm", endpoint.getScheme() + "://" + endpoint.getHost() + endpoint.getPath());
    consumer.setAdditionalParameters(encodedParams);
    try {
        consumer.sign(connection);
    } catch (Exception e) {
        throw new HttpRequestWriteException(e.getMessage(), e);
    }
}
Also used : HttpParameters(oauth.signpost.http.HttpParameters) AbstractHttpRequest(com.bluenimble.platform.http.request.impls.AbstractHttpRequest) DefaultOAuthConsumer(oauth.signpost.basic.DefaultOAuthConsumer) DefaultOAuthConsumer(oauth.signpost.basic.DefaultOAuthConsumer) OAuthConsumer(oauth.signpost.OAuthConsumer) HttpEndpoint(com.bluenimble.platform.http.HttpEndpoint) HttpParameter(com.bluenimble.platform.http.HttpParameter) HttpRequestWriteException(com.bluenimble.platform.http.request.HttpRequestWriteException) HttpRequestWriteException(com.bluenimble.platform.http.request.HttpRequestWriteException)

Example 2 with HttpParameter

use of com.bluenimble.platform.http.HttpParameter 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 3 with HttpParameter

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

the class BodyAwareRequest method write.

@Override
public void write(HttpURLConnection hc) throws HttpRequestWriteException {
    hc.setUseCaches(isCachingEnabled());
    String boundary = setContentType();
    if (visitor != null) {
        visitor.visit(this, hc);
    }
    addHeaders(hc);
    Writer writer = null;
    try {
        OutputStream os = null;
        if (isDebugMode()) {
            os = System.out;
        } else {
            os = hc.getOutputStream();
        }
        OutputStreamWriter osw = (charset == null ? new OutputStreamWriter(os) : new OutputStreamWriter(os, charset));
        writer = new PrintWriter(osw, true);
        if (hasParameters() && getBodyPartsCount() == 0) {
            writer.append(super.dumpParameters()).flush();
            return;
        }
        if (getBodyPartsCount() > 0) {
            if (hasParameters()) {
                String cs = charset != null ? charset : HttpUtils.DEFAULT_ENCODING;
                for (HttpParameter p : getParameters()) {
                    writer.append("--" + boundary).append(HttpMessageBody.CRLF);
                    writer.append("Content-Disposition: form-data; name=\"" + p.getName() + "\"").append(HttpMessageBody.CRLF);
                    writer.append("Content-Type: text/plain; charset=" + cs).append(HttpMessageBody.CRLF);
                    writer.append(HttpMessageBody.CRLF);
                    writer.append(String.valueOf(p.getValue())).append(HttpMessageBody.CRLF).flush();
                }
            }
            body.dump(os, charset, boundary);
            return;
        }
    } catch (Throwable th) {
        throw new HttpRequestWriteException(th);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
            // IGNORE
            }
        }
    }
}
Also used : OutputStream(java.io.OutputStream) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) HttpParameter(com.bluenimble.platform.http.HttpParameter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) HttpRequestWriteException(com.bluenimble.platform.http.request.HttpRequestWriteException)

Example 4 with HttpParameter

use of com.bluenimble.platform.http.HttpParameter 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 5 with HttpParameter

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

the class AccessSecretKeysBasedHttpRequestSigner method buildParameters.

private String buildParameters(List<HttpParameter> params) {
    String sParams = Lang.BLANK;
    if (params == null || params.isEmpty()) {
        return sParams;
    }
    StringBuilder sb = new StringBuilder();
    Collections.sort(params, PARAMETER_COMPARATOR);
    // add parameters
    for (int i = 0; i < params.size(); i++) {
        HttpParameter p = params.get(i);
        sb.append(encode(p.getName())).append(Lang.EQUALS);
        if (p.getValue() != null) {
            sb.append(encode(String.valueOf(p.getValue())));
        }
        if (i < (params.size() - 1)) {
            sb.append(Lang.AMP);
        }
    }
    sParams = sb.toString();
    sb.setLength(0);
    return sParams;
}
Also used : HttpParameter(com.bluenimble.platform.http.HttpParameter)

Aggregations

HttpParameter (com.bluenimble.platform.http.HttpParameter)7 HttpEndpoint (com.bluenimble.platform.http.HttpEndpoint)3 HttpHeader (com.bluenimble.platform.http.HttpHeader)3 HttpHeaderImpl (com.bluenimble.platform.http.impls.HttpHeaderImpl)3 HttpParameterImpl (com.bluenimble.platform.http.impls.HttpParameterImpl)3 URI (java.net.URI)3 HttpMessageBody (com.bluenimble.platform.http.HttpMessageBody)2 HttpMessageBodyImpl (com.bluenimble.platform.http.impls.HttpMessageBodyImpl)2 StringHttpMessageBodyPart (com.bluenimble.platform.http.impls.StringHttpMessageBodyPart)2 HttpRequestWriteException (com.bluenimble.platform.http.request.HttpRequestWriteException)2 AbstractHttpRequest (com.bluenimble.platform.http.request.impls.AbstractHttpRequest)2 JsonObject (com.bluenimble.platform.json.JsonObject)2 IOException (java.io.IOException)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 InputStreamHttpMessageBodyPart (com.bluenimble.platform.http.impls.InputStreamHttpMessageBodyPart)1