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.dao.DefaultInvoiceDao.java

@Override
public InvoicePaymentModelDao postChargeback(final UUID paymentId,
        final String chargebackTransactionExternalKey, final BigDecimal amount, final Currency currency,
        final InternalCallContext context) throws InvoiceApiException {
    final List<Tag> invoicesTags = getInvoicesTags(context);

    return transactionalSqlDao.execute(InvoiceApiException.class,
            new EntitySqlDaoTransactionWrapper<InvoicePaymentModelDao>() {
                @Override/*  w  ww .j a va  2  s.  c  om*/
                public InvoicePaymentModelDao inTransaction(
                        final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
                    final InvoicePaymentSqlDao transactional = entitySqlDaoWrapperFactory
                            .become(InvoicePaymentSqlDao.class);

                    final List<InvoicePaymentModelDao> invoicePayments = transactional
                            .getByPaymentId(paymentId.toString(), context);
                    final InvoicePaymentModelDao invoicePayment = Iterables
                            .tryFind(invoicePayments, new Predicate<InvoicePaymentModelDao>() {
                                @Override
                                public boolean apply(final InvoicePaymentModelDao input) {
                                    return input.getType() == InvoicePaymentType.ATTEMPT;
                                }
                            }).orNull();
                    if (invoicePayment == null) {
                        throw new InvoiceApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT, paymentId);
                    }
                    // We expect the code to correctly pass the account currency -- the payment code, more generic accept chargeBack in different currencies,
                    // but this is only for direct payment (no invoice)
                    Preconditions.checkArgument(invoicePayment.getCurrency() == currency,
                            String.format("Invoice payment currency %s doesn't match chargeback currency %s",
                                    invoicePayment.getCurrency(), currency));

                    final UUID invoicePaymentId = invoicePayment.getId();
                    final BigDecimal maxChargedBackAmount = invoiceDaoHelper
                            .getRemainingAmountPaidFromTransaction(invoicePaymentId, entitySqlDaoWrapperFactory,
                                    context);
                    final BigDecimal requestedChargedBackAmount = (amount == null) ? maxChargedBackAmount
                            : amount;
                    if (requestedChargedBackAmount.compareTo(BigDecimal.ZERO) <= 0) {
                        throw new InvoiceApiException(ErrorCode.CHARGE_BACK_AMOUNT_IS_NEGATIVE);
                    }
                    if (requestedChargedBackAmount.compareTo(maxChargedBackAmount) > 0) {
                        throw new InvoiceApiException(ErrorCode.CHARGE_BACK_AMOUNT_TOO_HIGH,
                                requestedChargedBackAmount, maxChargedBackAmount);
                    }

                    final InvoicePaymentModelDao payment = entitySqlDaoWrapperFactory
                            .become(InvoicePaymentSqlDao.class).getById(invoicePaymentId.toString(), context);
                    if (payment == null) {
                        throw new InvoiceApiException(ErrorCode.INVOICE_PAYMENT_NOT_FOUND,
                                invoicePaymentId.toString());
                    }
                    final InvoicePaymentModelDao chargeBack = new InvoicePaymentModelDao(UUIDs.randomUUID(),
                            context.getCreatedDate(), InvoicePaymentType.CHARGED_BACK, payment.getInvoiceId(),
                            payment.getPaymentId(), context.getCreatedDate(),
                            requestedChargedBackAmount.negate(), payment.getCurrency(),
                            payment.getProcessedCurrency(), chargebackTransactionExternalKey, payment.getId(),
                            true);
                    createAndRefresh(transactional, chargeBack, context);

                    // Notify the bus since the balance of the invoice changed
                    final UUID accountId = transactional
                            .getAccountIdFromInvoicePaymentId(chargeBack.getId().toString(), context);

                    cbaDao.doCBAComplexityFromTransaction(payment.getInvoiceId(), invoicesTags,
                            entitySqlDaoWrapperFactory, context);

                    notifyBusOfInvoicePayment(entitySqlDaoWrapperFactory, chargeBack, accountId,
                            context.getUserToken(), context);

                    return chargeBack;
                }
            });
}

From source file:org.killbill.billing.payment.invoice.InvoicePaymentControlPluginApi.java

