Example usage for com.google.common.base Optional or

List of usage examples for com.google.common.base Optional or

Introduction

In this page you can find the example usage for com.google.common.base Optional or.

Prototype

@Beta
public abstract T or(Supplier<? extends T> supplier);

Source Link

Document

Returns the contained instance if it is present; supplier.get() otherwise.

Usage

From source file:org.trinity.foundation.api.render.binding.BinderImpl.java

protected void bindViewElement(final ListeningExecutorService modelExecutor, final Object inheritedDataContext,
        final Object view, final Optional<DataContext> optionalFieldLevelDataContext,
        final Optional<EventSignals> optionalFieldLevelEventSignals,
        final Optional<ObservableCollection> optionalFieldLevelObservableCollection,
        final Optional<PropertySlots> optionalFieldLevelPropertySlots) {
    checkNotNull(inheritedDataContext);//  w  ww .j av  a 2 s.  com
    checkNotNull(view);

    final Class<?> viewClass = view.getClass();

    // check for class level annotations if field level annotations are
    // absent
    final Optional<DataContext> optionalDataContext = optionalFieldLevelDataContext
            .or(Optional.<DataContext>fromNullable(viewClass.getAnnotation(DataContext.class)));
    final Optional<EventSignals> optionalEventSignals = optionalFieldLevelEventSignals
            .or(Optional.<EventSignals>fromNullable(viewClass.getAnnotation(EventSignals.class)));
    final Optional<ObservableCollection> optionalObservableCollection = optionalFieldLevelObservableCollection
            .or(Optional
                    .<ObservableCollection>fromNullable(viewClass.getAnnotation(ObservableCollection.class)));
    final Optional<PropertySlots> optionalPropertySlots = optionalFieldLevelPropertySlots
            .or(Optional.<PropertySlots>fromNullable(viewClass.getAnnotation(PropertySlots.class)));

    Object dataContext = inheritedDataContext;
    if (optionalDataContext.isPresent()) {
        final Optional<Object> optionalDataContextValue = getDataContextValueForView(dataContext, view,
                optionalDataContext.get());
        if (optionalDataContextValue.isPresent()) {
            dataContext = optionalDataContextValue.get();
        } else {
            //no data context value available so we're not going to bind the view.
            return;
        }
    }

    //TODO only register a view with a datacontext if they have a binding.
    //FIXME do a proper clean up of views with child datacontexes.
    //        if (optionalEventSignals.isPresent() || optionalObservableCollection.isPresent() || optionalPropertySlots.isPresent()) {
    //            registerBinding(dataContext,
    //                    view);
    //        }

    registerBinding(dataContext, view);

    if (optionalEventSignals.isPresent()) {
        final EventSignal[] eventSignals = optionalEventSignals.get().value();
        bindEventSignals(modelExecutor, dataContext, view, eventSignals);
    }

    if (optionalObservableCollection.isPresent()) {
        final ObservableCollection observableCollection = optionalObservableCollection.get();
        bindObservableCollection(modelExecutor, dataContext, view, observableCollection);
    }

    if (optionalPropertySlots.isPresent()) {
        final PropertySlots propertySlots = optionalPropertySlots.get();
        bindPropertySlots(dataContext, view, propertySlots);
    }

    bindChildViewElements(modelExecutor, dataContext, view);
}

From source file:org.jclouds.softlayer.compute.functions.OperatingSystemToImage.java

