List of usage examples for com.google.common.collect Iterables tryFind
public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate)
From source file:com.thinkbiganalytics.nifi.rest.support.NifiPropertyUtil.java
/** * Return the first property in the collection that matches the {@link NifiProperty#getKey()} * * @param properties a collection of properties to inspect * @param propertyKey the key to match/*from w w w . ja v a2s . c om*/ * @return the first property in the collection that matches the {@link NifiProperty#getKey()} */ public static NifiProperty findFirstPropertyMatchingKey(Collection<NifiProperty> properties, final String propertyKey) { if (properties != null) { return Iterables.tryFind(properties, new Predicate<NifiProperty>() { @Override public boolean apply(NifiProperty property) { return property.getKey().equalsIgnoreCase(propertyKey); } }).orNull(); } else { return null; } }
From source file:com.eucalyptus.compute.vpc.VpcManager.java
public CreateNetworkAclEntryResponseType createNetworkAclEntry(final CreateNetworkAclEntryType request) throws EucalyptusCloudException { final CreateNetworkAclEntryResponseType 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); }/*from ww w. java 2s .co m*/ 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()); } final Supplier<NetworkAclEntry> allocator = transactional(new Supplier<NetworkAclEntry>() { @Override public NetworkAclEntry get() { 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> existingEntry = Iterables.tryFind( entries, entryPredicate(request.getEgress(), request.getRuleNumber())); if (existingEntry.isPresent()) { throw new ClientComputeException("NetworkAclEntryAlreadyExists", "Entry exists with rule number: " + request.getRuleNumber()); } if (CollectionUtils.reduce(entries, 0, CollectionUtils.count( entryPredicate(request.getEgress(), null))) >= VpcConfiguration .getRulesPerNetworkAcl()) { throw new ClientComputeException("NetworkAclEntryLimitExceeded", "Network ACL entry limit exceeded for " + request.getNetworkAclId()); } 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.add(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 create network ACL entry")); } } }); return null; } catch (Exception ex) { throw new RuntimeException(ex); } } }); try { allocator.get(); invalidate(networkAclId); } catch (Exception e) { throw handleException(e); } return reply; }
From source file:org.jclouds.vcloud.director.v1_5.compute.strategy.VCloudDirectorComputeServiceAdapter.java
private NetworkConfiguration networkConfiguration(Vdc vdc, final Reference network) { Set<Reference> networks = vdc.getAvailableNetworks(); Optional<Reference> parentNetwork = Iterables.tryFind(networks, new Predicate<Reference>() { @Override//from ww w . j a va 2s .co m public boolean apply(Reference reference) { return reference.getHref().equals(network.getHref()); } }); if (!parentNetwork.isPresent()) { throw new IllegalStateException("Cannot find a parent network: " + network.getName() + " given "); } return NetworkConfiguration.builder().parentNetwork(parentNetwork.get()) .fenceMode(Network.FenceMode.BRIDGED).retainNetInfoAcrossDeployments(false).build(); }
From source file:org.apache.brooklyn.entity.group.DynamicClusterImpl.java
/** * {@inheritDoc}//from w ww. j a va 2 s . c o m * * <strong>Note</strong> for sub-classes; this method can be called while synchronized on {@link #mutex}. */ @Override public String replaceMember(String memberId) { Entity member = getEntityManager().getEntity(memberId); LOG.info("In {}, replacing member {} ({})", new Object[] { this, memberId, member }); if (member == null) { throw new NoSuchElementException( "In " + this + ", entity " + memberId + " cannot be resolved, so not replacing"); } synchronized (mutex) { if (!getMembers().contains(member)) { throw new NoSuchElementException( "In " + this + ", entity " + member + " is not a member so not replacing"); } Location memberLoc = null; if (isAvailabilityZoneEnabled()) { // this member's location could be a machine provisioned by a sub-location, or the actual sub-location List<Location> subLocations = findSubLocations(getLocation(true)); Collection<Location> actualMemberLocs = member.getLocations(); boolean foundMatch = false; for (Iterator<Location> iter = actualMemberLocs.iterator(); !foundMatch && iter.hasNext();) { Location actualMemberLoc = iter.next(); Location contenderMemberLoc = actualMemberLoc; do { if (subLocations.contains(contenderMemberLoc)) { memberLoc = contenderMemberLoc; foundMatch = true; LOG.debug("In {} replacing member {} ({}), inferred its sub-location is {}", new Object[] { this, memberId, member, memberLoc }); } contenderMemberLoc = contenderMemberLoc.getParent(); } while (!foundMatch && contenderMemberLoc != null); } if (!foundMatch) { if (actualMemberLocs.isEmpty()) { memberLoc = subLocations.get(0); LOG.warn( "In {} replacing member {} ({}), has no locations; falling back to first availability zone: {}", new Object[] { this, memberId, member, memberLoc }); } else { memberLoc = Iterables .tryFind(actualMemberLocs, Predicates.instanceOf(MachineProvisioningLocation.class)) .or(Iterables.getFirst(actualMemberLocs, null)); LOG.warn( "In {} replacing member {} ({}), could not find matching sub-location; falling back to its actual location: {}", new Object[] { this, memberId, member, memberLoc }); } } else if (memberLoc == null) { // impossible to get here, based on logic above! throw new IllegalStateException("Unexpected condition! cluster=" + this + "; member=" + member + "; actualMemberLocs=" + actualMemberLocs); } } else { // Replacing member, so new member should be in the same location as that being replaced. // Expect this to agree with `getMemberSpec().getLocations()` (if set). If not, then // presumably there was a reason this specific member was started somewhere else! memberLoc = getLocation(false); } Entity replacement = replaceMember(member, memberLoc, ImmutableMap.of()); return replacement.getId(); } }
From source file:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java
private ResourcePool tryFindResourcePool(Folder folder, String hostname) { Iterable<ResourcePool> resourcePools = ImmutableSet.<ResourcePool>of(); try {/*from w w w . j a v a 2 s . co m*/ ManagedEntity[] resourcePoolEntities = new InventoryNavigator(folder) .searchManagedEntities("ResourcePool"); resourcePools = Iterables.transform(Arrays.asList(resourcePoolEntities), new Function<ManagedEntity, ResourcePool>() { public ResourcePool apply(ManagedEntity input) { return (ResourcePool) input; } }); Optional<ResourcePool> optionalResourcePool = Iterables.tryFind(resourcePools, VSpherePredicate.isResourcePoolOf(hostname)); return optionalResourcePool.orNull(); } catch (Exception e) { logger.error("Problem in finding a valid resource pool", e); } return null; }
From source file:org.killbill.billing.invoice.dao.DefaultInvoiceDao.java
@Override public InvoicePaymentModelDao createRefund(final UUID paymentId, final BigDecimal requestedRefundAmount, final boolean isInvoiceAdjusted, final Map<UUID, BigDecimal> invoiceItemIdsWithNullAmounts, final String transactionExternalKey, final InternalCallContext context) throws InvoiceApiException { if (isInvoiceAdjusted && invoiceItemIdsWithNullAmounts.size() == 0) { throw new InvoiceApiException(ErrorCode.INVOICE_ITEMS_ADJUSTMENT_MISSING); }//from ww w. j av a 2 s . co m final List<Tag> invoicesTags = getInvoicesTags(context); return transactionalSqlDao.execute(InvoiceApiException.class, new EntitySqlDaoTransactionWrapper<InvoicePaymentModelDao>() { @Override public InvoicePaymentModelDao inTransaction( final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception { final InvoicePaymentSqlDao transactional = entitySqlDaoWrapperFactory .become(InvoicePaymentSqlDao.class); final InvoiceSqlDao transInvoiceDao = entitySqlDaoWrapperFactory .become(InvoiceSqlDao.class); final List<InvoicePaymentModelDao> paymentsForId = transactional .getByPaymentId(paymentId.toString(), context); final InvoicePaymentModelDao payment = Iterables .tryFind(paymentsForId, new Predicate<InvoicePaymentModelDao>() { @Override public boolean apply(final InvoicePaymentModelDao input) { return input.getType() == InvoicePaymentType.ATTEMPT && input.getSuccess(); } }).orNull(); if (payment == null) { throw new InvoiceApiException(ErrorCode.INVOICE_PAYMENT_BY_ATTEMPT_NOT_FOUND, paymentId); } // Retrieve the amounts to adjust, if needed final Map<UUID, BigDecimal> invoiceItemIdsWithAmounts = invoiceDaoHelper .computeItemAdjustments(payment.getInvoiceId().toString(), invoicesTags, entitySqlDaoWrapperFactory, invoiceItemIdsWithNullAmounts, context); // Compute the actual amount to refund final BigDecimal requestedPositiveAmount = invoiceDaoHelper.computePositiveRefundAmount( payment, requestedRefundAmount, invoiceItemIdsWithAmounts); // Before we go further, check if that refund already got inserted -- the payment system keeps a state machine // and so this call may be called several time for the same paymentCookieId (which is really the refundId) final InvoicePaymentModelDao existingRefund = transactional .getPaymentForCookieId(transactionExternalKey, context); if (existingRefund != null) { return existingRefund; } final InvoicePaymentModelDao refund = new InvoicePaymentModelDao(UUIDs.randomUUID(), context.getCreatedDate(), InvoicePaymentType.REFUND, payment.getInvoiceId(), paymentId, context.getCreatedDate(), requestedPositiveAmount.negate(), payment.getCurrency(), payment.getProcessedCurrency(), transactionExternalKey, payment.getId(), true); createAndRefresh(transactional, refund, context); // Retrieve invoice after the Refund final InvoiceModelDao invoice = transInvoiceDao.getById(payment.getInvoiceId().toString(), context); Preconditions.checkState(invoice != null, "Invoice shouldn't be null for payment " + payment.getId()); invoiceDaoHelper.populateChildren(invoice, invoicesTags, entitySqlDaoWrapperFactory, context); final InvoiceItemSqlDao transInvoiceItemDao = entitySqlDaoWrapperFactory .become(InvoiceItemSqlDao.class); // At this point, we created the refund which made the invoice balance positive and applied any existing // available CBA to that invoice. // We now need to adjust the invoice and/or invoice items if needed and specified. if (isInvoiceAdjusted) { // Invoice item adjustment for (final UUID invoiceItemId : invoiceItemIdsWithAmounts.keySet()) { final BigDecimal adjAmount = invoiceItemIdsWithAmounts.get(invoiceItemId); final InvoiceItemModelDao item = invoiceDaoHelper.createAdjustmentItem( entitySqlDaoWrapperFactory, invoice.getId(), invoiceItemId, adjAmount, invoice.getCurrency(), context.getCreatedDate().toLocalDate(), context); createInvoiceItemFromTransaction(transInvoiceItemDao, item, context); invoice.addInvoiceItem(item); } } // The invoice object has been kept up-to-date cbaDao.doCBAComplexityFromTransaction(invoice, invoicesTags, entitySqlDaoWrapperFactory, context); if (isInvoiceAdjusted) { notifyBusOfInvoiceAdjustment(entitySqlDaoWrapperFactory, invoice.getId(), invoice.getAccountId(), context.getUserToken(), context); } notifyBusOfInvoicePayment(entitySqlDaoWrapperFactory, refund, invoice.getAccountId(), context.getUserToken(), context); return refund; } }); }
From source file:com.thinkbiganalytics.nifi.rest.support.NifiPropertyUtil.java
/** * Check to see if a collection of properties contains properties of a supplied processorType * * @param properties a collection of properties * @param processorType a processor type to match * @return {@code true} if the collection of properties contains the supplied processorType, {@code false} if the properties do not contain the processorType *//*from w w w. j av a2 s .com*/ public static boolean containsPropertiesForProcessorMatchingType(Collection<NifiProperty> properties, final String processorType) { if (StringUtils.isBlank(processorType)) { return false; } return Iterables.tryFind(properties, new Predicate<NifiProperty>() { @Override public boolean apply(NifiProperty property) { return processorType.equalsIgnoreCase(property.getProcessorType()); } }).orNull() != null; }
From source file:org.apache.aurora.scheduler.thrift.SchedulerThriftInterface.java
@Override public Response addInstances(InstanceKey key, int count) { IJobKey jobKey = JobKeys.assertValid(IJobKey.build(key.getJobKey())); Response response = empty();//from w w w .ja va 2 s. c o m return storage.write(storeProvider -> { try { if (getCronJob(storeProvider, jobKey).isPresent()) { return invalidRequest("Instances may not be added to cron jobs."); } lockManager.assertNotLocked(ILockKey.build(LockKey.job(jobKey.newBuilder()))); FluentIterable<IScheduledTask> currentTasks = FluentIterable .from(storeProvider.getTaskStore().fetchTasks(Query.jobScoped(jobKey).active())); if (count <= 0) { return invalidRequest(INVALID_INSTANCE_COUNT); } Optional<IScheduledTask> templateTask = Iterables.tryFind(currentTasks, e -> e.getAssignedTask().getInstanceId() == key.getInstanceId()); if (!templateTask.isPresent()) { return invalidRequest(INVALID_INSTANCE_ID); } int lastId = currentTasks.transform(e -> e.getAssignedTask().getInstanceId()).toList().stream() .max(Comparator.naturalOrder()).get(); Set<Integer> instanceIds = ContiguousSet.create(Range.openClosed(lastId, lastId + count), DiscreteDomain.integers()); ITaskConfig task = templateTask.get().getAssignedTask().getTask(); validateTaskLimits(task, Iterables.size(currentTasks) + instanceIds.size(), quotaManager.checkInstanceAddition(task, instanceIds.size(), storeProvider)); stateManager.insertPendingTasks(storeProvider, task, instanceIds); addInstancesCounter.addAndGet(instanceIds.size()); return response.setResponseCode(OK); } catch (LockException e) { return error(LOCK_ERROR, e); } catch (TaskValidationException | IllegalArgumentException e) { return error(INVALID_REQUEST, e); } }); }
From source file:com.eucalyptus.cluster.callback.reporting.CloudWatchHelper.java
public List<AbsoluteMetricQueueItem> collectMetricData(final Collection<String> expectedInstanceIds, final DescribeSensorsResponse msg) throws Exception { ArrayList<AbsoluteMetricQueueItem> absoluteMetricQueueItems = new ArrayList<>(); // cloudwatch metric caches final ConcurrentMap<String, DiskReadWriteMetricTypeCache> metricCacheMap = Maps.newConcurrentMap(); final EC2DiskMetricCache ec2DiskMetricCache = new EC2DiskMetricCache(); for (final SensorsResourceType sensorData : msg.getSensorsResources()) { if (!RESOURCE_TYPE_INSTANCE.equals(sensorData.getResourceType()) || !expectedInstanceIds.contains(sensorData.getResourceName())) continue; for (final MetricsResourceType metricType : sensorData.getMetrics()) { for (final MetricCounterType counterType : metricType.getCounters()) { for (final MetricDimensionsType dimensionType : counterType.getDimensions()) { // find and fire most recent value for metric/dimension final List<MetricDimensionsValuesType> values = Lists .newArrayList(stripMilliseconds(dimensionType.getValues())); //CloudWatch use case of metric data // best to enter older data first... Collections.sort(values, Ordering.natural().onResultOf(GetTimestamp.INSTANCE)); for (final MetricDimensionsValuesType value : values) { if (LOG.isTraceEnabled()) { LOG.trace("ResourceUUID: " + sensorData.getResourceUuid()); LOG.trace("ResourceName: " + sensorData.getResourceName()); LOG.trace("Metric: " + metricType.getMetricName()); LOG.trace("Dimension: " + dimensionType.getDimensionName()); LOG.trace("Timestamp: " + value.getTimestamp()); LOG.trace("Value: " + value.getValue()); }//from ww w . j a v a 2s . c om final Long currentTimeStamp = value.getTimestamp().getTime(); final Double currentValue = value.getValue(); if (currentValue == null) { LOG.debug("Event received with null 'value', skipping for cloudwatch"); continue; } boolean hasEc2DiskMetricName = EC2_DISK_METRICS .contains(metricType.getMetricName().replace("Volume", "Disk")); // Let's try only creating "zero" points for timestamps from disks if (hasEc2DiskMetricName) { ec2DiskMetricCache.initializeMetrics(sensorData.getResourceUuid(), sensorData.getResourceName(), currentTimeStamp); // Put a place holder in in case we don't have any non-EBS volumes } boolean isEbsMetric = dimensionType.getDimensionName().startsWith("vol-"); boolean isEc2DiskMetric = !isEbsMetric && hasEc2DiskMetricName; if (isEbsMetric || !isEc2DiskMetric) { addToQueueItems(absoluteMetricQueueItems, new Supplier<InstanceUsageEvent>() { @Override public InstanceUsageEvent get() { return new InstanceUsageEvent(sensorData.getResourceUuid(), sensorData.getResourceName(), metricType.getMetricName(), dimensionType.getSequenceNum(), dimensionType.getDimensionName(), currentValue, currentTimeStamp); } }); if (isEbsMetric) { // special case to calculate VolumeConsumedReadWriteOps // As it is (VolumeThroughputPercentage / 100) * (VolumeReadOps + VolumeWriteOps), and we are hard coding // VolumeThroughputPercentage as 100%, we will just use VolumeReadOps + VolumeWriteOps // And just in case VolumeReadOps is called DiskReadOps we do both cases... addToQueueItems(absoluteMetricQueueItems, combineReadWriteDiskMetric("DiskReadOps", "DiskWriteOps", metricCacheMap, "DiskConsumedReadWriteOps", metricType, sensorData, dimensionType, value)); addToQueueItems(absoluteMetricQueueItems, combineReadWriteDiskMetric("VolumeReadOps", "VolumeWriteOps", metricCacheMap, "VolumeConsumedReadWriteOps", metricType, sensorData, dimensionType, value)); // Also need VolumeTotalReadWriteTime to compute VolumeIdleTime addToQueueItems(absoluteMetricQueueItems, combineReadWriteDiskMetric("VolumeTotalReadTime", "VolumeTotalWriteTime", metricCacheMap, "VolumeTotalReadWriteTime", metricType, sensorData, dimensionType, value)); } } else { // see if it is a volume metric String metricName = metricType.getMetricName().replace("Volume", "Disk"); ec2DiskMetricCache.addToMetric(sensorData.getResourceUuid(), sensorData.getResourceName(), metricName, currentValue, currentTimeStamp); } } } } } if (Iterables .tryFind(absoluteMetricQueueItems, withMetric("AWS/EC2", null, "InstanceId", sensorData.getResourceName())) .isPresent() && !Iterables.tryFind(absoluteMetricQueueItems, withMetric("AWS/EC2", Count.StatusCheckFailed.name(), "InstanceId", sensorData.getResourceName())) .isPresent()) { absoluteMetricQueueItems.addAll(buildInstanceStatusPut(sensorData.getResourceName())); } } Collection<Supplier<InstanceUsageEvent>> ec2DiskMetrics = ec2DiskMetricCache.getMetrics(); List<Supplier<InstanceUsageEvent>> ec2DiskMetricsSorted = Lists.newArrayList(ec2DiskMetrics); Collections.sort(ec2DiskMetricsSorted, Ordering.natural().onResultOf(new Function<Supplier<InstanceUsageEvent>, Long>() { @Override @Nullable public Long apply(@Nullable Supplier<InstanceUsageEvent> supplier) { return supplier.get().getValueTimestamp(); } })); for (Supplier<InstanceUsageEvent> ec2DiskMetric : ec2DiskMetricsSorted) { try { addToQueueItems(absoluteMetricQueueItems, ec2DiskMetric); } catch (Exception ex) { LOG.debug("Unable to add system metric " + ec2DiskMetric, ex); } } return absoluteMetricQueueItems; }
From source file:org.apache.phoenix.hive.query.PhoenixQueryBuilder.java
private Expression findExpression(final IndexSearchCondition condition) { return Iterables.tryFind(Arrays.asList(Expression.values()), new Predicate<Expression>() { @Override/*from ww w. jav a 2s .c o m*/ public boolean apply(@Nullable Expression expr) { return expr.isFor(condition); } }).orNull(); }