List of usage examples for com.google.common.base Predicates equalTo
public static <T> Predicate<T> equalTo(@Nullable T target)
From source file:dagger2.internal.codegen.BindingGraphValidator.java
private void reportMissingBinding(Deque<ResolvedRequest> path, ValidationReport.Builder<BindingGraph> reportBuilder) { Key key = path.peek().request().key(); TypeMirror type = key.type(); String typeName = TypeNames.forTypeMirror(type).toString(); boolean requiresContributionMethod = !key.isValidImplicitProvisionKey(types); boolean requiresProvision = doesPathRequireProvisionOnly(path); StringBuilder errorMessage = new StringBuilder(); String requiresErrorMessageFormat = requiresContributionMethod ? requiresProvision ? REQUIRES_PROVIDER_FORMAT : REQUIRES_PROVIDER_OR_PRODUCER_FORMAT : requiresProvision ? REQUIRES_AT_INJECT_CONSTRUCTOR_OR_PROVIDER_FORMAT : REQUIRES_AT_INJECT_CONSTRUCTOR_OR_PROVIDER_OR_PRODUCER_FORMAT; errorMessage.append(String.format(requiresErrorMessageFormat, typeName)); if (key.isValidMembersInjectionKey() && !injectBindingRegistry.getOrFindMembersInjectionBinding(key).injectionSites().isEmpty()) { errorMessage.append(" ").append(ErrorMessages.MEMBERS_INJECTION_DOES_NOT_IMPLY_PROVISION); }// w w w. ja v a 2s .c o m ImmutableList<String> printableDependencyPath = FluentIterable.from(path) .transform(REQUEST_FROM_RESOLVED_REQUEST).transform(dependencyRequestFormatter) .filter(Predicates.not(Predicates.equalTo(""))).toList().reverse(); for (String dependency : printableDependencyPath.subList(1, printableDependencyPath.size())) { errorMessage.append("\n").append(dependency); } reportBuilder.addItem(errorMessage.toString(), path.getLast().request().requestElement()); }
From source file:brooklyn.entity.basic.AbstractSoftwareProcessSshDriver.java
/** * Sets up a {@link ScriptHelper} to generate a script that controls the given phase * (<em>check-running</em>, <em>launching</em> etc.) including default header and * footer commands./*from w w w. ja v a 2s . c o m*/ * <p> * Supported flags: * <ul> * <li><strong>usePidFile</strong> - <em>true</em> or <em>filename</em> to save and retrieve the PID * <li><strong>processOwner</strong> - <em>username</em> that owns the running process * <li><strong>nonStandardLayout</strong> - <em>true</em> to omit all default commands * <li><strong>installIncomplete</strong> - <em>true</em> to prevent marking complete * <li><strong>debug</strong> - <em>true</em> to enable shell debug output * </li> * * @param flags a {@link Map} of flags to control script generation * @param phase the phase to create the ScriptHelper for * * @see #newScript(String) * @see #USE_PID_FILE * @see #PROCESS_OWNER * @see #NON_STANDARD_LAYOUT * @see #INSTALL_INCOMPLETE * @see #DEBUG */ protected ScriptHelper newScript(Map<String, ?> flags, String phase) { if (!Entities.isManaged(getEntity())) throw new IllegalStateException( getEntity() + " is no longer managed; cannot create script to run here (" + phase + ")"); if (!Iterables.all(flags.keySet(), StringPredicates.equalToAny(VALID_FLAGS))) { throw new IllegalArgumentException("Invalid flags passed: " + flags); } ScriptHelper s = new ScriptHelper(this, phase + " " + elvis(entity, this)); if (!groovyTruth(flags.get(NON_STANDARD_LAYOUT))) { if (groovyTruth(flags.get(DEBUG))) { s.header.prepend("set -x"); } if (INSTALLING.equals(phase)) { // mutexId should be global because otherwise package managers will contend with each other s.useMutex(getLocation(), "installation lock at host", "installing " + elvis(entity, this)); s.header.append("export INSTALL_DIR=\"" + getInstallDir() + "\"", "mkdir -p $INSTALL_DIR", "cd $INSTALL_DIR", "test -f BROOKLYN && exit 0"); if (!groovyTruth(flags.get(INSTALL_INCOMPLETE))) { s.footer.append("date > $INSTALL_DIR/BROOKLYN"); } // don't set vars during install phase, prevent dependency resolution s.environmentVariablesReset(); } if (ImmutableSet.of(CUSTOMIZING, LAUNCHING, CHECK_RUNNING, STOPPING, KILLING, RESTARTING) .contains(phase)) { s.header.append("export RUN_DIR=\"" + getRunDir() + "\"", "mkdir -p $RUN_DIR", "cd $RUN_DIR"); } } if (ImmutableSet.of(LAUNCHING, RESTARTING).contains(phase)) { s.failIfBodyEmpty(); } if (ImmutableSet.of(STOPPING, KILLING).contains(phase)) { // stopping and killing allowed to have empty body if pid file set if (!groovyTruth(flags.get(USE_PID_FILE))) s.failIfBodyEmpty(); } if (ImmutableSet.of(INSTALLING, LAUNCHING).contains(phase)) { s.updateTaskAndFailOnNonZeroResultCode(); } if (phase.equalsIgnoreCase(CHECK_RUNNING)) { s.setInessential(); s.setTransient(); s.setFlag(SshTool.PROP_CONNECT_TIMEOUT, Duration.TEN_SECONDS.toMilliseconds()); s.setFlag(SshTool.PROP_SESSION_TIMEOUT, Duration.THIRTY_SECONDS.toMilliseconds()); s.setFlag(SshTool.PROP_SSH_TRIES, 1); } if (groovyTruth(flags.get(USE_PID_FILE))) { Object usePidFile = flags.get(USE_PID_FILE); String pidFile = (usePidFile instanceof CharSequence ? usePidFile : Os.mergePathsUnix(getRunDir(), PID_FILENAME)).toString(); String processOwner = (String) flags.get(PROCESS_OWNER); if (LAUNCHING.equals(phase)) { entity.setAttribute(SoftwareProcess.PID_FILE, pidFile); s.footer.prepend("echo $! > " + pidFile); } else if (CHECK_RUNNING.equals(phase)) { // old method, for supplied service, or entity.id // "ps aux | grep ${service} | grep \$(cat ${pidFile}) > /dev/null" // new way, preferred? if (processOwner != null) { s.body.append(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1", "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")"); } else { s.body.append("test -f " + pidFile + " || exit 1", "ps -p `cat " + pidFile + "`"); } // no pid, not running; 1 is not running s.requireResultCode(Predicates.or(Predicates.equalTo(0), Predicates.equalTo(1))); } else if (STOPPING.equals(phase)) { if (processOwner != null) { s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")", "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill $PID"), BashCommands.sudoAsUser(processOwner, "kill -9 $PID"), BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile)); } else { s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill $PID", "kill -9 $PID", "rm -f " + pidFile); } } else if (KILLING.equals(phase)) { if (processOwner != null) { s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")", "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill -9 $PID"), BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile)); } else { s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill -9 $PID", "rm -f " + pidFile); } } else if (RESTARTING.equals(phase)) { if (processOwner != null) { s.footer.prepend(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1", "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ") || exit 1"); } else { s.footer.prepend("test -f " + pidFile + " || exit 1", "ps -p $(cat " + pidFile + ") || exit 1"); } // no pid, not running; no process; can't restart, 1 is not running } else { log.warn(USE_PID_FILE + ": script option not valid for " + s.summary); } } return s; }
From source file:r.base.Types.java
@Primitive public static SEXP inherits(SEXP exp, StringVector what, boolean which) { if (!which) { return new LogicalVector(inherits(exp, what)); }/* w w w . j a va 2s. com*/ StringVector classes = getClass(exp); int result[] = new int[what.length()]; for (int i = 0; i != what.length(); ++i) { result[i] = Iterables.indexOf(classes, Predicates.equalTo(what.getElement(i))) + 1; } return new IntVector(result); }
From source file:org.apache.cassandra.thrift.CassandraServer.java
private void validateSchemaAgreement() throws SchemaDisagreementException { // unreachable hosts don't count towards disagreement Map<String, List<String>> versions = Maps.filterKeys(StorageProxy.describeSchemaVersions(), Predicates.not(Predicates.equalTo(StorageProxy.UNREACHABLE))); if (versions.size() > 1) throw new SchemaDisagreementException(); }
From source file:dagger2.internal.codegen.BindingGraphValidator.java
private void reportCycle(DependencyRequest request, Deque<ResolvedRequest> path, final ValidationReport.Builder<BindingGraph> reportBuilder) { ImmutableList<DependencyRequest> pathElements = ImmutableList.<DependencyRequest>builder().add(request) .addAll(Iterables.transform(path, REQUEST_FROM_RESOLVED_REQUEST)).build(); ImmutableList<String> printableDependencyPath = FluentIterable.from(pathElements) .transform(dependencyRequestFormatter).filter(Predicates.not(Predicates.equalTo(""))).toList() .reverse();/*from ww w .j a v a 2 s .com*/ DependencyRequest rootRequest = path.getLast().request(); TypeElement componentType = MoreElements.asType(rootRequest.requestElement().getEnclosingElement()); // TODO(cgruber): Restructure to provide a hint for the start and end of the cycle. reportBuilder .addItem( String.format(ErrorMessages.CONTAINS_DEPENDENCY_CYCLE_FORMAT, componentType.getQualifiedName(), rootRequest.requestElement().getSimpleName(), Joiner.on("\n") .join(printableDependencyPath.subList(1, printableDependencyPath.size()))), rootRequest.requestElement()); }
From source file:com.eucalyptus.autoscaling.activities.ActivityManager.java
private ScalingProcessTask<?, ?> perhapsScale(final AutoScalingGroupScalingView group) { final List<AutoScalingInstanceCoreView> currentInstances; try {/* w ww.j a va 2 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:org.eclipse.sirius.diagram.ui.tools.api.figure.locator.DBorderItemLocator.java
/** * Get the figures of the brother's border nodes of * <code>targetBorderItem</code>. * //from ww w . j ava 2 s .co m * @param targetBorderItem * Contextual border item. * @return The list of figure of the brother border nodes. */ protected List<IFigure> getBrotherFigures(final IFigure targetBorderItem) { @SuppressWarnings("unchecked") Iterable<IFigure> brotherFigures = Iterables.filter(targetBorderItem.getParent().getChildren(), Predicates .and(Predicates.instanceOf(IFigure.class), Predicates.not(Predicates.equalTo(targetBorderItem)))); return Lists.newArrayList(brotherFigures); }
From source file:org.obm.push.mail.MailBackendImpl.java
@Override public BackendId createFolder(UserDataRequest udr, FolderCreateRequest folderCreateRequest, Optional<BackendId> parent) throws BackendNotSupportedException { MailboxFolders subscribedFolders = mailboxService.listSubscribedFolders(udr); char serverDelimiter = findServerSeparator(udr, parent, subscribedFolders); MailboxFolder newMailboxFolder = findNameRelatedToParent(folderCreateRequest, parent, serverDelimiter); MailboxPath mailboxPath = MailboxPath.of(newMailboxFolder.getName(), newMailboxFolder.getImapSeparator()); Optional<MailboxFolder> subscribedFolder = Iterables.tryFind(subscribedFolders, Predicates.equalTo(newMailboxFolder)); if (subscribedFolder.isPresent()) { throw new FolderAlreadyExistsException("Cannot create two times a folder."); } else if (mailboxService.folderExists(udr, mailboxPath)) { mailboxService.subscribeToFolder(udr, newMailboxFolder); } else {/* w ww.ja va2 s. c om*/ mailboxService.createFolder(udr, newMailboxFolder); mailboxService.subscribeToFolder(udr, newMailboxFolder); } return mailboxPath; }
From source file:com.eucalyptus.bootstrap.Databases.java
/** * List all known databases.// ww w. ja v a 2s . c o m */ static Set<String> listDatabases() { final Set<String> dbNames = Sets.newHashSet(); final Predicate<String> dbNamePredicate = Predicates.or(Strings.startsWith("eucalyptus_"), Predicates.equalTo("database_events")); for (final Host h : Hosts.listActiveDatabases()) { Iterables.addAll(dbNames, Iterables .filter(Databases.getBootstrapper().listDatabases(h.getBindAddress()), dbNamePredicate)); } return dbNames; }
From source file:com.google.javascript.jscomp.NameAnalyzer.java
/** * Records a reference from one name to another name. *///w w w.j av a 2 s . co m private void recordReference(DiGraphNode<JsName, RefType> from, DiGraphNode<JsName, RefType> to, RefType depType) { if (from == to) { // Don't bother recording self-references. return; } if (!referenceGraph.isConnectedInDirection(from, Predicates.equalTo(depType), to)) { referenceGraph.connect(from, depType, to); } }