private boolean checkForIncompleteInvoicePaymentAndRepair(final Invoice invoice,
        final InternalCallContext internalContext) throws InvoiceApiException {

    final List<InvoicePayment> invoicePayments = invoice.getPayments();

    // Look for ATTEMPT matching that invoiceId that are not successful and extract matching paymentTransaction
    final InvoicePayment incompleteInvoicePayment = Iterables
            .tryFind(invoicePayments, new Predicate<InvoicePayment>() {
                @Override//from   w ww  . j  av  a 2  s. c  om
                public boolean apply(final InvoicePayment input) {
                    return input.getType() == InvoicePaymentType.ATTEMPT && !input.isSuccess();
                }
            }).orNull();

    // If such (incomplete) paymentTransaction exists, verify the state of the payment transaction
    if (incompleteInvoicePayment != null) {
        final String transactionExternalKey = incompleteInvoicePayment.getPaymentCookieId();
        final List<PaymentTransactionModelDao> transactions = paymentDao
                .getPaymentTransactionsByExternalKey(transactionExternalKey, internalContext);
        final PaymentTransactionModelDao successfulTransaction = Iterables
                .tryFind(transactions, new Predicate<PaymentTransactionModelDao>() {
                    @Override
                    public boolean apply(final PaymentTransactionModelDao input) {
                        //
                        // In reality this is more tricky because the matching transaction could be an UNKNOWN or PENDING (unsupported by the plugin) state
                        // In case of UNKNOWN, we don't know what to do: fixing it could result in not paying, and not fixing it could result in double payment
                        // Current code ignores it, which means we might end up in doing a double payment in that very edgy scenario, and customer would have to request a refund.
                        //
                        return input.getTransactionStatus() == TransactionStatus.SUCCESS;
                    }
                }).orNull();

        if (successfulTransaction != null) {
            log.info(String.format(
                    "Detected an incomplete invoicePayment row for invoiceId='%s' and transactionExternalKey='%s', will correct status",
                    invoice.getId(), successfulTransaction.getTransactionExternalKey()));

            invoiceApi.recordPaymentAttemptCompletion(invoice.getId(), successfulTransaction.getAmount(),
                    successfulTransaction.getCurrency(), successfulTransaction.getProcessedCurrency(),
                    successfulTransaction.getPaymentId(), successfulTransaction.getTransactionExternalKey(),
                    successfulTransaction.getCreatedDate(), true, internalContext);
            return true;

        }
    }
    return false;
}

From source file:clocker.docker.entity.DockerHostImpl.java

public void scanContainers() {
    getDynamicLocation().getLock().lock();
    try {//w  ww  .  j a  va  2 s. c  o m
        String output = runDockerCommand("ps");
        List<String> ps = Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings().splitToList(output);
        if (ps.size() > 1) {
            for (int i = 1; i < ps.size(); i++) {
                String line = ps.get(i);
                String id = Strings.getFirstWord(line);
                Optional<Entity> container = Iterables.tryFind(getDockerContainerCluster().getMembers(),
                        Predicates.compose(StringPredicates.startsWith(id),
                                EntityFunctions.attribute(DockerContainer.DOCKER_CONTAINER_ID)));
                if (container.isPresent())
                    continue;

                // Build an unmanged DockerContainer without a locations, as it may not be SSHable
                String containerId = Strings.getFirstWord(runDockerCommand("inspect --format {{.Id}} " + id));
                String imageId = Strings.getFirstWord(runDockerCommand("inspect --format {{.Image}} " + id));
                String imageName = Strings
                        .getFirstWord(runDockerCommand("inspect --format {{.Config.Image}} " + id));
                EntitySpec<DockerContainer> containerSpec = EntitySpec
                        .create(config().get(DOCKER_CONTAINER_SPEC));
                containerSpec.configure(SoftwareProcess.ENTITY_STARTED, Boolean.TRUE)
                        .configure(DockerContainer.DOCKER_HOST, this)
                        .configure(DockerContainer.DOCKER_INFRASTRUCTURE, getInfrastructure())
                        .configure(DockerContainer.DOCKER_IMAGE_ID, imageId)
                        .configure(DockerContainer.DOCKER_IMAGE_NAME, imageName)
                        .configure(DockerContainer.MANAGED, Boolean.FALSE)
                        .configure(DockerContainer.LOCATION_FLAGS,
                                MutableMap.<String, Object>of("container", getMachine()));

                // Create and start the container
                DockerContainer added = getDockerContainerCluster().addMemberChild(containerSpec);
                added.sensors().set(DockerContainer.DOCKER_CONTAINER_ID, containerId);
                added.start(ImmutableList.of(getDynamicLocation().getMachine()));
            }
        }
        for (Entity member : ImmutableList.copyOf(getDockerContainerCluster().getMembers())) {
            final String id = member.sensors().get(DockerContainer.DOCKER_CONTAINER_ID);
            if (id != null) {
                Optional<String> found = Iterables.tryFind(ps, new Predicate<String>() {
                    @Override
                    public boolean apply(String input) {
                        String firstWord = Strings.getFirstWord(input);
                        return id.startsWith(firstWord);
                    }
                });
                if (found.isPresent())
                    continue;
            }

            // Stop and then remove the container as it is no longer running unless ON_FIRE
            Lifecycle state = member.sensors().get(SERVICE_STATE_ACTUAL);
            if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                continue;
            } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                getDockerContainerCluster().removeMember(member);
                getDockerContainerCluster().removeChild(member);
                Entities.unmanage(member);
            } else {
                ServiceStateLogic.setExpectedState(member, Lifecycle.STOPPING);
            }
        }
    } finally {
        getDynamicLocation().getLock().unlock();
    }
}

