Example usage for com.google.gson JsonElement getAsJsonObject

List of usage examples for com.google.gson JsonElement getAsJsonObject

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonObject.

Prototype

public JsonObject getAsJsonObject() 

Source Link

Document

convenience method to get this element as a JsonObject .

Usage

From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java

License:Apache License

public String createVpcTier(String name, String displayText, String networkOfferingId, String zoneId,
        String vpcId, String gateway, String netmask) {

    //vpcid/*  w w w  .  java  2s  .c  o m*/
    Multimap<String, String> params = ArrayListMultimap.create();
    params.put("command", "createNetwork");

    params.put("displayText", displayText);
    params.put("name", name);
    params.put("networkofferingid", networkOfferingId);
    params.put("zoneid", zoneId);
    params.put("vpcid", vpcId);
    params.put("gateway", gateway);
    params.put("netmask", netmask);
    if (accAndDomain.isPresent()) {
        params.put("account", accAndDomain.get().account);
        params.put("domainid", accAndDomain.get().domainId);
    }

    params.put("apiKey", this.apiKey);
    params.put("response", "json");

    LOG.debug("createVpcTier GET " + params);

    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);
    // TODO does non-2xx response need to be handled separately ?

    JsonElement jr = json(response);
    LOG.debug("createVpcTier GOT " + jr);

    // seems this is created immediately
    return jr.getAsJsonObject().get("createnetworkresponse").getAsJsonObject().get("network").getAsJsonObject()
            .get("id").getAsString();
}

From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java

License:Apache License

protected JsonElement listPublicIpAddressesAtVpc(String vpcId) {
    Multimap<String, String> params = ArrayListMultimap.create();
    params.put("command", "listPublicIpAddresses");

    params.put("vpcid", vpcId);
    if (accAndDomain.isPresent()) {
        params.put("account", accAndDomain.get().account);
        params.put("domainid", accAndDomain.get().domainId);
    }/*from   ww  w. j  av a2 s  . c  o m*/

    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 jr = json(response);
    LOG.debug(pretty(jr));

    return jr.getAsJsonObject().get("listpublicipaddressesresponse");
}

From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java

License:Apache License

public void deleteIpsAtVpc(String vpcId) {
    JsonElement je = listPublicIpAddressesAtVpc(vpcId);
    LOG.debug(pretty(je));//  w ww.j a  v  a 2 s .  co m

    int i = 0;
    for (JsonElement jei : je.getAsJsonObject().get("publicipaddress").getAsJsonArray()) {
        String id = jei.getAsJsonObject().get("id").getAsString();
        LOG.debug("deleting IP " + id);
        getCloudstackGlobalClient().getAddressApi().disassociateIPAddress(id);
        i++;
    }
    if (i > 0)
        LOG.info("deleted " + i + " IP's at VPC " + vpcId);
}

From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java

License:Apache License

/**
 * Create port-forward rule./*from  w w w .j  a  va 2  s .com*/
 * <p/>
 * like jclouds version, but takes the networkId which is mandatory for VPCs.
 * <p/>
 * Does <em>NOT</em> open any firewall.
 *
 * @return job id.
 */
public String createPortForwardRule(String networkId, String ipAddressId, Protocol protocol, int publicPort,
        String targetVmId, int privatePort) {
    // needed because jclouds doesn't support supplying tier ID (for VPC's)
    Multimap<String, String> params = ArrayListMultimap.create();
    params.put("command", "createPortForwardingRule");

    params.put("networkid", networkId);
    params.put("ipaddressid", ipAddressId);
    params.put("protocol", protocol.toString());
    params.put("publicport", "" + publicPort);
    params.put("virtualmachineid", targetVmId);
    params.put("privateport", "" + privatePort);
    //        params.put("openfirewall", "" + false);

    params.put("apiKey", this.apiKey);
    params.put("response", "json");

    LOG.debug("createPortForwardingRule GET " + params);

    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);
    // TODO does non-2xx response need to be handled separately ?

    JsonElement jr = json(response);
    LOG.debug("createPortForwardingRule GOT " + jr);

    try {
        JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject();
        return 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 executing createPortForwardingRule(" + params + ")" + ": " + jr.toString());
    }
}

From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java

License:Apache License

/**
 * Create port-forward rule for a VM./*from  ww  w .  j  av  a 2  s .c  o m*/
 * <p/>
 * Does <em>NOT</em> open any firewall.
 */
