Search in sources :

Example 6 with Database

use of com.bluenimble.platform.db.Database in project serverless by bluenimble.

the class SignupServiceSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    JsonObject config = request.getService().getCustom();
    JsonObject payload = (JsonObject) request.get(ApiRequest.Payload);
    Database db = api.space().feature(Database.class, Json.getString(config, Config.Database, ApiSpace.Features.Default), request);
    DatabaseObject account = null;
    try {
        JsonObject where = null;
        JsonObject query = Json.getObject(config, Config.Query);
        if (query == null) {
            query = new JsonObject();
            where = new JsonObject();
            query.set(Query.Construct.where.name(), where);
        } else {
            where = Json.getObject(query, Query.Construct.where.name());
        }
        query.set(Database.Fields.Entity, Json.getString(config, Config.UsersEntity, Defaults.Users));
        where.set(Json.getString(config, Config.UserProperty, Fields.Email), Json.getString(payload, Spec.User));
        account = db.findOne(null, new JsonQuery(query));
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    if (account != null) {
        throw new ApiServiceExecutionException("account already exists").status(ApiResponse.CONFLICT);
    }
    boolean requiresActivation = Json.getBoolean(config, Config.RequiresActivation, false);
    try {
        account = db.create(Json.getString(config, Config.UsersEntity, Defaults.Users));
        account.load(payload);
        // set user property
        account.set(Json.getString(config, Config.UserProperty, Fields.Email), Json.getString(payload, Spec.User));
        account.remove(Spec.User);
        boolean encryptPassword = Json.getBoolean(config, Config.EncryptPassword, true);
        account.set(Json.getString(config, Config.PasswordProperty, Spec.Password), encryptPassword ? Crypto.md5(Json.getString(payload, Spec.Password), Encodings.UTF8) : Json.getString(payload, Spec.Password));
        JsonObject extraData = Json.getObject(config, Config.Data);
        if (extraData != null && !extraData.isEmpty()) {
            Iterator<String> keys = extraData.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                account.set(key, extraData.get(key));
            }
        }
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    try {
        String activationCode = null;
        if (requiresActivation) {
            String acType = Json.getString(config, Config.ActivationCodeType, ActivationCodeTypes.CPIN).toLowerCase();
            int pinLength = Json.getInteger(config, Config.PinLength, 6);
            if (acType.equals(ActivationCodeTypes.CPIN)) {
                activationCode = Lang.UUID(pinLength);
            } else if (acType.equals(ActivationCodeTypes.NPIN)) {
                activationCode = Lang.pin(pinLength);
            } else {
                activationCode = Lang.rand();
            }
            account.set(Json.getString(config, Config.ActivationCodeProperty, Defaults.ActivationCode), activationCode);
        }
        account.save();
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    payload.remove(Spec.Password);
    JsonObject result = account.toJson(DefaultDatabaseObjectSerializer.Default);
    String email = Json.getString(payload, Spec.Email);
    if (Lang.isNullOrEmpty(email)) {
        if (Json.getBoolean(config, Config.UseUserAsEmailAddress, false)) {
            email = Json.getString(payload, Spec.User);
        }
    }
    result.remove(Json.getString(config, Config.PasswordProperty, Spec.Password));
    if (!requiresActivation || Lang.isNullOrEmpty(email)) {
        Date now = new Date();
        // update lastLogin
        try {
            account.set(Json.getString(config, Config.LastLoginProperty, Fields.LastLogin), now);
            account.save();
        } catch (Exception ex) {
            throw new ApiServiceExecutionException(ex.getMessage(), ex);
        }
        // create token
        String[] tokenAndExpiration = SecurityUtils.tokenAndExpiration(api, result, now);
        result.set(Defaults.Token, tokenAndExpiration[0]);
        result.set(Defaults.ExpiresOn, tokenAndExpiration[1]);
        return new JsonApiOutput(result);
    }
    // requires activation and email is present in payload
    JsonObject oEmail = Json.getObject(config, Config.SignupEmail);
    String feature = Json.getString(oEmail, Email.Messenger);
    String template = Json.getString(oEmail, Email.Template);
    if (oEmail != null && !Lang.isNullOrEmpty(feature) && !Lang.isNullOrEmpty(template)) {
        String fromEmail = Json.getString(oEmail, Email.FromEmail);
        String fromName = Json.getString(oEmail, Email.FromName);
        String subject = Json.getString(oEmail, Email.Subject, "Welcome to " + api.getName());
        final Messenger messenger = api.space().feature(Messenger.class, feature, request);
        final JsonObject emailTemplateData = account.toJson(null);
        try {
            final String fEmail = email;
            api.space().executor().execute(new Callable<Void>() {

                @Override
                public Void call() {
                    try {
                        messenger.send(new JsonSender((JsonObject) new JsonObject().set(JsonActor.Spec.Id, fromEmail).set(JsonActor.Spec.Name, fromName)), new JsonRecipient[] { new JsonRecipient((JsonObject) new JsonObject().set(JsonActor.Spec.Id, fEmail)) }, subject, api.getResourcesManager().get(Lang.split(template, Lang.SLASH)), emailTemplateData);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex.getMessage(), ex);
                    }
                    return null;
                }
            }, CodeExecutor.Mode.Async);
        } catch (Exception ex) {
            throw new ApiServiceExecutionException(ex.getMessage(), ex);
        }
    }
    // call extend if any
    JsonObject onFinish = Json.getObject(config, Config.onFinish.class.getSimpleName());
    ApiOutput onFinishOutput = SecurityUtils.onFinish(api, consumer, request, onFinish, result);
    if (onFinishOutput != null) {
        result.set(Json.getString(onFinish, Config.onFinish.ResultProperty, Config.onFinish.class.getSimpleName()), onFinishOutput.data());
    }
    return new JsonApiOutput(result);
}
Also used : JsonQuery(com.bluenimble.platform.db.query.impls.JsonQuery) Config(com.bluenimble.platform.api.impls.im.LoginServiceSpi.Config) JsonObject(com.bluenimble.platform.json.JsonObject) JsonRecipient(com.bluenimble.platform.messaging.impls.JsonRecipient) Messenger(com.bluenimble.platform.messaging.Messenger) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Date(java.util.Date) JsonSender(com.bluenimble.platform.messaging.impls.JsonSender) ApiOutput(com.bluenimble.platform.api.ApiOutput) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Database(com.bluenimble.platform.db.Database) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 7 with Database