@Override
public Image apply(OperatingSystem operatingSystem) {
    checkNotNull(operatingSystem, "operatingSystem");
    final SoftwareLicense defaultSoftwareLicense = SoftwareLicense.builder()
            .softwareDescription(SoftwareDescription.builder().build()).build();
    SoftwareLicense softwareLicense = fromNullable(operatingSystem.getSoftwareLicense())
            .or(defaultSoftwareLicense);
    Optional<String> optOSReferenceCode = fromNullable(
            softwareLicense.getSoftwareDescription().getReferenceCode());
    Optional<String> optVersion = fromNullable(softwareLicense.getSoftwareDescription().getVersion());
    Optional<String> optLongDescription = fromNullable(
            softwareLicense.getSoftwareDescription().getLongDescription());
    OsFamily osFamily = OsFamily.UNRECOGNIZED;
    String osVersion = UNRECOGNIZED;
    Integer bits = null;/*from   w w  w  .j a  v a2  s  .  c  o m*/
    if (optOSReferenceCode.isPresent()) {
        String operatingSystemReferenceCode = optOSReferenceCode.get();
        osFamily = OperatingSystems.osFamily().apply(operatingSystemReferenceCode);
        bits = OperatingSystems.bits().apply(operatingSystemReferenceCode);
    }
    if (optVersion.isPresent()) {
        osVersion = OperatingSystems.version().apply(optVersion.get());
    }
    if (osFamily == OsFamily.UNRECOGNIZED) {
        logger.debug("Cannot determine os family for item: %s", operatingSystem);
    }
    if (osVersion == null) {
        logger.debug("Cannot determine os version for item: %s", operatingSystem);
    }
    if (bits == null) {
        logger.debug("Cannot determine os bits for item: %s", operatingSystem);
    }

    org.jclouds.compute.domain.OperatingSystem os = org.jclouds.compute.domain.OperatingSystem.builder()
            .description(optLongDescription.or(UNRECOGNIZED)).family(osFamily).version(osVersion)
            .is64Bit(Objects.equal(bits, 64)).build();

    return new ImageBuilder().ids(optOSReferenceCode.or(operatingSystem.getId()))
            .description(optOSReferenceCode.or(UNRECOGNIZED)).operatingSystem(os).status(Image.Status.AVAILABLE)
            .build();
}

From source file:com.addthis.hydra.job.web.resources.JobsResource.java

void stopJobHelper(IJob job, Optional<Boolean> cancelParam, Optional<Boolean> forceParam, int nodeId)
        throws Exception {
    String id = job.getId();//from   w w w  .  j  a  va 2 s. c o m
    boolean cancelRekick = cancelParam.or(false);
    boolean force = forceParam.or(false);
    // cancel re-spawning
    if (cancelRekick) {
        job.setRekickTimeout(null);
    }
    log.warn("[job.stop] {}/{}, cancel={}, force={}", job.getId(), nodeId, cancelRekick, force);
    // broadcast to all hosts if no node specified
    if (nodeId < 0) {
        if (force) {
            spawn.killJob(id);
        } else {
            spawn.stopJob(id);
        }
    } else {
        if (force) {
            spawn.killTask(id, nodeId);
        } else {
            spawn.stopTask(id, nodeId);
        }
    }
}

From source file:com.addthis.hydra.job.spawn.resources.JobsResource.java

boolean stopJobHelper(String id, Optional<Boolean> cancelParam, Optional<Boolean> forceParam, int nodeId)
        throws Exception {
    IJob job = spawn.getJob(id);/*from   w w  w  .  j  av  a  2  s. co  m*/
    if (job == null) {
        return false;
    }
    boolean cancelRekick = cancelParam.or(false);
    boolean force = forceParam.or(false);
    // cancel re-spawning
    if (cancelRekick) {
        job.setRekickTimeout(null);
    }
    log.warn("[job.stop] " + job.getId() + "/" + nodeId + ", cancel=" + cancelRekick + ", force=" + force);
    // broadcast to all hosts if no node specified
    if (nodeId < 0) {
        if (force) {
            spawn.killJob(id);
        } else {
            spawn.stopJob(id);
        }
    } else {
        if (force) {
            spawn.killTask(id, nodeId);
        } else {
            spawn.stopTask(id, nodeId);
        }
    }
    return true;
}

From source file:com.addthis.hydra.job.spawn.resources.JobsResource.java

