Example usage for com.google.gson JsonArray size

List of usage examples for com.google.gson JsonArray size

Introduction

In this page you can find the example usage for com.google.gson JsonArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:br.org.cesar.knot.lib.connection.ThingApi.java

License:Open Source License

/**
 * Get a specific device's gateway from Meshblu instance.
 *
 * @param device the device identifier (uuid)
 * @param clazz  The class for this device. Meshblu works with any type of objects and
 *               it is necessary deserialize the return to a valid object.
 *               Note: The class parameter should be a extension of {@link AbstractThingDevice}
 * @return an object based on the class parameter
 * @throws KnotException KnotException//from w  ww  .j a  v  a 2s  . c  o m
 */
public <T extends AbstractThingDevice> T getDeviceGateway(String device, Class<T> clazz)
        throws InvalidDeviceOwnerStateException, KnotException {
    // Check if the current state of device owner is valid
    if (!isValidDeviceOwner()) {
        throw new InvalidDeviceOwnerStateException("The device owner is invalid or null");
    }

    // Get a specific device's gateway from Meshblu instance.
    final String endPoint = mEndPoint + DEVICE_PATH + device + DEVICE_PROPERTY_PATH_GATEWAY;
    Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(),
            this.abstractDeviceOwner.getToken(), endPoint).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        JsonElement jsonElement = new JsonParser().parse(response.body().string());
        JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES);
        if (jsonArray.size() == 0) {
            return null;
        }
        return mGson.fromJson(jsonArray.get(0).toString(), clazz);
    } catch (Exception e) {
        throw new KnotException(e);
    }
}

From source file:br.org.cesar.knot.lib.connection.ThingApi.java

License:Open Source License

/**
 * @param device the device identifier (uuid)
 * @param type   object that will define what elements will returned by this method
 * @param knotQueryData  Date query/*w w  w  .  j  ava2 s. co  m*/
 * @return a List with data of the device
 * @throws KnotException KnotException
 */
public <T extends AbstractThingData> List<T> getDataList(String device, final KnotList<T> type,
        KnotQueryData knotQueryData) throws InvalidDeviceOwnerStateException, KnotException {
    // Check if the current state of device owner is valid
    if (!isValidDeviceOwner()) {
        throw new InvalidDeviceOwnerStateException("The device owner is invalid or null");
    }

    final String endPoint = mEndPoint + DATA_PATH + device + getDataParameter(knotQueryData);
    Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(),
            this.abstractDeviceOwner.getToken(), endPoint).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        JsonElement jsonElement = new JsonParser().parse(response.body().string());
        JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DATA);

        if (jsonArray == null || jsonArray.size() == 0) {
            return mGson.fromJson(EMPTY_ARRAY, type);
        }

        return mGson.fromJson(jsonArray.toString(), type);
    } catch (Exception e) {
        throw new KnotException(e);
    }
}

From source file:brooklyn.entity.mesos.framework.MesosFrameworkImpl.java

License:Apache License