use of com.bluenimble.platform.db.Database in project serverless by bluenimble.

the class Create method main.

public static void main(String[] args) throws DatabaseException {
    Database db = new DatabaseServer().get();
    DatabaseObject employee = db.create("Employees");
    JsonArray names = new JsonArray();
    names.add(new JsonObject().set("number", "4098776623").set("weight", 40));
    employee.set("name", "Simo");
    employee.set("age", 34);
    employee.set("active", true);
    employee.set("salary", 43.98);
    employee.set("names", names);
    employee.save();
    System.out.println(employee.toJson(null));
}
Also used : JsonArray(com.bluenimble.platform.json.JsonArray) Database(com.bluenimble.platform.db.Database) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) JsonObject(com.bluenimble.platform.json.JsonObject)

Example 8 with Database

use of com.bluenimble.platform.db.Database in project serverless by bluenimble.

the class CreateOne2One method main.

public static void main(String[] args) throws DatabaseException {
    Database db = new DatabaseServer().get();
    // create driver
    DatabaseObject driver = db.create("Drivers");
    driver.set("name", "One2One-New-1");
    driver.set("info", new JsonObject().set("x", "40987").set("y", 76623));
    driver.set("salary", 48.50);
    // create car
    DatabaseObject car = db.create("Cars");
    car.set("model", "Honda");
    car.set("year", "2040");
    driver.set("car", car);
    driver.save();
    System.out.println(driver.toJson(null));
}
Also used : Database(com.bluenimble.platform.db.Database) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) JsonObject(com.bluenimble.platform.json.JsonObject)

Example 9 with Database

use of com.bluenimble.platform.db.Database in project serverless by bluenimble.

the class UpdateSimple method main.

public static void main(String[] args) throws DatabaseException {
    Database db = new DatabaseServer().get();
    DatabaseObject employee = db.get("Employees", "5aa4192e5e6726413c7db45a");
    employee.set("address", "Got Found");
    DatabaseObject city = db.create("Cities");
    city.set("name", "Tetouan");
    employee.set("city", city);
    employee.save();
    System.out.println(employee.toString());
    System.out.println();
    System.out.println("+===============================================================================+");
    System.out.println();
    System.out.println(employee.toJson(new DefaultDatabaseObjectSerializer(2, 2)));
}
Also used : DefaultDatabaseObjectSerializer(com.bluenimble.platform.db.impls.DefaultDatabaseObjectSerializer) Database(com.bluenimble.platform.db.Database) DatabaseObject(com.bluenimble.platform.db.DatabaseObject)

Example 10 with Database

use of com.bluenimble.platform.db.Database in project serverless by bluenimble.

the class Update method main.

public static void main(String[] args) throws DatabaseException {
    Database db = new DatabaseServer().get();
    DatabaseObject employee = db.get("Employees", "e0e296f0-1937-4b7c-b077-1d7fe50e2482");
    employee.set("age", 43);
    employee.set("salary", 200.54);
    employee.set("contact", new JsonObject().set("phone", "4089786532").set("email", "alpha@beta.com"));
    DatabaseObject city = db.create("Cities");
    city.set("name", "Sunnyvale");
    employee.set("city", city);
    employee.save();
    System.out.println(employee.toJson(new DefaultDatabaseObjectSerializer(2, 2)));
}
Also used : DefaultDatabaseObjectSerializer(com.bluenimble.platform.db.impls.DefaultDatabaseObjectSerializer) Database(com.bluenimble.platform.db.Database) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) JsonObject(com.bluenimble.platform.json.JsonObject)

Aggregations

Database (com.bluenimble.platform.db.Database)41 DatabaseObject (com.bluenimble.platform.db.DatabaseObject)37 JsonObject (com.bluenimble.platform.json.JsonObject)27 DefaultDatabaseObjectSerializer (com.bluenimble.platform.db.impls.DefaultDatabaseObjectSerializer)20 JsonQuery (com.bluenimble.platform.db.query.impls.JsonQuery)14 ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)11 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)11 DatabaseException (com.bluenimble.platform.db.DatabaseException)8 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)6 ApiSpace (com.bluenimble.platform.api.ApiSpace)6 JsonArray (com.bluenimble.platform.json.JsonArray)5 ApiOutput (com.bluenimble.platform.api.ApiOutput)4 Date (java.util.Date)4 Config (com.bluenimble.platform.api.impls.im.LoginServiceSpi.Config)2 Messenger (com.bluenimble.platform.messaging.Messenger)2 JsonRecipient (com.bluenimble.platform.messaging.impls.JsonRecipient)2 JsonSender (com.bluenimble.platform.messaging.impls.JsonSender)2 Field (com.bluenimble.platform.db.Database.Field)1 File (java.io.File)1