@GET
@Path("/delete") //TODO: should this be a @delete?
@Produces(MediaType.APPLICATION_JSON)/*from w w  w . j a  va  2 s .c o  m*/
public Response deleteJob(@QueryParam("id") @DefaultValue("") String id,
        @QueryParam("user") Optional<String> user) {
    Job job = spawn.getJob(id);

    if (job != null && !job.getState().equals(JobState.IDLE)) {
        return Response.serverError().entity("A non IDLE job cannot be deleted").build();
    } else {
        emitLogLineForAction(user.or(defaultUser), "job delete on " + id);
        try {
            Spawn.DeleteStatus status = spawn.deleteJob(id);
            switch (status) {
            case SUCCESS:
                return Response.ok().build();
            case JOB_MISSING:
                log.warn("[job.delete] " + id + " missing job");
                return Response.status(Response.Status.NOT_FOUND).build();
            case JOB_DO_NOT_DELETE:
                return Response.status(Response.Status.NOT_MODIFIED).build();
            default:
                throw new IllegalStateException("Delete status " + status + " is not recognized");
            }
        } catch (Exception ex) {
            return buildServerError(ex);
        }
    }
}

From source file:clocker.docker.location.DockerHostLocation.java

@Override
public DockerContainerLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
    lock.readLock().lock();// w  w  w  .  java2s  . c o m
    try {
        // Lookup entity from context or flags
        Object context = flags.get(LocationConfigKeys.CALLER_CONTEXT.getName());
        if (context == null || !(context instanceof Entity)) {
            throw new IllegalStateException("Invalid location context: " + context);
        }
        Entity entity = (Entity) context;

        // Flag to configure adding SSHable layer
        boolean useSsh = entity.config().get(DockerContainer.DOCKER_USE_SSH)
                && dockerHost.config().get(DockerContainer.DOCKER_USE_SSH);

        // Configure the entity
        LOG.info("Configuring entity {} via subnet {}", entity, dockerHost.getSubnetTier());
        entity.config().set(SubnetTier.PORT_FORWARDING_MANAGER,
                dockerHost.getSubnetTier().getPortForwardManager());
        entity.config().set(SubnetTier.PORT_FORWARDER, portForwarder);
        if (getOwner().config().get(SdnAttributes.SDN_ENABLE)) {
            SdnAgent agent = getOwner().sensors().get(SdnAgent.SDN_AGENT);
            if (agent == null) {
                throw new IllegalStateException("SDN agent entity on " + getOwner() + " is null");
            }
            Map<String, Cidr> networks = agent.sensors().get(SdnAgent.SDN_PROVIDER).sensors()
                    .get(SdnProvider.SUBNETS);
            entity.config().set(SubnetTier.SUBNET_CIDR, networks.get(entity.getApplicationId()));
        } else {
            entity.config().set(SubnetTier.SUBNET_CIDR, Cidr.UNIVERSAL);
        }

        // Add the entity Dockerfile if configured
        String dockerfile = entity.config().get(DockerAttributes.DOCKERFILE_URL);
        String entrypoint = entity.config().get(DockerAttributes.DOCKERFILE_ENTRYPOINT_URL);
        String contextArchive = entity.config().get(DockerAttributes.DOCKERFILE_CONTEXT_URL);
        String imageId = entity.config().get(DockerAttributes.DOCKER_IMAGE_ID);

        Optional<String> baseImage = Optional
                .fromNullable(entity.config().get(DockerAttributes.DOCKER_IMAGE_NAME));
        String imageTag = Optional.fromNullable(entity.config().get(DockerAttributes.DOCKER_IMAGE_TAG))
                .or("latest");

        boolean autoCheckpointImagePostInstall = Boolean.TRUE
                .equals(entity.config().get(DockerAttributes.AUTO_CHECKPOINT_DOCKER_IMAGE_POST_INSTALL));

        // TODO incorporate more info (incl registry?)
        String imageName;
        if (autoCheckpointImagePostInstall) {
            imageName = DockerUtils.imageName(entity, dockerfile);
        } else {
            // Generate a random id, and avoid collisions
            boolean collision;
            do {
                imageName = DockerUtils.randomImageName();
                collision = dockerHost.getImageNamed(imageName, imageTag).isPresent();
                if (collision)
                    LOG.info("Random image name collision '{}' on host {}; generating new id", imageName,
                            getOwner());
            } while (collision);
        }

        // Lookup image ID or build new image from Dockerfile
        LOG.info("ImageName ({}) for entity {}: {}",
                new Object[] { (autoCheckpointImagePostInstall ? "hash" : "random"), entity, imageName });

        if (dockerHost.getImageNamed(imageName, imageTag).isPresent()) {
            assert autoCheckpointImagePostInstall : "random imageName " + imageName + " collision on host "
                    + getOwner();

            // Wait until committed before continuing - Brooklyn may be midway through its creation.
            waitForImage(imageName);

            // Look up imageId again
            imageId = dockerHost.getImageNamed(imageName, imageTag).get();
            LOG.info("Found image {} for entity: {}", imageName, imageId);

            // Skip install phase
            entity.config().set(SoftwareProcess.SKIP_INSTALLATION, true);
        } else if (baseImage.isPresent()) {
            // Use the repository configured on the entity if present
            Optional<String> imageRepo = Optional
                    .fromNullable(entity.config().get(DockerAttributes.DOCKER_IMAGE_REGISTRY_URL));
            // Otherwise only use the configured repo here if it we created it or it is writeable
            Optional<String> localRepo = Optional.absent();
            if (config().get(DockerInfrastructure.DOCKER_SHOULD_START_REGISTRY)
                    || config().get(DockerInfrastructure.DOCKER_IMAGE_REGISTRY_WRITEABLE)) {
                localRepo = Optional.fromNullable(
                        getDockerInfrastructure().sensors().get(DockerAttributes.DOCKER_IMAGE_REGISTRY_URL));
                ;
            }
            imageName = Joiner.on('/')
                    .join(Optional.presentInstances(ImmutableList.of(imageRepo.or(localRepo), baseImage)));
            String fullyQualifiedName = imageName + ":" + imageTag;

            if (useSsh) {
                // Create an SSHable image from the one configured
                imageId = dockerHost.layerSshableImageOnFullyQualified(fullyQualifiedName);
                LOG.info("Created SSHable image from {}: {}", fullyQualifiedName, imageId);
            } else {
                try {
                    dockerHost.runDockerCommand(String.format("pull %s", fullyQualifiedName));
                } catch (Exception e) {
                    // XXX pulls fail sometimes but issue fixed in Docker 1.9.1
                    LOG.debug("Caught exception pulling {}: {}", fullyQualifiedName, e.getMessage());
                }
                imageId = dockerHost.getImageNamed(imageName, imageTag).orNull();
            }
            entity.config().set(SoftwareProcess.SKIP_INSTALLATION, true);
        } else {
            // Push or commit the image, otherwise Clocker will make a new one for the entity once it is installed.
            if (autoCheckpointImagePostInstall) {
                if (getDockerInfrastructure().config().get(DockerInfrastructure.DOCKER_IMAGE_REGISTRY_WRITEABLE)
                        && (getDockerInfrastructure().config()
                                .get(DockerInfrastructure.DOCKER_SHOULD_START_REGISTRY)
                                || Strings.isNonBlank(getDockerInfrastructure().sensors()
                                        .get(DockerInfrastructure.DOCKER_IMAGE_REGISTRY_URL)))) {
                    insertCallback(entity, SoftwareProcess.POST_INSTALL_COMMAND, DockerCallbacks.push());
                } else {
                    insertCallback(entity, SoftwareProcess.POST_INSTALL_COMMAND, DockerCallbacks.commit());
                }
            }

            if (Strings.isNonBlank(dockerfile)) {
                if (imageId != null) {
                    LOG.warn("Ignoring container imageId {} as dockerfile URL is set: {}", imageId, dockerfile);
                }
                Map<String, Object> substitutions = getExtraTemplateSubstitutions(imageName, entity);
                imageId = dockerHost.buildImage(dockerfile, entrypoint, contextArchive, imageName, useSsh,
                        substitutions);
            }
            if (Strings.isBlank(imageId)) {
                imageId = getOwner().sensors().get(DockerHost.DOCKER_IMAGE_ID);
            }

            // Tag the image name and create its latch
            imageLatches.putIfAbsent(imageName, new CountDownLatch(1));
            dockerHost.runDockerCommand(String.format("tag -f %s %s:latest", imageId, imageName));
        }

        // Look up hardware ID
        String hardwareId = entity.config().get(DockerAttributes.DOCKER_HARDWARE_ID);
        if (Strings.isEmpty(hardwareId)) {
            hardwareId = getOwner().config().get(DockerAttributes.DOCKER_HARDWARE_ID);
        }

        // Fix missing device link for urandom on some containers
        insertCallback(entity, SoftwareProcess.PRE_INSTALL_COMMAND,
                "if [ ! -e /dev/random ] ; then ln -s /dev/urandom /dev/random ; fi");

        // Create new Docker container in the host cluster
        LOG.info("Starting container with imageId {} and hardwareId {} at {}",
                new Object[] { imageId, hardwareId, machine });
        Map<Object, Object> containerFlags = MutableMap.builder().putAll(flags).put("useSsh", useSsh)
                .put("entity", entity).putIfNotNull("imageId", imageId)
                .putIfNotNull("imageName", imageId == null ? imageName : null)
                .putIfNotNull("imageTag", imageId == null ? imageTag : null)
                .putIfNotNull("hardwareId", hardwareId).build();
        Group cluster = dockerHost.getDockerContainerCluster();
        EntitySpec<DockerContainer> spec = EntitySpec
                .create(getOwner().sensors().get(DockerHost.DOCKER_CONTAINER_SPEC));
        spec.configure(containerFlags);
        Entity added = cluster.addMemberChild(spec);
        if (added == null) {
            throw new NoMachinesAvailableException(
                    String.format("Failed to create container at %s", dockerHost));
        } else {
            if (LOG.isDebugEnabled())
                LOG.debug("Starting container {} at {}, config {}", new Object[] { added, machine,
                        Sanitizer.sanitize(((EntityInternal) added).config().getBag()) });
            Entities.invokeEffector(entity, added, Startable.START,
                    MutableMap.of("locations", ImmutableList.of(machine))).getUnchecked();
        }
        DockerContainer dockerContainer = (DockerContainer) added;

        // Save the container attributes
        dockerContainer.sensors().set(DockerContainer.DOCKER_IMAGE_ID, imageId);
        dockerContainer.sensors().set(DockerContainer.DOCKER_IMAGE_NAME, imageName);
        dockerContainer.sensors().set(DockerContainer.DOCKER_HARDWARE_ID, hardwareId);

        // record SDN application network details
        if (getOwner().config().get(SdnAttributes.SDN_ENABLE)) {
            SdnAgent agent = getOwner().sensors().get(SdnAgent.SDN_AGENT);
            Cidr applicationCidr = agent.sensors().get(SdnAgent.SDN_PROVIDER)
                    .getSubnetCidr(entity.getApplicationId());
            entity.sensors().set(SdnProvider.APPLICATION_CIDR, applicationCidr);
            dockerContainer.sensors().set(SdnProvider.APPLICATION_CIDR, applicationCidr);
        }

        return dockerContainer.getDynamicLocation();
    } finally {
        lock.readLock().unlock();
    }
}

