List of usage examples for com.google.common.base Predicates compose
public static <A, B> Predicate<A> compose(Predicate<B> predicate, Function<A, ? extends B> function)
From source file:forge.itemmanager.ItemManager.java
/** * //from w w w .j a v a 2s . co m * updateView. * * @param bForceFilter */ public void updateView(final boolean forceFilter, final Iterable<T> itemsToSelect) { final boolean useFilter = (forceFilter && (filterPredicate != null)) || !isUnfiltered(); if (useFilter || forceFilter) { model.clear(); Iterable<Entry<T, Integer>> items = pool; if (useFilter) { Predicate<Entry<T, Integer>> pred = Predicates.compose(filterPredicate, pool.FN_GET_KEY); items = Iterables.filter(pool, pred); } model.addItems(items); } currentView.refresh(itemsToSelect, getSelectedIndex(), forceFilter ? 0 : currentView.getScrollValue()); //update ratio of # in filtered pool / # in total pool int totalCount; int filteredCount = getFilteredItems().countAll(); if (useFilter) { totalCount = pool.countAll(); } else { totalCount = filteredCount; } searchFilter.setRatio("(" + filteredCount + " / " + totalCount + ")"); }
From source file:com.eucalyptus.vm.VmControl.java
public DescribeBundleTasksResponseType describeBundleTasks(final DescribeBundleTasksType request) throws EucalyptusCloudException { final DescribeBundleTasksResponseType reply = request.getReply(); final Filter filter = Filters.generate(request.getFilterSet(), VmBundleTask.class); final EntityTransaction db = Entities.get(VmInstance.class); try {//from w ww.jav a2 s .c o m // Get all from cache that match filters...... final Predicate<? super VmBundleTask> filteredAndBundling = Predicates.and(filter.asPredicate(), VmBundleTask.Filters.BUNDLING); Collection<VmBundleTask> cachedValues = Bundles.getPreviousBundleTasks().values(); final Map<String, VmBundleTask> cachedBundles = buildMap( Collections2.filter(cachedValues, filteredAndBundling)); final Predicate<? super VmInstance> requestedAndAccessible = CloudMetadatas .filteringFor(VmInstance.class).byId(toInstanceIds(request.getBundleIds())).byPrivileges() .buildPredicate(); // Get all from the db that are owned final Predicate<? super VmInstance> filteredInstances = Predicates.compose(filter.asPredicate(), VmInstances.bundleTask()); final Filter noFilters = Filters.generate(new ArrayList<edu.ucsb.eucalyptus.msgs.Filter>(), VmBundleTask.class); final Collection<VmInstance> dbBundles = VmInstances.list(null, noFilters.asCriterion(), noFilters.getAliases(), requestedAndAccessible); for (final VmInstance v : dbBundles) { if (filteredInstances.apply(v) && VmInstance.Filters.BUNDLING.apply(v)) { LOG.debug("Getting current bundle for " + v.getInstanceId()); reply.getBundleTasks().add(Bundles.transform(v.getRuntimeState().getBundleTask())); } else { if (!VmInstance.Filters.BUNDLING.apply(v) && cachedBundles.containsKey(v.getInstanceId())) { LOG.debug("Getting previous bundle for " + v.getInstanceId()); reply.getBundleTasks().add(Bundles.transform(cachedBundles.get(v.getInstanceId()))); } } } } catch (Exception ex) { Logs.exhaust().error(ex, ex); throw new EucalyptusCloudException(ex); } finally { db.rollback(); } return reply; }
From source file:com.eucalyptus.autoscaling.AutoScalingService.java
public DescribeTagsResponseType describeTags(final DescribeTagsType request) throws EucalyptusCloudException { final DescribeTagsResponseType reply = request.getReply(); //TODO: MaxRecords / NextToken support for DescribeTags final Collection<Predicate<Tag>> tagFilters = Lists.newArrayList(); for (final Filter filter : request.filters()) { final Function<Tag, String> extractor = tagFilterExtractors.get(filter.getName()); if (extractor == null) { throw new ValidationErrorException("Filter type " + filter.getName() + " is not correct. Allowed Filter types are: auto-scaling-group key value propagate-at-launch"); }//from www . j a v a2s . c om final Function<String, String> tagValueConverter = Objects .firstNonNull(tagValuePreProcessors.get(filter.getName()), Functions.<String>identity()); tagFilters.add(Predicates .compose(Predicates.in(Collections2.transform(filter.values(), tagValueConverter)), extractor)); } final Context context = Contexts.lookup(); final Ordering<Tag> ordering = Ordering.natural().onResultOf(Tags.resourceId()) .compound(Ordering.natural().onResultOf(Tags.key())) .compound(Ordering.natural().onResultOf(Tags.value())); try { final TagDescriptionList tagDescriptions = new TagDescriptionList(); for (final Tag tag : ordering .sortedCopy(Tags.list(context.getUserFullName().asAccountFullName(), Predicates.and(tagFilters), Restrictions.conjunction(), Collections.<String, String>emptyMap()))) { if (Permissions.isAuthorized(PolicySpec.VENDOR_AUTOSCALING, tag.getResourceType(), tag.getKey(), context.getAccount(), PolicySpec.describeAction(PolicySpec.VENDOR_AUTOSCALING, tag.getResourceType()), context.getUser())) { tagDescriptions.getMember().add(TypeMappers.transform(tag, TagDescription.class)); } } if (!tagDescriptions.getMember().isEmpty()) { reply.getDescribeTagsResult().setTags(tagDescriptions); } } catch (AutoScalingMetadataNotFoundException e) { handleException(e); } return reply; }
From source file:com.eucalyptus.autoscaling.backend.AutoScalingBackendService.java
public DescribeTagsResponseType describeTags(final DescribeTagsType request) throws EucalyptusCloudException { final DescribeTagsResponseType reply = request.getReply(); //TODO: MaxRecords / NextToken support for DescribeTags final Collection<Predicate<Tag>> tagFilters = Lists.newArrayList(); for (final Filter filter : request.filters()) { final Function<Tag, String> extractor = tagFilterExtractors.get(filter.getName()); if (extractor == null) { throw new ValidationErrorException("Filter type " + filter.getName() + " is not correct. Allowed Filter types are: auto-scaling-group key value propagate-at-launch"); }//from w w w . j a va 2 s . c o m final Function<String, String> tagValueConverter = Objects .firstNonNull(tagValuePreProcessors.get(filter.getName()), Functions.<String>identity()); tagFilters.add(Predicates .compose(Predicates.in(Collections2.transform(filter.values(), tagValueConverter)), extractor)); } final Context context = Contexts.lookup(); final Ordering<Tag> ordering = Ordering.natural().onResultOf(Tags.resourceId()) .compound(Ordering.natural().onResultOf(Tags.key())) .compound(Ordering.natural().onResultOf(Tags.value())); try { final TagDescriptionList tagDescriptions = new TagDescriptionList(); for (final Tag tag : ordering .sortedCopy(Tags.list(context.getUserFullName().asAccountFullName(), Predicates.and(tagFilters), Restrictions.conjunction(), Collections.<String, String>emptyMap()))) { if (Permissions.isAuthorized(PolicySpec.VENDOR_AUTOSCALING, tag.getResourceType(), tag.getKey(), context.getAccount(), PolicySpec.describeAction(PolicySpec.VENDOR_AUTOSCALING, tag.getResourceType()), context.getAuthContext())) { tagDescriptions.getMember().add(TypeMappers.transform(tag, TagDescription.class)); } } if (!tagDescriptions.getMember().isEmpty()) { reply.getDescribeTagsResult().setTags(tagDescriptions); } } catch (AutoScalingMetadataNotFoundException e) { handleException(e); } return reply; }
From source file:com.eucalyptus.loadbalancing.workflow.LoadBalancingActivitiesImpl.java
@Override public AutoscalingGroupSetupActivityResult autoscalingGroupSetup(final String accountNumber, final String lbName, String instanceProfileName, String securityGroupName, List<String> zones, Map<String, String> zoneToSubnetIdMap) throws LoadBalancingActivityException { if (LoadBalancingWorkerProperties.IMAGE == null) throw new LoadBalancingActivityException("Loadbalancer's EMI is not configured"); final AutoscalingGroupSetupActivityResult activityResult = new AutoscalingGroupSetupActivityResult(); final LoadBalancer lbEntity; final LoadBalancer.LoadBalancerCoreView lb; try {//from ww w . ja va 2 s . co m lbEntity = LoadBalancers.getLoadbalancer(accountNumber, lbName); lb = lbEntity.getCoreView(); if (zoneToSubnetIdMap == null) { zoneToSubnetIdMap = CollectionUtils.putAll( Iterables.filter(lbEntity.getZones(), Predicates.compose(Predicates.notNull(), subnetId())), Maps.<String, String>newHashMap(), name(), subnetId()); } } catch (NoSuchElementException ex) { throw new LoadBalancingActivityException("Failed to find the loadbalancer " + lbName, ex); } catch (Exception ex) { throw new LoadBalancingActivityException("Failed due to query exception", ex); } if (zones == null) return null; // do nothing when zone/groups are not specified for (final String availabilityZone : zones) { final String groupName = getAutoScalingGroupName(accountNumber, lbName, availabilityZone); String launchConfigName = null; boolean asgFound = false; try { final DescribeAutoScalingGroupsResponseType response = EucalyptusActivityTasks.getInstance() .describeAutoScalingGroups(Lists.newArrayList(groupName), lb.useSystemAccount()); final List<AutoScalingGroupType> groups = response.getDescribeAutoScalingGroupsResult() .getAutoScalingGroups().getMember(); if (groups.size() > 0 && groups.get(0).getAutoScalingGroupName().equals(groupName)) { asgFound = true; launchConfigName = groups.get(0).getLaunchConfigurationName(); } } catch (final Exception ex) { asgFound = false; } activityResult.setGroupNames(Sets.<String>newHashSet()); activityResult.setLaunchConfigNames(Sets.<String>newHashSet()); activityResult.setCreatedGroupNames(Sets.<String>newHashSet()); activityResult.setCreatedLaunchConfigNames(Sets.<String>newHashSet()); final List<String> availabilityZones = Lists.newArrayList(availabilityZone); String vpcZoneIdentifier = null; String systemVpcZoneIdentifier = null; if (!asgFound) { try { vpcZoneIdentifier = zoneToSubnetIdMap.isEmpty() ? null : Strings.emptyToNull(Joiner.on(',').skipNulls().join( Iterables.transform(availabilityZones, Functions.forMap(zoneToSubnetIdMap)))); if (vpcZoneIdentifier != null) systemVpcZoneIdentifier = LoadBalancingSystemVpcs.getSystemVpcSubnetId(vpcZoneIdentifier); else systemVpcZoneIdentifier = null; } catch (final Exception ex) { throw new LoadBalancingActivityException("Failed to look up subnet ID", ex); } try { Set<String> securityGroupNamesOrIds = null; if (systemVpcZoneIdentifier == null) { securityGroupNamesOrIds = Sets.newHashSet(); if (!lb.getSecurityGroupIdsToNames().isEmpty()) { securityGroupNamesOrIds.addAll(lb.getSecurityGroupIdsToNames().keySet()); } else { if (securityGroupName != null) { securityGroupNamesOrIds.add(securityGroupName); } } } else { // if system VPC is used, use it's security group securityGroupNamesOrIds = Sets.newHashSet(); securityGroupNamesOrIds .add(LoadBalancingSystemVpcs.getSecurityGroupId(systemVpcZoneIdentifier)); } final String KEYNAME = LoadBalancingWorkerProperties.KEYNAME; final String keyName = KEYNAME != null && KEYNAME.length() > 0 ? KEYNAME : null; final String userData = B64.standard .encString(String.format("%s\n%s", getCredentialsString(), getLoadBalancerUserData( LoadBalancingWorkerProperties.INIT_SCRIPT, lb.getOwnerAccountNumber()))); launchConfigName = getLaunchConfigName(lb.getOwnerAccountNumber(), lb.getDisplayName(), availabilityZone); EucalyptusActivityTasks.getInstance().createLaunchConfiguration( LoadBalancingWorkerProperties.IMAGE, LoadBalancingWorkerProperties.INSTANCE_TYPE, instanceProfileName, launchConfigName, securityGroupNamesOrIds, keyName, userData, zoneToSubnetIdMap.isEmpty() ? null : false, lb.useSystemAccount()); activityResult.getLaunchConfigNames().add(launchConfigName); activityResult.getCreatedLaunchConfigNames().add(launchConfigName); } catch (Exception ex) { throw new LoadBalancingActivityException("Failed to create launch configuration", ex); } } activityResult.getLaunchConfigNames().add(launchConfigName); /// FIXME Integer capacity = LoadBalancingServiceProperties.getCapacityPerZone(); if (!asgFound) { // create autoscaling group with the zone and desired capacity try { EucalyptusActivityTasks.getInstance().createAutoScalingGroup(groupName, availabilityZones, systemVpcZoneIdentifier, capacity, launchConfigName, TAG_KEY, TAG_VALUE, lb.useSystemAccount()); activityResult.getGroupNames().add(groupName); activityResult.getCreatedGroupNames().add(groupName); if (activityResult.getNumVMsPerZone() == null || activityResult.getNumVMsPerZone() == 0) { activityResult.setNumVMsPerZone(capacity); } else { activityResult.setNumVMsPerZone(activityResult.getNumVMsPerZone() + capacity); } } catch (Exception ex) { throw new LoadBalancingActivityException("Failed to create autoscaling group", ex); } } else { try { EucalyptusActivityTasks.getInstance().updateAutoScalingGroup(groupName, availabilityZones, capacity, launchConfigName, lb.useSystemAccount()); } catch (Exception ex) { throw new LoadBalancingActivityException("Failed to update the autoscaling group", ex); } } activityResult.getGroupNames().add(groupName); if (activityResult.getNumVMsPerZone() == null || activityResult.getNumVMsPerZone() == 0) { activityResult.setNumVMsPerZone(capacity); } else { activityResult.setNumVMsPerZone(activityResult.getNumVMsPerZone() + capacity); } // commit ASG record to the database try (final TransactionResource db = Entities.transactionFor(LoadBalancerAutoScalingGroup.class)) { try { final LoadBalancerAutoScalingGroup group = Entities .uniqueResult(LoadBalancerAutoScalingGroup.named(lbEntity, availabilityZone)); if (capacity != null) group.setCapacity(capacity); } catch (NoSuchElementException ex) { final LoadBalancerAutoScalingGroup group = LoadBalancerAutoScalingGroup.newInstance(lbEntity, availabilityZone, vpcZoneIdentifier, systemVpcZoneIdentifier, groupName, launchConfigName); if (capacity != null) group.setCapacity(capacity); Entities.persist(group); } db.commit(); } catch (final Exception ex) { throw new LoadBalancingActivityException("Failed to commit the database", ex); } } // end of for all zones return activityResult; }
From source file:clocker.docker.entity.DockerHostImpl.java
public void scanContainers() { getDynamicLocation().getLock().lock(); try {/* ww w .j av a 2s . 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.autoscaling.activities.ActivityManager.java
private Predicate<AutoScalingInstanceCoreView> withAvailabilityZone( final Collection<String> availabilityZones) { return Predicates.compose(Predicates.in(availabilityZones), availabilityZone()); }
From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java
/** * This will throw if we have a value changed conflict. This means that either we changed the * value and anyone did a write after our start timestamp, or we just touched the value (put the * same value as before) and a changed value was written after our start time. */// w w w . j a v a2 s. co m private void throwIfValueChangedConflict(String table, Map<Cell, byte[]> writes, Set<CellConflict> spanningWrites, Set<CellConflict> dominatingWrites, LockRefreshToken commitLocksToken) { Map<Cell, CellConflict> cellToConflict = Maps.newHashMap(); Map<Cell, Long> cellToTs = Maps.newHashMap(); for (CellConflict c : Sets.union(spanningWrites, dominatingWrites)) { cellToConflict.put(c.cell, c); cellToTs.put(c.cell, c.theirStart + 1); } Map<Cell, byte[]> oldValues = getIgnoringLocalWrites(table, cellToTs.keySet()); Map<Cell, Value> conflictingValues = keyValueService.get(table, cellToTs); Set<Cell> conflictingCells = Sets.newHashSet(); for (Entry<Cell, Long> cellEntry : cellToTs.entrySet()) { Cell cell = cellEntry.getKey(); if (!writes.containsKey(cell)) { Validate.isTrue(false, "Missing write for cell: " + cellToConflict.get(cell) + " for table " + table); } if (!conflictingValues.containsKey(cell)) { // This error case could happen if our locks expired. throwIfExternalAndCommitLocksNotValid(commitLocksToken); Validate.isTrue(false, "Missing conflicting value for cell: " + cellToConflict.get(cell) + " for table " + table); } if (conflictingValues.get(cell).getTimestamp() != (cellEntry.getValue() - 1)) { // This error case could happen if our locks expired. throwIfExternalAndCommitLocksNotValid(commitLocksToken); Validate.isTrue(false, "Wrong timestamp for cell in table " + table + " Expected: " + cellToConflict.get(cell) + " Actual: " + conflictingValues.get(cell)); } @Nullable byte[] oldVal = oldValues.get(cell); byte[] writeVal = writes.get(cell); byte[] conflictingVal = conflictingValues.get(cell).getContents(); if (!Transactions.cellValuesEqual(oldVal, writeVal) || !Arrays.equals(writeVal, conflictingVal)) { conflictingCells.add(cell); } else if (log.isInfoEnabled()) { log.info("Another transaction committed to the same cell before us but " + "their value was the same. " + "Cell: " + cell + " Table: " + table); } } if (conflictingCells.isEmpty()) { return; } Predicate<CellConflict> conflicting = Predicates.compose(Predicates.in(conflictingCells), CellConflict.getCellFunction()); throw TransactionConflictException.create(table, getStartTimestamp(), Sets.filter(spanningWrites, conflicting), Sets.filter(dominatingWrites, conflicting), System.currentTimeMillis() - timeCreated); }