List of usage examples for com.google.common.base Predicates equalTo
public static <T> Predicate<T> equalTo(@Nullable T target)
From source file:brooklyn.util.osgi.Osgis.java
/** @deprecated since 0.7.0 use {@link #bundleFinder(Framework)} */ @Deprecated/*from ww w . ja v a 2 s . c o m*/ public static Maybe<Bundle> getBundle(Framework framework, String symbolicName, Version version) { return bundleFinder(framework).symbolicName(symbolicName).version(Predicates.equalTo(version)).findUnique(); }
From source file:org.apache.brooklyn.entity.nosql.couchbase.CouchbaseClusterImpl.java
@Override protected void doStart() { sensors().set(IS_CLUSTER_INITIALIZED, false); super.doStart(); connectSensors();// w w w . ja v a2 s .c o m sensors().set(BUCKET_CREATION_IN_PROGRESS, false); //start timeout before adding the servers Tasks.setBlockingDetails("Pausing while Couchbase stabilizes"); Time.sleep(getConfig(NODES_STARTED_STABILIZATION_DELAY)); Optional<Set<Entity>> upNodes = Optional .<Set<Entity>>fromNullable(getAttribute(COUCHBASE_CLUSTER_UP_NODES)); if (upNodes.isPresent() && !upNodes.get().isEmpty()) { Tasks.setBlockingDetails("Adding servers to Couchbase"); //TODO: select a new primary node if this one fails Entity primaryNode = upNodes.get().iterator().next(); ((EntityInternal) primaryNode).sensors().set(CouchbaseNode.IS_PRIMARY_NODE, true); sensors().set(COUCHBASE_PRIMARY_NODE, primaryNode); Set<Entity> serversToAdd = MutableSet.<Entity>copyOf(getUpNodes()); if (serversToAdd.size() >= getQuorumSize() && serversToAdd.size() > 1) { log.info("Number of SERVICE_UP nodes:{} in cluster:{} reached Quorum:{}, adding the servers", new Object[] { serversToAdd.size(), getId(), getQuorumSize() }); addServers(serversToAdd); //wait for servers to be added to the couchbase server try { Tasks.setBlockingDetails("Delaying before advertising cluster up"); Time.sleep(getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER)); } finally { Tasks.resetBlockingDetails(); } ((CouchbaseNode) getPrimaryNode()).rebalance(); } else { if (getQuorumSize() > 1) { log.warn(this + " is not quorate; will likely fail later, but proceeding for now"); } for (Entity server : serversToAdd) { ((EntityInternal) server).sensors().set(CouchbaseNode.IS_IN_CLUSTER, true); } } if (getConfig(CREATE_BUCKETS) != null) { try { Tasks.setBlockingDetails("Creating buckets in Couchbase"); createBuckets(); DependentConfiguration.waitInTaskForAttributeReady(this, CouchbaseCluster.BUCKET_CREATION_IN_PROGRESS, Predicates.equalTo(false)); } finally { Tasks.resetBlockingDetails(); } } if (getConfig(REPLICATION) != null) { try { Tasks.setBlockingDetails("Configuring replication rules"); List<Map<String, Object>> replRules = getConfig(REPLICATION); for (Map<String, Object> replRule : replRules) { DynamicTasks.queue(Effectors.invocation(getPrimaryNode(), CouchbaseNode.ADD_REPLICATION_RULE, replRule)); } DynamicTasks.waitForLast(); } finally { Tasks.resetBlockingDetails(); } } sensors().set(IS_CLUSTER_INITIALIZED, true); } else { throw new IllegalStateException("No up nodes available after starting"); } }
From source file:clocker.docker.location.DockerLocation.java
@Override public void release(MachineLocation machine) { if (provisioner == null) { throw new IllegalStateException("No provisioner available to release " + machine); }/*from w w w.java2 s. c om*/ String id = machine.getId(); Set<DockerHostLocation> set = Multimaps.filterValues(containers, Predicates.equalTo(id)).keySet(); if (set.isEmpty()) { throw new IllegalArgumentException( "Request to release " + machine + ", but this machine is not currently allocated"); } DockerHostLocation host = Iterables.getOnlyElement(set); LOG.debug("Request to remove container mapping {} to {}", host, id); host.release((DockerContainerLocation) machine); if (containers.remove(host, id)) { if (containers.get(host).isEmpty()) { LOG.debug("Empty Docker host: {}", host); // Remove hosts when it has no containers, except for the last one if (infrastructure.config().get(DockerInfrastructure.REMOVE_EMPTY_DOCKER_HOSTS) && set.size() > 1) { LOG.info("Removing empty Docker host: {}", host); remove(host); } } } else { throw new IllegalArgumentException( "Request to release " + machine + ", but container mapping not found"); } }
From source file:org.apache.druid.server.coordinator.CostBalancerStrategy.java
protected double computeCost(final DataSegment proposalSegment, final ServerHolder server, final boolean includeCurrentServer) { final long proposalSegmentSize = proposalSegment.getSize(); // (optional) Don't include server if it is already serving segment if (!includeCurrentServer && server.isServingSegment(proposalSegment)) { return Double.POSITIVE_INFINITY; }/*w ww . ja v a 2s . c o m*/ // Don't calculate cost if the server doesn't have enough space or is loading the segment if (proposalSegmentSize > server.getAvailableSize() || server.isLoadingSegment(proposalSegment)) { return Double.POSITIVE_INFINITY; } // The contribution to the total cost of a given server by proposing to move the segment to that server is... double cost = 0d; // the sum of the costs of other (exclusive of the proposalSegment) segments on the server cost += computeJointSegmentsCost(proposalSegment, Iterables.filter( server.getServer().getSegments().values(), Predicates.not(Predicates.equalTo(proposalSegment)))); // plus the costs of segments that will be loaded cost += computeJointSegmentsCost(proposalSegment, server.getPeon().getSegmentsToLoad()); // minus the costs of segments that are marked to be dropped cost -= computeJointSegmentsCost(proposalSegment, server.getPeon().getSegmentsMarkedToDrop()); return cost; }
From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.edit.validator.ISEComplexMoveValidator.java
private boolean moveIsValid(ISequenceEvent ise, boolean topLevel) { final Range futureExtRange = getFutureExtendedRange(ise); Option<Lifeline> lifeline = ise.getLifeline(); boolean result = true; if (lifeline.some()) { EventFinder futureParentFinder = new EventFinder(lifeline.get()); futureParentFinder.setEventsToIgnore(Predicates.equalTo(ise)); futureParentFinder.setVerticalRangefunction(rangeFunction); Range insertionPoint = getInsertionPoint(ise, futureExtRange); ISequenceEvent insertionParent = futureParentFinder.findMostSpecificEvent(insertionPoint); if (insertionParent == null) { if (lifeline.get().isExplicitlyCreated() || lifeline.get().isExplicitlyDestroyed()) { return false; } else { insertionParent = lifeline.get(); }/*w ww . java 2 s. c o m*/ } // check Operand; boolean stableOperand = checkOperandStability(ise, topLevel, insertionParent); // check expansion need boolean validExpansion = stableOperand && checkExpansionNeed(ise, topLevel, insertionParent, futureExtRange, insertionPoint, Collections.singletonList(lifeline.get())); // Test remote expansion boolean validRemoteExpansion = validExpansion && checkRemoteExpansion(ise, topLevel, futureExtRange, insertionPoint); result = stableOperand && validExpansion && validRemoteExpansion; } else if (ise instanceof InteractionUse) { InteractionUseMoveValidator subValidator = new InteractionUseMoveValidator((InteractionUse) ise, request); subValidator.setMovedElements(movedElements); result = subValidator.isValid(); expansionZone = expansionZone.union(subValidator.getExpansionZone()); } else if (ise instanceof CombinedFragment) { CombinedFragmentMoveValidator subValidator = new CombinedFragmentMoveValidator((CombinedFragment) ise, request); subValidator.setMovedElements(movedElements); result = subValidator.isValid(); expansionZone = expansionZone.union(subValidator.getExpansionZone()); } else if (ise instanceof Message) { result = messageMoveIsValid((Message) ise); } return result; }
From source file:org.gradle.plugins.ide.idea.model.internal.IdeaDependenciesProvider.java
private boolean isMappedToIdeaScope(final Configuration configuration, IdeaModule ideaModule) { Iterable<IdeaScopeMappingRule> rules = Iterables.concat(scopeMappings.values()); boolean matchesRule = Iterables.any(rules, new Predicate<IdeaScopeMappingRule>() { public boolean apply(IdeaScopeMappingRule ideaScopeMappingRule) { return ideaScopeMappingRule.configurationNames.contains(configuration.getName()); }//from www .ja va 2s.c o m }); if (matchesRule) { return true; } for (Map<String, Collection<Configuration>> scopeMap : ideaModule.getScopes().values()) { Iterable<Configuration> configurations = Iterables.concat(scopeMap.values()); if (Iterables.any(configurations, Predicates.equalTo(configuration))) { return true; } } return false; }
From source file:org.eclipse.sirius.ui.business.internal.viewpoint.ViewpointSelectionDialog.java
/** * Get missing dependencies from the current selection * /*from www .j a v a 2 s.c o m*/ * @return missing dependencies */ private Map<String, Collection<String>> getMissingDependencies() { Set<Viewpoint> selected = Maps.filterValues(selection, Predicates.equalTo(Boolean.TRUE)).keySet(); Multimap<String, String> result = HashMultimap.create(); for (Viewpoint viewpoint : selected) { for (RepresentationExtensionDescription extension : new ViewpointQuery(viewpoint) .getAllRepresentationExtensionDescriptions()) { String extended = extension.getViewpointURI(); final Pattern pattern = Pattern.compile(extended); // Is there at least one available selected viewpoint URI ? if (!Iterables.any(selected, new Predicate<Viewpoint>() { @Override public boolean apply(Viewpoint vp) { Option<URI> uri = new ViewpointQuery(vp).getViewpointURI(); if (uri.some()) { Matcher matcher = pattern.matcher(uri.get().toString()); return matcher.matches(); } else { return false; } } })) { result.put(viewpoint.getName(), extended.trim().replaceFirst("^viewpoint:/[^/]+/", "")); //$NON-NLS-1$ //$NON-NLS-2$ } } } return result.asMap(); }
From source file:com.twitter.aurora.scheduler.state.CronJobManager.java
/** * Triggers execution of a cron job, depending on the cron collision policy for the job. * * @param config The config of the job to be triggered. *//* ww w .j a v a 2 s. co m*/ @VisibleForTesting void cronTriggered(SanitizedConfiguration config) { IJobConfiguration job = config.getJobConfig(); LOG.info(String.format("Cron triggered for %s at %s with policy %s", JobKeys.toPath(job), new Date(), job.getCronCollisionPolicy())); cronJobsTriggered.incrementAndGet(); ImmutableMap.Builder<Integer, ITaskConfig> builder = ImmutableMap.builder(); final Query.Builder activeQuery = Query.jobScoped(job.getKey()).active(); Set<IScheduledTask> activeTasks = Storage.Util.consistentFetchTasks(storage, activeQuery); if (activeTasks.isEmpty()) { builder.putAll(config.getTaskConfigs()); } else { // Assign a default collision policy. CronCollisionPolicy collisionPolicy = orDefault(job.getCronCollisionPolicy()); switch (collisionPolicy) { case KILL_EXISTING: try { schedulerCore.killTasks(activeQuery, CRON_USER); // Check immediately if the tasks are gone. This could happen if the existing tasks // were pending. if (!hasTasks(activeQuery)) { builder.putAll(config.getTaskConfigs()); } else { delayedRun(activeQuery, config); } } catch (ScheduleException e) { LOG.log(Level.SEVERE, "Failed to kill job.", e); } break; case CANCEL_NEW: break; case RUN_OVERLAP: Map<Integer, IScheduledTask> byInstance = Maps.uniqueIndex(activeTasks, Tasks.SCHEDULED_TO_INSTANCE_ID); Map<Integer, ScheduleStatus> existingTasks = Maps.transformValues(byInstance, Tasks.GET_STATUS); if (existingTasks.isEmpty()) { builder.putAll(config.getTaskConfigs()); } else if (Iterables.any(existingTasks.values(), Predicates.equalTo(PENDING))) { LOG.info("Job " + JobKeys.toPath(job) + " has pending tasks, suppressing run."); } else { // To safely overlap this run, we need to adjust the instance IDs of the overlapping // run (maintaining the role/job/instance UUID invariant). int instanceOffset = Ordering.natural().max(existingTasks.keySet()) + 1; LOG.info("Adjusting instance IDs of " + JobKeys.toPath(job) + " by " + instanceOffset + " for overlapping cron run."); for (Map.Entry<Integer, ITaskConfig> entry : config.getTaskConfigs().entrySet()) { builder.put(entry.getKey() + instanceOffset, entry.getValue()); } } break; default: LOG.severe("Unrecognized cron collision policy: " + job.getCronCollisionPolicy()); } } Map<Integer, ITaskConfig> newTasks = builder.build(); if (!newTasks.isEmpty()) { stateManager.insertPendingTasks(newTasks); } }
From source file:io.selendroid.server.model.DeviceStore.java
private Predicate<AndroidDevice> deviceSatisfiesCapabilities(final SelendroidCapabilities capabilities) { return new Predicate<AndroidDevice>() { @Override// w w w.j a v a 2 s. c o m public boolean apply(AndroidDevice candidate) { ArrayList<Boolean> booleanExpressions = Lists.newArrayList( candidate.screenSizeMatches(capabilities.getScreenSize()), capabilities.getEmulator() == null ? true : capabilities.getEmulator() ? candidate instanceof DefaultAndroidEmulator : candidate instanceof DefaultHardwareDevice, StringUtils.isNotBlank(capabilities.getSerial()) ? capabilities.getSerial().equals(candidate.getSerial()) : true); return Iterables.all(booleanExpressions, Predicates.equalTo(true)); } }; }
From source file:clocker.docker.entity.DockerInfrastructureImpl.java
@Override public void init() { String version = config().get(DOCKER_VERSION); if (VersionComparator.getInstance().compare("1.9", version) > 1) { throw new IllegalStateException("Requires libnetwork capable Docker > 1.9"); }// ww w .j av a2s . c o m LOG.info("Starting Docker infrastructure id {}", getId()); registerLocationResolver(); super.init(); int initialSize = config().get(DOCKER_HOST_CLUSTER_MIN_SIZE); Map<String, String> runtimeFiles = ImmutableMap.of(); if (!config().get(DOCKER_GENERATE_TLS_CERTIFICATES)) { runtimeFiles = ImmutableMap.<String, String>builder() .put(config().get(DOCKER_SERVER_CERTIFICATE_PATH), "cert.pem") .put(config().get(DOCKER_SERVER_KEY_PATH), "key.pem") .put(config().get(DOCKER_CA_CERTIFICATE_PATH), "ca.pem").build(); } // Try and set the registry URL if configured and not starting local registry if (!config().get(DOCKER_SHOULD_START_REGISTRY)) { ConfigToAttributes.apply(this, DOCKER_IMAGE_REGISTRY_URL); } try { String caCertPath = config().get(DOCKER_CA_CERTIFICATE_PATH); try (InputStream caCert = ResourceUtils.create().getResourceFromUrl(caCertPath)) { X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(caCert); KeyStore store = SecureKeys.newKeyStore(); store.setCertificateEntry("ca", certificate); X509TrustManager trustManager = SecureKeys.getTrustManager(certificate); // TODO incorporate this trust manager into jclouds SSL context } } catch (IOException | KeyStoreException | CertificateException e) { Exceptions.propagate(e); } EntitySpec<?> dockerHostSpec = EntitySpec.create(config().get(DOCKER_HOST_SPEC)); dockerHostSpec.configure(DockerHost.DOCKER_INFRASTRUCTURE, this) .configure(DockerHost.RUNTIME_FILES, runtimeFiles) .configure(SoftwareProcess.CHILDREN_STARTABLE_MODE, ChildStartableMode.BACKGROUND_LATE); String dockerVersion = config().get(DOCKER_VERSION); if (Strings.isNonBlank(dockerVersion)) { dockerHostSpec.configure(SoftwareProcess.SUGGESTED_VERSION, dockerVersion); } if (Boolean.TRUE.equals(config().get(SdnAttributes.SDN_DEBUG))) { dockerHostSpec.configure(DockerAttributes.DOCKERFILE_URL, DockerUtils.UBUNTU_NETWORKING_DOCKERFILE); } sensors().set(DOCKER_HOST_SPEC, dockerHostSpec); DynamicCluster hosts = addChild( EntitySpec.create(DynamicCluster.class).configure(Cluster.INITIAL_SIZE, initialSize) .configure(DynamicCluster.QUARANTINE_FAILED_ENTITIES, true) .configure(DynamicCluster.MEMBER_SPEC, dockerHostSpec) .configure(DynamicCluster.RUNNING_QUORUM_CHECK, QuorumChecks.atLeastOneUnlessEmpty()) .configure(DynamicCluster.UP_QUORUM_CHECK, QuorumChecks.atLeastOneUnlessEmpty()) .configure(BrooklynCampConstants.PLAN_ID, "docker-hosts").displayName("Docker Hosts")); EntitySpec<?> etcdNodeSpec = EntitySpec.create(config().get(EtcdCluster.ETCD_NODE_SPEC)); String etcdVersion = config().get(ETCD_VERSION); if (Strings.isNonBlank(etcdVersion)) { etcdNodeSpec.configure(SoftwareProcess.SUGGESTED_VERSION, etcdVersion); } sensors().set(EtcdCluster.ETCD_NODE_SPEC, etcdNodeSpec); EtcdCluster etcd = addChild(EntitySpec.create(EtcdCluster.class).configure(Cluster.INITIAL_SIZE, 0) .configure(EtcdCluster.ETCD_NODE_SPEC, etcdNodeSpec).configure(EtcdCluster.CLUSTER_NAME, "docker") .configure(EtcdCluster.CLUSTER_TOKEN, "etcd-docker") .configure(DynamicCluster.QUARANTINE_FAILED_ENTITIES, true) .configure(DynamicCluster.RUNNING_QUORUM_CHECK, QuorumChecks.atLeastOneUnlessEmpty()) .configure(DynamicCluster.UP_QUORUM_CHECK, QuorumChecks.atLeastOneUnlessEmpty()) .displayName("Etcd Cluster")); sensors().set(ETCD_CLUSTER, etcd); DynamicGroup fabric = addChild(EntitySpec.create(DynamicGroup.class) .configure(DynamicGroup.ENTITY_FILTER, Predicates.and(Predicates.instanceOf(DockerContainer.class), EntityPredicates.attributeEqualTo(DockerContainer.DOCKER_INFRASTRUCTURE, this))) .displayName("All Docker Containers")); if (config().get(SDN_ENABLE) && config().get(SDN_PROVIDER_SPEC) != null) { EntitySpec entitySpec = EntitySpec.create(config().get(SDN_PROVIDER_SPEC)); entitySpec.configure(DockerAttributes.DOCKER_INFRASTRUCTURE, this); Entity sdn = addChild(entitySpec); sensors().set(SDN_PROVIDER, sdn); } sensors().set(DOCKER_HOST_CLUSTER, hosts); sensors().set(DOCKER_CONTAINER_FABRIC, fabric); hosts.enrichers().add(Enrichers.builder().aggregating(DockerHost.CPU_USAGE).computingAverage().fromMembers() .publishing(MachineAttributes.AVERAGE_CPU_USAGE).valueToReportIfNoSensors(0d).build()); hosts.enrichers().add(Enrichers.builder().aggregating(DOCKER_CONTAINER_COUNT).computingSum().fromMembers() .publishing(DOCKER_CONTAINER_COUNT).build()); enrichers().add(Enrichers.builder().propagating(DOCKER_CONTAINER_COUNT, MachineAttributes.AVERAGE_CPU_USAGE) .from(hosts).build()); enrichers().add(Enrichers.builder() .propagating(ImmutableMap.of(DynamicCluster.GROUP_SIZE, DOCKER_HOST_COUNT)).from(hosts).build()); Integer headroom = config().get(ContainerHeadroomEnricher.CONTAINER_HEADROOM); Double headroomPercent = config().get(ContainerHeadroomEnricher.CONTAINER_HEADROOM_PERCENTAGE); if ((headroom != null && headroom > 0) || (headroomPercent != null && headroomPercent > 0d)) { enrichers().add(EnricherSpec.create(ContainerHeadroomEnricher.class) .configure(ContainerHeadroomEnricher.CONTAINER_HEADROOM, headroom) .configure(ContainerHeadroomEnricher.CONTAINER_HEADROOM_PERCENTAGE, headroomPercent)); hosts.enrichers() .add(Enrichers.builder() .propagating(ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_COLD, ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_HOT, ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_OK) .from(this).build()); hosts.policies() .add(PolicySpec.create(AutoScalerPolicy.class) .configure(AutoScalerPolicy.POOL_COLD_SENSOR, ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_COLD) .configure(AutoScalerPolicy.POOL_HOT_SENSOR, ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_HOT) .configure(AutoScalerPolicy.POOL_OK_SENSOR, ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_OK) .configure(AutoScalerPolicy.MIN_POOL_SIZE, initialSize) .configure(AutoScalerPolicy.RESIZE_UP_STABILIZATION_DELAY, Duration.THIRTY_SECONDS) .configure(AutoScalerPolicy.RESIZE_DOWN_STABILIZATION_DELAY, Duration.FIVE_MINUTES) .displayName("Headroom Auto Scaler")); } sensors().set(Attributes.MAIN_URI, URI.create("/clocker")); // Override the health-check: just interested in the docker infrastructure/SDN, rather than // the groups that show the apps. Entity sdn = sensors().get(SDN_PROVIDER); enrichers() .add(EnricherSpec.create(ComputeServiceIndicatorsFromChildrenAndMembers.class) .uniqueTag(ComputeServiceIndicatorsFromChildrenAndMembers.DEFAULT_UNIQUE_TAG) .configure(ComputeServiceIndicatorsFromChildrenAndMembers.FROM_CHILDREN, true) .configure(ComputeServiceIndicatorsFromChildrenAndMembers.ENTITY_FILTER, Predicates.or( Predicates.<Entity>equalTo(hosts), (sdn == null ? Predicates.<Entity>alwaysFalse() : Predicates.equalTo(sdn))))); }