public List<String> scanTasks(JsonArray frameworks) {
    String frameworkId = sensors().get(FRAMEWORK_ID);
    Entity mesosCluster = sensors().get(MESOS_CLUSTER);
    LOG.debug("Periodic scanning of framework tasks: frameworkId={}, mesosCluster={}", frameworkId,
            mesosCluster);/*from   ww  w  . j a  v  a 2 s . co  m*/

    for (int i = 0; i < frameworks.size(); i++) {
        JsonObject framework = frameworks.get(i).getAsJsonObject();
        if (frameworkId.equals(framework.get("id").getAsString())) {
            JsonArray completed = framework.getAsJsonArray("completed_tasks");
            JsonArray tasks = framework.getAsJsonArray("tasks");
            sensors().set(MESOS_COMPLETED_TASKS, completed.size());
            sensors().set(MESOS_RUNNING_TASKS, tasks.size());

            List<String> taskNames = MutableList.<String>of();
            for (int j = 0; j < tasks.size(); j++) {
                JsonObject json = tasks.get(j).getAsJsonObject();
                String id = json.get("id").getAsString();
                String name = json.get("name").getAsString();
                String state = json.get("state").getAsString();

                Optional<Entity> taskEntity = Iterables.tryFind(sensors().get(FRAMEWORK_TASKS).getMembers(),
                        Predicates.compose(Predicates.equalTo(id),
                                EntityFunctions.attribute(MesosTask.TASK_ID)));
                MesosTask task = null;
                if (taskEntity.isPresent()) {
                    // Only interested in tasks for our own use of Marathon.
                    // Tasks that other people create we'll ignore.
                    task = (MesosTask) taskEntity.get();
                }
                if (task != null) {
                    taskNames.add(name);
                    task.sensors().set(MesosTask.TASK_ID, id);
                    task.sensors().set(MesosTask.TASK_STATE, state);
                }
            }

            Set<String> taskNamesSet = Sets.newHashSet(taskNames);
            for (Entity member : ImmutableList.copyOf(getTaskCluster().getMembers())) {
                final String name = member.sensors().get(MesosTask.TASK_NAME);
                if (name != null) {
                    boolean found = taskNamesSet.contains(name);
                    if (found)
                        continue;
                }

                // Stop and then remove the task as it is no longer running, unless ON_FIRE
                //
                // TODO Aled worries about this: if task has gone, then MarathonTask polling
                // the task's URL will fail, setting the serviceUp to false, setting it 
                // on-fire. What will ever remove the task on a graceful shutdown of a container?
                // Or is that handled elsewhere?
                Lifecycle state = member.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    getTaskCluster().removeMember(member);
                    getTaskCluster().removeChild(member);
                    Entities.unmanage(member);
                } else {
                    ServiceStateLogic.setExpectedState(member, Lifecycle.STOPPING);
                }
            }
            return taskNames;
        }
    }
    // not found
    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;//  w ww  .j  av  a  2 s. com
        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.MesosClusterImpl.java

License:Apache License

