Example usage for com.google.common.collect Iterables getOnlyElement

List of usage examples for com.google.common.collect Iterables getOnlyElement

Introduction

In this page you can find the example usage for com.google.common.collect Iterables getOnlyElement.

Prototype

public static <T> T getOnlyElement(Iterable<T> iterable) 

Source Link

Document

Returns the single element contained in iterable .

Usage

From source file:org.apache.druid.indexing.common.task.ArchiveTask.java

@Override
public TaskStatus run(TaskToolbox toolbox) throws Exception {
    // Confirm we have a lock (will throw if there isn't exactly one element)
    final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox.getTaskActionClient()));

    if (!myLock.getDataSource().equals(getDataSource())) {
        throw new ISE("WTF?! Lock dataSource[%s] != task dataSource[%s]", myLock.getDataSource(),
                getDataSource());/*from  w  w w .  ja v a2s.  c  o m*/
    }

    if (!myLock.getInterval().equals(getInterval())) {
        throw new ISE("WTF?! Lock interval[%s] != task interval[%s]", myLock.getInterval(), getInterval());
    }

    // List unused segments
    final List<DataSegment> unusedSegments = toolbox.getTaskActionClient()
            .submit(new SegmentListUnusedAction(myLock.getDataSource(), myLock.getInterval()));

    // Verify none of these segments have versions > lock version
    for (final DataSegment unusedSegment : unusedSegments) {
        if (unusedSegment.getVersion().compareTo(myLock.getVersion()) > 0) {
            throw new ISE("WTF?! Unused segment[%s] has version[%s] > task version[%s]",
                    unusedSegment.getIdentifier(), unusedSegment.getVersion(), myLock.getVersion());
        }

        log.info("OK to archive segment: %s", unusedSegment.getIdentifier());
    }

    // Move segments
    for (DataSegment segment : unusedSegments) {
        final DataSegment archivedSegment = toolbox.getDataSegmentArchiver().archive(segment);
        if (archivedSegment != null) {
            toolbox.getTaskActionClient()
                    .submit(new SegmentMetadataUpdateAction(ImmutableSet.of(archivedSegment)));
        } else {
            log.info("No action was taken for [%s]", segment);
        }
    }

    return TaskStatus.success(getId());
}

From source file:com.b2international.snowowl.datastore.converter.BaseResourceConverter.java

@Override
public final R convert(T component) {
    return Iterables.getOnlyElement(convert(Collections.singleton(component), null, null, 1, 1));
}

From source file:org.jclouds.location.suppliers.RegionToProviderOrJustProvider.java

protected Builder<Location> buildJustProviderOrRegions() {
    Builder<Location> locations = ImmutableSet.builder();
    Location provider = Iterables.getOnlyElement(super.get());
    if (regions.size() == 0)
        return locations.add(provider);
    else/*from  ww w.j ava 2 s  .c  om*/
        for (String region : regions) {
            LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region)
                    .description(region).parent(provider);
            if (isoCodesById.containsKey(region))
                builder.iso3166Codes(isoCodesById.get(region));
            locations.add(builder.build());
        }
    return locations;
}

From source file:com.google.walkaround.wave.server.attachment.AttachmentUploadHandler.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
    List<BlobKey> blobKeys = blobs.get(ATTACHMENT_UPLOAD_PARAM);
    log.info("blobKeys: " + blobKeys);
    BlobKey blobKey = Iterables.getOnlyElement(blobKeys);
    AttachmentId newId = rawAttachmentService.turnBlobIntoAttachment(blobKey);
    UploadResult.write(resp.getWriter(), new GxpContext(getLocale(req)), analyticsAccount, newId.getId());
}

From source file:org.summer.dsl.xbase.typesystem.util.BoundTypeArgumentMerger.java