From source file:com.eucalyptus.compute.vpc.VpcManager.java

public CreateRouteResponseType createRoute(final CreateRouteType request) throws EucalyptusCloudException {
    final CreateRouteResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final AccountFullName accountFullName = ctx.getUserFullName().asAccountFullName();
    final String gatewayId = Identifier.igw.normalize(request.getGatewayId());
    final String routeTableId = Identifier.rtb.normalize(request.getRouteTableId());
    final String destinationCidr = request.getDestinationCidrBlock();
    final Optional<Cidr> destinationCidrOption = Cidr.parse().apply(destinationCidr);
    if (!destinationCidrOption.isPresent()) {
        throw new ClientComputeException("InvalidParameterValue", "Cidr invalid: " + destinationCidr);
    }/*from  w  w  w.  jav  a 2 s  .c o  m*/
    final Supplier<Route> allocator = transactional(new Supplier<Route>() {
        @Override
        public Route get() {
            try {
                final InternetGateway internetGateway = internetGateways.lookupByName(accountFullName,
                        gatewayId, Functions.<InternetGateway>identity());
                routeTables.updateByExample(RouteTable.exampleWithName(accountFullName, routeTableId),
                        accountFullName, request.getRouteTableId(), new Callback<RouteTable>() {
                            @Override
                            public void fire(final RouteTable routeTable) {
                                try {
                                    if (RestrictedTypes.filterPrivileged().apply(routeTable)) {
                                        final Optional<Route> existingRoute = Iterables.tryFind(
                                                routeTable.getRoutes(),
                                                CollectionUtils.propertyPredicate(destinationCidr,
                                                        RouteTables.RouteFilterStringFunctions.DESTINATION_CIDR));

                                        if (existingRoute.isPresent()) {
                                            throw new ClientComputeException("RouteAlreadyExists",
                                                    "Route exists for cidr: " + destinationCidr);
                                        }

                                        if (routeTable.getRoutes().size() >= VpcConfiguration
                                                .getRoutesPerTable()) {
                                            throw new ClientComputeException("RouteLimitExceeded",
                                                    "Route limit exceeded for " + request.getRouteTableId());
                                        }

                                        routeTable.getRoutes()
                                                .add(Route.create(routeTable, Route.RouteOrigin.CreateRoute,
                                                        destinationCidr, internetGateway));
                                        routeTable.updateTimeStamps(); // ensure version of table increments also
                                    } else {
                                        throw new ClientUnauthorizedComputeException(
                                                "Not authorized to create route");
                                    }
                                } catch (Exception e) {
                                    throw Exceptions.toUndeclared(e);
                                }
                            }
                        });
                return null;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });

    try {
        allocator.get();
        invalidate(routeTableId);
    } catch (Exception e) {
        throw handleException(e);
    }

    return reply;
}

From source file:org.apache.brooklyn.container.location.kubernetes.KubernetesLocation.java

protected LocationSpec<KubernetesSshMachineLocation> prepareSshableLocationSpec(Entity entity, ConfigBag setup,
        Namespace namespace, String deploymentName, Service service, Pod pod) {
    InetAddress node = Networking.getInetAddressWithFixedName(pod.getSpec().getNodeName());
    String podAddress = pod.getStatus().getPodIP();
    LocationSpec<KubernetesSshMachineLocation> locationSpec = LocationSpec
            .create(KubernetesSshMachineLocation.class).configure("address", node)
            .configure(SshMachineLocation.PRIVATE_ADDRESSES, ImmutableSet.of(podAddress))
            .configure(CALLER_CONTEXT, setup.get(CALLER_CONTEXT));
    if (!isDockerContainer(entity)) {
        Optional<ServicePort> sshPort = Iterables.tryFind(service.getSpec().getPorts(),
                new Predicate<ServicePort>() {
                    @Override//from  w  w  w  .  j  av a2 s  .c o  m
                    public boolean apply(ServicePort input) {
                        return input.getProtocol().equalsIgnoreCase("TCP") && input.getPort().intValue() == 22;
                    }
                });
        Optional<Integer> sshPortNumber;
        if (sshPort.isPresent()) {
            sshPortNumber = Optional.of(sshPort.get().getNodePort());
        } else {
            LOG.warn("No port-mapping found to ssh port 22, for container {}", service);
            sshPortNumber = Optional.absent();
        }
        locationSpec.configure(CloudLocationConfig.USER, setup.get(KubernetesLocationConfig.LOGIN_USER))
                .configure(SshMachineLocation.PASSWORD, setup.get(KubernetesLocationConfig.LOGIN_USER_PASSWORD))
                .configureIfNotNull(SshMachineLocation.SSH_PORT, sshPortNumber.orNull())
                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true)
                .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp");
    }
    return locationSpec;
}

From source file:com.eucalyptus.compute.vpc.VpcManager.java

public CreateSubnetResponseType createSubnet(final CreateSubnetType request) throws EucalyptusCloudException {
    final CreateSubnetResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final AccountFullName accountFullName = ctx.getUserFullName().asAccountFullName();
    final String vpcId = Identifier.vpc.normalize(request.getVpcId());
    final Optional<String> availabilityZone = Iterables.tryFind(Clusters.getInstance().listValues(),
            Predicates.and(/*from   ww w.  j  av a2 s . c  o m*/
                    request.getAvailabilityZone() == null ? Predicates.<RestrictedType>alwaysTrue()
                            : CollectionUtils.propertyPredicate(request.getAvailabilityZone(),
                                    CloudMetadatas.toDisplayName()),
                    RestrictedTypes.filterPrivilegedWithoutOwner()))
            .transform(CloudMetadatas.toDisplayName());
    final Optional<Cidr> subnetCidr = Cidr.parse().apply(request.getCidrBlock());
    if (!subnetCidr.isPresent()) {
        throw new ClientComputeException("InvalidParameterValue", "Cidr invalid: " + request.getCidrBlock());
    }
    if (!availabilityZone.isPresent()) {
        throw new ClientComputeException("InvalidParameterValue",
                "Availability zone invalid: " + request.getAvailabilityZone());
    }
    final Supplier<Subnet> allocator = new Supplier<Subnet>() {
        @Override
        public Subnet get() {
            try {
                final Vpc vpc = vpcs.lookupByName(accountFullName, vpcId, Functions.<Vpc>identity());
                final Iterable<Subnet> subnetsInVpc = subnets.listByExample(
                        Subnet.exampleWithOwner(accountFullName), CollectionUtils
                                .propertyPredicate(vpc.getDisplayName(), Subnets.FilterStringFunctions.VPC_ID),
                        Functions.<Subnet>identity());
                if (Iterables.size(subnetsInVpc) >= VpcConfiguration.getSubnetsPerVpc()) {
                    throw new ClientComputeException("SubnetLimitExceeded",
                            "Subnet limit exceeded for " + vpc.getDisplayName());
                }
                if (!Cidr.parse(vpc.getCidr()).contains(subnetCidr.get())) {
                    throw new ClientComputeException("InvalidParameterValue",
                            "Cidr not valid for vpc " + request.getCidrBlock());
                }
                final Iterable<Cidr> existingCidrs = Iterables.transform(subnetsInVpc,
                        Functions.compose(Cidr.parseUnsafe(), Subnets.FilterStringFunctions.CIDR));
                if (Iterables.any(existingCidrs, subnetCidr.get().contains())
                        || Iterables.any(existingCidrs, subnetCidr.get().containedBy())) {
                    throw new ClientComputeException("InvalidSubnet.Conflict",
                            "Cidr conflict for " + request.getCidrBlock());
                }
                final NetworkAcl networkAcl = networkAcls.lookupDefault(vpc.getDisplayName(),
                        Functions.<NetworkAcl>identity());
                return subnets.save(Subnet.create(ctx.getUserFullName(), vpc, networkAcl,
                        Identifier.subnet.generate(), request.getCidrBlock(), availabilityZone.get()));
            } catch (VpcMetadataNotFoundException ex) {
                throw Exceptions.toUndeclared(new ClientComputeException("InvalidVpcID.NotFound",
                        "Vpc not found '" + request.getVpcId() + "'"));
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
    reply.setSubnet(allocate(allocator, Subnet.class, SubnetType.class));
    invalidate(reply.getSubnet().getSubnetId());
    return reply;
}

From source file:org.obm.push.mail.MailBackendImpl.java

@Override
public BackendId createFolder(UserDataRequest udr, FolderCreateRequest folderCreateRequest,
        Optional<BackendId> parent) throws BackendNotSupportedException {

    MailboxFolders subscribedFolders = mailboxService.listSubscribedFolders(udr);
    char serverDelimiter = findServerSeparator(udr, parent, subscribedFolders);

    MailboxFolder newMailboxFolder = findNameRelatedToParent(folderCreateRequest, parent, serverDelimiter);

    MailboxPath mailboxPath = MailboxPath.of(newMailboxFolder.getName(), newMailboxFolder.getImapSeparator());

    Optional<MailboxFolder> subscribedFolder = Iterables.tryFind(subscribedFolders,
            Predicates.equalTo(newMailboxFolder));
    if (subscribedFolder.isPresent()) {
        throw new FolderAlreadyExistsException("Cannot create two times a folder.");
    } else if (mailboxService.folderExists(udr, mailboxPath)) {
        mailboxService.subscribeToFolder(udr, newMailboxFolder);
    } else {//from w  ww .j av  a  2s. co  m
        mailboxService.createFolder(udr, newMailboxFolder);
        mailboxService.subscribeToFolder(udr, newMailboxFolder);
    }

    return mailboxPath;
}

From source file:com.eucalyptus.cluster.callback.reporting.CloudWatchHelper.java

private static Predicate<MetricDatum> withMetricDimension(final String dimensionName,
        final String dimensionValue) {
    return new Predicate<MetricDatum>() {
        private final Predicate<Dimension> dimensionPredicate = withDimension(dimensionName, dimensionValue);

        @Override//from www  .j  a v a2 s.co m
        public boolean apply(@Nullable final MetricDatum metricDatum) {
            return metricDatum != null && metricDatum.getDimensions() != null
                    && metricDatum.getDimensions().getMember() != null && Iterables
                            .tryFind(metricDatum.getDimensions().getMember(), dimensionPredicate).isPresent();
        }
    };
}

From source file:org.opendaylight.netconf.sal.restconf.impl.RestconfImpl.java

@Override
public Response deleteConfigurationData(final String identifier) {
    final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
    final DOMMountPoint mountPoint = iiWithData.getMountPoint();
    final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();

    try {//from   www  . java 2s  . co m
        if (mountPoint != null) {
            this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
        } else {
            this.broker.commitConfigurationDataDelete(normalizedII).get();
        }
    } catch (final Exception e) {
        final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
                Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
        if (searchedException.isPresent()) {
            throw new RestconfDocumentedException("Data specified for deleting doesn't exist.",
                    ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
        }
        final String errMsg = "Error while deleting data";
        LOG.info(errMsg, e);
        throw new RestconfDocumentedException(errMsg, e);
    }
    return Response.status(Status.OK).build();
}

From source file:org.apache.brooklyn.container.location.kubernetes.KubernetesLocation.java

public boolean implementsInterface(Entity entity, Class<?> type) {
    return Iterables.tryFind(Arrays.asList(entity.getClass().getInterfaces()), Predicates.assignableFrom(type))
            .isPresent();//from  w ww.ja v  a  2s. c o  m
}