use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class OrientDatabase method bulk.
@Override
public JsonObject bulk(JsonObject data) throws DatabaseException {
JsonObject result = (JsonObject) new JsonObject().set(Database.Fields.Total, 0);
if (data == null || data.isEmpty()) {
return result;
}
db.declareIntent(new OIntentMassiveInsert());
try {
Iterator<String> entities = data.keys();
while (entities.hasNext()) {
int count = 0;
String entityName = entities.next();
Object oRecords = data.get(entityName);
if (!(oRecords instanceof JsonArray)) {
continue;
}
JsonArray records = Json.getArray(data, entityName);
for (int i = 0; i < records.count(); i++) {
Object oRec = records.get(i);
if (!(oRec instanceof JsonObject)) {
continue;
}
// TODO: Reuse object
DatabaseObject entity = create(entityName);
// TODO: REVIEW
// set data
entity.load((JsonObject) oRec);
// put record
entity.save();
// clear object
entity.clear();
count++;
}
result.set(entityName, count);
result.set(Database.Fields.Total, Json.getInteger(result, Database.Fields.Total, 0) + count);
}
} finally {
db.declareIntent(null);
}
return result;
}
use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class Find method main.
public static void main(String[] args) throws DatabaseException {
Database db = new DatabaseServer().get();
final JsonArray records = new JsonArray();
JsonObject result = (JsonObject) new JsonObject().set("records", records);
db.find("Cities", new JsonQuery(new JsonObject()), new Database.Visitor() {
@Override
public boolean onRecord(DatabaseObject dbo) {
try {
dbo.set("org", "Labs");
dbo.save();
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
records.add(dbo.toJson(null));
return false;
}
@Override
public boolean optimize() {
return true;
}
});
System.out.println(result);
}
use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class AbstractApiServer method describe.
@Override
public JsonObject describe(DescribeOption... options) {
if (options == null || options.length == 0) {
return JsonObject.Blank;
}
Map<DescribeOption.Option, DescribeOption> opts = DescribeUtils.toMap(options);
JsonObject describe = new JsonObject();
if (opts.containsKey(DescribeOption.Option.info)) {
describe.set(ConfigKeys.Name, Json.getString(descriptor, ConfigKeys.Name));
describe.set(ConfigKeys.Description, Json.getString(descriptor, ConfigKeys.Description));
describe.set(ConfigKeys.Version, Json.getString(descriptor, ConfigKeys.Version));
}
if (opts.containsKey(DescribeOption.Option.keys)) {
JsonObject okeys = keys.toJson().duplicate();
okeys.remove(KeyPair.Fields.SecretKey);
describe.set(DescribeOption.Option.keys.name(), okeys);
}
if (instanceDescriber != null && opts.containsKey(DescribeOption.Option.hardware)) {
describe.set(DescribeOption.Option.hardware.name(), instanceDescriber.describe());
}
// plugins
if (opts.containsKey(DescribeOption.Option.plugins)) {
JsonArray aPlugins = new JsonArray();
describe.set(DescribeOption.Option.plugins.name(), aPlugins);
Iterator<String> pNames = pluginsRegistry.getNames();
while (pNames.hasNext()) {
String pName = pNames.next();
Plugin plugin = pluginsRegistry.lockup(pName);
JsonObject oPlugin = new JsonObject();
oPlugin.set(ConfigKeys.Namespace, plugin.getName());
oPlugin.set(ConfigKeys.Name, plugin.getTitle());
oPlugin.set(ConfigKeys.Description, plugin.getDescription());
oPlugin.set(ConfigKeys.Version, plugin.getVersion());
oPlugin.set(ConfigKeys.Vendor, plugin.getVendor());
aPlugins.add(oPlugin);
}
}
// features
if (opts.containsKey(DescribeOption.Option.features)) {
JsonObject oFeatures = new JsonObject();
describe.set(DescribeOption.Option.features.name(), oFeatures);
for (ServerFeature feature : features.values()) {
String name = feature.type().getAnnotation(Feature.class).name();
JsonArray aVendors = Json.getArray(oFeatures, name);
if (aVendors == null) {
aVendors = new JsonArray();
oFeatures.set(name, aVendors);
}
JsonObject oVendor = new JsonObject();
oVendor.set(Describe.Vendor, feature.implementor().getVendor());
aVendors.add(oVendor);
}
}
// spaces
if (opts.containsKey(DescribeOption.Option.spaces)) {
Collection<ApiSpace> spaces = spaces();
if (spaces != null && !spaces.isEmpty()) {
JsonArray aSpaces = new JsonArray();
describe.set(DescribeOption.Option.spaces.name(), aSpaces);
for (ApiSpace space : spaces) {
aSpaces.add(space.describe(options));
}
}
}
return describe;
}
use of com.bluenimble.platform.json.JsonArray 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();
}
}
use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class ApiImpl method start.
public void start(boolean pause) {
// create classLoader
try {
if (new File(home, ConfigKeys.Folders.Lib).exists() || Json.getArray(descriptor, ConfigKeys.Classpath) != null) {
this.classLoader = new ApiClassLoader(space.getNamespace() + Lang.DOT + getNamespace(), InstallUtils.toUrls(home, Json.getArray(descriptor, ConfigKeys.Classpath)));
}
} catch (Exception ex) {
failed(ex);
}
// start resources manager
try {
resourcesManager.onStart();
} catch (Exception ex) {
failed(ex);
}
// load messages
try {
loadI18n();
} catch (Exception ex) {
failed(ex);
}
// create spi
try {
spi = (ApiSpi) BeanUtils.create(this.getClassLoader(), Json.getObject(descriptor, ConfigKeys.Spi), space.getServer().getPluginsRegistry());
} catch (Exception ex) {
failed(ex);
}
if (spi == null) {
spi = DefaultApiSpi;
}
space.tracer().log(Tracer.Level.Info, "\t Namespace: {0}", getNamespace());
space.tracer().log(Tracer.Level.Info, "\t Name: {0}", getName());
space.tracer().log(Tracer.Level.Info, "\tDescription: {0}", getDescription());
// init tracer
JsonObject oTracer = Json.getObject(descriptor, ConfigKeys.Tracer);
if (!Json.isNullOrEmpty(oTracer)) {
try {
tracer = (Tracer) BeanUtils.create(this.getClassLoader(), oTracer, space.getServer().getPluginsRegistry());
} catch (Exception ex) {
failed(ex);
}
}
tracer.onInstall(this);
ApiContext context = new DefaultApiContext();
try {
// start spi
try {
// initialize any linked datasource
JsonArray datasources = Json.getArray(getRuntime(), DataSources);
if (datasources != null && !datasources.isEmpty()) {
// change classloader
for (int i = 0; i < datasources.count(); i++) {
Recyclable recyclable = space.getRecyclable(RemoteDataSource.class.getAnnotation(Feature.class).name() + Lang.DOT + space.getNamespace() + Lang.DOT + (String) datasources.get(i));
if (recyclable == null) {
continue;
}
// create factory
recyclable.set(space, this.getClassLoader(), (String) datasources.get(i));
}
}
// start api
spi.onStart(this, context);
} catch (Exception ex) {
failed(ex);
}
// start services manager
try {
servicesManager.onStart(context);
} catch (Exception ex) {
failed(ex);
}
} finally {
context.recycle();
}
// update/save status
if (!ApiStatus.Failed.equals(status)) {
setStatus(pause ? ApiStatus.Paused : ApiStatus.Running, true);
if (Lang.isDebugMode()) {
final StringBuilder sb = new StringBuilder(space.getNamespace() + Lang.SLASH + getNamespace() + " available services\n");
servicesManager.list(new Selector() {
@Override
public boolean select(ApiService service) {
sb.append(Lang.TAB).append(Lang.PARENTH_OPEN).append(service.status().name().substring(0, 1)).append(Lang.PARENTH_CLOSE).append(Lang.SPACE).append(service.getVerb()).append(Lang.COLON).append(Json.getString(service.toJson(), ApiService.Spec.Endpoint));
if (ApiStatus.Failed.equals(service.status())) {
sb.append(Lang.ENDLN).append(service.getFailure().toString(2));
}
sb.append(Lang.ENDLN);
return false;
}
});
space.tracer().log(Tracer.Level.Info, sb);
sb.setLength(0);
}
}
space.tracer().log(Tracer.Level.Info, "\tapi {0} {1}", getNamespace(), status);
}
Aggregations