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

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

Introduction

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

Prototype

public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

Usage

From source file:org.killbill.billing.invoice.tree.SubscriptionItemTree.java

/**
 * Merge a new proposed item in the tree.
 *
 * @param invoiceItem new proposed item that should be merged in the existing tree
 *//*  w  ww.  ja v a2s.c o  m*/
public void mergeProposedItem(final InvoiceItem invoiceItem) {
    Preconditions.checkState(!isBuilt, "Tree already built, unable to add new invoiceItem=%s", invoiceItem);

    switch (invoiceItem.getInvoiceItemType()) {
    case RECURRING:
        // merged means we've either matched the proposed to an existing, or triggered a repair
        final boolean merged = root.addProposedItem(
                new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.ADD)));
        if (!merged) {
            items.add(new Item(invoiceItem, targetInvoiceId, ItemAction.ADD));
        }
        break;

    case FIXED:
        final InvoiceItem existingItem = Iterables.tryFind(existingFixedItems, new Predicate<InvoiceItem>() {
            @Override
            public boolean apply(final InvoiceItem input) {
                return input.matches(invoiceItem);
            }
        }).orNull();
        if (existingItem == null) {
            remainingFixedItems.put(invoiceItem.getStartDate(), invoiceItem);
        }
        break;

    default:
        Preconditions.checkState(false, "Unexpected proposed item " + invoiceItem);
    }
}

From source file:clocker.docker.policy.ContainerHeadroomEnricher.java

private void recalculate() {
    Integer maxContainers = null;
    List<DockerAwarePlacementStrategy> strategies = entity.config()
            .get(DockerInfrastructure.PLACEMENT_STRATEGIES);
    Optional<DockerAwarePlacementStrategy> lookup = Iterables.tryFind(strategies,
            Predicates.instanceOf(MaxContainersPlacementStrategy.class));
    if (lookup.isPresent()) {
        maxContainers = ((MaxContainersPlacementStrategy) lookup.get()).config()
                .get(MaxContainersPlacementStrategy.DOCKER_CONTAINER_CLUSTER_MAX_SIZE);
    }/*from www. j av  a2  s . com*/
    if (maxContainers == null) {
        maxContainers = entity.config().get(MaxContainersPlacementStrategy.DOCKER_CONTAINER_CLUSTER_MAX_SIZE);
    }
    if (maxContainers == null) {
        maxContainers = MaxContainersPlacementStrategy.DEFAULT_MAX_CONTAINERS;
    }
    boolean tooColdEnabled = Boolean.TRUE.equals(config().get(CLUSTER_TOO_COLD_ENABLED));

    // Calculate cluster state
    Integer containers = entity.sensors().get(DockerInfrastructure.DOCKER_CONTAINER_COUNT);
    Integer hosts = entity.sensors().get(DockerInfrastructure.DOCKER_HOST_COUNT);
    if (containers == null || hosts == null)
        return;
    int possible = maxContainers * hosts;
    int available = possible - containers;

    // Calculate headroom
    Integer headroom = config().get(CONTAINER_HEADROOM);
    Double percent = config().get(CONTAINER_HEADROOM_PERCENTAGE);
    if (headroom == null) {
        headroom = (int) Math.ceil(percent * possible);
    }

    // Calculate requirements
    int needed = headroom - available;
    double utilisation = (double) containers / (double) possible;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Headroom enricher: {} containers on {} hosts, {} available and {} needed",
                new Object[] { containers, hosts, available, needed });
    }

    double lowThreshold = (double) (possible - (headroom + maxContainers)) / (double) possible;
    lowThreshold = Math.max(0d, lowThreshold);

    double highThreshold = (double) (possible - headroom) / (double) possible;
    highThreshold = Math.max(0d, highThreshold);

    // Emit current status of the pool as sensor data
    emit(CONTAINERS_NEEDED, needed);
    emit(DOCKER_CONTAINER_UTILISATION, utilisation);

    // Emit pool hot or cold sensors if headroom requirements not met
    Map<String, Object> properties = ImmutableMap.<String, Object>of(AutoScalerPolicy.POOL_CURRENT_SIZE_KEY,
            hosts, AutoScalerPolicy.POOL_CURRENT_WORKRATE_KEY, utilisation,
            AutoScalerPolicy.POOL_LOW_THRESHOLD_KEY, lowThreshold, AutoScalerPolicy.POOL_HIGH_THRESHOLD_KEY,
            highThreshold);
    if (needed > 0) {
        lastPublished = DOCKER_CONTAINER_CLUSTER_HOT;
        emit(DOCKER_CONTAINER_CLUSTER_HOT, properties);
    } else if (tooColdEnabled && available > (headroom + maxContainers)) {
        lastPublished = DOCKER_CONTAINER_CLUSTER_COLD;
        emit(DOCKER_CONTAINER_CLUSTER_COLD, properties);
    } else {
        // Only emit ok if we weren't previously
        if (lastPublished != null && lastPublished != DOCKER_CONTAINER_CLUSTER_OK) {
            lastPublished = DOCKER_CONTAINER_CLUSTER_OK;
            emit(DOCKER_CONTAINER_CLUSTER_OK, properties);
        }
    }
}

