List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:io.imoji.sdk.objects.json.CategoryResultsDeserializer.java
License:Open Source License
@Override public CategoriesResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject root = json.getAsJsonObject(); JsonArray categories = root.getAsJsonArray("categories"); List<Category> converted; if (categories.size() > 0) { converted = new ArrayList<>(categories.size()); for (JsonElement c : categories) { converted.add(context.<Category>deserialize(c, Category.class)); }/*from w w w .j av a 2 s . co m*/ } else { converted = Collections.emptyList(); } return new CategoriesResponse(converted); }
From source file:io.imoji.sdk.objects.json.ImojiDeserializer.java
License:Open Source License
@Override public Imoji deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject root = json.getAsJsonObject(); String identifier;//from w w w .j av a2 s . c om if (root.has("imojiId")) { identifier = root.get("imojiId").getAsString(); } else { identifier = root.get("id").getAsString(); } JsonArray tagsArray = root.getAsJsonArray("tags"); List<String> tags; if (tagsArray != null && tagsArray.size() > 0) { tags = new ArrayList<>(tagsArray.size()); for (JsonElement tag : tagsArray) { tags.add(tag.getAsString()); } } else { tags = Collections.emptyList(); } Imoji.LicenseStyle licenseStyle = Imoji.LicenseStyle.NonCommercial; if (root.has("licenseStyle")) { String licenseStyleStr = root.get("licenseStyle").getAsString(); if ("commercialPrint".equals((licenseStyleStr))) { licenseStyle = Imoji.LicenseStyle.CommercialPrint; } } Map<RenderingOptions, Imoji.Metadata> metadataMap = new HashMap<>(); JsonObject images = root.get("images").getAsJsonObject(); for (RenderingOptions.BorderStyle borderStyle : RenderingOptions.BorderStyle.values()) { for (RenderingOptions.ImageFormat imageFormat : RenderingOptions.ImageFormat.values()) { for (RenderingOptions.Size size : RenderingOptions.Size.values()) { JsonObject subDocument; switch (borderStyle) { case Sticker: subDocument = images.getAsJsonObject("bordered"); break; case None: if (imageFormat == RenderingOptions.ImageFormat.AnimatedGif || imageFormat == RenderingOptions.ImageFormat.AnimatedWebp) { subDocument = images.getAsJsonObject("animated"); } else { subDocument = images.getAsJsonObject("unbordered"); } break; default: subDocument = null; break; } if (subDocument == null) { continue; } switch (imageFormat) { case Png: subDocument = subDocument.getAsJsonObject("png"); break; case WebP: case AnimatedWebp: subDocument = subDocument.getAsJsonObject("webp"); break; case AnimatedGif: subDocument = subDocument.getAsJsonObject("gif"); break; } if (subDocument == null) { continue; } switch (size) { case Thumbnail: subDocument = subDocument.getAsJsonObject("150"); break; case FullResolution: subDocument = subDocument.getAsJsonObject("1200"); break; case Resolution320: subDocument = subDocument.getAsJsonObject("320"); break; case Resolution512: subDocument = subDocument.getAsJsonObject("512"); break; } if (subDocument != null) { Uri url = Uri.parse(subDocument.get("url").getAsString()); Integer width = null, height = null, fileSize = null; if (subDocument.has("width")) { JsonElement widthObj = subDocument.get("width"); if (widthObj.isJsonPrimitive()) { width = widthObj.getAsInt(); } } if (subDocument.has("height")) { JsonElement heightObj = subDocument.get("height"); if (heightObj.isJsonPrimitive()) { height = heightObj.getAsInt(); } } if (subDocument.has("fileSize")) { JsonElement fileSizeObj = subDocument.get("fileSize"); if (fileSizeObj.isJsonPrimitive()) { fileSize = fileSizeObj.getAsInt(); } } metadataMap.put(new RenderingOptions(borderStyle, imageFormat, size), new Imoji.Metadata(url, width, height, fileSize)); } } } } return new Imoji(identifier, tags, metadataMap, licenseStyle); }
From source file:io.imoji.sdk.objects.json.ImojiResultsDeserializer.java
License:Open Source License
@Override public ImojisResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject root = json.getAsJsonObject(); List<Imoji> imojis = new ArrayList<>(); if (root.has("results")) { JsonArray results = root.getAsJsonArray("results"); for (JsonElement result : results) { imojis.add(context.<Imoji>deserialize(result, Imoji.class)); }// w w w. ja v a 2 s .c om } String followupSearchTerm = null; if (root.has("followupSearchTerm")) { followupSearchTerm = root.get("followupSearchTerm").getAsString(); } List<Category> relatedCategories = new ArrayList<>(); if (root.has("relatedCategories")) { JsonArray categoriesJSON = root.getAsJsonArray("relatedCategories"); for (JsonElement result : categoriesJSON) { relatedCategories.add(context.<Category>deserialize(result, Category.class)); } } return new ImojisResponse(imojis, followupSearchTerm, relatedCategories); }
From source file:io.kodokojo.bdd.stage.ApplicationThen.java
License:Open Source License
private void getUserDetails(String username, boolean complete) { OkHttpClient httpClient = new OkHttpClient(); UserInfo requesterUserInfo = currentUsers.get(currentUserLogin); UserInfo targetUserInfo = currentUsers.get(username); String url = getApiBaseUrl() + "/user"; if (!requesterUserInfo.getIdentifier().equals(targetUserInfo.getIdentifier())) { url += "/" + targetUserInfo.getIdentifier(); }/*from w w w. j a va 2 s .c om*/ Request.Builder builder = new Request.Builder().get().url(url); Request request = HttpUserSupport.addBasicAuthentification(requesterUserInfo, builder).build(); Response response = null; try { response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); JsonParser parser = new JsonParser(); String body = response.body().string(); JsonObject json = (JsonObject) parser.parse(body); assertThat(json.getAsJsonPrimitive("name").getAsString()).isNotEmpty(); if (complete) { assertThat(json.getAsJsonPrimitive("password").getAsString()).isNotEmpty(); assertThat(json.getAsJsonPrimitive("email").getAsString()).isNotEmpty(); assertThat(json.getAsJsonPrimitive("sshPublicKey").getAsString()).isNotEmpty(); } else { assertThat(json.getAsJsonPrimitive("password").getAsString()).isEmpty(); } if (StringUtils.isNotBlank(projectConfigurationId)) { assertThat(json.has("projectConfigurationIds")); JsonArray projectConfigurationIds = json.getAsJsonArray("projectConfigurationIds"); assertThat(projectConfigurationIds).isNotEmpty(); boolean foundCurrentProjectConfigurationId = false; Iterator<JsonElement> projectConfigIt = projectConfigurationIds.iterator(); while (projectConfigIt.hasNext()) { JsonObject projectConfig = (JsonObject) projectConfigIt.next(); assertThat(projectConfig.has("projectConfigurationId")); foundCurrentProjectConfigurationId = projectConfigurationId .equals(projectConfig.getAsJsonPrimitive("projectConfigurationId").getAsString()); } assertThat(foundCurrentProjectConfigurationId).isTrue(); } } catch (IOException e) { fail("Unable to get User details on Url " + url, e); } finally { if (response != null) { try { response.body().close(); } catch (IOException e) { fail("Fail to close Http response.", e); } } } }
From source file:io.kodokojo.bdd.stage.ApplicationThen.java
License:Open Source License
private ProjectConfigDto getProjectConfigurationFromCurrentProjectConfigId() { OkHttpClient httpClient = new OkHttpClient(); UserInfo requesterUserInfo = currentUsers.get(currentUserLogin); Request.Builder builder = new Request.Builder() .url(getApiBaseUrl() + "/projectconfig/" + projectConfigurationId).get(); Request request = HttpUserSupport.addBasicAuthentification(requesterUserInfo, builder).build(); Response response = null;/*from w w w.ja v a2s . c om*/ try { response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); String bodyResponse = response.body().string(); Gson gson = new GsonBuilder().create(); ProjectConfigDto projectConfigDto = gson.fromJson(bodyResponse, ProjectConfigDto.class); assertThat(projectConfigDto).isNotNull(); assertThat(projectConfigDto.getAdmins().get(0).getUsername()) .isEqualTo(requesterUserInfo.getUsername()); assertThat(projectConfigDto.getUsers()).isNotEmpty(); assertThat(projectConfigDto.getStackConfigs()).isNotEmpty(); JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(bodyResponse); assertThat(json.has("name")).isTrue(); assertThat(json.has("identifier")).isTrue(); assertThat(json.has("admins")).isTrue(); JsonArray admins = json.getAsJsonArray("admins"); assertThat(admins).isNotEmpty(); jsonUserAreValid(admins.iterator()); JsonArray users = json.getAsJsonArray("users"); jsonUserAreValid(users.iterator()); assertThat(users).isNotEmpty(); JsonArray stackConfigs = json.getAsJsonArray("stackConfigs"); assertThat(stackConfigs).isNotEmpty(); Iterator<JsonElement> stackConfigurationIt = stackConfigs.iterator(); while (stackConfigurationIt.hasNext()) { JsonObject stackConf = (JsonObject) stackConfigurationIt.next(); jsonStackConfigIsValid(stackConf); } return projectConfigDto; } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { closeQuietly(response.body()); } } return null; }
From source file:io.kodokojo.bdd.stage.ApplicationThen.java
License:Open Source License
private void jsonStackConfigIsValid(JsonObject stackConf) { assertThat(stackConf.has("name")).isTrue(); assertThat(stackConf.has("type")).isTrue(); JsonArray brickConfigs = stackConf.getAsJsonArray("brickConfigs"); assertThat(brickConfigs).isNotEmpty(); Iterator<JsonElement> brickConfigIt = brickConfigs.iterator(); while (brickConfigIt.hasNext()) { JsonObject brickConfig = (JsonObject) brickConfigIt.next(); jsonBrickIsValid(brickConfig);//from w w w . j a v a 2s . c o m } }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java
License:Open Source License
private void killAllAppInMarathon(String marathonUrl) { OkHttpClient httpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder().url(marathonUrl + "/v2/apps").get(); Response response = null;//w w w.j a v a 2 s . c om Set<String> appIds = new HashSet<>(); try { response = httpClient.newCall(builder.build()).execute(); String body = response.body().string(); JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(body); JsonArray apps = json.getAsJsonArray("apps"); for (JsonElement appEl : apps) { JsonObject app = (JsonObject) appEl; appIds.add(app.getAsJsonPrimitive("id").getAsString()); } } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } appIds.stream().forEach(id -> { Request.Builder rmBuilder = new Request.Builder().url(marathonUrl + "/v2/apps/" + id).delete(); Response responseRm = null; try { LOGGER.debug("Delete Marathon application id {}.", id); responseRm = httpClient.newCall(rmBuilder.build()).execute(); } catch (IOException e) { fail(e.getMessage()); } finally { if (responseRm != null) { IOUtils.closeQuietly(responseRm.body()); } } }); }
From source file:io.kodokojo.commons.utils.servicelocator.marathon.MarathonServiceLocator.java
License:Open Source License
@Override public Set<Service> getService(String type, String name) { Set<String> appIds = new HashSet<>(); JsonObject json = marathonRestApi.getAllApplications(); JsonArray apps = json.getAsJsonArray("apps"); for (int i = 0; i < apps.size(); i++) { JsonObject app = (JsonObject) apps.get(i); String id = app.getAsJsonPrimitive("id").getAsString(); JsonObject labels = app.getAsJsonObject("labels"); if (labels.has("project")) { String project = labels.getAsJsonPrimitive("project").getAsString(); String apptype = labels.getAsJsonPrimitive("componentType").getAsString(); if (type.equals(apptype) && name.equals(project)) { appIds.add(id);//from w w w . j av a 2 s. c om } } } Set<Service> res = new HashSet<>(); for (String appId : appIds) { JsonObject applicationConfiguration = marathonRestApi.getApplicationConfiguration(appId); res.addAll(convertToService(name + "-" + type, applicationConfiguration)); } return res; }
From source file:io.kodokojo.commons.utils.servicelocator.marathon.MarathonServiceLocator.java
License:Open Source License
private static Set<Service> convertToService(String name, JsonObject json) { Set<Service> res = new HashSet<>(); JsonObject app = json.getAsJsonObject("app"); JsonObject container = app.getAsJsonObject("container"); String containerType = container.getAsJsonPrimitive("type").getAsString(); if ("DOCKER".equals(containerType)) { List<String> ports = new ArrayList<>(); JsonObject docker = container.getAsJsonObject("docker"); JsonArray portMappings = docker.getAsJsonArray("portMappings"); for (int i = 0; i < portMappings.size(); i++) { JsonObject portMapping = (JsonObject) portMappings.get(i); ports.add(portMapping.getAsJsonPrimitive("containerPort").getAsString()); }/*from w w w . j a va2s .c o m*/ JsonArray tasks = app.getAsJsonArray("tasks"); for (int i = 0; i < tasks.size(); i++) { JsonObject task = (JsonObject) tasks.get(i); String host = task.getAsJsonPrimitive("host").getAsString(); boolean alive = false; if (task.has("healthCheckResults")) { JsonArray healthCheckResults = task.getAsJsonArray("healthCheckResults"); for (int j = 0; j < healthCheckResults.size() && !alive; j++) { JsonObject healthCheck = (JsonObject) healthCheckResults.get(j); alive = healthCheck.getAsJsonPrimitive("alive").getAsBoolean(); } } if (alive) { JsonArray jsonPorts = task.getAsJsonArray("ports"); for (int j = 0; j < jsonPorts.size(); j++) { JsonPrimitive jsonPort = (JsonPrimitive) jsonPorts.get(j); String portName = ports.get(j); res.add(new Service(name + "-" + portName, host, jsonPort.getAsInt())); } } } } return res; }
From source file:io.socket.IOConnection.java
License:Open Source License
/** * Transport message. {@link IOTransport} calls this, when a message has * been received.//from ww w . j a v a2 s .com * * @param text * the text */ public void transportMessage(String text) { logger.info("< " + text); IOMessage message; try { message = new IOMessage(text); } catch (Exception e) { error(new SocketIOException("Garbage from server: " + text, e)); return; } resetTimeout(); switch (message.getType()) { case IOMessage.TYPE_DISCONNECT: try { findCallback(message).onDisconnect(); } catch (Exception e) { error(new SocketIOException("Exception was thrown in onDisconnect()", e)); } break; case IOMessage.TYPE_CONNECT: try { if (firstSocket != null && "".equals(message.getEndpoint())) { setState(STATE_READY); if (firstSocket.getNamespace().equals("")) { firstSocket.getCallback().onConnect(); } else { IOMessage connect = new IOMessage(IOMessage.TYPE_CONNECT, firstSocket.getNamespace(), ""); sendPlain(connect.toString()); } // should flush after connecting to namespace flushBuffer(); } else { findCallback(message).onConnect(); } firstSocket = null; } catch (Exception e) { error(new SocketIOException("Exception was thrown in onConnect()", e)); } break; case IOMessage.TYPE_HEARTBEAT: sendPlain("2::"); break; case IOMessage.TYPE_MESSAGE: try { findCallback(message).onMessage(message.getData(), remoteAcknowledge(message)); } catch (Exception e) { error(new SocketIOException( "Exception was thrown in onMessage(String).\n" + "Message was: " + message.toString(), e)); } break; case IOMessage.TYPE_JSON_MESSAGE: try { JsonElement obj = null; String data = message.getData(); if (data.trim().equals("null") == false) obj = new JsonParser().parse(data); try { findCallback(message).onMessage(obj, remoteAcknowledge(message)); } catch (Exception e) { error(new SocketIOException("Exception was thrown in onMessage(JSONObject).\n" + "Message was: " + message.toString(), e)); } } catch (JsonParseException e) { logger.warning("Malformated JSON received"); } break; case IOMessage.TYPE_EVENT: try { JsonObject event = new JsonParser().parse(message.getData()).getAsJsonObject(); JsonElement[] argsArray; if (event.has("args")) { JsonArray args = event.getAsJsonArray("args"); argsArray = new JsonElement[args.size()]; for (int i = 0; i < args.size(); i++) { if (args.get(i) != null) argsArray[i] = args.get(i); } } else argsArray = new JsonElement[0]; String eventName = event.get("name").getAsString(); try { findCallback(message).on(eventName, remoteAcknowledge(message), argsArray); } catch (Exception e) { error(new SocketIOException("Exception was thrown in on(String, JSONObject[]).\n" + "Message was: " + message.toString(), e)); } } catch (JsonParseException e) { logger.warning("Malformated JSON received"); } break; case IOMessage.TYPE_ACK: String[] data = message.getData().split("\\+", 2); if (data.length == 2) { try { int id = Integer.parseInt(data[0]); IOAcknowledge ack = acknowledge.get(id); if (ack == null) logger.warning("Received unknown ack packet"); else { JsonArray array = new JsonParser().parse(data[1]).getAsJsonArray(); JsonElement[] args = new JsonElement[array.size()]; for (int i = 0; i < args.length; i++) { args[i] = array.get(i); } ack.ack(args); } } catch (NumberFormatException e) { logger.warning( "Received malformated Acknowledge! This is potentially filling up the acknowledges!"); } catch (JsonParseException e) { logger.warning("Received malformated Acknowledge data!"); } } else if (data.length == 1) { sendPlain("6:::" + data[0]); } break; case IOMessage.TYPE_ERROR: try { findCallback(message).onError(new SocketIOException(message.getData())); } catch (SocketIOException e) { error(e); } if (message.getData().endsWith("+0")) { // We are advised to disconnect cleanup(); } break; case IOMessage.TYPE_NOOP: break; default: logger.warning("Unkown type received" + message.getType()); break; } }