use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class Json method resolve.
public static Object resolve(Object obj, ExpressionCompiler compiler, VariableResolver vr) {
if (obj == null || vr == null) {
return obj;
}
if (obj instanceof JsonObject) {
JsonObject o = (JsonObject) obj;
if (o.isEmpty()) {
return o;
}
Iterator<String> keys = o.keys();
while (keys.hasNext()) {
String key = keys.next();
o.set(key, resolve(o.get(key), compiler, vr));
}
return o;
} else if (obj instanceof JsonArray) {
JsonArray array = (JsonArray) obj;
for (int i = 0; i < array.count(); i++) {
Object resolved = resolve(array.get(i), compiler, vr);
array.remove(i);
array.add(i, resolved);
}
return array;
} else {
String exp = String.valueOf(obj);
if (Lang.isNullOrEmpty(exp)) {
return obj;
}
return compiler.compile(exp, null).eval(vr);
}
}
use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class Lang method toError.
public static JsonObject toError(Throwable th) {
if (th == null) {
return null;
}
Throwable first = th;
th = Lang.getRootCause(th);
String message = th.getMessage();
if (message == null) {
StackTraceElement ste = th.getStackTrace()[0];
message = th.getClass().getSimpleName() + Lang.GREATER + Lang.SPACE + ste.getClassName() + Lang.SPACE + ", Method: " + ste.getMethodName() + ", Line: " + ste.getLineNumber();
}
JsonObject error = new JsonObject();
error.set(ApiResponse.Error.Message, message);
if (!Lang.isDebugMode()) {
return error;
}
JsonArray trace = new JsonArray();
error.set(ApiResponse.Error.Trace, trace);
if (th instanceof NashornException) {
if (UndefinedMessage.equals(message)) {
error.set(ApiResponse.Error.Message, UndefinedMessage + " variable");
} else if (message.startsWith(TypeError)) {
error.set(ApiResponse.Error.Message, Lang.replace(message, TypeError, Lang.BLANK));
}
readNashornError(th, first, trace);
return error;
}
StackTraceElement[] stack = th.getStackTrace();
for (StackTraceElement line : stack) {
JsonObject oLine = new JsonObject();
trace.add(oLine);
oLine.set(ApiResponse.Error.Line, line.getLineNumber());
oLine.set(ApiResponse.Error.Function, line.getMethodName());
String className = line.getClassName();
int indeOfNashornScript = className.indexOf(NashornScript);
if (indeOfNashornScript > 0) {
String file = line.getFileName();
// if the error is coming from the platform core scripts
int indexOfPath = file.indexOf(PlatformPath);
if (indexOfPath <= 0) {
indexOfPath = file.indexOf(ApiResourcePath);
}
if (indexOfPath > 0) {
file = file.substring(indexOfPath);
}
oLine.set(ApiResponse.Error.File, file);
// break here
break;
} else {
int indexOfDot = className.lastIndexOf(Lang.DOT);
if (indexOfDot > 0) {
className = className.substring(indexOfDot + 1);
}
oLine.set(ApiResponse.Error.Clazz, className);
}
}
return error;
}
use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class CreateEntitySpi method execute.
@Override
public ApiOutput execute(Api api, final ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
String provider = (String) request.get(CommonSpec.Provider);
String sEntity = (String) request.get(CommonSpec.Entity);
ApiSpace space;
try {
space = MgmUtils.space(consumer, api);
} catch (ApiAccessDeniedException e) {
throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
}
JsonObject payload = (JsonObject) request.get(ApiRequest.Payload);
JsonArray aFields = Json.getArray(payload, CommonSpec.Fields);
if (aFields == null || aFields.isEmpty()) {
throw new ApiServiceExecutionException("missing fields definition").status(ApiResponse.BAD_REQUEST);
}
Field[] fields = new Field[aFields.count()];
for (int i = 0; i < aFields.count(); i++) {
Object o = aFields.get(i);
if (o == null || !(o instanceof JsonObject)) {
continue;
}
final JsonObject oField = (JsonObject) o;
fields[i] = new Field() {
@Override
public String name() {
return Json.getString(oField, Spec.Field.Name);
}
@Override
public boolean required() {
return Json.getBoolean(oField, Spec.Field.Required, false);
}
@Override
public Type type() {
try {
return Type.valueOf(Json.getString(oField, Spec.Field.Type, Type.String.name()));
} catch (Exception ex) {
return Type.String;
}
}
@Override
public boolean unique() {
return Json.getBoolean(oField, Spec.Field.Unique, false);
}
};
}
try {
Database db = space.feature(Database.class, provider, request);
db.createEntity(sEntity, fields);
} catch (DatabaseException e) {
throw new ApiServiceExecutionException(e.getMessage(), e);
} catch (Exception e) {
throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.NOT_FOUND);
}
return new JsonApiOutput((JsonObject) new JsonObject().set(CommonOutput.Dropped, true));
}
use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class JettyPlugin method init.
@Override
public void init(final ApiServer server) throws Exception {
Log.setLog(new JettyLogger(this));
// load favicon
InputStream favicon = null;
try {
favicon = new FileInputStream(new File(home, FavIcon));
FavIconContent = IOUtils.toByteArray(favicon);
} finally {
IOUtils.closeQuietly(favicon);
}
Integer poolIdleTimeout = Json.getInteger(pool, Pool.IdleTimeout, 300);
/*
It is very important to limit the task queue of Jetty. By default, the queue is unbounded! As a result,
if under high load in excess of the processing power of the webapp, jetty will keep a lot of requests on the queue.
Even after the load has stopped, Jetty will appear to have stopped responding to new requests as it still has lots of requests on
the queue to handle.
For a high reliability system, it should reject the excess requests immediately (fail fast) by using a queue with
a bounded capability. The capability (maximum queue length) should be calculated according to the "no-response" time tolerable.
For example, if the webapp can handle 100 requests per second, and if you can allow it one minute to recover from excessive high load,
you can set the queue capability to 60*100=6000. If it is set too low, it will reject requests too soon and can't handle normal load
spike.
Below is a sample configuration:
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<Set name="ThreadPool">
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<!-- specify a bounded queue -->
<Arg>
<New class="java.util.concurrent.ArrayBlockingQueue">
<Arg type="int">6000</Arg>
</New>
</Arg>
<Set name="minThreads">10</Set>
<Set name="maxThreads">200</Set>
<Set name="detailedDump">false</Set>
</New>
</Set>
</Configure>
Configure the number of threads according to the webapp.
That is, how many threads it needs in order to achieve the best performance.
Configure with mind to limiting memory usage maximum available. Typically >50 and <500.
*/
int capacity = server.weight() + 2;
QueuedThreadPool tp = new QueuedThreadPool(capacity, capacity, poolIdleTimeout * 1000, new ArrayBlockingQueue<Runnable>(capacity * 2));
tp.setDetailedDump(false);
tp.setThreadsPriority(Thread.NORM_PRIORITY);
httpServer = new Server(tp);
ServerConnector connector = new ServerConnector(httpServer);
connector.setPort(port);
connector.setIdleTimeout(idleTimeout * 1000);
httpServer.addConnector(connector);
if (ssl != null && !Lang.isNullOrEmpty(ssl.getString(Ssl.Keystore)) && !Lang.isNullOrEmpty(ssl.getString(Ssl.Password))) {
HttpConfiguration https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(new File(ssl.getString(Ssl.Keystore)).getAbsolutePath());
sslContextFactory.setKeyStorePassword(Json.getString(ssl, Ssl.Password));
sslContextFactory.setKeyManagerPassword(Json.getString(ssl, Ssl.StorePassword, Json.getString(ssl, Ssl.Password)));
sslContextFactory.setKeyStoreType(Json.getString(ssl, Ssl.StoreType, "JKS"));
String[] aCiphers = null;
// include ciphers
JsonArray ciphers = Json.getArray(Json.getObject(ssl, Ssl.ciphers.class.getSimpleName()), Ssl.ciphers.Include);
if (ciphers != null && !ciphers.isEmpty()) {
aCiphers = new String[ciphers.count()];
for (int i = 0; i < ciphers.count(); i++) {
aCiphers[i] = (String) ciphers.get(i);
}
sslContextFactory.setIncludeCipherSuites(aCiphers);
}
// exclude ciphers
ciphers = Json.getArray(Json.getObject(ssl, Ssl.ciphers.class.getSimpleName()), Ssl.ciphers.Exclude);
if (ciphers != null && !ciphers.isEmpty()) {
aCiphers = new String[ciphers.count()];
for (int i = 0; i < ciphers.count(); i++) {
aCiphers[i] = (String) ciphers.get(i);
}
sslContextFactory.setExcludeCipherSuites(aCiphers);
}
ServerConnector sslConnector = new ServerConnector(httpServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https));
int sslPort = Json.getInteger(ssl, Ssl.Port, 443);
sslConnector.setPort(sslPort);
sslConnector.setIdleTimeout(Json.getInteger(ssl, Ssl.IdleTimeout, idleTimeout) * 1000);
httpServer.addConnector(sslConnector);
}
for (Connector cn : httpServer.getConnectors()) {
for (ConnectionFactory x : cn.getConnectionFactories()) {
if (x instanceof HttpConnectionFactory) {
((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(false);
((HttpConnectionFactory) x).getHttpConfiguration().setSendXPoweredBy(false);
}
}
}
ServletContextHandler sContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
sContext.setContextPath(context);
if (gzip) {
sContext.setGzipHandler(new GzipHandler());
}
httpServer.setHandler(sContext);
ServletHolder apiHolder = new ServletHolder(new HttpServlet() {
private static final long serialVersionUID = -4391155835460802144L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (FavIconPath.equals(req.getRequestURI())) {
resp.getOutputStream().write(FavIconContent);
return;
}
execute(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
execute(req, resp);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
execute(req, resp);
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
execute(req, resp);
}
protected void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
ApiRequest request = new HttpApiRequest(req, tracer());
request.getNode().set(ApiRequest.Fields.Node.Id, server.id());
request.getNode().set(ApiRequest.Fields.Node.Type, server.type());
request.getNode().set(ApiRequest.Fields.Node.Version, server.version());
server.execute(request, new HttpApiResponse(request.getNode(), request.getId(), resp), CodeExecutor.Mode.Async);
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
});
sContext.addServlet(apiHolder, Lang.SLASH + Lang.STAR);
// cross origin
FilterHolder holder = new FilterHolder(CORSFilter.class);
holder.setName("CORS");
holder.setInitParameter("cors.supportedMethods", "GET, POST, HEAD, PUT, DELETE, PATCH, OPTIONS");
holder.setInitParameter("cors.exposedHeaders", "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With,BN-Execution-Time,BN-Node-Id,BN-Node-Type");
sContext.addFilter(holder, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.REQUEST, DispatcherType.ERROR));
// monitor
if (monitor) {
MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
httpServer.addEventListener(mbContainer);
httpServer.addBean(mbContainer);
httpServer.addBean(Log.getLog());
}
// start server
httpServer.start();
httpServer.join();
}
use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.
the class SecurityUtils method salt.
private static String salt(Api api, JsonObject entity) {
JsonArray fields = Json.getArray(api.getSecurity(), Api.Spec.Security.Encrypt);
if (fields == null || fields.isEmpty()) {
return String.valueOf(entity.get(Database.Fields.Id));
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fields.count(); i++) {
Object v = Json.find(entity, Lang.split(String.valueOf(fields.get(i)), Lang.DOT));
if (v != null) {
sb.append(String.valueOf(v));
}
if (i < (fields.count() - 1)) {
sb.append(Lang.SEMICOLON);
}
}
String salt = sb.toString();
sb.setLength(0);
return salt;
}
Aggregations