public String createPortForwardRuleForVm(String publicIpId, Protocol protocol, int publicPort,
        String targetVmId, int privatePort) {
    // needed because jclouds doesn't support CIDR
    //        return cloudstackClient.getCloudstackGlobalClient().getFirewallClient().
    //                createPortForwardingRuleForVirtualMachine(
    //                        publicIpId, PortForwardingRule.Protocol.TCP, publicPort, targetVmId, privatePort).
    //                getJobId();

    Multimap<String, String> params = ArrayListMultimap.create();
    params.put("command", "createPortForwardingRule");

    params.put("ipaddressid", publicIpId);
    params.put("protocol", protocol.toString());
    params.put("publicport", "" + publicPort);
    params.put("virtualmachineid", targetVmId);
    params.put("privateport", "" + privatePort);
    //        params.put("openfirewall", "" + false);

    params.put("apiKey", this.apiKey);
    params.put("response", "json");

    LOG.debug("createPortForwardingRule GET " + params);

    HttpRequest request = HttpRequest.builder().method("GET").endpoint(this.endpoint).addQueryParams(params)
            .addHeader("Accept", "application/json").build();

    request = getQuerySigner().filter(request);

    request.getEndpoint().toString().replace("+", "%2B");
    //request = request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).query(decodedParams).build()).build();

    HttpToolResponse response = HttpUtil.invoke(request);
    // TODO does non-2xx response need to be handled separately ?

    JsonElement jr = json(response);
    LOG.debug("createPortForwardingRule GOT " + jr);

    try {
        JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject();
        return 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 executing createPortForwardingRule(" + params + ")" + ": " + jr.toString());
    }
}

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  a v a 2 s. co  m*/
    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:ca.ualberta.cmput301w14t08.geochan.json.BitmapJsonConverter.java

License:Apache License

/**
 * Deserializes a Bitmap from a base64 JSON string.
 * /*w  w w  . j  a  va 2s . c  o  m*/
 * @param jsonElement
 *            the JSON element to deserialize
 * @param type
 *            the Type
 * @param jsc
 *            the JSON deserialization context
 * @return The deserialized Bitmap.
 * 
 * @throws JsonParseException
 */
@Override
public Bitmap deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsc)
        throws JsonParseException {
    Bitmap image = null;
    JsonObject object = jsonElement.getAsJsonObject();
    String encodedImage = object.get("image").getAsString();
    byte[] byteArray = Base64.decode(encodedImage, Base64.NO_WRAP);

    /*
     * http://stackoverflow.com/a/5878773
     * Sando's workaround for running out of memory on decoding bitmaps.
     */
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inDither = false;
    opts.inPurgeable = true;
    opts.inInputShareable = true;
    opts.inTempStorage = new byte[32 * 1024];
    image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, opts);

    return image;
}

From source file:ca.ualberta.cmput301w14t08.geochan.json.CommentJsonConverter.java

License:Apache License

/**
 * Deserializes a Comment object from JSON format.
 * @param json//w ww .j  a  v  a2  s.c  o m
 *            the JSON element to deserialize
 * @param type
 *            the Type
 * @param context
 *            the JSON deserialization context
 *            
 * @return The deserialized Comment.
 * 
 * @throws JsonParseException
 */
@Override
public Comment deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject object = json.getAsJsonObject();

    long commentDate = object.get("commentDate").getAsLong();

    String locationString = object.get("location").getAsString();
    List<String> locationEntries = Arrays.asList(locationString.split(","));
    double latitude = Double.parseDouble(locationEntries.get(0));
    double longitude = Double.parseDouble(locationEntries.get(1));
    String locationDescription = null;
    if (object.get("locationDescription") != null) {
        locationDescription = object.get("locationDescription").getAsString();
    }
    GeoLocation location = new GeoLocation(latitude, longitude);
    location.setLocationDescription(locationDescription);

    String user = object.get("user").getAsString();
    String hash = object.get("hash").getAsString();
    String id = object.get("id").getAsString();

    String textPost = object.get("textPost").getAsString();

    Bitmap thumbnail = null;
    boolean hasImage = object.get("hasImage").getAsBoolean();
    if (hasImage) {
        /*
         * http://stackoverflow.com/questions/20594833/convert-byte-array-or-
         * bitmap-to-picture
         *
         * http://stackoverflow.com/a/5878773
         * Sando's workaround for running out of memory on decoding bitmaps.
         * 
         * Only deserialize the thumbnail as the full image is downloaded
         * and deserialized separately.
         */
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inDither = false;
        opts.inPurgeable = true;
        opts.inInputShareable = true;
        opts.inTempStorage = new byte[32 * 1024];
        String encodedThumb = object.get("imageThumbnail").getAsString();
        byte[] thumbArray = Base64.decode(encodedThumb, Base64.NO_WRAP);
        thumbnail = BitmapFactory.decodeByteArray(thumbArray, 0, thumbArray.length, opts);
    }

    int depth = object.get("depth").getAsInt();

    final Comment comment = new Comment(textPost, null, location, null);
    comment.getCommentDate().setTime(commentDate);
    comment.setUser(user);
    comment.setHash(hash);
    comment.setDepth(depth);
    comment.setId(Long.parseLong(id));
    if (hasImage) {
        comment.setImageThumb(thumbnail);
    }

    return comment;
}

