Search in sources :

Example 1 with VariableResolver

use of com.bluenimble.platform.templating.VariableResolver in project serverless by bluenimble.

the class HttpRemote method request.

private boolean request(ApiVerb verb, JsonObject spec, Callback callback, ApiStreamSource... attachments) {
    JsonObject rdata = Json.getObject(spec, Spec.Data);
    if (!Json.isNullOrEmpty(featureSpec)) {
        JsonObject master = featureSpec.duplicate();
        Json.resolve(master, ECompiler, new VariableResolver() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object resolve(String namespace, String... property) {
                Object v = Json.find(rdata, property);
                Json.remove(rdata, property);
                return v;
            }
        });
        spec = master.merge(spec);
    }
    String endpoint = Json.getString(spec, Spec.Endpoint);
    String path = Json.getString(spec, Spec.Path);
    if (!Lang.isNullOrEmpty(path)) {
        endpoint += path;
    }
    Serializer.Name serName = null;
    try {
        serName = Serializer.Name.valueOf(Json.getString(spec, Spec.Serializer, Serializer.Name.text.name()).toLowerCase());
    } catch (Exception ex) {
        // ignore
        serName = Serializer.Name.text;
    }
    Serializer serializer = Serializers.get(serName);
    Request request = null;
    Response response = null;
    try {
        // contentType
        String contentType = null;
        // resole and add headers
        JsonObject headers = Json.getObject(spec, Spec.Headers);
        if (!Json.isNullOrEmpty(headers)) {
            Json.resolve(headers, ECompiler, new VariableResolver() {

                private static final long serialVersionUID = 1L;

                @Override
                public Object resolve(String namespace, String... property) {
                    return Json.find(rdata, property);
                }
            });
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                if (HttpHeaders.CONTENT_TYPE.toUpperCase().equals(hn.toUpperCase())) {
                    contentType = hv;
                }
            }
        }
        if (Lang.isNullOrEmpty(contentType)) {
            contentType = ContentTypes.FormUrlEncoded;
        }
        contentType = contentType.trim();
        MediaType mediaType = MediaTypes.get(contentType);
        RequestBody body = null;
        List<RequestParameter> parameters = null;
        if (attachments != null && attachments.length > 0 && !Json.isNullOrEmpty(rdata)) {
            // multipart body
            MultipartBody.Builder builder = new MultipartBody.Builder();
            Iterator<String> pnames = rdata.keys();
            while (pnames.hasNext()) {
                String pn = pnames.next();
                builder.addFormDataPart(pn, String.valueOf(rdata.get(pn)));
            }
            for (ApiStreamSource ss : attachments) {
                try {
                    builder.addFormDataPart(ss.name(), ss.name(), RequestBody.create(MediaType.parse(contentType), IOUtils.toByteArray(ss.stream())));
                } catch (Exception ex) {
                    callback.onError(Error.Other, ex.getMessage());
                    return false;
                }
            }
        } else if (contentType.startsWith(ContentTypes.Json)) {
            body = RequestBody.create(mediaType, rdata == null ? JsonObject.EMPTY_OBJECT : rdata.toString());
        } else {
            if (!Json.isNullOrEmpty(rdata)) {
                // for bnb signature only
                if (Signers.Bnb.equals(Json.find(spec, Spec.Sign, Spec.SignProtocol))) {
                    parameters = new ArrayList<RequestParameter>();
                }
                if (verb.equals(ApiVerb.POST) || verb.equals(ApiVerb.PUT) || verb.equals(ApiVerb.PATCH)) {
                    FormBody.Builder fb = new FormBody.Builder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        fb.add(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    body = fb.build();
                } else if (verb.equals(ApiVerb.GET)) {
                    HttpUrl.Builder urlBuilder = HttpUrl.parse(endpoint).newBuilder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        urlBuilder.addQueryParameter(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    endpoint = urlBuilder.build().toString();
                }
            }
        }
        // create the request builder
        Request.Builder rBuilder = new Request.Builder().url(endpoint);
        rBuilder.header(HttpHeaders.USER_AGENT, DefaultUserAgent);
        // add headers
        if (!Json.isNullOrEmpty(headers)) {
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                rBuilder.header(hn, hv);
            }
        }
        // create request
        switch(verb) {
            case GET:
                rBuilder.get();
                break;
            case POST:
                rBuilder.post(body);
                break;
            case DELETE:
                rBuilder.delete();
                break;
            case PUT:
                rBuilder.put(body);
                break;
            case PATCH:
                rBuilder.patch(body);
                break;
            case HEAD:
                rBuilder.head();
                break;
            default:
                break;
        }
        // build then sign
        request = sign(rBuilder.build(), spec, parameters);
        response = http.newCall(request).execute();
        if (response.code() > Json.getInteger(spec, Spec.SuccessCode, 202)) {
            callback.onError(response.code(), response.body().string());
            return false;
        } else {
            callback.onSuccess(response.code(), serializer.serialize(response.body().byteStream()));
            return true;
        }
    } catch (UnknownHostException uhex) {
        callback.onError(Error.UnknownHost, "Endpoint " + endpoint + " can't be resolved. Check your internet connection and make sure the endpoint is correct");
        return false;
    } catch (SocketTimeoutException stoex) {
        callback.onError(Error.Timeout, "Endpoint " + endpoint + " was found but " + stoex.getMessage());
        return false;
    } catch (Exception ex) {
        callback.onError(Error.Other, Lang.toError(ex));
        return false;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(com.bluenimble.platform.json.JsonObject) Iterator(java.util.Iterator) MediaType(okhttp3.MediaType) TextSerializer(com.bluenimble.platform.remote.impls.serializers.TextSerializer) Serializer(com.bluenimble.platform.remote.Serializer) StreamSerializer(com.bluenimble.platform.remote.impls.serializers.StreamSerializer) JsonSerializer(com.bluenimble.platform.remote.impls.serializers.JsonSerializer) XmlSerializer(com.bluenimble.platform.remote.impls.serializers.XmlSerializer) RequestBody(okhttp3.RequestBody) UnknownHostException(java.net.UnknownHostException) Request(okhttp3.Request) FormBody(okhttp3.FormBody) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) SocketTimeoutException(java.net.SocketTimeoutException) MultipartBody(okhttp3.MultipartBody) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver)

