use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.
the class SmtpMessengerPlugin method dropSessions.
private void dropSessions(ApiSpace space) {
JsonObject msgFeature = Json.getObject(space.getFeatures(), feature);
Set<String> recyclables = space.getRecyclables();
for (String r : recyclables) {
if (!r.startsWith(feature + Lang.DOT)) {
continue;
}
String name = r.substring((feature + Lang.DOT).length());
if (msgFeature == null || msgFeature.containsKey(name)) {
// it's deleted
RecyclableMessenger rm = (RecyclableMessenger) space.getRecyclable(r);
// remove from recyclables
space.removeRecyclable(r);
// recycle
rm.recycle();
}
}
}
use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.
the class HttpRemote method sign.
private Request sign(Request request, JsonObject spec, List<RequestParameter> parameters) throws Exception {
if (!spec.containsKey(Spec.Sign)) {
return request;
}
Object sign = Json.getObject(spec, Spec.Sign);
if (!(sign instanceof JsonObject)) {
return request;
}
JsonObject oSign = (JsonObject) sign;
String signer = Json.getString(oSign, Spec.SignProtocol, Signers.OAuth).toLowerCase();
if (Signers.OAuth.equals(signer)) {
String key = Json.getString(oSign, Spec.SignKey);
if (Lang.isNullOrEmpty(key)) {
throw new Exception("oauth consumer key not found in spec");
}
String secret = Json.getString(oSign, Spec.SignSecret);
if (Lang.isNullOrEmpty(secret)) {
throw new Exception("oauth consumer secret not found in spec");
}
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(key, secret);
String token = Json.getString(oSign, Spec.SignToken);
if (!Lang.isNullOrEmpty(token)) {
String tokenSecret = Json.getString(oSign, Spec.SignTokenSecret);
if (Lang.isNullOrEmpty(tokenSecret)) {
throw new Exception("oauth token secret not found in spec");
}
consumer.setTokenWithSecret(token, secret);
}
return (Request) consumer.sign(request).unwrap();
} else if (Signers.Bnb.equals(signer)) {
// bnb sign
String key = Json.getString(oSign, Spec.SignKey);
if (Lang.isNullOrEmpty(key)) {
throw new Exception("bnb key not found in spec");
}
String secret = Json.getString(oSign, Spec.SignSecret);
if (Lang.isNullOrEmpty(secret)) {
throw new Exception("bnb secret not found in spec");
}
return BnBSigner.sign(request, parameters, oSign);
} else if (Signers.Basic.equals(signer)) {
// bnb sign
String user = Json.getString(oSign, Spec.User);
if (Lang.isNullOrEmpty(user)) {
throw new Exception("basic-auth user not found in spec");
}
String password = Json.getString(oSign, Spec.Password);
if (Lang.isNullOrEmpty(password)) {
throw new Exception("basic-auth password not found in spec");
}
return request.newBuilder().header(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64String((user + Lang.COLON + password).getBytes())).trim()).build();
} else {
throw new Exception("unsupported signature protocol " + signer);
}
}
use of com.bluenimble.platform.json.JsonObject 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();
}
}
}
use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.
the class AccessSecretKeysBasedHttpRequestSigner method sign.
// private static final String DefaultSignatureName = "Signature";
// private static final PlaceHolder
// DefaultPlaceHolder = PlaceHolder.header;
public Request sign(Request request, List<RequestParameter> params, JsonObject spec) throws Exception {
JsonObject replace = Json.getObject(spec, Remote.Spec.SignReplace);
String timestamp = Lang.utc();
String signature = null;
try {
URI uri = request.url().uri();
signature = generate(params, spec, timestamp, resolve(uri.getScheme() + "://" + uri.getHost(), replace), uri.getPort(), resolve(uri.getPath(), replace), request.method());
} catch (Throwable th) {
throw new Exception(th);
}
// placeholder
PlaceHolder placeholder = PlaceHolder.header;
try {
placeholder = PlaceHolder.valueOf(Json.getString(spec, Remote.Spec.SignPlaceholder, PlaceHolder.header.name()));
} catch (Exception ex) {
/* Ignore */
}
if (placeholder.equals(PlaceHolder.header)) {
return request.newBuilder().header(HttpHeaders.AUTHORIZATION, Json.getString(spec, Remote.Spec.SignScheme, DefaultScheme) + " " + Json.getString(spec, Remote.Spec.SignKey) + ":" + signature).header(ApiHeaders.Timestamp, timestamp).build();
}
return request;
}
use of com.bluenimble.platform.json.JsonObject in project serverless by bluenimble.
the class AccessSecretKeysBasedHttpRequestSigner method generate.
private String generate(List<RequestParameter> params, JsonObject oSpec, String timestamp, String host, int port, String path, String verb) throws Exception {
String sParams = buildParameters(params);
StringBuilder sb = new StringBuilder();
String accessKey = Json.getString(oSpec, Remote.Spec.SignKey);
String secretKey = Json.getString(oSpec, Remote.Spec.SignSecret);
String payload = Json.getString(oSpec, Remote.Spec.SignPayload, DefaultPayload);
JsonObject data = Json.getObject(oSpec, Remote.Spec.SignData);
if (payload != null) {
char[] chars = payload.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'm') {
sb.append(verb);
} else if (chars[i] == 'h') {
sb.append(host);
if (port > 0) {
sb.append(Lang.COLON).append(String.valueOf(port));
}
} else if (chars[i] == 'p') {
sb.append(path);
} else if (chars[i] == 'd') {
sb.append(sParams);
} else if (chars[i] == 'k') {
sb.append(accessKey);
} else if (chars[i] == '>') {
sb.append(Lang.ENDLN);
} else if (chars[i] == 't') {
sb.append(timestamp);
} else {
String d = Json.getString(data, String.valueOf(chars[i]));
if (d != null) {
sb.append(d);
} else {
sb.append(String.valueOf(chars[i]));
}
}
}
}
String toSign = sb.toString();
sb.setLength(0);
sb = null;
System.out.println("====SING====");
System.out.println(toSign);
System.out.println("====SING====");
byte[] bsecret = (Lang.isNullOrEmpty(secretKey) ? null : secretKey.getBytes(DataSigner.UTF8));
String signature = DataSigner.sign(toSign.getBytes(DataSigner.UTF8), bsecret, Json.getString(oSpec, Remote.Spec.SignAlgorithm, DefaultSignatureAlgorithm), Json.getString(oSpec, Remote.Spec.SignHashing, DefaultHashingAlgorithm), DataSigner.UTF8);
return signature;
}
Aggregations