use of com.bluenimble.platform.http.request.HttpRequest in project serverless by bluenimble.
the class RemoteUtils method request.
@SuppressWarnings("unchecked")
private static HttpRequest request(JsonObject oKeys, JsonObject spec, Tool tool, JsonObject config, Map<String, String> options, List<Object> streams) throws Exception {
Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
String service = (String) eval(Json.getString(spec, Spec.request.Service), vars, config, options, oKeys);
HttpRequest request = HttpRequests.get(Json.getString(spec, Spec.request.Method, HttpMethods.GET).toUpperCase()).getConstructor(new Class[] { HttpEndpoint.class }).newInstance(HttpUtils.createEndpoint(new URI(service)));
String contentType = Json.getString(spec, Spec.request.ContentType);
// set headers
List<HttpHeader> headers = request.getHeaders();
if (headers == null) {
headers = new ArrayList<HttpHeader>();
request.setHeaders(headers);
}
JsonObject oHeaders = Json.getObject(spec, Spec.request.Headers);
// add default Accept header application/json
if (oHeaders == null || !oHeaders.containsKey(ApiHeaders.Accept)) {
String accept = (String) vars.get(DefaultVars.RemoteHeadersAccept);
if (Lang.isNullOrEmpty(accept)) {
accept = ApiContentTypes.Json;
}
headers.add(new HttpHeaderImpl(ApiHeaders.Accept, accept));
}
if (oHeaders != null && !oHeaders.isEmpty()) {
Iterator<String> hNames = oHeaders.keys();
while (hNames.hasNext()) {
String hName = hNames.next();
headers.add(new HttpHeaderImpl(hName, String.valueOf(eval(Json.getString(oHeaders, hName), vars, config, options, oKeys))));
}
}
// set parameters
JsonObject oParameters = Json.getObject(spec, Spec.request.Parameters);
if (oParameters != null && !oParameters.isEmpty()) {
List<HttpParameter> parameters = request.getParameters();
if (parameters == null) {
parameters = new ArrayList<HttpParameter>();
request.setParameters(parameters);
}
Iterator<String> pNames = oParameters.keys();
while (pNames.hasNext()) {
String pName = pNames.next();
parameters.add(new HttpParameterImpl(pName, String.valueOf(eval(Json.getString(oParameters, pName), vars, config, options, oKeys))));
}
}
// set body
JsonObject oBody = Json.getObject(spec, Spec.request.Body);
if (oBody != null && !oBody.isEmpty()) {
HttpMessageBody body = new HttpMessageBodyImpl();
request.setBody(body);
Iterator<String> bNames = oBody.keys();
while (bNames.hasNext()) {
String bName = bNames.next();
Object value = eval(Json.getString(oBody, bName), vars, config, options, oKeys);
if (value == null) {
continue;
}
if (ContentTypes.Json.equals(contentType)) {
Object ov = null;
String varName = String.valueOf(value);
if (EmptyPayload.equals(varName)) {
ov = JsonObject.Blank;
} else {
ov = ((Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS)).get(varName);
if (ov == null) {
throw new Exception("variable " + value + " not found");
}
if (!(ov instanceof JsonObject)) {
throw new Exception(value + " isn't a valid json object");
}
}
body.add(new StringHttpMessageBodyPart(ov.toString()));
continue;
}
String fileName = null;
InputStream stream = null;
if (value instanceof File) {
File file = (File) value;
fileName = file.getName();
stream = new FileInputStream(file);
streams.add(stream);
} else if (value instanceof StreamPointer) {
StreamPointer sp = (StreamPointer) value;
fileName = sp.getPointer().getName();
stream = sp.getStream();
streams.add(sp);
} else if (value instanceof String) {
tool.printer().info("Api File/Folder ==> " + value);
File file = new File((String) value);
if (!file.exists()) {
continue;
// throw new Exception ("file or folder '" + value + "' doesn't exist");
}
fileName = file.getName();
if (file.isFile()) {
stream = new FileInputStream(file);
streams.add(stream);
} else if (file.isDirectory()) {
fileName += ".api";
File zipFile = new File(BlueNimble.Work, Lang.UUID(20) + ".api");
ArchiveUtils.compress(file, zipFile, true, new ArchiveUtils.CompressVisitor() {
@Override
public boolean onAdd(File file) {
if (file.getName().startsWith(Lang.DOT)) {
return false;
}
return true;
}
});
StreamPointer sp = new StreamPointer(zipFile, true);
streams.add(sp);
stream = sp.getStream();
}
}
body.add(new InputStreamHttpMessageBodyPart(bName, fileName, stream));
}
}
if (request.getBody() != null && request.getBody().count() == 0) {
request.setBody(null);
}
// set content type
if (!Lang.isNullOrEmpty(contentType)) {
if (ApiContentTypes.Multipart.equals(contentType)) {
if (request.getBody() != null) {
request.setContentType(contentType);
}
} else {
request.setContentType(contentType);
}
}
// sign request
boolean sign = Json.getBoolean(spec, Spec.request.Sign, true);
if (sign) {
String space = Json.getString(oKeys, Keys.Spec.Space);
String accessKey = Json.getString(oKeys, KeyPair.Fields.AccessKey);
String secretKey = Json.getString(oKeys, KeyPair.Fields.SecretKey);
AccessSecretKeysBasedHttpRequestSigner signer = new AccessSecretKeysBasedHttpRequestSigner("m>h>p>d>k>t", "Bearer", space == null ? accessKey : space + Lang.DOT + accessKey, secretKey);
String timestamp = Lang.utc();
headers.add(new HttpHeaderImpl(ApiHeaders.Timestamp, timestamp));
signer.getData().put('t', timestamp);
signer.sign(request);
}
if (Lang.isDebugMode()) {
tool.printer().content("Http Request", request.toString());
}
return request;
}
use of com.bluenimble.platform.http.request.HttpRequest in project serverless by bluenimble.
the class RemoteUtils method processRequest.
public static CommandResult processRequest(Tool tool, JsonObject source, final Map<String, String> options) throws CommandExecutionException {
if (Lang.isDebugMode()) {
tool.printer().content("Remote Command", source.toString());
}
JsonObject oKeys = null;
Keys keys = BlueNimble.keys();
if (keys != null) {
oKeys = keys.json();
} else {
oKeys = new JsonObject();
}
@SuppressWarnings("unchecked") Map<String, Object> vars = (Map<String, Object>) tool.getContext(Tool.ROOT_CTX).get(ToolContext.VARS);
Object oTrustAll = vars.get(DefaultVars.SslTrust);
if (oTrustAll == null) {
Http.setTrustAll(false);
} else {
Http.setTrustAll(Lang.TrueValues.contains(String.valueOf(oTrustAll)));
}
boolean isOutFile = AbstractTool.CMD_OUT_FILE.equals(vars.get(AbstractTool.CMD_OUT));
List<Object> streams = new ArrayList<Object>();
HttpResponse response = null;
try {
HttpRequest request = request(oKeys, Json.getObject(source, Spec.request.class.getSimpleName()), tool, BlueNimble.Config, options, streams);
response = Http.send(request);
String contentType = response.getContentType();
if (contentType == null) {
contentType = ApiContentTypes.Text;
}
int indexOfSemi = contentType.indexOf(Lang.SEMICOLON);
if (indexOfSemi > 0) {
contentType = contentType.substring(0, indexOfSemi).trim();
}
OutputStream out = System.out;
if (Printable.contains(contentType) && !isOutFile) {
out = new ByteArrayOutputStream();
response.getBody().dump(out, Encodings.UTF8, null);
}
List<HttpHeader> rHeaders = response.getHeaders();
if (rHeaders != null && !rHeaders.isEmpty()) {
JsonObject oHeaders = new JsonObject();
for (HttpHeader h : rHeaders) {
oHeaders.set(h.getName(), Lang.join(h.getValues(), Lang.COMMA));
}
vars.put(RemoteResponseHeaders, oHeaders);
}
if (contentType.startsWith(ApiContentTypes.Json)) {
JsonObject result = new JsonObject(new String(((ByteArrayOutputStream) out).toByteArray()));
String trace = null;
if (response.getStatus() >= 400) {
trace = result.getString("trace");
result.remove("trace");
}
if (trace != null && Lang.isDebugMode()) {
vars.put(RemoteResponseError, trace);
}
if (response.getStatus() < 400) {
return new DefaultCommandResult(CommandResult.OK, result);
} else {
return new DefaultCommandResult(CommandResult.KO, result);
}
} else if (contentType.startsWith(ApiContentTypes.Yaml)) {
Yaml yaml = new Yaml();
String ys = new String(((ByteArrayOutputStream) out).toByteArray());
ys = Lang.replace(ys, Lang.TAB, " ");
@SuppressWarnings("unchecked") Map<String, Object> map = yaml.loadAs(ys, Map.class);
Object trace = null;
if (response.getStatus() >= 400) {
trace = map.get("trace");
map.remove("trace");
}
if (trace != null && Lang.isDebugMode()) {
vars.put(RemoteResponseError, trace);
}
if (response.getStatus() < 400) {
return new DefaultCommandResult(CommandResult.OK, new YamlObject(map));
} else {
return new DefaultCommandResult(CommandResult.KO, new YamlObject(map));
}
} else if (contentType.startsWith(ApiContentTypes.Text) || contentType.startsWith(ApiContentTypes.Html)) {
String content = new String(((ByteArrayOutputStream) out).toByteArray());
if (response.getStatus() < 400) {
return new DefaultCommandResult(CommandResult.OK, content);
} else {
return new DefaultCommandResult(CommandResult.KO, content);
}
} else {
if (response.getStatus() < 400) {
if (isOutFile) {
return new DefaultCommandResult(CommandResult.OK, response.getBody().get(0).toInputStream());
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getBody().dump(baos, Encodings.UTF8, null);
return new DefaultCommandResult(CommandResult.OK, new String(((ByteArrayOutputStream) baos).toByteArray()));
}
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getBody().dump(baos, Encodings.UTF8, null);
return new DefaultCommandResult(CommandResult.KO, new String(((ByteArrayOutputStream) baos).toByteArray()));
}
}
} catch (Exception e) {
throw new CommandExecutionException(e.getMessage(), e);
} finally {
if (streams != null) {
for (Object s : streams) {
if (s instanceof InputStream) {
IOUtils.closeQuietly((InputStream) s);
} else if (s instanceof StreamPointer) {
StreamPointer sp = (StreamPointer) s;
IOUtils.closeQuietly(sp.getStream());
if (sp.shouldDelete()) {
try {
FileUtils.delete(sp.getPointer());
} catch (IOException e) {
// IGNORE
}
}
}
}
}
}
}
Aggregations