From source file:blusunrize.immersiveengineering.common.blocks.metal.TileEntityAssembler.java

@Override
public void update() {
    super.update();

    if (isDummy() || isRSDisabled() || world.isRemote
            || world.getTotalWorldTime() % 16 != ((getPos().getX() ^ getPos().getZ()) & 15))
        return;/*  w  w  w . j  a  v  a2  s  .  com*/
    boolean update = false;
    NonNullList<ItemStack>[] outputBuffer = new NonNullList[patterns.length];
    for (int p = 0; p < patterns.length; p++) {
        CrafterPatternInventory pattern = patterns[p];
        if ((controllingComputers != 0) && !computerOn[p])
            return;
        if (!pattern.inv.get(9).isEmpty() && canOutput(pattern.inv.get(9), p)) {
            ItemStack output = pattern.inv.get(9).copy();
            ArrayList<ItemStack> queryList = new ArrayList<>();//List of all available inputs in the inventory
            for (NonNullList<ItemStack> bufferedStacks : outputBuffer)
                if (bufferedStacks != null)
                    for (ItemStack stack : bufferedStacks)
                        if (!stack.isEmpty())
                            queryList.add(stack.copy());
            for (ItemStack stack : this.inventory)
                if (!stack.isEmpty())
                    queryList.add(stack.copy());
            int consumed = IEConfig.Machines.assembler_consumption;
            if (this.energyStorage.extractEnergy(consumed, true) == consumed
                    && this.hasIngredients(pattern, queryList)) {
                this.energyStorage.extractEnergy(consumed, false);
                NonNullList<ItemStack> outputList = NonNullList.create();//List of all outputs for the current recipe. This includes discarded containers
                outputList.add(output);
                AssemblerHandler.IRecipeAdapter adapter = AssemblerHandler.findAdapter(pattern.recipe);
                AssemblerHandler.RecipeQuery[] queries = adapter.getQueriedInputs(pattern.recipe, pattern.inv);
                NonNullList<ItemStack> gridItems = NonNullList.withSize(9, ItemStack.EMPTY);
                for (int i = 0; i < queries.length; i++)
                    if (queries[i] != null) {
                        AssemblerHandler.RecipeQuery recipeQuery = queries[i];
                        Optional<ItemStack> taken = Optional.absent();
                        for (int j = 0; j < outputBuffer.length; j++)
                            if (outputBuffer[j] != null) {
                                taken = consumeItem(recipeQuery.query, recipeQuery.querySize, outputBuffer[j],
                                        outputList);
                                if (taken.isPresent())
                                    break;
                            }
                        if (!taken.isPresent())
                            taken = this.consumeItem(recipeQuery.query, recipeQuery.querySize, inventory,
                                    outputList);
                        gridItems.set(i, taken.or(ItemStack.EMPTY));
                    }
                NonNullList<ItemStack> remainingItems = pattern.recipe.getRemainingItems(
                        Utils.InventoryCraftingFalse.createFilledCraftingInventory(3, 3, gridItems));
                for (ItemStack rem : remainingItems)
                    if (!rem.isEmpty())
                        outputList.add(rem);
                outputBuffer[p] = outputList;
                update = true;
            }
        }
    }
    BlockPos outputPos = getPos().offset(facing, 2);
    TileEntity inventoryTile = Utils.getExistingTileEntity(world, outputPos);
    for (int buffer = 0; buffer < outputBuffer.length; buffer++)
        if (outputBuffer[buffer] != null && outputBuffer[buffer].size() > 0)
            for (int iOutput = 0; iOutput < outputBuffer[buffer].size(); iOutput++) {
                ItemStack output = outputBuffer[buffer].get(iOutput);
                if (!output.isEmpty() && output.getCount() > 0) {
                    if (!isRecipeIngredient(output, buffer) && inventoryTile != null) {
                        output = Utils.insertStackIntoInventory(inventoryTile, output, facing.getOpposite());
                        if (output.isEmpty() || output.getCount() <= 0)
                            continue;
                    }
                    int free = -1;
                    if (iOutput == 0)//Main recipe output
                    {
                        if (this.inventory.get(18 + buffer).isEmpty() && free < 0)
                            free = 18 + buffer;
                        else if (!this.inventory.get(18 + buffer).isEmpty()
                                && OreDictionary.itemMatches(output, this.inventory.get(18 + buffer), true)
                                && this.inventory.get(18 + buffer).getCount()
                                        + output.getCount() <= this.inventory.get(18 + buffer)
                                                .getMaxStackSize()) {
                            this.inventory.get(18 + buffer).grow(output.getCount());
                            free = -1;
                            continue;
                        }
                    } else
                        for (int i = 0; i < this.inventory.size(); i++) {
                            if (this.inventory.get(i).isEmpty() && free < 0)
                                free = i;
                            else if (!this.inventory.get(i).isEmpty()
                                    && OreDictionary.itemMatches(output, this.inventory.get(i), true)
                                    && this.inventory.get(i).getCount() + output.getCount() <= this.inventory
                                            .get(i).getMaxStackSize()) {
                                this.inventory.get(i).grow(output.getCount());
                                free = -1;
                                break;
                            }
                        }
                    if (free >= 0)
                        this.inventory.set(free, output.copy());
                }
            }
    for (int i = 0; i < 3; i++)
        if (!isRecipeIngredient(this.inventory.get(18 + i), i) && inventoryTile != null)
            this.inventory.set(18 + i, Utils.insertStackIntoInventory(inventoryTile, this.inventory.get(18 + i),
                    facing.getOpposite()));

    if (update) {
        this.markDirty();
        this.markContainingBlockForUpdate(null);
    }
}