From source file:org.ow2.petals.cloud.manager.core.services.DefaultManagementService.java

/**
 * Get the account to be used with the node and defined provider manager
 *
 * @param node/*from   w  w  w. j a  v  a2 s  .co  m*/
 * @return
 */
protected Provider getProvider(final Deployment descriptor, final Node node) {
    return Iterables.tryFind(descriptor.getProviders(), new Predicate<Provider>() {
        public boolean apply(org.ow2.petals.cloud.manager.api.deployment.Provider input) {
            return input.getName().equals(node.getProvider());
        }
    }).orNull();
}

From source file:com.siemens.sw360.datahandler.common.CommonUtils.java

public static Optional<Attachment> getAttachmentOptional(final String attachmentId,
        Set<Attachment> attachments) {
    return Iterables.tryFind(attachments, new Predicate<Attachment>() {
        @Override// www  .  j  a  v a 2s.  c  o  m
        public boolean apply(Attachment input) {
            return attachmentId.equals(input.getAttachmentContentId());
        }
    });
}

From source file:com.thinkbiganalytics.nifi.rest.support.NifiConnectionUtil.java

/**
 * Return a input or output port dto matching a give name
 *
 * @param ports a collection of port objects
 * @param name  a name to match/*from  www .  ja v a 2s .c  o  m*/
 * @return the first port dto matching the supplied name
 */
public static PortDTO findPortMatchingName(Collection<PortDTO> ports, final String name) {

    return Iterables.tryFind(ports, new Predicate<PortDTO>() {
        @Override
        public boolean apply(PortDTO portDTO) {
            return portDTO.getName().equalsIgnoreCase(name);
        }
    }).orNull();
}

From source file:org.zanata.action.ProjectPermissionDialog.java

/**
 * Update role membership for a locale-specific role based on the current
 * checkbox value.//w  w  w.  j  a  v a  2  s.co m
 *
 * @param localeRole
 *            represents both the locale and the role format:
 *            {localeId}:{role}. e.g en-US:Reviewer
 * @param checked
 *            the current checkbox value
 */
public void bindTranslationRole(String localeRole, boolean checked) {
    String[] localeRoleList = StringUtils.split(localeRole, ':');
    final HLocale hLocale = localeServiceImpl.getByLocaleId(localeRoleList[0]);
    String role = localeRoleList[1];
    final Optional<PersonProjectMemberships.LocaleRoles> matchingLocaleRoles = Iterables
            .tryFind(data.getLocaleRoles(), localeEqualsPredicate(hLocale));
    if (matchingLocaleRoles.isPresent()) {
        PersonProjectMemberships.LocaleRoles localeRoles = matchingLocaleRoles.get();
        if (StringUtils.equalsIgnoreCase(role, LocaleRole.Translator.name())) {
            localeRoles.setTranslator(checked);
        } else if (StringUtils.equalsIgnoreCase(role, LocaleRole.Reviewer.name())) {
            localeRoles.setReviewer(checked);
        } else if (StringUtils.equalsIgnoreCase(role, LocaleRole.Coordinator.name())) {
            localeRoles.setCoordinator(checked);
        } else if (StringUtils.equalsIgnoreCase(role, LocaleRole.Glossarist.name())) {
            localeRoles.setGlossarist(checked);
        }
    } else {
        // No LocaleRoles for the given locale, so create a new one.
        List<LocaleRole> roleList = Lists.newArrayList(LocaleRole.valueOf(role));
        data.addLocaleRoles(hLocale, roleList);
    }
}

From source file:org.killbill.billing.osgi.OSGIListener.java

private NodeCommandMetadata deserializeNodeCommand(final String nodeCommand, final String type)
        throws IOException {

    final SystemNodeCommandType systemType = Iterables.tryFind(
            ImmutableList.copyOf(SystemNodeCommandType.values()), new Predicate<SystemNodeCommandType>() {
                @Override//ww  w.j  a  v  a  2s.c o m
                public boolean apply(final SystemNodeCommandType input) {
                    return input.name().equals(type);
                }
            }).orNull();
    return (systemType != null) ? objectMapper.readValue(nodeCommand, systemType.getCommandMetadataClass())
            : objectMapper.readValue(nodeCommand, DefaultNodeCommandMetadata.class);
}

