use of com.bluenimble.platform.http.response.HttpResponse in project serverless by bluenimble.
the class SimplePostRequest method main.
public static void main(String[] args) throws Exception {
JsonObject spec = (JsonObject) new JsonObject().set("url", "http://discuss.bluenimble.com/api/users").set("headers", new JsonObject().set("Content-Type", "application/json").set("Authorization", "Token 3NpuOJs7BBYcUVyKswLQ1d7ETfvzTsJixSHZcFSm")).set("data", new JsonObject().set("data", new JsonObject().set("attributes", new JsonObject().set("username", "Simo").set("email", "loukili.mohammed@gmail.com").set("password", "Alph@2016"))));
HttpResponse response = Http.post(spec, null);
System.out.println("Status: " + response.getStatus());
HttpMessageBody body = response.getBody();
if (body == null || body.count() == 0) {
throw new Exception("response body is empty");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
body.dump(out, "UTF-8", null);
System.out.println(new JsonObject(new String(out.toByteArray())));
}
use of com.bluenimble.platform.http.response.HttpResponse in project serverless by bluenimble.
the class SimpleGetRequest method main.
public static void main(String[] args) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
GetRequest request = new GetRequest(HttpUtils.createEndpoint(new URI("https://api.indix.com/v2/summary/products?countryCode=US&app_id=2a4049dd&app_key=444978937e94a8adebdcd701660da344")));
request.getParameters().add(new HttpParameterImpl("q", "hello kitty"));
HttpResponse response = client.send(request);
response.getBody().dump(System.out, "utf-8", null);
}
use of com.bluenimble.platform.http.response.HttpResponse in project serverless by bluenimble.
the class OAuthServiceSpi method execute.
@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
JsonObject config = request.getService().getCustom();
JsonObject providers = Json.getObject(config, Providers);
JsonObject provider = Json.getObject(providers, (String) request.get(Spec.Provider));
if (provider == null || provider.isEmpty()) {
throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + " not supported").status(ApiResponse.NOT_ACCEPTABLE);
}
JsonObject oAuthKeys = Json.getObject(provider, OAuth.Keys);
if (oAuthKeys == null || oAuthKeys.isEmpty()) {
throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". client_id and client_secret not found").status(ApiResponse.NOT_ACCEPTABLE);
}
JsonObject oAuthEndpoints = Json.getObject(provider, OAuth.Endpoints);
if (oAuthEndpoints == null || oAuthEndpoints.isEmpty()) {
throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". oAuth endpoints authorize and profile not configured").status(ApiResponse.NOT_ACCEPTABLE);
}
JsonObject endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Authorize);
if (endpoint == null || endpoint.isEmpty()) {
throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". oAuth authorize endpoint not configured").status(ApiResponse.NOT_ACCEPTABLE);
}
JsonObject data = (JsonObject) new JsonObject().set(OAuth.Code, request.get(Spec.AuthCode)).set(OAuth.ClientId, Json.getString(oAuthKeys, OAuth.ClientId)).set(OAuth.ClientSecret, Json.getString(oAuthKeys, OAuth.ClientSecret));
if (provider.containsKey(OAuth.Redirect)) {
data.set(OAuth.RedirectUri, Json.getString(provider, OAuth.Redirect));
}
JsonObject params = Json.getObject(endpoint, OAuth.Endpoint.Parameters);
if (params != null && !params.isEmpty()) {
Iterator<String> keys = params.keys();
while (keys.hasNext()) {
String p = keys.next();
data.set(p, params.get(p));
}
}
JsonObject hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
HttpResponse hResponse = null;
try {
hResponse = Http.post(hRequest, null);
} catch (HttpClientException e) {
throw new ApiServiceExecutionException(e.getMessage(), e);
}
if (hResponse.getStatus() != 200) {
throw new ApiServiceExecutionException("invalid authorization code");
}
InputStream out = hResponse.getBody().get(0).toInputStream();
JsonObject oAuthResult = null;
try {
oAuthResult = new JsonObject(out);
} catch (Exception e) {
throw new ApiServiceExecutionException(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(out);
}
// get profile
endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Profile);
if (endpoint == null || endpoint.isEmpty()) {
return new JsonApiOutput(oAuthResult);
}
String accessToken = Json.getString(oAuthResult, OAuth.AccessToken);
data.clear();
data.set(OAuth.AccessToken, accessToken);
hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
try {
hResponse = Http.post(hRequest, null);
} catch (HttpClientException e) {
throw new ApiServiceExecutionException(e.getMessage(), e);
}
if (hResponse.getStatus() != 200) {
throw new ApiServiceExecutionException("invalid access token");
}
out = hResponse.getBody().get(0).toInputStream();
try {
oAuthResult = new JsonObject(out);
} catch (Exception e) {
throw new ApiServiceExecutionException(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(out);
}
// email endpoint
endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Email);
if (endpoint == null || endpoint.isEmpty()) {
return new JsonApiOutput(oAuthResult);
}
hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
try {
hResponse = Http.post(hRequest, null);
} catch (HttpClientException e) {
throw new ApiServiceExecutionException(e.getMessage(), e);
}
if (hResponse.getStatus() != 200) {
throw new ApiServiceExecutionException("invalid access token");
}
out = hResponse.getBody().get(0).toInputStream();
JsonObject oEmail = null;
try {
oEmail = new JsonObject(out);
} catch (Exception e) {
throw new ApiServiceExecutionException(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(out);
}
Iterator<String> keys = oEmail.keys();
while (keys.hasNext()) {
String k = keys.next();
oAuthResult.set(k, oEmail.get(k));
}
// call extend if any
JsonObject onFinish = Json.getObject(config, Config.onFinish.class.getSimpleName());
ApiOutput onFinishOutput = SecurityUtils.onFinish(api, consumer, request, onFinish, oAuthResult);
if (onFinishOutput != null) {
oAuthResult.set(Json.getString(onFinish, Config.onFinish.ResultProperty, Config.onFinish.class.getSimpleName()), onFinishOutput.data());
}
return new JsonApiOutput(oAuthResult);
}
use of com.bluenimble.platform.http.response.HttpResponse 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
}
}
}
}
}
}
}
use of com.bluenimble.platform.http.response.HttpResponse in project serverless by bluenimble.
the class BnMgmICli method download.
private static boolean download() {
JsonObject endpoints = Json.getObject(Software, Spec.endpoints.class.getSimpleName());
String uVersion = Json.getString(endpoints, Spec.endpoints.Version);
if (Lang.isNullOrEmpty(uVersion)) {
return false;
}
String uDownload = Json.getString(endpoints, Spec.endpoints.Download);
if (Lang.isNullOrEmpty(uDownload)) {
return false;
}
System.out.println("\n Checking for a newer version of the software ...");
try {
HttpResponse response = Http.send(new GetRequest(HttpUtils.createEndpoint(new URI(uVersion))));
if (response.getStatus() != 200) {
System.out.println("\n Warning: Unable to get software version!");
return false;
}
OutputStream out = new ByteArrayOutputStream();
response.getBody().dump(out, Encodings.UTF8, null);
JsonObject oVersion = new JsonObject(new String(((ByteArrayOutputStream) out).toByteArray()));
if (version(oVersion) > CliUtils.iVersion(Home)) {
String newVersion = Json.getString(oVersion, Spec.version.Major) + Lang.DOT + Json.getString(oVersion, Spec.version.Minor) + Lang.DOT + Json.getString(oVersion, Spec.version.Patch, "0");
System.out.println("\n Newer version found " + newVersion);
System.out.println("\n Download [" + newVersion + "]");
GetRequest downloadRequest = new GetRequest(HttpUtils.createEndpoint(new URI(uDownload)));
response = Http.send(downloadRequest);
if (response.getStatus() != 200) {
return false;
}
OutputStream os = null;
try {
os = new FileOutputStream(new File(Home, Json.getString(Software, Spec.Package)));
IOUtils.copy(response.getBody().get(0).toInputStream(), os);
} finally {
IOUtils.closeQuietly(os);
}
System.out.println("\n Boot using the new version ...\n");
return true;
}
System.out.println("\n Software is up to date!\n");
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return false;
}
Aggregations