From source file:com.arpnetworking.clusteraggregator.client.AggClientConnection.java

private Optional<PeriodicData> buildPeriodicData(final Messages.StatisticSetRecord setRecord) {
    final CombinedMetricData combinedMetricData = CombinedMetricData.Builder.fromStatisticSetRecord(setRecord)
            .build();/*from w  w w .ja  va 2s .co m*/
    final ImmutableList.Builder<AggregatedData> builder = ImmutableList.builder();
    final ImmutableMap.Builder<String, String> dimensionBuilder = ImmutableMap.builder();

    Optional<String> host = Optional.absent();
    Optional<String> service = Optional.absent();
    Optional<String> cluster = Optional.absent();
    for (final Messages.DimensionEntry dimensionEntry : setRecord.getDimensionsList()) {
        if (CombinedMetricData.HOST_KEY.equals(dimensionEntry.getKey())) {
            host = Optional.fromNullable(dimensionEntry.getValue());
        } else if (CombinedMetricData.SERVICE_KEY.equals(dimensionEntry.getKey())) {
            service = Optional.fromNullable(dimensionEntry.getValue());
        } else if (CombinedMetricData.CLUSTER_KEY.equals(dimensionEntry.getKey())) {
            cluster = Optional.fromNullable(dimensionEntry.getValue());
        } else {
            dimensionBuilder.put(dimensionEntry.getKey(), dimensionEntry.getValue());
        }
    }

    if (!service.isPresent()) {
        service = Optional.fromNullable(setRecord.getService());
    }

    if (!cluster.isPresent()) {
        cluster = Optional.fromNullable(setRecord.getCluster());
        if (!cluster.isPresent()) {
            cluster = _clusterName;
        }
    }

    if (!host.isPresent()) {
        host = _hostName;
    }

    dimensionBuilder.put(CombinedMetricData.HOST_KEY, host.or(""));
    dimensionBuilder.put(CombinedMetricData.SERVICE_KEY, service.or(""));
    dimensionBuilder.put(CombinedMetricData.CLUSTER_KEY, cluster.or(""));

    if (!(host.isPresent() && service.isPresent() && cluster.isPresent())) {
        INCOMPLETE_RECORD_LOGGER.warn()
                .setMessage("Cannot process StatisticSet record, missing required fields.")
                .addData("host", host).addData("service", service).addData("cluster", cluster).log();
        return Optional.absent();
    }

    final ImmutableMap<String, String> dimensions = dimensionBuilder.build();

    for (final Map.Entry<Statistic, CombinedMetricData.StatisticValue> record : combinedMetricData
            .getCalculatedValues().entrySet()) {
        final AggregatedData aggregatedData = new AggregatedData.Builder()
                .setFQDSN(
                        new FQDSN.Builder().setCluster(setRecord.getCluster()).setMetric(setRecord.getMetric())
                                .setService(setRecord.getService()).setStatistic(record.getKey()).build())
                .setHost(host.get()).setIsSpecified(record.getValue().getUserSpecified())
                .setPeriod(combinedMetricData.getPeriod()).setPopulationSize(1L)
                .setSamples(Collections.emptyList()).setStart(combinedMetricData.getPeriodStart())
                .setSupportingData(record.getValue().getValue().getData())
                .setValue(record.getValue().getValue().getValue()).build();
        builder.add(aggregatedData);
    }
    return Optional.of(new PeriodicData.Builder().setData(builder.build()).setConditions(ImmutableList.of())
            .setDimensions(dimensions).setPeriod(combinedMetricData.getPeriod())
            .setStart(combinedMetricData.getPeriodStart()).build());
}