From source file:org.apache.brooklyn.entity.group.AbstractGroupImpl.java

/**
 * Adds the given entity as a member of this group <em>and</em> this group as one of the groups of the child
 *///from   w w w  . j a v a  2 s .  co m
@Override
public boolean addMember(Entity member) {
    synchronized (members) {
        if (Entities.isNoLongerManaged(member)) {
            // Don't add dead entities, as they could never be removed (because addMember could be called in
            // concurrent thread as removeMember triggered by the unmanage).
            // Not using Entities.isManaged here, as could be called in entity.init()
            log.debug("Group {} ignoring new member {}, because it is no longer managed", this, member);
            return false;
        }

        // FIXME do not set sensors on members; possibly we don't need FIRST at all, just look at the first in MEMBERS, and take care to guarantee order there
        Entity first = getAttribute(FIRST);
        if (first == null) {
            ((EntityLocal) member).sensors().set(FIRST_MEMBER, true);
            ((EntityLocal) member).sensors().set(FIRST, member);
            sensors().set(FIRST, member);
        } else {
            if (first.equals(member) || first.equals(member.getAttribute(FIRST))) {
                // do nothing (rebinding)
            } else {
                ((EntityLocal) member).sensors().set(FIRST_MEMBER, false);
                ((EntityLocal) member).sensors().set(FIRST, first);
            }
        }

        member.addGroup((Group) getProxyIfAvailable());
        boolean changed = addMemberInternal(member);
        if (changed) {
            log.debug("Group {} got new member {}", this, member);
            sensors().set(GROUP_SIZE, getCurrentSize());
            sensors().set(GROUP_MEMBERS, getMembers());
            // emit after the above so listeners can use getMembers() and getCurrentSize()
            sensors().emit(MEMBER_ADDED, member);

            if (Boolean.TRUE.equals(getConfig(MEMBER_DELEGATE_CHILDREN))) {
                log.warn("Use of deprecated ConfigKey {} in {} (as of 0.9.0)",
                        MEMBER_DELEGATE_CHILDREN.getName(), this);
                Optional<Entity> result = Iterables.tryFind(getChildren(), Predicates.equalTo(member));
                if (!result.isPresent()) {
                    String nameFormat = Optional.fromNullable(getConfig(MEMBER_DELEGATE_NAME_FORMAT)).or("%s");
                    DelegateEntity child = addChild(EntitySpec.create(DelegateEntity.class)
                            .configure(DelegateEntity.DELEGATE_ENTITY, member)
                            .displayName(String.format(nameFormat, member.getDisplayName())));
                }
            }

            getManagementSupport().getEntityChangeListener().onMembersChanged();
        }
        return changed;
    }
}

From source file:brooklyn.entity.cloud.CloudEnvironmentImpl.java

@Override
public void start(Collection<? extends Location> locations) {
    Optional<? extends Location> location = Optional.absent();
    if (Iterables.size(locations) > 0) {
        location = Iterables.tryFind(locations, Predicates.instanceOf(MachineProvisioningLocation.class));
    }/* w ww  .  j a v a 2  s.  co m*/
    Location provisioner;
    if (!location.isPresent() || location.get() instanceof LocalhostMachineProvisioningLocation) {
        LocationSpec<?> spec = getConfig(CLOUD_LOCATION_SPEC);
        provisioner = getManagementContext().getLocationManager().createLocation(spec);
    } else {
        provisioner = location.get();
    }
    log.info("Creating new CloudLocation wrapping {}", provisioner);

    Map<String, ?> flags = MutableMap.<String, Object>builder().putAll(getConfig(LOCATION_FLAGS))
            .put("provisioner", provisioner).build();
    createLocation(flags);

    super.start(locations);
}

From source file:springfox.documentation.schema.property.bean.BeanModelPropertyProvider.java

private Optional<ResolvedMethod> findAccessorMethod(ResolvedType resolvedType, final String propertyName,
        final AnnotatedMember member) {
    return Iterables.tryFind(accessors.in(resolvedType), new Predicate<ResolvedMethod>() {
        public boolean apply(ResolvedMethod accessorMethod) {
            return BeanModelProperty.accessorMemberIs(accessorMethod, Annotations.memberName(member))
                    && propertyName.equals(Accessors.propertyName(accessorMethod.getRawMember()));
        }/*from  ww w .j a va2  s .  c o  m*/
    });
}