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.opendaylight.controller.sal.restconf.impl.RestconfImpl.java

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

    try {/*from  w  ww  . j  a v  a2s . c om*/
        if (mountPoint != null) {
            broker.commitConfigurationDataDelete(mountPoint, normalizedII);
        } else {
            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.killbill.billing.invoice.dao.DefaultInvoiceDao.java

private void notifyOfPaymentCompletionInternal(final InvoicePaymentModelDao invoicePayment,
        final boolean completion, final InternalCallContext context) {
    transactionalSqlDao.execute(new EntitySqlDaoTransactionWrapper<Void>() {
        @Override/*from  ww w  .  j av a  2  s  .c o m*/
        public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory)
                throws Exception {
            final InvoicePaymentSqlDao transactional = entitySqlDaoWrapperFactory
                    .become(InvoicePaymentSqlDao.class);
            //
            // In case of notifyOfPaymentInit we always want to record the row with success = false
            // Otherwise, if the payment id is null, the payment wasn't attempted (e.g. no payment method so we don't record an attempt but send
            // an event nonetheless (e.g. for Overdue)
            //
            if (!completion || invoicePayment.getPaymentId() != null) {
                //
                // extract entries by invoiceId (which is always set, as opposed to paymentId) and then filter based on type and
                // paymentCookieId = transactionExternalKey
                //
                final List<InvoicePaymentModelDao> invoicePayments = transactional
                        .getAllPaymentsForInvoiceIncludedInit(invoicePayment.getInvoiceId().toString(),
                                context);
                final InvoicePaymentModelDao existingAttempt = Iterables
                        .tryFind(invoicePayments, new Predicate<InvoicePaymentModelDao>() {
                            @Override
                            public boolean apply(final InvoicePaymentModelDao input) {
                                return input.getType() == InvoicePaymentType.ATTEMPT && input
                                        .getPaymentCookieId().equals(invoicePayment.getPaymentCookieId());
                            }
                        }).orNull();

                if (existingAttempt == null) {
                    createAndRefresh(transactional, invoicePayment, context);
                } else {
                    transactional.updateAttempt(existingAttempt.getRecordId(),
                            invoicePayment.getPaymentId().toString(), invoicePayment.getPaymentDate().toDate(),
                            invoicePayment.getAmount(), invoicePayment.getCurrency(),
                            invoicePayment.getProcessedCurrency(), invoicePayment.getPaymentCookieId(), null,
                            invoicePayment.getSuccess(), context);
                }
            }

            if (completion) {
                final UUID accountId = nonEntityDao.retrieveIdFromObjectInTransaction(
                        context.getAccountRecordId(), ObjectType.ACCOUNT, objectIdCacheController,
                        entitySqlDaoWrapperFactory.getHandle());
                notifyBusOfInvoicePayment(entitySqlDaoWrapperFactory, invoicePayment, accountId,
                        context.getUserToken(), context);
            }
            return null;
        }
    });
}

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

public CreateVpcResponseType createVpc(final CreateVpcType request) throws EucalyptusCloudException {
    final CreateVpcResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final UserFullName userFullName = ctx.getUserFullName();
    final boolean createDefault = ctx.isAdministrator() && request.getCidrBlock().matches("[0-9]{12}");
    if (!Cidr.parse().apply(request.getCidrBlock()).transform(Cidr.prefix())
            .transform(Functions.forPredicate(Range.closed(16, 28))).or(createDefault)) {
        throw new ClientComputeException("InvalidVpcRange", "Cidr range invalid: " + request.getCidrBlock());
    }/*  w w w.  j  a  v  a 2 s.c o m*/
    final Supplier<Vpc> allocator = new Supplier<Vpc>() {
        @Override
        public Vpc get() {
            try {
                final String vpcCidr;
                final AccountFullName vpcAccountFullName;
                final UserFullName vpcOwnerFullName;
                Vpc vpc = null;
                RouteTable routeTable = null;
                NetworkAcl networkAcl = null;
                if (createDefault) {
                    final UserPrincipal user = Accounts.lookupPrincipalByAccountNumber(request.getCidrBlock());
                    vpcCidr = Vpcs.DEFAULT_VPC_CIDR;
                    vpcAccountFullName = AccountFullName.getInstance(user.getAccountNumber());
                    vpcOwnerFullName = UserFullName.getInstance(user);

                    // check for existing vpc
                    try {
                        vpc = vpcs.lookupDefault(vpcAccountFullName, Functions.<Vpc>identity());
                        routeTable = routeTables.lookupMain(vpc.getDisplayName(),
                                Functions.<RouteTable>identity());
                        networkAcl = networkAcls.lookupDefault(vpc.getDisplayName(),
                                Functions.<NetworkAcl>identity());
                    } catch (final VpcMetadataNotFoundException e) {
                        // so create it
                    }
                } else {
                    vpcCidr = request.getCidrBlock();
                    vpcAccountFullName = userFullName.asAccountFullName();
                    vpcOwnerFullName = userFullName;
                }
                if (vpc == null) {
                    DhcpOptionSet options;
                    try {
                        options = dhcpOptionSets.lookupByExample(
                                DhcpOptionSet.exampleDefault(vpcAccountFullName), vpcAccountFullName, "default",
                                Predicates.alwaysTrue(), Functions.<DhcpOptionSet>identity());
                    } catch (VpcMetadataNotFoundException e) {
                        options = dhcpOptionSets.save(DhcpOptionSet.createDefault(vpcOwnerFullName,
                                Identifier.dopt.generate(), VmInstances.INSTANCE_SUBDOMAIN));
                    }
                    vpc = vpcs.save(Vpc.create(vpcOwnerFullName, Identifier.vpc.generate(), options, vpcCidr,
                            createDefault));
                    routeTable = routeTables.save(RouteTable.create(vpcOwnerFullName, vpc,
                            Identifier.rtb.generate(), vpc.getCidr(), true));
                    networkAcl = networkAcls
                            .save(NetworkAcl.create(vpcOwnerFullName, vpc, Identifier.acl.generate(), true));
                    final NetworkGroup group = NetworkGroup.create(vpcOwnerFullName, vpc,
                            ResourceIdentifiers.generateString(NetworkGroup.ID_PREFIX),
                            NetworkGroups.defaultNetworkName(), "default VPC security group");
                    final Collection<NetworkPeer> peers = Lists.newArrayList(NetworkPeer
                            .create(group.getOwnerAccountNumber(), group.getName(), group.getGroupId()));
                    group.addNetworkRules(Lists.newArrayList(
                            NetworkRule.create(null/*protocol name*/, -1, null/*low port*/, null/*high port*/,
                                    peers, null/*cidrs*/ ),
                            NetworkRule.createEgress(null/*protocol name*/, -1, null/*low port*/,
                                    null/*high port*/, null/*peers*/, Collections.singleton("0.0.0.0/0"))));
                    securityGroups.save(group);
                }
                if (createDefault && routeTable != null && networkAcl != null) {
                    // ensure there is an internet gateway for the vpc and a route in place
                    InternetGateway internetGateway;
                    try {
                        internetGateway = internetGateways.lookupByVpc(vpcAccountFullName, vpc.getDisplayName(),
                                Functions.<InternetGateway>identity());
                    } catch (final VpcMetadataNotFoundException e) {
                        internetGateway = internetGateways
                                .save(InternetGateway.create(vpcOwnerFullName, Identifier.igw.generate()));
                        internetGateway.setVpc(vpc);
                    }

                    final Optional<Route> defaultRoute = Iterables.tryFind(routeTable.getRoutes(),
                            CollectionUtils.propertyPredicate("0.0.0.0/0",
                                    RouteTables.RouteFilterStringFunctions.DESTINATION_CIDR));

                    if (!defaultRoute.isPresent()) {
                        routeTable.getRoutes().add(Route.create(routeTable, Route.RouteOrigin.CreateRouteTable,
                                "0.0.0.0/0", internetGateway));
                        routeTable.updateTimeStamps(); // ensure version of table increments also
                    }

                    // ensure there is a default subnet in each availability zone
                    final Set<String> cidrsInUse = Sets.newHashSet();
                    final Set<String> zonesWithoutSubnets = Sets.newTreeSet();
                    for (final String zone : Iterables.transform(Clusters.getInstance().listValues(),
                            CloudMetadatas.toDisplayName())) {
                        try {
                            cidrsInUse.add(subnets.lookupDefault(vpcAccountFullName, zone,
                                    Subnets.FilterStringFunctions.CIDR));
                        } catch (final VpcMetadataNotFoundException e) {
                            zonesWithoutSubnets.add(zone);
                        }
                    }
                    final List<String> subnetCidrs = Lists.newArrayList(
                            Iterables.transform(Cidr.parseUnsafe().apply(Vpcs.DEFAULT_VPC_CIDR).split(16),
                                    Functions.toStringFunction()));
                    subnetCidrs.removeAll(cidrsInUse);
                    for (final String zone : zonesWithoutSubnets) {
                        final Subnet subnet = subnets.save(Subnet.create(vpcOwnerFullName, vpc, networkAcl,
                                Identifier.subnet.generate(), subnetCidrs.remove(0), zone));
                        subnet.setDefaultForAz(true);
                        subnet.setMapPublicIpOnLaunch(true);
                    }
                }
                return vpc;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
    reply.setVpc(allocate(allocator, Vpc.class, VpcType.class));
    invalidate(reply.getVpc().getVpcId());
    return reply;
}

From source file:com.eucalyptus.bootstrap.Hosts.java

public static Host lookup(final InetAddress address) {
    if (hostMap.containsKey(address.getHostAddress())) {
        return hostMap.get(address.getHostAddress());
    } else {/*ww w .  j a va  2  s .co  m*/
        return Iterables.tryFind(Hosts.list(), new Predicate<Host>() {
            @Override
            public boolean apply(Host input) {
                return input.getHostAddresses().contains(address);
            }
        }).orNull();
    }
}

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

public DeleteNetworkAclEntryResponseType deleteNetworkAclEntry(final DeleteNetworkAclEntryType request)
        throws EucalyptusCloudException {
    final DeleteNetworkAclEntryResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final AccountFullName accountFullName = ctx.isAdministrator() ? null
            : ctx.getUserFullName().asAccountFullName();
    final String networkAclId = Identifier.acl.normalize(request.getNetworkAclId());
    try {/* ww w .j  a  va2 s.  co m*/
        networkAcls.withRetries().updateByExample(NetworkAcl.exampleWithName(accountFullName, networkAclId),
                accountFullName, request.getNetworkAclId(), new Callback<NetworkAcl>() {
                    @Override
                    public void fire(final NetworkAcl networkAcl) {
                        try {
                            if (RestrictedTypes.filterPrivileged().apply(networkAcl)) {
                                final Optional<NetworkAclEntry> entry = Iterables.tryFind(
                                        networkAcl.getEntries(),
                                        entryPredicate(request.getEgress(), request.getRuleNumber()));
                                if (entry.isPresent()) {
                                    networkAcl.getEntries().remove(entry.get());
                                    networkAcl.updateTimeStamps(); // ensure version of table increments also
                                } else {
                                    throw new ClientComputeException("InvalidNetworkAclEntry.NotFound",
                                            "Entry not found for number: " + request.getRuleNumber());
                                }
                            } else {
                                throw new ClientUnauthorizedComputeException(
                                        "Not authorized to delete network ACL entry");
                            }
                        } catch (Exception e) {
                            throw Exceptions.toUndeclared(e);
                        }
                    }
                });
        invalidate(networkAclId);
    } catch (Exception e) {
        throw handleException(e);
    }
    return reply;
}

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

public DeleteRouteResponseType deleteRoute(final DeleteRouteType request) throws EucalyptusCloudException {
    final DeleteRouteResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final AccountFullName accountFullName = ctx.isAdministrator() ? null
            : ctx.getUserFullName().asAccountFullName();
    final String routeTableId = Identifier.rtb.normalize(request.getRouteTableId());
    try {/* w ww  . j ava  2 s. c o  m*/
        routeTables.withRetries().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> route = Iterables.tryFind(routeTable.getRoutes(),
                                        CollectionUtils.propertyPredicate(request.getDestinationCidrBlock(),
                                                RouteTables.RouteFilterStringFunctions.DESTINATION_CIDR));
                                if (route.isPresent()) {
                                    routeTable.getRoutes().remove(route.get());
                                    routeTable.updateTimeStamps(); // ensure version of table increments also
                                } else {
                                    throw new ClientComputeException("InvalidRoute.NotFound",
                                            "Route not found for cidr: " + request.getDestinationCidrBlock());
                                }
                            } else {
                                throw Exceptions.toUndeclared(new ClientUnauthorizedComputeException(
                                        "Not authorized to delete route"));
                            }
                        } catch (Exception e) {
                            throw Exceptions.toUndeclared(e);
                        }
                    }
                });
        invalidate(routeTableId);
    } catch (Exception e) {
        throw handleException(e);
    }
    return reply;
}