From source file:ca.ualberta.cmput301w14t08.geochan.json.CommentOfflineJsonConverter.java

License:Apache License

/**
 * Deserializes a Comment object from JSON format (for offline storage).
 * @param json/*from   ww w  .j  a  v  a 2s  .c o  m*/
 *            the JSON element to deserialize
 * @param type
 *            the Type
 * @param context
 *            the JSON deserialization context
 *            
 * @return The deserialized Comment.
 * 
 * @throws JsonParseException
 */
@Override
public Comment deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject object = json.getAsJsonObject();

    long commentDate = object.get("commentDate").getAsLong();

    String locationString = object.get("location").getAsString();
    List<String> locationEntries = Arrays.asList(locationString.split(","));
    double latitude = Double.parseDouble(locationEntries.get(0));
    double longitude = Double.parseDouble(locationEntries.get(1));
    String locationDescription = null;
    if (object.get("locationDescription") != null) {
        locationDescription = object.get("locationDescription").getAsString();
    }
    GeoLocation location = new GeoLocation(latitude, longitude);
    location.setLocationDescription(locationDescription);

    String user = object.get("user").getAsString();
    String hash = object.get("hash").getAsString();
    String id = object.get("id").getAsString();

    String textPost = object.get("textPost").getAsString();

    Bitmap thumbnail = null;
    boolean hasImage = object.get("hasImage").getAsBoolean();
    if (hasImage) {
        /*
         * http://stackoverflow.com/a/5878773
         * Sando's workaround for running out of memory on decoding bitmaps.
         * 
         * Only deserialize the thumbnail as the full image is deserialized 
         * separately.
         */
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inDither = false;
        opts.inPurgeable = true;
        opts.inInputShareable = true;
        opts.inTempStorage = new byte[32 * 1024];
        String encodedThumb = object.get("imageThumbnail").getAsString();
        byte[] thumbArray = Base64.decode(encodedThumb, Base64.NO_WRAP);
        thumbnail = BitmapFactory.decodeByteArray(thumbArray, 0, thumbArray.length, opts);
    }

    int depth = object.get("depth").getAsInt();

    final Comment comment = new Comment(textPost, null, location, null);
    comment.getCommentDate().setTime(commentDate);
    comment.setUser(user);
    comment.setHash(hash);
    comment.setDepth(depth);
    comment.setId(Long.parseLong(id));
    if (hasImage) {
        comment.setImageThumb(thumbnail);
    }

    return comment;
}

From source file:ca.ualberta.cmput301w14t08.geochan.json.LocationJsonConverter.java

License:Apache License

/**
 * Deserializes data into a Location from JSON format.
 * /*  w  w w.j av a  2s. c o m*/
 * (Some of this code is taken from a stackOverflow user
 * Brian Roach, for details, see: http://stackoverflow.com/a/13997920)
 * 
 * @param je
 *            the JSON element to deserialize
 * @param type
 *            the Type
 * @param jdc
 *            the JSON deserialization context
 *
 * @return The deserialized Location object.
 * 
 * @throws JsonParseException
  */
@Override
public Location deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException {
    JsonObject jo = je.getAsJsonObject();

    Location l = new Location(jo.getAsJsonPrimitive("mProvider").getAsString());
    l.setAccuracy(jo.getAsJsonPrimitive("mAccuracy").getAsFloat());
    l.setLongitude(jo.getAsJsonPrimitive("longitude").getAsFloat());
    l.setLatitude(jo.getAsJsonPrimitive("latitude").getAsFloat());

    return l;
}