From source file:com.eucalyptus.ws.server.NioServerHandler.java

private void sendError(final ChannelHandlerContext ctx, final HttpResponseStatus restStatus, Throwable t) {
    Logs.exhaust().error(t, t);//w w  w.  j a v a 2s.c om

    HttpResponseStatus status = restStatus;
    ChannelBuffer buffer = null;
    Optional<String> contentType = Optional.absent();
    if (ctx.getPipeline().get(SoapMarshallingHandler.class) != null) {
        final SOAPEnvelope soapEnvelope = Binding.createFault(
                status.getCode() < 500 ? "soapenv:Client" : "soapenv:Server", t.getMessage(),
                Logs.isExtrrreeeme() ? Exceptions.string(t) : t.getMessage());
        try {
            final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            HoldMe.canHas.lock();
            try {
                soapEnvelope.serialize(byteOut);
            } finally {
                HoldMe.canHas.unlock();
            }
            status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
            buffer = ChannelBuffers.wrappedBuffer(byteOut.toByteArray());
            contentType = Optional.of("text/xml; charset=UTF-8");
        } catch (Exception e) {
            Logs.exhaust().error(e, e);
        }
    }

    if (buffer == null) {
        buffer = ChannelBuffers.copiedBuffer(Binding.createRestFault(status.toString(), t.getMessage(),
                Logs.isExtrrreeeme() ? Exceptions.string(t) : t.getMessage()), "UTF-8");

    }

    final HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    response.addHeader(HttpHeaders.Names.CONTENT_TYPE, contentType.or("text/plain; charset=UTF-8"));
    response.addHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buffer.readableBytes()));
    response.setContent(buffer);

    ChannelFuture writeFuture = Channels.future(ctx.getChannel());
    writeFuture.addListener(ChannelFutureListener.CLOSE);
    response.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    if (ctx.getChannel().isConnected()) {
        Channels.write(ctx, writeFuture, response);
    }
}