From source file:com.eucalyptus.simpleworkflow.SimpleWorkflowService.java

public DecisionTask pollForDecisionTask(final PollForDecisionTaskRequest request)
        throws SimpleWorkflowException {
    final Context ctx = Contexts.lookup();
    final UserFullName userFullName = ctx.getUserFullName();
    final AccountFullName accountFullName = userFullName.asAccountFullName();
    final Predicate<? super WorkflowExecution> accessible = SimpleWorkflowMetadatas
            .filteringFor(WorkflowExecution.class).byPrivileges().buildPredicate();

    final String domain = request.getDomain();
    final String taskList = request.getTaskList().getName();
    final Callable<DecisionTask> taskCallable = new Callable<DecisionTask>() {
        @Override//w w  w  .  java 2s.  com
        public DecisionTask call() throws Exception {
            final List<WorkflowExecution> pending = workflowExecutions.listByExample(
                    WorkflowExecution.exampleWithPendingDecision(accountFullName, domain, taskList), accessible,
                    Functions.<WorkflowExecution>identity());
            Collections.sort(pending, Ordering.natural().onResultOf(AbstractPersistentSupport.creation()));
            DecisionTask decisionTask = null;
            for (final WorkflowExecution execution : pending) {
                if (decisionTask != null)
                    break;
                boolean retry = true;
                while (retry)
                    try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, execution.getDomainUuid(),
                            execution.getDisplayName())) {
                        retry = false;
                        decisionTask = workflowExecutions.updateByExample(
                                WorkflowExecution.exampleWithUniqueName(accountFullName,
                                        execution.getDomainName(), execution.getDisplayName()),
                                accountFullName, execution.getDisplayName(),
                                new Function<WorkflowExecution, DecisionTask>() {
                                    @Nullable
                                    @Override
                                    public DecisionTask apply(final WorkflowExecution workflowExecution) {
                                        if (workflowExecution.getDecisionStatus() == Pending) {
                                            final List<WorkflowHistoryEvent> events = workflowExecution
                                                    .getWorkflowHistory();
                                            final List<WorkflowHistoryEvent> reverseEvents = Lists
                                                    .reverse(events);
                                            final WorkflowHistoryEvent scheduled = Iterables.find(reverseEvents,
                                                    CollectionUtils.propertyPredicate("DecisionTaskScheduled",
                                                            EVENT_TYPE));
                                            final Optional<WorkflowHistoryEvent> previousStarted = Iterables
                                                    .tryFind(reverseEvents, CollectionUtils.propertyPredicate(
                                                            "DecisionTaskStarted", EVENT_TYPE));
                                            workflowExecution.setDecisionStatus(Active);
                                            workflowExecution.setDecisionTimestamp(new Date());
                                            final WorkflowHistoryEvent started = WorkflowHistoryEvent.create(
                                                    workflowExecution,
                                                    new DecisionTaskStartedEventAttributes()
                                                            .withIdentity(request.getIdentity())
                                                            .withScheduledEventId(scheduled.getEventId()));
                                            workflowExecution.addHistoryEvent(started);
                                            return new DecisionTask().withWorkflowExecution(
                                                    new com.eucalyptus.simpleworkflow.common.model.WorkflowExecution()
                                                            .withWorkflowId(workflowExecution.getWorkflowId())
                                                            .withRunId(workflowExecution.getDisplayName()))
                                                    .withWorkflowType(
                                                            new com.eucalyptus.simpleworkflow.common.model.WorkflowType()
                                                                    .withName(workflowExecution
                                                                            .getWorkflowType().getDisplayName())
                                                                    .withVersion(
                                                                            workflowExecution.getWorkflowType()
                                                                                    .getWorkflowVersion()))
                                                    .withTaskToken(taskTokenManager.encryptTaskToken(
                                                            new TaskToken(accountFullName.getAccountNumber(),
                                                                    workflowExecution.getDomain()
                                                                            .getNaturalId(),
                                                                    workflowExecution.getDisplayName(),
                                                                    scheduled.getEventId(),
                                                                    started.getEventId(),
                                                                    System.currentTimeMillis(),
                                                                    System.currentTimeMillis()))) //TODO:STEVE: token expiry date
                                                    .withStartedEventId(started.getEventId())
                                                    .withPreviousStartedEventId(previousStarted.transform(
                                                            WorkflowExecutions.WorkflowHistoryEventLongFunctions.EVENT_ID)
                                                            .or(0L))
                                                    .withEvents(Collections2.transform(
                                                            Objects.firstNonNull(request.isReverseOrder(),
                                                                    Boolean.FALSE) ? reverseEvents : events,
                                                            TypeMappers.lookup(WorkflowHistoryEvent.class,
                                                                    HistoryEvent.class)));
                                        }
                                        return null;
                                    }
                                });
                    } catch (Exception e) {
                        final StaleObjectStateException stale = Exceptions.findCause(e,
                                StaleObjectStateException.class);
                        if (stale != null)
                            try {
                                Entities.evictCache(Class.forName(stale.getEntityName()));
                            } catch (ClassNotFoundException ce) {
                                /* eviction failure */ }
                        if (PersistenceExceptions.isStaleUpdate(e)) {
                            logger.info("Decision task for workflow " + execution.getDisplayName()
                                    + " already taken.");
                        } else if (PersistenceExceptions.isLockError(e)) {
                            logger.info("Decision task for workflow " + execution.getDisplayName()
                                    + " locking error, will retry.");
                            Thread.sleep(10);
                            retry = true;
                        } else {
                            logger.error(
                                    "Error taking decision task for workflow " + execution.getDisplayName(), e);
                        }
                    }
            }
            return decisionTask;
        }
    };

    try {
        handleTaskPolling(accountFullName, domain, "decision", taskList, request.getCorrelationId(),
                new DecisionTask(), taskCallable);
    } catch (Exception e) {
        throw handleException(e);
    }

    return null;
}

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