Example 2 with VariableResolver

use of com.bluenimble.platform.templating.VariableResolver in project serverless by bluenimble.

the class LoadFeatureHandler method execute.

@Override
public CommandResult execute(Tool tool, String... args) throws CommandExecutionException {
    if (args == null || args.length < 1) {
        throw new CommandExecutionException("feature file path required. ex. load feature aTempate.json");
    }
    String path = args[0];
    File templateFile = new File(path + ".json");
    String name = templateFile.getName();
    if (!templateFile.exists() || !templateFile.isFile()) {
        throw new CommandExecutionException("invalid file path > " + path);
    }
    String key = name.substring(0, name.lastIndexOf(Lang.DOT));
    JsonObject oFeature;
    try {
        oFeature = Json.load(templateFile);
    } catch (Exception e) {
        throw new CommandExecutionException(e.getMessage(), e);
    }
    String provider = key;
    String[] variables = null;
    int indexOfDash = key.indexOf(Lang.DASH);
    if (indexOfDash > 0) {
        provider = key.substring(0, indexOfDash);
        variables = Lang.split(key.substring(indexOfDash + 1), "__", true);
    }
    oFeature.set("name", "default");
    oFeature.set("provider", provider);
    final Map<String, String> mVariables = new HashMap<String, String>();
    if (variables != null && variables.length > 0) {
        for (String v : variables) {
            String vKey = v.substring(0, v.indexOf(Lang.UNDERSCORE));
            String vValue = v.substring(v.indexOf(Lang.UNDERSCORE) + 1);
            mVariables.put(vKey, vValue);
        }
    }
    if (mVariables != null) {
        oFeature = (JsonObject) Json.resolve(oFeature, ExpressionCompiler, new VariableResolver() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object resolve(String namespace, String... property) {
                return mVariables.get(Lang.join(property, Lang.DOT));
            }
        });
    }
    @SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.currentContext().get(ToolContext.VARS);
    vars.put(key, oFeature);
    return new DefaultCommandResult(CommandResult.OK, oFeature);
}
Also used : HashMap(java.util.HashMap) JsonObject(com.bluenimble.platform.json.JsonObject) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) DefaultCommandResult(com.bluenimble.platform.cli.command.impls.DefaultCommandResult) CommandExecutionException(com.bluenimble.platform.cli.command.CommandExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with VariableResolver

use of com.bluenimble.platform.templating.VariableResolver in project serverless by bluenimble.

the class DataSourceVendor method url.

public String url(String host, int port, String database) {
    if (port <= 0) {
        port = Json.getInteger(descriptor, DataSourcePlugin.Spec.Port, 0);
    }
    final JsonObject data = (JsonObject) new JsonObject().set(DataSourcePlugin.Spec.Host, host).set(DataSourcePlugin.Spec.Port, port).set(DataSourcePlugin.Spec.Database, database);
    VariableResolver vr = new VariableResolver() {

        private static final long serialVersionUID = -485939153491337463L;

        @Override
        public Object resolve(String namespace, String... property) {
            String firstChar = property[0].substring(0, 1);
            if (Tokens.contains(firstChar)) {
                property[0] = property[0].substring(1);
            } else {
                firstChar = Lang.BLANK;
            }
            Object v = Json.find(data, property);
            if (v != null) {
                return firstChar + v;
            }
            return null;
        }
    };
    return (String) Compiler.compile(Json.getString(descriptor, Template), null).eval(vr);
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver)

Example 4 with VariableResolver

use of com.bluenimble.platform.templating.VariableResolver in project serverless by bluenimble.

the class FileSystemApiServer method setup.

private void setup() throws Exception {
    if (tenantHome != null) {
        File varsFile = new File(tenantHome, ConfigKeys.VariablesFile);
        if (varsFile.exists() && varsFile.isFile()) {
            variables = Json.load(new File(tenantHome, ConfigKeys.VariablesFile));
        }
    }
    variablesResolver = new VariableResolver() {

        private static final long serialVersionUID = -485939153491337463L;

        @Override
        public Object resolve(String namespace, String... property) {
            if (Lang.isNullOrEmpty(namespace)) {
                return null;
            }
            if (namespace.equals("server")) {
                return Json.find(descriptor, property);
            } else if (namespace.equals("sys")) {
                return System.getProperty(Lang.join(property, Lang.DOT));
            } else if (namespace.equals("vars")) {
                if (variables == null) {
                    return null;
                }
                return Json.find(variables, property);
            }
            return null;
        }
    };
    if (!runtimeHome.exists()) {
        runtimeHome.mkdir();
    }
    if (tenantHome != null) {
        runtimeLogs = new File(tenantHome, ConfigKeys.Folders.Logs);
    } else {
        runtimeLogs = new File(runtimeHome, ConfigKeys.Folders.Logs);
    }
    if (!runtimeLogs.exists()) {
        runtimeLogs.mkdirs();
    }
    descriptor = null;
    File bluenimbleFile = new File(installHome, ConfigKeys.InstanceConfig);
    if (bluenimbleFile.exists()) {
        descriptor = resolve((JsonObject) Json.load(bluenimbleFile));
    } else {
        descriptor = new JsonObject();
    }
    // resolve descriptor
    Lang.setDebugMode(Json.getBoolean(descriptor, ConfigKeys.Debug, false));
    File pluginsFolder = new File(installHome, ConfigKeys.Folders.Plugins);
    if (!pluginsFolder.exists()) {
        pluginsFolder.mkdir();
    }
    File backup = new File(runtimeHome, ConfigKeys.Folders.Backup);
    if (!backup.exists()) {
        backup.mkdir();
    }
    File logs = new File(runtimeHome, ConfigKeys.Folders.Logs);
    if (!logs.exists()) {
        logs.mkdir();
    }
    File spacesFolder = new File(runtimeHome, ConfigKeys.Folders.Spaces);
    if (!spacesFolder.exists()) {
        spacesFolder.mkdir();
    }
    // copy pre-installed spaces
    copySpacesToRuntime();
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver) File(java.io.File)

Example 5 with VariableResolver

use of com.bluenimble.platform.templating.VariableResolver in project serverless by bluenimble.

the class TestTemplate method main.

public static void main(String[] args) {
    String exp1 = "[model.a] [NoNs]";
    String exp2 = "Hello [model.c]";
    String exp3 = "[model.b] done";
    String exp4 = "simple text";
    String exp5 = "simple [model.b] [alpha.a] [beta | 'alpha']";
    String exp6 = "{ price: '[model.b]' }>>json";
    final JsonObject model = (JsonObject) new JsonObject().set("a", "A Value").set("b", 409).set("c", "Hello");
    VariableResolver vr = new VariableResolver() {

        private static final long serialVersionUID = -485939153491337463L;

        @Override
        public Object resolve(String namespace, String... property) {
            System.out.println(namespace);
            if (namespace == null) {
                return null;
            }
            System.out.println(Lang.join(property, Lang.DOT));
            if (namespace == null || namespace.equals("model")) {
                return Json.find(model, property);
            }
            return null;
        }
    };
    DefaultExpressionCompiler compiler = new DefaultExpressionCompiler();
    System.out.println("exp1: " + compiler.compile(exp1, null).eval(vr));
    System.out.println("exp2: " + compiler.compile(exp2, null).eval(vr));
    System.out.println("exp3: " + compiler.compile(exp3, null).eval(vr));
    System.out.println("exp4: " + compiler.compile(exp4, null).eval(vr));
    System.out.println("exp5: " + compiler.compile(exp5, null).eval(vr));
    System.out.println("exp6: " + compiler.compile(exp6, null).eval(vr));
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) DefaultExpressionCompiler(com.bluenimble.platform.templating.impls.DefaultExpressionCompiler) VariableResolver(com.bluenimble.platform.templating.VariableResolver)

Aggregations

JsonObject (com.bluenimble.platform.json.JsonObject)5 VariableResolver (com.bluenimble.platform.templating.VariableResolver)5 File (java.io.File)2 ApiStreamSource (com.bluenimble.platform.api.ApiStreamSource)1 CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)1 DefaultCommandResult (com.bluenimble.platform.cli.command.impls.DefaultCommandResult)1 Serializer (com.bluenimble.platform.remote.Serializer)1 JsonSerializer (com.bluenimble.platform.remote.impls.serializers.JsonSerializer)1 StreamSerializer (com.bluenimble.platform.remote.impls.serializers.StreamSerializer)1 TextSerializer (com.bluenimble.platform.remote.impls.serializers.TextSerializer)1 XmlSerializer (com.bluenimble.platform.remote.impls.serializers.XmlSerializer)1 DefaultExpressionCompiler (com.bluenimble.platform.templating.impls.DefaultExpressionCompiler)1 SocketTimeoutException (java.net.SocketTimeoutException)1 UnknownHostException (java.net.UnknownHostException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 FormBody (okhttp3.FormBody)1 HttpUrl (okhttp3.HttpUrl)1