@Nullable
public LightweightMergedBoundTypeArgument merge(Collection<LightweightBoundTypeArgument> allArguments,
        ITypeReferenceOwner owner) {//from  w  w w . j  a v  a2  s .  co  m
    if (allArguments.isEmpty())
        return null;
    if (allArguments.size() == 1) {
        LightweightBoundTypeArgument argument = Iterables.getOnlyElement(allArguments);
        return getSingleArgumentAsMergedArgument(argument);
    }
    List<LightweightTypeReference> invariantTypes = Lists.newArrayListWithCapacity(3);
    List<VarianceInfo> invariantVariances = Lists.newArrayListWithCapacity(3);
    List<LightweightTypeReference> outTypes = Lists.newArrayListWithCapacity(3);
    List<LightweightTypeReference> constraintOutTypes = Lists.newArrayListWithCapacity(3);
    List<VarianceInfo> outVariances = Lists.newArrayListWithCapacity(3);
    List<LightweightTypeReference> inTypes = Lists.newArrayListWithCapacity(3);
    List<VarianceInfo> inVariances = Lists.newArrayListWithCapacity(3);
    Set<Object> seenOrigin = Sets.newHashSet();
    for (LightweightBoundTypeArgument boundTypeArgument : allArguments) {
        Object origin = boundTypeArgument.getOrigin();
        switch (boundTypeArgument.getDeclaredVariance()) {
        case INVARIANT:
            invariantTypes.add(boundTypeArgument.getTypeReference());
            if (seenOrigin.add(origin) || origin == null || boundTypeArgument.isValidVariancePair()) {
                invariantVariances.add(boundTypeArgument.getActualVariance());
            }
            break;
        case OUT:
            if (boundTypeArgument.getSource() == BoundTypeArgumentSource.CONSTRAINT) {
                constraintOutTypes.add(boundTypeArgument.getTypeReference());
            } else {
                outTypes.add(boundTypeArgument.getTypeReference());
            }
            if (seenOrigin.add(origin) || origin == null || boundTypeArgument.isValidVariancePair()) {
                outVariances.add(boundTypeArgument.getActualVariance());
            }
            break;
        case IN:
            inTypes.add(boundTypeArgument.getTypeReference());
            if (seenOrigin.add(origin) || origin == null || boundTypeArgument.isValidVariancePair()) {
                inVariances.add(boundTypeArgument.getActualVariance());
            }
            break;
        }
    }
    LightweightTypeReference type = null;
    VarianceInfo variance = null;
    if (outTypes.isEmpty()) {
        outTypes.addAll(constraintOutTypes);
    }
    if (!invariantTypes.isEmpty()) {
        type = invariantTypes.get(0);
        variance = VarianceInfo.INVARIANT.mergeDeclaredWithActuals(invariantVariances);
        if (variance == null && invariantVariances.contains(VarianceInfo.IN) && invariantTypes.size() > 1) {
            TypeConformanceComputer conformanceComputer = owner.getServices().getTypeConformanceComputer();
            type = conformanceComputer.getCommonSuperType(invariantTypes, owner);
        }
        if (!outVariances.isEmpty()) {
            VarianceInfo outVariance = VarianceInfo.OUT.mergeDeclaredWithActuals(outVariances);
            variance = VarianceInfo.OUT.mergeInvariance(variance, outVariance);
        } else if (!inVariances.isEmpty()) {
            VarianceInfo inVariance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
            variance = VarianceInfo.IN.mergeInvariance(variance, inVariance);
        }
    } else if (!outTypes.isEmpty()) {
        TypeConformanceComputer conformanceComputer = owner.getServices().getTypeConformanceComputer();
        type = conformanceComputer.getCommonSuperType(outTypes, owner);
        if (type == null)
            throw new IllegalStateException("common super type may not be null");
        variance = VarianceInfo.OUT.mergeDeclaredWithActuals(outVariances);
        if (!inVariances.isEmpty()) {
            LightweightTypeReference inType = getMostSpecialType(inTypes);
            boolean conformant = type.isAssignableFrom(inType,
                    new TypeConformanceComputationArgument(false, true, false, false, true, false));
            if (conformant) {
                VarianceInfo inVariance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
                variance = VarianceInfo.IN.mergeWithOut(variance, inVariance, conformant);
            } else {
                boolean reverseConformant = inType.isAssignableFrom(type,
                        new TypeConformanceComputationArgument(false, false, false, false, true, false));
                if (reverseConformant && variance == VarianceInfo.INVARIANT
                        && VarianceInfo.IN.mergeDeclaredWithActuals(inVariances) == VarianceInfo.INVARIANT) {
                    if (VarianceInfo.IN.mergeDeclaredWithActuals(outVariances) != null) {
                        type = inType;
                        variance = VarianceInfo.OUT;
                    }
                } else {
                    VarianceInfo inVariance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
                    variance = VarianceInfo.IN.mergeWithOut(variance, inVariance, conformant);
                }
            }
        }
    } else if (!inTypes.isEmpty()) {
        type = getMostSpecialType(inTypes);
        variance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
    }
    return new LightweightMergedBoundTypeArgument(type, variance);
}