public List<String> scanSlaves(JsonArray slaves) throws UnknownHostException {
    List<String> slaveIds = MutableList.<String>of();
    for (int i = 0; i < slaves.size(); i++) {
        JsonObject slave = slaves.get(i).getAsJsonObject();
        boolean active = slave.get("active").getAsBoolean();
        String id = slave.get("id").getAsString();
        String hostname = slave.get("hostname").getAsString();
        Double registered = slave.get("registered_time").getAsDouble();
        Group group = sensors().get(MESOS_SLAVES);

        Optional<Entity> entity = Iterables.tryFind(group.getMembers(), Predicates
                .compose(Predicates.equalTo(id), EntityFunctions.attribute(MesosSlave.MESOS_SLAVE_ID)));
        if (entity.isPresent()) {
            Entity found = entity.get();
            found.sensors().set(MesosSlave.SLAVE_ACTIVE, active);
            if (!active) {
                Lifecycle state = found.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    group.removeMember(found);
                    group.removeChild(found);
                    Entities.unmanage(found);
                } else {
                    ServiceStateLogic.setExpectedState(found, Lifecycle.STOPPING);
                }// w  ww.j  a va 2  s .c  o  m
            }
        } else if (active) {
            LocationSpec<SshMachineLocation> spec = LocationSpec.create(SshMachineLocation.class)
                    .configure(SshMachineLocation.SSH_HOST, hostname)
                    .configure("address", InetAddress.getByName(hostname)).displayName(hostname);
            if (config().get(MESOS_SLAVE_ACCESSIBLE)) {
                spec.configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "true")
                        .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, true)
                        .configure(SshMachineLocation.SSH_PORT, config().get(MesosSlave.SLAVE_SSH_PORT))
                        .configure(LocationConfigKeys.USER, config().get(MesosSlave.SLAVE_SSH_USER))
                        .configure(LocationConfigKeys.PASSWORD, config().get(MesosSlave.SLAVE_SSH_PASSWORD))
                        .configure(SshTool.PROP_PASSWORD, config().get(MesosSlave.SLAVE_SSH_PASSWORD))
                        .configure(SshTool.PROP_PORT, config().get(MesosSlave.SLAVE_SSH_PORT))
                        .configure(LocationConfigKeys.PRIVATE_KEY_DATA,
                                config().get(MesosSlave.SLAVE_SSH_PRIVATE_KEY_DATA))
                        .configure(LocationConfigKeys.PRIVATE_KEY_FILE,
                                config().get(MesosSlave.SLAVE_SSH_PRIVATE_KEY_FILE));
            } else {
                spec.configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "false")
                        .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, false);
            }
            SshMachineLocation machine = getManagementContext().getLocationManager().createLocation(spec);

            // Setup port forwarding
            MarathonPortForwarder portForwarder = new MarathonPortForwarder();
            portForwarder.setManagementContext(getManagementContext());

            EntitySpec<MesosSlave> slaveSpec = EntitySpec.create(MesosSlave.class)
                    .configure(MesosSlave.MESOS_SLAVE_ID, id)
                    .configure(MesosSlave.REGISTERED_AT, registered.longValue())
                    .configure(MesosSlave.MESOS_CLUSTER, this).displayName("Mesos Slave (" + hostname + ")");
            MesosSlave added = sensors().get(MESOS_SLAVES).addMemberChild(slaveSpec);
            added.sensors().set(MesosSlave.SLAVE_ACTIVE, active);
            added.sensors().set(MesosSlave.HOSTNAME, hostname);
            added.sensors().set(MesosSlave.ADDRESS, hostname);

            added.start(ImmutableList.of(machine));
            portForwarder.init(hostname, this);

            // Setup subnet tier
            SubnetTier subnetTier = added.addChild(
                    EntitySpec.create(SubnetTier.class).configure(SubnetTier.PORT_FORWARDER, portForwarder)
                            .configure(SubnetTier.SUBNET_CIDR, Cidr.UNIVERSAL));
            Entities.start(subnetTier, ImmutableList.of(machine));
            added.sensors().set(MesosSlave.SUBNET_TIER, subnetTier);
        }

        if (active)
            slaveIds.add(id);
    }
    return slaveIds;
}

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 v a2 s. c  om*/
            .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.entity.mesos.task.marathon.MarathonTaskImpl.java

License:Apache License

