List of usage examples for com.google.common.collect Iterables all
public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate)
From source file:com.eucalyptus.compute.common.internal.vm.VmInstance.java
/** * *//*w ww . j a v a 2 s.c om*/ public boolean eachVolumeAttachment(final Predicate<VmVolumeAttachment> predicate) { if (VmStateSet.DONE.contains(this.getState()) && !VmStateSet.EXPECTING_TEARDOWN.contains(this.getLastState())) { return false; } else { final EntityTransaction db = Entities.get(VmInstance.class); try { final VmInstance entity = Entities.merge(this); Set<VmVolumeAttachment> persistentAttachments = Sets .<VmVolumeAttachment>newHashSet(entity.getBootRecord().getPersistentVolumes()); boolean ret = Iterables.all(persistentAttachments, new Predicate<VmVolumeAttachment>() { @Override public boolean apply(final VmVolumeAttachment arg0) { return predicate.apply(arg0); } }); ret |= entity.getTransientVolumeState().eachVolumeAttachment(new Predicate<VmVolumeAttachment>() { @Override public boolean apply(final VmVolumeAttachment arg0) { return predicate.apply(arg0); } }); db.commit(); return ret; } catch (final Exception ex) { Logs.extreme().error(ex, ex); db.rollback(); return false; } } }
From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java
/** * Create a new Type instance that is return-type-substitutable for all * of a list of types. If necessary, a new class is created and added * to the current scope.//from w w w . jav a 2 s. co m */ private Type createType(AST ast, ITypeBinding scope, List<BodyDeclaration> scopeBody, List<ITypeBinding> types) { assert types.size() > 0; // Check for a type to return directly. ITypeBinding type = null; for (ITypeBinding otherType : types) { if (otherType.isPrimitive() || otherType.isArray() || otherType.isEnum()) { type = otherType; break; } } if (type != null) { // Assume that the other types are all compatible. This should have // been verified by the Java compiler before dead code elimination. return createType(ast, scope, type); } // All classes or interfaces--try to find one that satisfies the others. for (ITypeBinding baseType : types) { if (Iterables.all(types, isSubstitutableBy(baseType))) { return createType(ast, scope, baseType); } } // No suitable class--make a new one. ITypeBinding parent = null; List<ITypeBinding> interfaces = Lists.newArrayList(); for (ITypeBinding otherType : types) { if (otherType.isClass()) { if (parent == null) { parent = otherType; } else if (isSubstitutableBy(otherType).apply(parent)) { parent = otherType; } else if (isSubstitutableBy(parent).apply(otherType)) { // do nothing } else { throw new AssertionError("Impossible common type: unrelated classes"); } } else { assert otherType.isInterface(); interfaces.add(otherType); } } // Create the new abstract class and add it to the current scope. TypeDeclaration newClass = createClass(ast, scope, parent, interfaces); scopeBody.add(newClass); return ast.newSimpleType(ast.newName(newClass.getName().getFullyQualifiedName())); }
From source file:com.eucalyptus.vm.VmControl.java
public StopInstancesResponseType stopInstances(final StopInstancesType request) throws EucalyptusCloudException { final StopInstancesResponseType reply = request.getReply(); try {//from w ww . jav a2s. com final Context ctx = Contexts.lookup(); final List<TerminateInstancesItemType> results = reply.getInstancesSet(); Predicate<String> stopPredicate = new Predicate<String>() { @Override public boolean apply(final String instanceId) { try { final VmInstance v = VmInstances.lookup(instanceId); if (RestrictedTypes.filterPrivileged().apply(v)) { if (!MigrationState.isMigrating(v) && v.getBootRecord().getMachine() instanceof BlockStorageImageInfo) { final int oldCode = v.getState().getCode(), newCode = VmState.STOPPING.getCode(); final String oldState = v.getState().getName(), newState = VmState.STOPPING.getName(); TerminateInstancesItemType termInfo = new TerminateInstancesItemType( v.getInstanceId(), oldCode, oldState, newCode, newState); if (!results.contains(termInfo)) { results.add(termInfo); } VmInstances.stopped(v); } } return true;//GRZE: noop needs to be true to continue Iterables.all } catch (final NoSuchElementException e) { try { VmInstances.stopped(instanceId); return true; } catch (final NoSuchElementException e1) { return true; } catch (TransactionException ex) { Logs.extreme().error(ex, ex); return true; } } catch (Exception ex) { LOG.error(ex); Logs.extreme().error(ex, ex); throw Exceptions.toUndeclared(ex); } } }; final List<String> identifiers = normalizeIdentifiers(request.getInstancesSet()); for (final String instanceId : identifiers) { try { final VmInstance vm = VmInstances.lookup(instanceId); if (!vm.isBlockStorage()) throw new ClientComputeException("UnsupportedOperation", String.format( "The instance '%s' does not have an 'ebs' root device type and cannot be stopped.", instanceId)); } catch (final TerminatedInstanceException ex) { throw new ClientComputeException("IncorrectInstanceState", String.format( "This instance '%s' is not in a state from which it can be stopped.", instanceId)); } catch (final NoSuchElementException ex) { throw new ClientComputeException("InvalidInstanceID.NotFound", String.format("The instance ID '%s' does not exist", instanceId)); } catch (final EucalyptusCloudException ex) { throw ex; } } Predicate<String> stopTx = Entities.asTransaction(VmInstance.class, stopPredicate); Iterables.all(identifiers, stopTx); reply.set_return(!reply.getInstancesSet().isEmpty()); return reply; } catch (final EucalyptusCloudException ex) { throw ex; } catch (final Throwable e) { LOG.error(e); LOG.debug(e, e); throw new EucalyptusCloudException(e.getMessage()); } }
From source file:com.eucalyptus.autoscaling.activities.ActivityManager.java
private ScalingProcessTask<?, ?> perhapsScale(final AutoScalingGroupScalingView group) { final List<AutoScalingInstanceCoreView> currentInstances; try {/*from ww w .j a va2 s .c o m*/ currentInstances = autoScalingInstances.listByGroup(group, Predicates.alwaysTrue(), TypeMappers.lookup(AutoScalingInstance.class, AutoScalingInstanceCoreView.class)); } catch (final Exception e) { logger.error(e, e); return new LaunchInstancesScalingProcessTask(group, 0, ""); } if (group.getCapacity() > group.getDesiredCapacity()) { if (!Iterables.all(currentInstances, Predicates.and(LifecycleState.InService.forView(), ConfigurationState.Registered.forView(), HealthStatus.Healthy.forView()))) { // Wait for terminations / launches to complete before further scaling. if (logger.isTraceEnabled()) { logger.trace("Group over desired capacity (" + group.getCapacity() + "/" + group.getDesiredCapacity() + "), waiting for scaling operations to complete."); } return new LaunchInstancesScalingProcessTask(group, 0, ""); } return perhapsTerminateInstances(group, group.getCapacity() - group.getDesiredCapacity()); } else { final List<String> zones = Lists.transform(currentInstances, AutoScalingInstances.availabilityZone()); final Set<String> groupZones = Sets.newLinkedHashSet(group.getAvailabilityZones()); final Set<String> unavailableZones = zoneMonitor .getUnavailableZones(AutoScalingConfiguration.getZoneFailureThresholdMillis()); groupZones.removeAll(unavailableZones); final int expectedInstancesPerZone = group.getCapacity() / Math.max(1, groupZones.size()); int requiredInstances = 0; for (final String zone : groupZones) { int instanceCount = CollectionUtils.reduce(zones, 0, CollectionUtils.count(Predicates.equalTo(zone))); if (instanceCount < expectedInstancesPerZone) { requiredInstances += expectedInstancesPerZone - instanceCount; } } final int hardInstanceLimit = group.getDesiredCapacity() + Math.max(1, group.getDesiredCapacity() / 10); if (requiredInstances + group.getCapacity() > hardInstanceLimit) { requiredInstances = hardInstanceLimit - group.getCapacity(); } else if (requiredInstances + group.getCapacity() < group.getDesiredCapacity()) { requiredInstances = group.getDesiredCapacity() - group.getCapacity(); } if (requiredInstances == 0) { setScalingNotRequired(group); } else if (!scalingProcessEnabled(ScalingProcessType.AZRebalance, group) && group.getCapacity().equals(group.getDesiredCapacity())) { if (logger.isTraceEnabled()) { logger.trace( "AZ rebalancing disabled, suppressing launch of " + requiredInstances + " instance(s)"); } requiredInstances = 0; // rebalancing disabled } String cause; if (group.getCapacity() < group.getDesiredCapacity()) { cause = String.format( "an instance was started in response to a difference between desired and actual capacity, increasing the capacity from %1$d to %2$d", group.getCapacity(), group.getCapacity() + requiredInstances); } else { final Set<String> groupZoneSet = Sets.newHashSet(group.getAvailabilityZones()); final Set<String> invalidZoneSet = Sets.newTreeSet(); Iterables.addAll(invalidZoneSet, Sets.intersection(groupZoneSet, unavailableZones)); Iterables.addAll(invalidZoneSet, Sets.difference(Sets.newHashSet(zones), groupZoneSet)); final List<Integer> invalidZoneCounts = Lists.newArrayList(); for (final String zone : invalidZoneSet) { invalidZoneCounts .add(CollectionUtils.reduce(zones, 0, CollectionUtils.count(Predicates.equalTo(zone)))); } final String invalidZones = Joiner.on(", ").join(invalidZoneSet); final String invalidZoneInstanceCounts = Joiner.on(", ").join(invalidZoneCounts); cause = String.format( "invalid availability zones %1$s had %2$s instances respectively. An instance was launched to aid in migrating instances from these zones to valid ones", invalidZones, invalidZoneInstanceCounts); } return new LaunchInstancesScalingProcessTask(group, requiredInstances, cause); } }
From source file:msi.gama.lang.gaml.expression.GamlExpressionCompiler.java
@Override public IExpression caseArray(final Array object) { final List<? extends Expression> list = EGaml.getExprsOf(object.getExprs()); final boolean allPairs = !list.isEmpty() && Iterables.all(list, each -> "::".equals(EGaml.getKeyOf(each))); final Iterable<IExpression> result = Iterables.transform(list, input -> compile(input)); return allPairs ? getFactory().createMap(result) : getFactory().createList(result); }
From source file:org.eclipse.viatra.query.patternlanguage.emf.validation.PatternLanguageValidator.java
@Check(CheckType.NORMAL) public void checkNegativeCallParameters(PatternCompositionConstraint constraint) { Predicate<ValueReference> isSingleUseVariable = input -> input instanceof VariableReference ? ((VariableReference) input).getVar().startsWith("_") : false;/* ww w . ja va 2 s.c o m*/ if (constraint.isNegative()) { List<ValueReference> callVariables = PatternLanguageHelper.getCallParameters(constraint.getCall()); List<IInputKey> expectedTypes = PatternLanguageHelper.calculateExpectedTypes(constraint.getCall(), typeSystem, typeInferrer); //maxIndex is used to avoid overindexing in case of incorrect number of parameters int maxIndex = Math.min(callVariables.size(), expectedTypes.size()); if (Iterables.all(callVariables, isSingleUseVariable)) { warning("This negative pattern call is a global constraint: " + "it expresses that there are no matches of the called pattern at all. " + "Make sure this is intentional!", PatternLanguagePackage.Literals.PATTERN_COMPOSITION_CONSTRAINT__CALL, IssueCodes.NEGATIVE_PATTERN_CALL_WITH_ONLY_SINGLE_USE_VARIABLES); } produceParameterTypeWarnings(callVariables, expectedTypes, maxIndex); } }
From source file:dagger2.internal.codegen.ComponentGenerator.java
private void initializeFrameworkTypes(BindingGraph input, ClassWriter componentWriter, ConstructorWriter constructorWriter, Optional<ClassName> builderName, Map<TypeElement, MemberSelect> componentContributionFields, ImmutableMap<BindingKey, MemberSelect> memberSelectSnippets, ImmutableMap<ContributionBinding, Snippet> parentMultibindingContributionSnippets, ImmutableMap<ContributionBinding, Snippet> multibindingContributionSnippets) throws AssertionError { List<List<BindingKey>> partitions = Lists.partition(input.resolvedBindings().keySet().asList(), 100); for (int i = 0; i < partitions.size(); i++) { MethodWriter initializeMethod = componentWriter.addMethod(VoidName.VOID, "initialize" + ((i == 0) ? "" : i)); initializeMethod.body();/*w ww . j a va 2s. com*/ initializeMethod.addModifiers(PRIVATE); if (builderName.isPresent()) { initializeMethod.addParameter(builderName.get(), "builder").addModifiers(FINAL); constructorWriter.body().addSnippet("%s(builder);", initializeMethod.name()); } else { constructorWriter.body().addSnippet("%s();", initializeMethod.name()); } for (BindingKey bindingKey : partitions.get(i)) { Snippet memberSelectSnippet = memberSelectSnippets.get(bindingKey) .getSnippetFor(componentWriter.name()); ResolvedBindings resolvedBindings = input.resolvedBindings().get(bindingKey); switch (bindingKey.kind()) { case CONTRIBUTION: ImmutableSet<? extends ContributionBinding> bindings = resolvedBindings.contributionBindings(); switch (ContributionBinding.bindingTypeFor(bindings)) { case SET: boolean hasOnlyProvisions = Iterables.all(bindings, Predicates.instanceOf(ProvisionBinding.class)); ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder(); for (ContributionBinding binding : bindings) { if (multibindingContributionSnippets.containsKey(binding)) { Snippet initializeSnippet = initializeFactoryForContributionBinding(binding, input, componentWriter.name(), componentContributionFields, memberSelectSnippets); Snippet snippet = multibindingContributionSnippets.get(binding); initializeMethod.body().addSnippet("this.%s = %s;", snippet, initializeSnippet); parameterSnippets.add(snippet); } else if (parentMultibindingContributionSnippets.containsKey(binding)) { parameterSnippets.add(parentMultibindingContributionSnippets.get(binding)); } else { throw new IllegalStateException(binding + " was not found in"); } } Snippet initializeSetSnippet = Snippet.format("%s.create(%s)", hasOnlyProvisions ? ClassName.fromClass(SetFactory.class) : ClassName.fromClass(SetProducer.class), Snippet.makeParametersSnippet(parameterSnippets.build())); initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeSetSnippet); break; case MAP: if (Sets.filter(bindings, Predicates.instanceOf(ProductionBinding.class)).isEmpty()) { @SuppressWarnings("unchecked") // checked by the instanceof filter above ImmutableSet<ProvisionBinding> provisionBindings = (ImmutableSet<ProvisionBinding>) bindings; for (ProvisionBinding provisionBinding : provisionBindings) { if (!isNonProviderMap(provisionBinding) && multibindingContributionSnippets.containsKey(provisionBinding)) { Snippet snippet = multibindingContributionSnippets.get(provisionBinding); initializeMethod.body().addSnippet("this.%s = %s;", snippet, initializeFactoryForProvisionBinding(provisionBinding, componentWriter.name(), input.componentDescriptor().dependencyMethodIndex(), componentContributionFields, memberSelectSnippets)); } } if (!provisionBindings.isEmpty()) { Snippet initializeMapSnippet = initializeMapBinding(componentWriter.name(), memberSelectSnippets, new ImmutableMap.Builder<ContributionBinding, Snippet>() .putAll(parentMultibindingContributionSnippets) .putAll(multibindingContributionSnippets).build(), provisionBindings); initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeMapSnippet); } } else { // TODO(user): Implement producer map bindings. throw new IllegalStateException("producer map bindings not implemented yet"); } break; case UNIQUE: if (!resolvedBindings.ownedContributionBindings().isEmpty()) { ContributionBinding binding = Iterables.getOnlyElement(bindings); if (binding instanceof ProvisionBinding) { ProvisionBinding provisionBinding = (ProvisionBinding) binding; if (!provisionBinding.factoryCreationStrategy().equals(ENUM_INSTANCE) || provisionBinding.scope().isPresent()) { initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeFactoryForProvisionBinding(provisionBinding, componentWriter.name(), input.componentDescriptor().dependencyMethodIndex(), componentContributionFields, memberSelectSnippets)); } } else if (binding instanceof ProductionBinding) { ProductionBinding productionBinding = (ProductionBinding) binding; initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeFactoryForProductionBinding(productionBinding, input, componentWriter.name(), input.componentDescriptor().dependencyMethodIndex(), componentContributionFields, memberSelectSnippets)); } else { throw new AssertionError(); } } break; default: throw new IllegalStateException(); } break; case MEMBERS_INJECTION: MembersInjectionBinding binding = Iterables .getOnlyElement(resolvedBindings.membersInjectionBindings()); if (!binding.injectionStrategy().equals(MembersInjectionBinding.Strategy.NO_OP)) { initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeMembersInjectorForBinding(componentWriter.name(), binding, memberSelectSnippets)); } break; default: throw new AssertionError(); } } } }
From source file:org.eclipse.viatra.query.patternlanguage.validation.PatternLanguageJavaValidator.java
@Check(CheckType.NORMAL) public void checkNegativeCallParameters(PatternCompositionConstraint constraint) { Predicate<ValueReference> isSingleUseVariable = new Predicate<ValueReference>() { @Override/*from www . j a v a 2 s .c o m*/ public boolean apply(ValueReference input) { if (input instanceof VariableValue) { VariableValue variableValue = (VariableValue) input; return variableValue.getValue().getVar().startsWith("_"); } else { return false; } } }; if (constraint.isNegative() && Iterables.all(constraint.getCall().getParameters(), isSingleUseVariable)) { warning("This negative pattern call is a global constraint: " + "it expresses that there are no matches of the called pattern at all. " + "Make sure this is intentional!", PatternLanguagePackage.Literals.PATTERN_COMPOSITION_CONSTRAINT__CALL, IssueCodes.NEGATIVE_PATTERN_CALL_WITH_ONLY_SINGLE_USE_VARIABLES); } }
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
private static Function<String, VolumeInfo> invalidateAndDetachAll() { final Predicate<VolumeToken> invalidateExports = new Predicate<VolumeToken>() { @Override/*from w w w. j a v a 2 s . c om*/ public boolean apply(VolumeToken volToken) { VolumeToken tokenEntity = Entities.merge(volToken); try { tokenEntity.invalidateAllExportsAndToken(); return true; } catch (Exception e) { LOG.error("Failed invalidating exports for token " + tokenEntity.getToken()); return false; } } }; //Could save cycles by statically setting all of these functions that don't require closures so they are not //constructed for each request. return new Function<String, VolumeInfo>() { @Override public VolumeInfo apply(String volumeId) { try { VolumeInfo volumeEntity = Entities.uniqueResult(new VolumeInfo(volumeId)); try { LOG.debug("Invalidating all tokens and all exports for " + volumeId); //Invalidate all tokens and exports and forcibly detach. if (!Iterables.all(volumeEntity.getAttachmentTokens(), invalidateExports)) { //At least one failed. LOG.error("Failed to invalidate all tokens and exports"); } } catch (Exception e) { LOG.error("Error invalidating tokens", e); } try { LOG.debug("Unexporting volume " + volumeId + "from all hosts"); blockManager.unexportVolumeFromAll(volumeId); } catch (EucalyptusCloudException ex) { LOG.error("Detaching volume " + volumeId + " from all hosts failed", ex); } } catch (NoSuchElementException e) { LOG.error("Cannot force detach of volume " + volumeId + " because it is not found in database"); return null; } catch (TransactionException e) { LOG.error("Failed to lookup volume " + volumeId); } return null; } }; }
From source file:edu.ucsb.eucalyptus.cloud.ws.BlockStorage.java
public DetachStorageVolumeResponseType detachVolume(DetachStorageVolumeType request) throws EucalyptusCloudException { DetachStorageVolumeResponseType reply = request.getReply(); String volumeId = request.getVolumeId(); LOG.info("Processing DetachVolume request for volume " + volumeId); final Predicate<VolumeToken> invalidateExports = new Predicate<VolumeToken>() { @Override/*w ww .java 2 s . c om*/ public boolean apply(VolumeToken volToken) { VolumeToken tokenEntity = Entities.merge(volToken); try { tokenEntity.invalidateAllExportsAndToken(); return true; } catch (Exception e) { LOG.error("Failed invalidating exports for token " + tokenEntity.getToken()); return false; } } }; //Could save cycles by statically setting all of these functions that don't require closures so they are not // constructed for each request. final Function<String, VolumeInfo> invalidateAndDetachAll = new Function<String, VolumeInfo>() { @Override public VolumeInfo apply(String volumeId) { try { VolumeInfo volumeEntity = Entities.uniqueResult(new VolumeInfo(volumeId)); try { LOG.debug("Invalidating all tokens and all exports for " + volumeId); //Invalidate all tokens and exports and forcibly detach. if (!Iterables.all(volumeEntity.getAttachmentTokens(), invalidateExports)) { //At least one failed. LOG.error("Failed to invalidate all tokens and exports"); } } catch (Exception e) { LOG.error("Error invalidating tokens", e); } try { LOG.debug("Unexporting volume " + volumeId + "from all hosts"); blockManager.unexportVolumeFromAll(volumeId); } catch (EucalyptusCloudException ex) { LOG.error("Detaching volume " + volumeId + " from all hosts failed", ex); } } catch (NoSuchElementException e) { LOG.error("Cannot force detach of volume " + volumeId + " because it is not found in database"); return null; } catch (TransactionException e) { LOG.error("Failed to lookup volume " + volumeId); } return null; } }; //Do the work. try { LOG.info("Detaching volume " + volumeId + " from all hosts"); Entities.asTransaction(VolumeInfo.class, invalidateAndDetachAll).apply(volumeId); } catch (final Exception e) { LOG.error("Failed to fully detach volume " + volumeId); reply.set_return(false); } return reply; }