public ReplaceNetworkAclEntryResponseType replaceNetworkAclEntry(final ReplaceNetworkAclEntryType request)
        throws EucalyptusCloudException {
    final ReplaceNetworkAclEntryResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final AccountFullName accountFullName = ctx.getUserFullName().asAccountFullName();
    final String networkAclId = Identifier.acl.normalize(request.getNetworkAclId());
    final String cidr = request.getCidrBlock();
    final Optional<Cidr> cidrOptional = Cidr.parse().apply(cidr);
    if (!cidrOptional.isPresent()) {
        throw new ClientComputeException("InvalidParameterValue", "Cidr invalid: " + cidr);
    }/* www.  ja  v a 2  s.  c  om*/
    final Optional<Integer> protocolOptional = protocolNumber(request.getProtocol());
    if (!protocolOptional.isPresent()) {
        throw new ClientComputeException("InvalidParameterValue", "Protocol invalid: " + request.getProtocol());
    }
    if (!Range.closed(1, 32766).apply(request.getRuleNumber())) {
        throw new ClientComputeException("InvalidParameterValue",
                "Rule number invalid: " + request.getRuleNumber());
    }
    try {
        networkAcls.updateByExample(NetworkAcl.exampleWithName(accountFullName, networkAclId), accountFullName,
                request.getNetworkAclId(), new Callback<NetworkAcl>() {
                    @Override
                    public void fire(final NetworkAcl networkAcl) {
                        if (RestrictedTypes.filterPrivileged().apply(networkAcl))
                            try {
                                final List<NetworkAclEntry> entries = networkAcl.getEntries();
                                final Optional<NetworkAclEntry> oldEntry = Iterables.tryFind(entries,
                                        entryPredicate(request.getEgress(), request.getRuleNumber()));

                                if (!oldEntry.isPresent()) {
                                    throw new ClientComputeException("InvalidNetworkAclEntry.NotFound",
                                            "Entry not found for rule number: " + request.getRuleNumber());
                                }

                                final NetworkAclEntry entry;
                                switch (protocolOptional.get()) {
                                case 1:
                                    entry = NetworkAclEntry.createIcmpEntry(networkAcl, request.getRuleNumber(),
                                            Enums.valueOfFunction(NetworkAclEntry.RuleAction.class)
                                                    .apply(request.getRuleAction()),
                                            request.getEgress(), cidr, request.getIcmpTypeCode().getCode(),
                                            request.getIcmpTypeCode().getType());
                                    break;
                                case 6:
                                case 17:
                                    entry = NetworkAclEntry.createTcpUdpEntry(networkAcl,
                                            request.getRuleNumber(), protocolOptional.get(),
                                            Enums.valueOfFunction(NetworkAclEntry.RuleAction.class)
                                                    .apply(request.getRuleAction()),
                                            request.getEgress(), cidr, request.getPortRange().getFrom(),
                                            request.getPortRange().getTo());
                                    break;
                                default:
                                    entry = NetworkAclEntry
                                            .createEntry(networkAcl, request.getRuleNumber(),
                                                    protocolOptional.get(),
                                                    Enums.valueOfFunction(NetworkAclEntry.RuleAction.class)
                                                            .apply(request.getRuleAction()),
                                                    request.getEgress(), cidr);
                                }

                                entries.set(entries.indexOf(oldEntry.get()), entry);
                                networkAcl.updateTimeStamps(); // ensure version of table increments also
                            } catch (Exception e) {
                                throw Exceptions.toUndeclared(e);
                            }
                        else {
                            throw Exceptions.toUndeclared(new ClientUnauthorizedComputeException(
                                    "Not authorized to replace network ACL entry"));
                        }
                    }
                });
        invalidate(networkAclId);
    } catch (Exception e) {
        throw handleException(e);
    }
    return reply;
}

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