@Override
public MarathonTaskLocation createLocation(Map<String, ?> flags) {
    Entity entity = getRunningEntity();
    MesosSlave slave = getMesosCluster().getMesosSlave(getHostname());
    SubnetTier subnet = slave.getSubnetTier();
    Boolean sdn = config().get(MesosCluster.SDN_ENABLE);

    // Configure the entity subnet
    LOG.info("Configuring entity {} via subnet {}", entity, subnet);
    entity.config().set(SubnetTier.PORT_FORWARDING_MANAGER, subnet.getPortForwardManager());
    entity.config().set(SubnetTier.PORT_FORWARDER, subnet.getPortForwarder());
    entity.config().set(SubnetTier.SUBNET_CIDR, Cidr.UNIVERSAL);
    DockerUtils.configureEnrichers(subnet, entity);

    // Lookup mapped ports
    List<Map.Entry<Integer, Integer>> portBindings = (List) flags.get("portBindings");
    Map<Integer, String> tcpMappings = MutableMap.of();
    Optional<JsonElement> application = getApplicationJson();
    if (application.isPresent()) {
        JsonArray tasks = application.get().getAsJsonObject().get("app").getAsJsonObject().get("tasks")
                .getAsJsonArray();//  www.  ja  v  a  2 s .co m
        for (JsonElement each : tasks) {
            JsonElement ports = each.getAsJsonObject().get("ports");
            if (ports != null && !ports.isJsonNull()) {
                JsonArray array = ports.getAsJsonArray();
                if (array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        int hostPort = array.get(i).getAsInt();
                        int containerPort = portBindings.get(i).getKey();
                        String address = sdn ? sensors().get(Attributes.SUBNET_ADDRESS) : getId();
                        String target = address + ":" + containerPort;
                        tcpMappings.put(hostPort, target);
                        if (containerPort == 22) { // XXX should be a better way?
                            sensors().set(DockerAttributes.DOCKER_MAPPED_SSH_PORT,
                                    HostAndPort.fromParts(getHostname(), hostPort).toString());
                        }
                    }
                }
            }
        }
    } else {
        throw new IllegalStateException(
                "Cannot retrieve application details for " + sensors().get(APPLICATION_ID));
    }

    // Create our wrapper location around the task
    Boolean useSsh = config().get(DockerAttributes.DOCKER_USE_SSH);
    LocationSpec<MarathonTaskLocation> spec = LocationSpec.create(MarathonTaskLocation.class)
            .parent(getMarathonFramework().getDynamicLocation()).configure(flags)
            .configure(DynamicLocation.OWNER, this).configure("entity", getRunningEntity())
            .configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "false")
            .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, useSsh)
            .configure(SshMachineLocation.TCP_PORT_MAPPINGS, tcpMappings).displayName(getShortName());
    if (useSsh) {
        spec.configure(SshMachineLocation.SSH_HOST, getHostname())
                .configure(SshMachineLocation.SSH_PORT, getSshPort()).configure("address", getAddress())
                .configure(LocationConfigKeys.USER, "root") // TODO from slave
                .configure(LocationConfigKeys.PASSWORD, "p4ssw0rd").configure(SshTool.PROP_PASSWORD, "p4ssw0rd")
                .configure(SshTool.PROP_HOST, getHostname()).configure(SshTool.PROP_PORT, getSshPort())
                .configure(LocationConfigKeys.PRIVATE_KEY_DATA, (String) null) // TODO used to generate authorized_keys
                .configure(LocationConfigKeys.PRIVATE_KEY_FILE, (String) null);
    }
    MarathonTaskLocation location = getManagementContext().getLocationManager().createLocation(spec);
    sensors().set(DYNAMIC_LOCATION, location);
    sensors().set(LOCATION_NAME, location.getId());

    // Record port mappings
    LOG.debug("Recording port mappings for {} at {}: {}", new Object[] { entity, location, tcpMappings });
    for (Integer hostPort : tcpMappings.keySet()) {
        HostAndPort target = HostAndPort.fromString(tcpMappings.get(hostPort));
        subnet.getPortForwarder().openPortForwarding(location, target.getPort(), Optional.of(hostPort),
                Protocol.TCP, Cidr.UNIVERSAL);
        subnet.getPortForwarder().openFirewallPort(entity, hostPort, Protocol.TCP, Cidr.UNIVERSAL);
        LOG.debug("Forwarded port: {} => {}", hostPort, target.getPort());
    }

    LOG.info("New task location {} created", location);
    if (useSsh) {
        DockerUtils.addExtraPublicKeys(entity, location);
    }
    return location;
}

From source file:brooklyn.entity.nosql.couchbase.CouchbaseClusterImpl.java

License:Apache License