From source file:org.apache.aurora.common.zookeeper.ZooKeeperClient.java

/**
 * Creates an unconnected client that will lazily attempt to connect on the first call to
 * {@link #get}.  All successful connections will be authenticated with the given
 * {@code credentials}./*from w  ww .ja  v a2s. c om*/
 *
 * @param sessionTimeout the ZK session timeout
 * @param credentials the credentials to authenticate with
 * @param chrootPath an optional chroot path
 * @param zooKeeperServers the set of servers forming the ZK cluster
 */
public ZooKeeperClient(Amount<Integer, Time> sessionTimeout, Optional<Credentials> credentials,
        Optional<String> chrootPath, Iterable<InetSocketAddress> zooKeeperServers) {
    this.sessionTimeoutMs = Preconditions.checkNotNull(sessionTimeout).as(Time.MILLISECONDS);
    this.credentials = Preconditions.checkNotNull(credentials);

    if (chrootPath.isPresent()) {
        PathUtils.validatePath(chrootPath.get());
    }

    Preconditions.checkNotNull(zooKeeperServers);
    Preconditions.checkArgument(!Iterables.isEmpty(zooKeeperServers), "Must present at least 1 ZK server");

    Thread watcherProcessor = new Thread("ZookeeperClient-watcherProcessor") {
        @Override
        public void run() {
            while (true) {
                try {
                    WatchedEvent event = eventQueue.take();
                    for (Watcher watcher : watchers) {
                        watcher.process(event);
                    }
                } catch (InterruptedException e) {
                    /* ignore */ }
            }
        }
    };
    watcherProcessor.setDaemon(true);
    watcherProcessor.start();

    Iterable<String> servers = Iterables.transform(ImmutableSet.copyOf(zooKeeperServers),
            InetSocketAddressHelper::toString);
    this.zooKeeperServers = Joiner.on(',').join(servers).concat(chrootPath.or(""));
}