List of usage examples for com.google.gson JsonElement getAsString
public String getAsString()
From source file:br.com.sgejs.util.DateGsonDeserializer.java
@Override public Date deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { try {/* w w w.j a va2 s. com*/ return (new SimpleDateFormat("dd/MM/yyyy")).parse(je.getAsString()); } catch (ParseException ex) { Logger.getLogger(DateGsonDeserializer.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:br.com.thiaguten.contrib.JsonContrib.java
License:Apache License
private static String getJsonElementAsString(JsonElement jsonElement) { if (jsonElement == null) { return JsonNull.INSTANCE.toString(); }/* ww w . j a v a 2s.c o m*/ if (jsonElement.isJsonPrimitive()) { return jsonElement.getAsString(); } return jsonElement.toString(); }
From source file:br.ufg.inf.es.saep.sandbox.dominio.infraestrutura.ValorDeserializer.java
License:Creative Commons License
@Override public Valor deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); byte tipo = jsonObject.get("tipo").getAsByte(); JsonElement valor = jsonObject.get("valor"); if (tipo == Valor.STRING) { return new Valor(valor.getAsString()); } else if (tipo == REAL) { return new Valor(valor.getAsFloat()); } else if (tipo == LOGICO) { return new Valor(valor.getAsBoolean()); } else if (tipo == DATA) { return Valor.dataFromString(valor.getAsString()); }/*from w w w . j a v a 2 s . co m*/ return null; }
From source file:brooklyn.entity.mesos.MesosClusterImpl.java
License:Apache License
public List<String> scanFrameworks(JsonArray frameworks) { List<String> frameworkNames = MutableList.<String>of(); for (int i = 0; i < frameworks.size(); i++) { JsonObject task = frameworks.get(i).getAsJsonObject(); String id = task.get("id").getAsString(); JsonElement pidObj = task.get("pid"); String pid = null;/*from ww w. j av a 2s.c om*/ if (pidObj != null && !pidObj.isJsonNull()) { pid = pidObj.getAsString(); } String name = task.get("name").getAsString(); String url = task.get("webui_url").getAsString(); frameworkNames.add(name); Optional<Entity> entity = Iterables.tryFind(sensors().get(MESOS_FRAMEWORKS).getMembers(), Predicates .compose(Predicates.equalTo(id), EntityFunctions.attribute(MesosFramework.FRAMEWORK_ID))); if (entity.isPresent()) continue; EntitySpec<? extends MesosFramework> frameworkSpec = EntitySpec .create(FRAMEWORKS.containsKey(name) ? FRAMEWORKS.get(name) : EntitySpec.create(MesosFramework.class)) .configure(MesosFramework.FRAMEWORK_ID, id).configure(MesosFramework.FRAMEWORK_PID, pid) .configure(MesosFramework.FRAMEWORK_NAME, name).configure(MesosFramework.FRAMEWORK_URL, url) .configure(MesosFramework.MESOS_CLUSTER, this) .displayName(String.format("%s Framework", Strings.toInitialCapOnly(name))); MesosFramework added = sensors().get(MESOS_FRAMEWORKS).addMemberChild(frameworkSpec); added.start(ImmutableList.<Location>of()); } return frameworkNames; }
From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java
License:Apache License
@Override public void connectSensors() { // TODO If we are not "mesos.task.managed", then we are just guessing at the appId. We may get // it wrong. If it's wrong then our uri will always give 404. We should not mark the task as // "serviceUp=false", and we should not clear the TASK_ID (which was correctly set in // MesosFramework.scanTasks, which is where this task came from in the first place). // The new behaviour of showing it as healthy (and not clearing the taskId, which caused // another instance to be automatically added!) is better than it was, but it definitely // needs more attention. final boolean managed = Boolean.TRUE.equals(sensors().get(MANAGED)); String uri = Urls.mergePaths(getFramework().sensors().get(MarathonFramework.FRAMEWORK_URL), "/v2/apps", sensors().get(APPLICATION_ID), "tasks"); HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(2000, TimeUnit.MILLISECONDS) .baseUri(uri)// w w w . j a va2s .c o m .credentialsIfNotNull( config().get(MesosCluster.MESOS_USERNAME), config().get(MesosCluster.MESOS_PASSWORD)) .header("Accept", "application/json") .poll(new HttpPollConfig<Boolean>(SERVICE_UP).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Boolean>() { @Override public Boolean apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); return tasks.size() == 1; } })) .onFailureOrException(Functions.constant(managed ? Boolean.FALSE : true))) .poll(new HttpPollConfig<Long>(TASK_STARTED_AT).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Long>() { @Override public Long apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement startedAt = each.getAsJsonObject().get("startedAt"); if (startedAt != null && !startedAt.isJsonNull()) { return Time.parseDate(startedAt.getAsString()).getTime(); } } return null; } })) .onFailureOrException(Functions.<Long>constant(-1L))) .poll(new HttpPollConfig<Long>(TASK_STAGED_AT).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Long>() { @Override public Long apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement stagedAt = each.getAsJsonObject().get("stagedAt"); if (stagedAt != null && !stagedAt.isJsonNull()) { return Time.parseDate(stagedAt.getAsString()).getTime(); } } return null; } })) .onFailureOrException(Functions.<Long>constant(-1L))) .poll(new HttpPollConfig<String>(Attributes.HOSTNAME).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement host = each.getAsJsonObject().get("host"); if (host != null && !host.isJsonNull()) { return host.getAsString(); } } return null; } })) .onFailureOrException(Functions.<String>constant(null))) .poll(new HttpPollConfig<String>(TASK_ID).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement id = each.getAsJsonObject().get("id"); if (id != null && !id.isJsonNull()) { return id.getAsString(); } } return null; } })) .onFailureOrException( (Function) Functions.<Object>constant(managed ? null : FeedConfig.UNCHANGED))) .poll(new HttpPollConfig<String>(Attributes.ADDRESS).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement host = each.getAsJsonObject().get("host"); if (host != null && !host.isJsonNull()) { try { return InetAddress.getByName(host.getAsString()) .getHostAddress(); } catch (UnknownHostException uhe) { Exceptions.propagate(uhe); } } } return null; } })) .onFailureOrException(Functions.<String>constant(null))); httpFeed = httpFeedBuilder.build(); }
From source file:brooklyn.event.feed.http.JsonFunctions.java
License:Apache License
@SuppressWarnings("unchecked") public static <T> Function<JsonElement, T> cast(final Class<T> expected) { return new Function<JsonElement, T>() { @Override/*from ww w. ja v a 2 s. co m*/ public T apply(JsonElement input) { if (input == null) { return (T) null; } else if (input.isJsonNull()) { return (T) null; } else if (expected == boolean.class || expected == Boolean.class) { return (T) (Boolean) input.getAsBoolean(); } else if (expected == char.class || expected == Character.class) { return (T) (Character) input.getAsCharacter(); } else if (expected == byte.class || expected == Byte.class) { return (T) (Byte) input.getAsByte(); } else if (expected == short.class || expected == Short.class) { return (T) (Short) input.getAsShort(); } else if (expected == int.class || expected == Integer.class) { return (T) (Integer) input.getAsInt(); } else if (expected == long.class || expected == Long.class) { return (T) (Long) input.getAsLong(); } else if (expected == float.class || expected == Float.class) { return (T) (Float) input.getAsFloat(); } else if (expected == double.class || expected == Double.class) { return (T) (Double) input.getAsDouble(); } else if (expected == BigDecimal.class) { return (T) input.getAsBigDecimal(); } else if (expected == BigInteger.class) { return (T) input.getAsBigInteger(); } else if (Number.class.isAssignableFrom(expected)) { // TODO Will result in a class-cast if it's an unexpected sub-type of Number not handled above return (T) input.getAsNumber(); } else if (expected == String.class) { return (T) input.getAsString(); } else if (expected.isArray()) { JsonArray array = input.getAsJsonArray(); Class<?> componentType = expected.getComponentType(); if (JsonElement.class.isAssignableFrom(componentType)) { JsonElement[] result = new JsonElement[array.size()]; for (int i = 0; i < array.size(); i++) { result[i] = array.get(i); } return (T) result; } else { Object[] result = (Object[]) Array.newInstance(componentType, array.size()); for (int i = 0; i < array.size(); i++) { result[i] = cast(componentType).apply(array.get(i)); } return (T) result; } } else { throw new IllegalArgumentException("Cannot cast json element to type " + expected); } } }; }
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
protected String waitForJobCompletion(int statusCode, InputStream payload, String message) throws InterruptedException { if (statusCode < 200 || statusCode >= 300) { String payloadStr = null; try {/* ww w . j a v a 2 s . c o m*/ payloadStr = Streams.readFullyString(payload); } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.debug("On HttpResponse failure, failed to get string payload; continuing with reporting error", e); } throw new RuntimeException( "Error " + statusCode + ": " + message + (payloadStr != null ? "; " + payloadStr : "")); } JsonElement jr = json(payload); LOG.debug(pretty(jr)); String responseId; String jobId; try { JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject(); JsonElement responseIdJson = jobfields.get("id"); responseId = responseIdJson != null ? responseIdJson.getAsString() : null; jobId = jobfields.get("jobid").getAsString(); } catch (NullPointerException | NoSuchElementException | IllegalStateException e) { // TODO Not good using exceptions for normal control flow; but easiest way to handle // problems in unexpected json structure. throw new IllegalStateException("Problem parsing job response: " + jr.toString()); } do { AsyncJob<Object> job = getAsyncJobClient().getAsyncJob(jobId); LOG.debug("waiting: " + job); if (job.hasFailed()) throw new IllegalStateException("Failed job: " + job); if (job.hasSucceed()) { Status status = job.getStatus(); if (Status.FAILED.equals(status)) throw new IllegalStateException("Failed job: " + job); if (Status.SUCCEEDED.equals(status)) return responseId; } Thread.sleep(1000); } while (true); }
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
public Maybe<String> findVpcIdFromNetworkId(final String networkId) { Multimap<String, String> params = ArrayListMultimap.create(); params.put("command", "listNetworks"); if (accAndDomain.isPresent()) { params.put("account", accAndDomain.get().account); params.put("domainid", accAndDomain.get().domainId); }//from www . j ava 2 s .c om params.put("apiKey", this.apiKey); params.put("response", "json"); HttpRequest request = HttpRequest.builder().method("GET").endpoint(this.endpoint).addQueryParams(params) .addHeader("Accept", "application/json").build(); request = getQuerySigner().filter(request); HttpToolResponse response = HttpUtil.invoke(request); JsonElement networks = json(response); LOG.debug("LIST NETWORKS\n" + pretty(networks)); //get the first network object Optional<JsonElement> matchingNetwork = Iterables.tryFind(networks.getAsJsonObject() .get("listnetworksresponse").getAsJsonObject().get("network").getAsJsonArray(), new Predicate<JsonElement>() { @Override public boolean apply(JsonElement jsonElement) { JsonObject contender = jsonElement.getAsJsonObject(); return contender.get("id").getAsString().equals(networkId); } }); if (matchingNetwork == null) { throw new NoSuchElementException("No network found matching " + networkId + "; networks: " + networks); } JsonElement vpcid = matchingNetwork.get().getAsJsonObject().get("vpcid"); if (vpcid == null) { return Maybe.absent("No vcpid for network " + networkId); } return Maybe.of(vpcid.getAsString()); }
From source file:by.gdgminsk.animationguide.data.deserializer.UriDeserializer.java
License:Apache License
@Override public Uri deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String uri = json.getAsString(); return TextUtils.isEmpty(uri) ? null : Uri.parse(uri); }
From source file:ca.jackymok.tomatoes.toolbox.GsonRequest.java
License:Apache License
public GsonRequest(int method, String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.mClazz = clazz; this.mListener = listener; //Create Gson qith custom Date parsing GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { final java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); @Override/* w ww .j a v a2 s . co m*/ public Date deserialize(JsonElement arg0, java.lang.reflect.Type arg1, JsonDeserializationContext arg2) throws JsonParseException { try { return df.parse(arg0.getAsString()); } catch (final java.text.ParseException e) { e.printStackTrace(); return null; } } }); mGson = gsonBuilder.create(); }