public void createBucket(final Entity primaryNode, final String bucketName, final String bucketType,
        final Integer bucketPort, final Integer bucketRamSize, final Integer bucketReplica) {
    DynamicTasks.queueIfPossible(/*  w  w w. ja  v  a2 s .com*/
            TaskBuilder.<Void>builder().name("Creating bucket " + bucketName).body(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    DependentConfiguration.waitInTaskForAttributeReady(CouchbaseClusterImpl.this,
                            CouchbaseCluster.BUCKET_CREATION_IN_PROGRESS, Predicates.equalTo(false));
                    if (CouchbaseClusterImpl.this.resetBucketCreation.get() != null) {
                        CouchbaseClusterImpl.this.resetBucketCreation.get().stop();
                    }
                    setAttribute(CouchbaseCluster.BUCKET_CREATION_IN_PROGRESS, true);
                    HostAndPort hostAndPort = BrooklynAccessUtils.getBrooklynAccessibleAddress(primaryNode,
                            primaryNode.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT));

                    CouchbaseClusterImpl.this.resetBucketCreation.set(HttpFeed.builder()
                            .entity(CouchbaseClusterImpl.this).period(500, TimeUnit.MILLISECONDS)
                            .baseUri(String.format("http://%s/pools/default/buckets/%s", hostAndPort,
                                    bucketName))
                            .credentials(primaryNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_USERNAME),
                                    primaryNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_PASSWORD))
                            .poll(new HttpPollConfig<Boolean>(BUCKET_CREATION_IN_PROGRESS)
                                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                                            JsonFunctions.walkN("nodes"), new Function<JsonElement, Boolean>() {
                                                @Override
                                                public Boolean apply(JsonElement input) {
                                                    // Wait until bucket has been created on all nodes and the couchApiBase element has been published (indicating that the bucket is useable)
                                                    JsonArray servers = input.getAsJsonArray();
                                                    if (servers.size() != CouchbaseClusterImpl.this.getMembers()
                                                            .size()) {
                                                        return true;
                                                    }
                                                    for (JsonElement server : servers) {
                                                        Object api = server.getAsJsonObject()
                                                                .get("couchApiBase");
                                                        if (api == null
                                                                || Strings.isEmpty(String.valueOf(api))) {
                                                            return true;
                                                        }
                                                    }
                                                    return false;
                                                }
                                            }))
                                    .onFailureOrException(new Function<Object, Boolean>() {
                                        @Override
                                        public Boolean apply(Object input) {
                                            if (input instanceof brooklyn.util.http.HttpToolResponse) {
                                                if (((brooklyn.util.http.HttpToolResponse) input)
                                                        .getResponseCode() == 404) {
                                                    return true;
                                                }
                                            }
                                            if (input instanceof Throwable)
                                                Exceptions.propagate((Throwable) input);
                                            throw new IllegalStateException(
                                                    "Unexpected response when creating bucket:" + input);
                                        }
                                    }))
                            .build());

                    // TODO: Bail out if bucket creation fails, to allow next bucket to proceed
                    Entities.invokeEffectorWithArgs(CouchbaseClusterImpl.this, primaryNode,
                            CouchbaseNode.BUCKET_CREATE, bucketName, bucketType, bucketPort, bucketRamSize,
                            bucketReplica);
                    DependentConfiguration.waitInTaskForAttributeReady(CouchbaseClusterImpl.this,
                            CouchbaseCluster.BUCKET_CREATION_IN_PROGRESS, Predicates.equalTo(false));
                    if (CouchbaseClusterImpl.this.resetBucketCreation.get() != null) {
                        CouchbaseClusterImpl.this.resetBucketCreation.get().stop();
                    }
                    return null;
                }
            }).build()).orSubmitAndBlock();
}

From source file:brooklyn.event.feed.http.JsonFunctions.java

License:Apache License

public static <T> Function<JsonElement, List<T>> forEach(final Function<JsonElement, T> func) {
    return new Function<JsonElement, List<T>>() {
        @Override//from   www  . j  a v a  2 s.co m
        public List<T> apply(JsonElement input) {
            JsonArray array = (JsonArray) input;
            List<T> result = Lists.newArrayList();
            for (int i = 0; i < array.size(); i++) {
                result.add(func.apply(array.get(i)));
            }
            return result;
        }
    };
}

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//ww w.j a  v  a  2  s.  c o  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);
            }
        }
    };
}