Search in sources :

Example 46 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class ChangePasswordSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    JsonObject config = request.getService().getCustom();
    Database db = api.space().feature(Database.class, Json.getString(config, Config.Database, ApiSpace.Features.Default), request);
    DatabaseObject account = null;
    try {
        account = db.get(Json.getString(config, Config.UsersEntity, Defaults.Users), (String) consumer.get(ApiConsumer.Fields.Id));
        account.set(Json.getString(config, Config.PasswordProperty, Spec.Password), Lang.md5((String) request.get(Spec.Password)));
        account.save();
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    ApiOutput result = new JsonApiOutput(JsonObject.Blank);
    // call extend if any
    if (config.containsKey(Config.onFinish.class.getSimpleName())) {
        JsonObject oAccount = account.toJson(null);
        result = SecurityUtils.onFinish(api, consumer, request, Json.getObject(config, Config.onFinish.class.getSimpleName()), oAccount);
    }
    return result;
}
Also used : 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) JsonObject(com.bluenimble.platform.json.JsonObject) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 47 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class DefaultApiInterceptor method intercept.

@Override
public void intercept(Api api, ApiRequest request, ApiResponse response) {
    logDebug(api, "<" + request.getId() + "> Process Request \n" + request.toString());
    ServerRequestTrack track = server.getRequestTracker(Json.getString(api.getTracking(), Api.Spec.Tracking.Tracker)).create(api, request);
    request.track(track);
    response.set(ApiHeaders.NodeID, Json.getString(request.getNode(), ApiRequest.Fields.Node.Id));
    response.set(ApiHeaders.NodeType, Json.getString(request.getNode(), ApiRequest.Fields.Node.Type));
    response.set(ApiHeaders.NodeVersion, Json.getString(request.getNode(), ApiRequest.Fields.Node.Version));
    ApiMediaProcessor mediaProcessor = null;
    ApiConsumer consumer = null;
    ApiService service = null;
    try {
        // api life cycle - onRequest
        api.getSpi().onRequest(api, request, response);
        // resolve service
        service = ((ApiImpl) api).lockup(request);
        ApiResponse.Status notFoundStatus = null;
        String notFoundMessage = null;
        if (service == null) {
            notFoundStatus = ApiResponse.NOT_FOUND;
            notFoundMessage = api.message(request.getLang(), Messages.ServiceNotFound, request.getVerb().name() + Lang.SPACE + request.getPath());
        } else if (service.status() != ApiStatus.Running) {
            notFoundStatus = ApiResponse.SERVICE_UNAVAILABLE;
            notFoundMessage = api.message(request.getLang(), Messages.ServiceNotAvailable, service.getName());
        }
        if (notFoundStatus != null) {
            if (response instanceof ContainerApiResponse) {
                ((ContainerApiResponse) response).setException(new ApiServiceExecutionException(notFoundMessage).status(notFoundStatus));
            } else {
                response.error(notFoundStatus, notFoundMessage);
                writeError(mediaProcessor, api, null, null, request, response);
            }
            track.finish((JsonObject) new JsonObject().set(ApiResponse.Error.Code, notFoundStatus.getCode()).set(ApiResponse.Error.Message, notFoundMessage));
            return;
        }
        ((AbstractApiRequest) request).setService(service);
        // Lookup media processor
        mediaProcessor = api.lockupMediaProcessor(request, service);
        track.update(service);
        logInfo(api, "<" + request.getId() + "> Using service " + service.getVerb() + Lang.SPACE + Json.getString(service.toJson(), ApiService.Spec.Endpoint) + Lang.SPACE + Lang.PARENTH_OPEN + service.getName() + Lang.PARENTH_CLOSE);
        // api life cycle - onService
        api.getSpi().onService(api, service, request, response);
        logInfo(api, "<" + request.getId() + "> Interceptor will use media.processor [" + mediaProcessor.getClass().getSimpleName() + "]");
        JsonObject apiSecMethods = Json.getObject(api.getSecurity(), Api.Spec.Security.Schemes);
        if (apiSecMethods == null) {
            apiSecMethods = JsonObject.Blank;
        }
        JsonArray serviceSecMethods = Json.getArray(service.getSecurity(), ApiService.Spec.Security.Schemes);
        ApiConsumerResolver resolver = null;
        try {
            Iterator<String> rKeys = apiSecMethods.keys();
            if (rKeys != null) {
                while (rKeys.hasNext()) {
                    String resolverName = rKeys.next();
                    if (serviceSecMethods != null && !serviceSecMethods.contains(resolverName)) {
                        continue;
                    }
                    ApiConsumerResolver r = server.getConsumerResolver(resolverName);
                    if (r == null) {
                        continue;
                    }
                    consumer = r.resolve(api, service, request);
                    if (consumer != null) {
                        resolver = r;
                        break;
                    }
                }
            }
            if (consumer == null) {
                consumer = new DefaultApiConsumer(ApiConsumer.Type.Unknown);
            }
            api.getSpi().findConsumer(api, service, request, consumer);
            if (resolver != null) {
                resolver.authorize(api, service, request, consumer);
            }
        } catch (ApiAuthenticationException e) {
            if (response instanceof ContainerApiResponse) {
                ((ContainerApiResponse) response).setException(new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.UNAUTHORIZED));
            } else {
                response.error(ApiResponse.UNAUTHORIZED, e.getMessage());
                writeError(mediaProcessor, api, consumer, service, request, response);
            }
            track.finish((JsonObject) new JsonObject().set(ApiResponse.Error.Code, ApiResponse.UNAUTHORIZED.getCode()).set(ApiResponse.Error.Message, e.getMessage()));
            return;
        }
        try {
            server.getServiceValidator().validate(api, Json.getObject(service.toJson(), ApiService.Spec.Spec), consumer, request);
        } catch (ApiServiceValidatorException e) {
            if (response instanceof ContainerApiResponse) {
                ((ContainerApiResponse) response).setException(new ApiServiceExecutionException(e.getMessage(), e));
            } else {
                writeValidationError(api, consumer, service, request, response, mediaProcessor, e);
            }
            Object error = null;
            if (e.getFeedback() != null) {
                error = e.getFeedback();
            } else {
                error = e.getMessage();
            }
            track.finish((JsonObject) new JsonObject().set(ApiResponse.Error.Code, ApiResponse.UNPROCESSABLE_ENTITY.getCode()).set(ApiResponse.Error.Message, error));
            return;
        }
        ApiOutput output = null;
        JsonObject mock = Json.getObject(service.toJson(), ApiService.Spec.Mock);
        if (mock != null && Json.getBoolean(mock, ConfigKeys.Enabled, false)) {
            output = new JsonApiOutput(Json.getObject(mock, ApiService.Spec.Output));
            logInfo(api, "<" + request.getId() + "> Service using mock output");
        } else {
            // api life cycle - onExecute
            api.getSpi().onExecute(api, consumer, service, request, response);
            output = service.getSpi().execute(api, consumer, request, response);
            // api life cycle - afterExecute
            api.getSpi().afterExecute(api, consumer, service, request, response);
        }
        if (request instanceof ContainerApiRequest) {
            request.set(ApiRequest.Output, output);
        } else {
            response.set(ApiHeaders.ExecutionTime, (System.currentTimeMillis() - request.getTimestamp().getTime()));
            if (response.isCommitted()) {
                logInfo(api, "<" + request.getId() + "> Response already committed. No media processing required");
                long time = System.currentTimeMillis() - request.getTimestamp().getTime();
                track.finish((JsonObject) new JsonObject().set(ApiResponse.Error.Code, ApiResponse.OK.getCode()).set(ApiResponse.Error.Message, time));
                logInfo(api, " <" + request.getId() + "> ExecTime-Cancel: Service " + Json.getString(service.toJson(), ApiService.Spec.Endpoint) + " - Time " + time + " millis");
                return;
            }
            mediaProcessor.process(api, service, consumer, output, request, response);
        }
        int iStatus = ApiResponse.OK.getCode();
        ApiResponse.Status status = response.getStatus();
        if (status != null) {
            iStatus = status.getCode();
        }
        long time = System.currentTimeMillis() - request.getTimestamp().getTime();
        track.finish((JsonObject) new JsonObject().set(ApiResponse.Error.Code, iStatus).set(ApiResponse.Error.Message, time));
        logInfo(api, "<" + request.getId() + "> ExecTime-Success: Service " + Json.getString(service.toJson(), ApiService.Spec.Endpoint) + " - Time " + time + " millis");
    } catch (Throwable th) {
        if (response instanceof ContainerApiResponse) {
            if (th instanceof ApiServiceExecutionException) {
                ((ContainerApiResponse) response).setException((ApiServiceExecutionException) th);
            } else {
                ((ContainerApiResponse) response).setException(new ApiServiceExecutionException(th.getMessage(), th));
            }
            // String [] msg = Lang.toMessage (th);
            track.finish((JsonObject) Lang.toError(th).set(ApiResponse.Error.Code, ApiResponse.INTERNAL_SERVER_ERROR.getCode()));
        } else {
            ApiResponse.Status status = null;
            if (th instanceof ApiServiceExecutionException) {
                status = ((ApiServiceExecutionException) th).status();
            }
            if (status == null) {
                status = ApiResponse.INTERNAL_SERVER_ERROR;
            }
            boolean isValidationError = false;
            if (th instanceof ApiServiceExecutionException) {
                Throwable rootCause = ((ApiServiceExecutionException) th).getRootCause();
                if (rootCause instanceof ApiServiceValidatorException) {
                    ApiServiceValidatorException vex = (ApiServiceValidatorException) rootCause;
                    isValidationError = true;
                    writeValidationError(api, consumer, service, request, response, mediaProcessor, vex);
                    Object error = null;
                    if (vex.getFeedback() != null) {
                        error = vex.getFeedback();
                    } else {
                        error = vex.getMessage();
                    }
                    track.finish((JsonObject) new JsonObject().set(ApiResponse.Error.Code, ApiResponse.UNPROCESSABLE_ENTITY.getCode()).set(ApiResponse.Error.Message, error));
                }
            }
            if (!isValidationError) {
                JsonObject oError = Lang.toError(th);
                // logError (api, "<" + request.getId () + "> - Execute Service / Media Processing - caused an error\n" + oError.toString (), null);
                response.error(status, new Object[] { oError.get(ApiResponse.Error.Message), oError.get(ApiResponse.Error.Trace) });
                writeError(mediaProcessor, api, consumer, service, request, response);
                track.finish((JsonObject) oError.set(ApiResponse.Error.Code, status.getCode()));
            }
        }
    } finally {
        request.destroy();
    }
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) ContainerApiResponse(com.bluenimble.platform.api.impls.ContainerApiResponse) AbstractApiRequest(com.bluenimble.platform.api.impls.AbstractApiRequest) ContainerApiResponse(com.bluenimble.platform.api.impls.ContainerApiResponse) ApiResponse(com.bluenimble.platform.api.ApiResponse) ApiOutput(com.bluenimble.platform.api.ApiOutput) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) DefaultApiConsumer(com.bluenimble.platform.server.security.impls.DefaultApiConsumer) ApiConsumer(com.bluenimble.platform.api.security.ApiConsumer) ApiAuthenticationException(com.bluenimble.platform.api.security.ApiAuthenticationException) ApiServiceValidatorException(com.bluenimble.platform.api.validation.ApiServiceValidatorException) ServerRequestTrack(com.bluenimble.platform.server.tracking.ServerRequestTrack) ApiStatus(com.bluenimble.platform.api.ApiStatus) ApiMediaProcessor(com.bluenimble.platform.api.media.ApiMediaProcessor) ContainerApiRequest(com.bluenimble.platform.api.impls.ContainerApiRequest) JsonArray(com.bluenimble.platform.json.JsonArray) ApiService(com.bluenimble.platform.api.ApiService) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiConsumerResolver(com.bluenimble.platform.api.security.ApiConsumerResolver) JsonObject(com.bluenimble.platform.json.JsonObject) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) DefaultApiConsumer(com.bluenimble.platform.server.security.impls.DefaultApiConsumer)