From source file:com.google.template.soy.internal.proto.Field.java

/** Returns the set of fields indexed by soy accessor name for the given type. */
public static <T extends Field> ImmutableMap<String, T> getFieldsForType(Descriptor descriptor,
        Set<FieldDescriptor> extensions, Factory<T> factory) {
    ImmutableMap.Builder<String, T> fields = ImmutableMap.builder();
    for (FieldDescriptor fieldDescriptor : descriptor.getFields()) {
        if (ProtoUtils.shouldJsIgnoreField(fieldDescriptor)) {
            continue;
        }//from   www  . j  a v a 2 s .  c  o  m
        T field = factory.create(fieldDescriptor);
        fields.put(field.getName(), field);
    }

    SetMultimap<String, T> extensionsBySoyName = MultimapBuilder.hashKeys().hashSetValues().build();
    for (FieldDescriptor extension : extensions) {
        T field = factory.create(extension);
        extensionsBySoyName.put(field.getName(), field);
    }

    for (Map.Entry<String, Set<T>> group : Multimaps.asMap(extensionsBySoyName).entrySet()) {
        Set<T> ambiguousFields = group.getValue();
        String fieldName = group.getKey();
        if (ambiguousFields.size() == 1) {
            fields.put(fieldName, Iterables.getOnlyElement(ambiguousFields));
        } else {
            T value = factory.createAmbiguousFieldSet(ambiguousFields);
            logger.severe("Proto " + descriptor.getFullName() + " has multiple extensions with the name \""
                    + fieldName + "\": " + fullFieldNames(ambiguousFields)
                    + "\nThis field will not be accessible from soy");
            fields.put(fieldName, value);
        }
    }

    return fields.build();
}

From source file:org.jclouds.gogrid.compute.suppliers.GoGridLocationSupplier.java

@Override
public Set<? extends Location> get() {
    Builder<Location> locations = ImmutableSet.builder();
    Set<Option> list = sync.getServerServices().getDatacenters();
    Location provider = Iterables.getOnlyElement(super.get());
    if (list.size() == 0)
        locations.add(provider);//from   w  w w .  j  a v  a2 s  . c o m
    else
        for (Option from : list) {
            LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(from.getId() + "")
                    .description(from.getDescription()).parent(provider);
            if (isoCodesById.containsKey(from.getId() + ""))
                builder.iso3166Codes(isoCodesById.get(from.getId() + ""));
            locations.add(builder.build());
        }
    return locations.build();
}

From source file:org.apache.brooklyn.entity.proxy.StubAppServer.java

@Override
public void start(Collection<? extends Location> locations) {
    Location location = Iterables.getOnlyElement(locations);
    if (location instanceof MachineProvisioningLocation) {
        startInLocation((MachineProvisioningLocation) location);
    } else {//w w  w.  jav  a2 s  .  c  om
        startInLocation((MachineLocation) location);
    }
}

From source file:org.jclouds.cloudtransformer.openstack.CreateDevstackNode.java

@Override
public NodeMetadata apply(ComputeServiceContext input) {
    ComputeService original = input.getComputeService();

    logger.info("Creating devstack node on provider: %s", input.getProviderSpecificContext().getDescription());
    NodeMetadata devstackNode;/*  www.  ja v a  2 s . co  m*/

    try {
        devstackNode = Iterables.getOnlyElement(input.getComputeService().createNodesInGroup("devstack", 1));
    } catch (RunNodesException e) {
        throw Throwables.propagate(e);
    }
    original.runScriptOnNode(devstackNode.getId(), AdminAccess.standard());
    String address = Iterables.getFirst(devstackNode.getPublicAddresses(), null);
    logger.info("Running devstack script on node: [id= " + devstackNode.getId() + " address= " + address + "]");
    try {
        checkState(original.submitScriptOnNode(devstackNode.getId(), Devstack.inVm(), RunScriptOptions.NONE)
                .get(20, TimeUnit.MINUTES).getExitStatus() == 0);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    logger.info("Devstack installed. Dashboard available at: http://%s Ssh available at: ssh me@%s", address,
            address);
    return devstackNode;

}

From source file:com.facebook.presto.sql.planner.plan.ChildReplacer.java

@Override
public PlanNode visitLimit(LimitNode node, List<PlanNode> newChildren) {
    return new LimitNode(node.getId(), Iterables.getOnlyElement(newChildren), node.getCount());
}