public ReplaceRouteResponseType replaceRoute(final ReplaceRouteType request) throws EucalyptusCloudException {
    final ReplaceRouteResponseType 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);
    }/*  w w  w .  j a v a 2 s  .c o  m*/
    try {
        routeTables.updateByExample(RouteTable.exampleWithName(accountFullName, routeTableId), accountFullName,
                request.getRouteTableId(), new Callback<RouteTable>() {
                    @Override
                    public void fire(final RouteTable routeTable) {
                        if (RestrictedTypes.filterPrivileged().apply(routeTable))
                            try {
                                final InternetGateway internetGateway = internetGateways.lookupByName(
                                        accountFullName, gatewayId, Functions.<InternetGateway>identity());

                                final List<Route> routes = routeTable.getRoutes();
                                final Optional<Route> oldRoute = Iterables.tryFind(routes,
                                        CollectionUtils.propertyPredicate(destinationCidr,
                                                RouteTables.RouteFilterStringFunctions.DESTINATION_CIDR));

                                if (!oldRoute.isPresent()) {
                                    throw new ClientComputeException("InvalidRoute.NotFound",
                                            "Route not found for cidr: " + destinationCidr);
                                }

                                routes.set(routes.indexOf(oldRoute.get()), Route.create(routeTable,
                                        Route.RouteOrigin.CreateRoute, destinationCidr, internetGateway));
                                routeTable.updateTimeStamps(); // ensure version of table increments also
                            } catch (Exception e) {
                                throw Exceptions.toUndeclared(e);
                            }
                        else {
                            throw Exceptions.toUndeclared(
                                    new ClientUnauthorizedComputeException("Not authorized to replace route"));
                        }
                    }
                });
        invalidate(routeTableId);
    } catch (Exception e) {
        throw handleException(e);
    }
    return reply;
}

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

private static Optional<Integer> protocolNumber(final String protocol) {
    switch (Objects.toString(protocol, "-1").toLowerCase()) {
    case "tcp":
    case "6":
        return Optional.of(6);
    case "udp":
    case "17":
        return Optional.of(17);
    case "icmp":
    case "1":
        return Optional.of(1);
    default:/*from w w  w .  ja v a2s  .  c  o m*/
        return Iterables.tryFind(Optional.fromNullable(Ints.tryParse(protocol)).asSet(), Range.closed(-1, 255));
    }
}