Example 48 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class AddObjectSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    ApiSpace space;
    try {
        space = MgmUtils.space(consumer, api);
    } catch (ApiAccessDeniedException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
    }
    String provider = (String) request.get(CommonSpec.Provider);
    ApiStreamSource stream = (ApiStreamSource) request.get(ApiRequest.Payload, Scope.Stream);
    Storage storage = space.feature(Storage.class, provider, request);
    String path = (String) request.get(Spec.Object);
    try {
        Folder root = storage.root();
        if (!Lang.isNullOrEmpty(path)) {
            String[] aPath = Lang.split(path, Lang.SLASH);
            for (String p : aPath) {
                if (!root.contains(p)) {
                    root = root.add(p, true);
                } else {
                    StorageObject so = root.get(p);
                    if (!so.isFolder()) {
                        throw new StorageException(p + " isn't a valid folder");
                    }
                    root = (Folder) so;
                }
            }
        }
        if (stream != null) {
            root.add(stream, stream.name(), true);
        }
    } catch (StorageException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    return new JsonApiOutput((JsonObject) new JsonObject().set(CommonOutput.Added, true));
}
Also used : ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) Storage(com.bluenimble.platform.storage.Storage) StorageObject(com.bluenimble.platform.storage.StorageObject) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) Folder(com.bluenimble.platform.storage.Folder) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) StorageException(com.bluenimble.platform.storage.StorageException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 49 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class CopyObjectSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    ApiSpace space;
    try {
        space = MgmUtils.space(consumer, api);
    } catch (ApiAccessDeniedException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
    }
    String provider = (String) request.get(CommonSpec.Provider);
    String path = (String) request.get(Spec.Object);
    String sFolder = (String) request.get(Spec.Folder);
    Boolean move = (Boolean) request.get(Spec.Move);
    if (move == null) {
        move = false;
    }
    Storage storage = space.feature(Storage.class, provider, request);
    Folder root = null;
    StorageObject so = null;
    try {
        root = storage.root();
    } catch (StorageException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    try {
        so = root.get(path);
    } catch (StorageException e) {
        throw new ApiServiceExecutionException("storage object '" + path + "' not found", e).status(ApiResponse.NOT_FOUND);
    }
    Folder folder = root;
    StorageObject soFolder = null;
    if (!Lang.isNullOrEmpty(sFolder)) {
        try {
            soFolder = root.get(sFolder);
        } catch (StorageException e) {
            throw new ApiServiceExecutionException("folder '" + sFolder + "' not found", e).status(ApiResponse.NOT_FOUND);
        }
    }
    if (!soFolder.isFolder()) {
        throw new ApiServiceExecutionException("storage object '" + sFolder + "' isn't a valid folder").status(ApiResponse.BAD_REQUEST);
    }
    try {
        so.copy(folder, move);
    } catch (StorageException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    return new JsonApiOutput((JsonObject) new JsonObject().set(move ? CommonOutput.Moved : CommonOutput.Copied, true));
}
Also used : ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) Storage(com.bluenimble.platform.storage.Storage) StorageObject(com.bluenimble.platform.storage.StorageObject) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) Folder(com.bluenimble.platform.storage.Folder) StorageException(com.bluenimble.platform.storage.StorageException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 50 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class GetObjectSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    ApiSpace space;
    try {
        space = MgmUtils.space(consumer, api);
    } catch (ApiAccessDeniedException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
    }
    String provider = (String) request.get(CommonSpec.Provider);
    Storage storage = space.feature(Storage.class, provider, request);
    String path = (String) request.get(Spec.Object);
    String filter = (String) request.get(Spec.Filter);
    Folder root = null;
    StorageObject so = null;
    try {
        root = storage.root();
        so = root;
    } catch (StorageException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    try {
        if (!Lang.isNullOrEmpty(path) && !path.trim().equals(Lang.DOT)) {
            so = root.get(path);
        }
    } catch (StorageException e) {
        throw new ApiServiceExecutionException("storage object '" + path + "' not found", e).status(ApiResponse.NOT_FOUND);
    }
    try {
        return so.toOutput(StorageUtils.guessFilter(filter), null, null);
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
}
Also used : ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) Storage(com.bluenimble.platform.storage.Storage) StorageObject(com.bluenimble.platform.storage.StorageObject) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Folder(com.bluenimble.platform.storage.Folder) StorageException(com.bluenimble.platform.storage.StorageException) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) StorageException(com.bluenimble.platform.storage.StorageException)

Aggregations

ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)52 JsonObject (com.bluenimble.platform.json.JsonObject)41 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)39 ApiSpace (com.bluenimble.platform.api.ApiSpace)31 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)28 Database (com.bluenimble.platform.db.Database)13 DatabaseObject (com.bluenimble.platform.db.DatabaseObject)9 ApiOutput (com.bluenimble.platform.api.ApiOutput)8 DatabaseException (com.bluenimble.platform.db.DatabaseException)8 Storage (com.bluenimble.platform.storage.Storage)8 StorageException (com.bluenimble.platform.storage.StorageException)8 StorageObject (com.bluenimble.platform.storage.StorageObject)8 Api (com.bluenimble.platform.api.Api)6 ApiManagementException (com.bluenimble.platform.api.ApiManagementException)5 JsonArray (com.bluenimble.platform.json.JsonArray)5 ScriptingEngine (com.bluenimble.platform.scripting.ScriptingEngine)5 ScriptingEngineException (com.bluenimble.platform.scripting.ScriptingEngineException)5 Date (java.util.Date)5 ApiStreamSource (com.bluenimble.platform.api.ApiStreamSource)4 ApiVerb (com.bluenimble.platform.api.ApiVerb)4