List of usage examples for com.google.common.base Predicates and
public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second)
From source file:brooklyn.management.internal.LocalEntityManager.java
@Override public synchronized Collection<Entity> findEntitiesInApplication(Application application, Predicate<? super Entity> filter) { Predicate<Entity> predicate = Predicates.and(EntityPredicates.applicationIdEqualTo(application.getId()), filter);// www . jav a 2 s .c o m return ImmutableList.copyOf(Iterables.filter(entityProxiesById.values(), predicate)); }
From source file:alien4cloud.webconfiguration.RestDocumentationConfig.java
private Predicate<String> otherApiPredicate() { Predicate<String> notAlreadyTreated = Predicates.not(Predicates.or(predicates)); Predicate<String> isCurrentVersionApi = PathSelectors .regex("/rest/" + PREFIXED_CURRENT_API_VERSION + "/.*"); return Predicates.and(notAlreadyTreated, isCurrentVersionApi); }
From source file:org.apache.isis.core.unittestsupport.bidir.BidirectionalRelationshipContractTestAbstract.java
private void process(Parent p, Child c) { // mappedBy field final Set<Field> parentFields = ReflectionUtils.getAllFields(c.entityType, Predicates .and(ReflectionUtils.withName(p.mappedBy), ReflectUtils.withTypeAssignableFrom(p.entityType))); assertThat(c.entityType.getName() + ": could not locate '" + p.mappedBy + "' field, returning supertype of " + p.entityType.getSimpleName() + ", (as per @Persistent(mappedBy=...) in parent " + p.entityType.getSimpleName() + ")", parentFields.size(), is(1)); c.parentField = CollectUtils.firstIn(parentFields); // getter//from w w w . j a v a2s. co m String getterMethod = StringUtils.methodNamed("get", c.parentField); final Set<Method> getterMethods = ReflectionUtils.getAllMethods(c.entityType, Predicates.and(withConcreteMethodNamed(getterMethod), ReflectionUtils.withParametersCount(0), ReflectUtils.withReturnTypeAssignableFrom(p.entityType))); assertThat(p.descRel(c) + ": could not locate getter " + getterMethod + "() returning supertype of " + p.entityType.getSimpleName(), getterMethods.size(), is(1)); c.getMethod = CollectUtils.firstIn(getterMethods); // modify String modifyMethod = StringUtils.methodNamed("modify", c.parentField); final Set<Method> modifyMethods = ReflectionUtils.getAllMethods(c.entityType, Predicates.and(withConcreteMethodNamed(modifyMethod), ReflectionUtils.withParametersCount(1), ReflectUtils.withParametersAssignableFrom(p.entityType))); if (modifyMethods.size() != 1) { // just skip out.println("no modifyXxx() method in child"); return; } c.modifyMethod = CollectUtils.firstIn(modifyMethods); // clear String clearMethod = StringUtils.methodNamed("clear", c.parentField); final Set<Method> clearMethods = ReflectionUtils.getAllMethods(c.entityType, Predicates.and(withConcreteMethodNamed(clearMethod), ReflectionUtils.withParametersCount(0))); if (clearMethods.size() != 1) { // just skip out.println("no clearXxx() method in child"); return; } c.clearMethod = CollectUtils.firstIn(clearMethods); exercise(p, c); }
From source file:org.apache.brooklyn.core.management.internal.LocalEntityManager.java
@Override public Collection<Entity> findEntitiesInApplication(Application application, Predicate<? super Entity> filter) { Predicate<Entity> predicate = Predicates.and(EntityPredicates.applicationIdEqualTo(application.getId()), filter);// ww w. j a v a2s. c o m return ImmutableList.copyOf(Iterables.filter(entityProxiesById.values(), predicate)); }
From source file:org.apache.aurora.scheduler.preemptor.PendingTaskProcessor.java
private List<TaskGroupKey> fetchIdlePendingGroups(StoreProvider store) { Multiset<TaskGroupKey> taskGroupCounts = HashMultiset .create(FluentIterable.from(store.getTaskStore().fetchTasks(Query.statusScoped(PENDING))) .filter(Predicates.and(isIdleTask, Predicates.not(hasCachedSlot))) .transform(Functions.compose(ASSIGNED_TO_GROUP_KEY, IScheduledTask::getAssignedTask))); return getPreemptionSequence(taskGroupCounts, reservationBatchSize); }
From source file:com.twitter.aurora.scheduler.periodic.Preempter.java
/** * Creates a static filter that will identify tasks that may preempt the provided task. * A task may preempt another task if the following conditions hold true: * - The resources reserved for {@code preemptableTask} are sufficient to satisfy the task. * - The tasks are owned by the same user and the priority of {@code preemptableTask} is lower * OR {@code preemptableTask} is non-production and the compared task is production. * * @param preemptableTask Task to possibly preempt. * @return A filter that will compare the priorities and resources required by other tasks * with {@code preemptableTask}.//from ww w .j a v a 2s . c o m */ private Predicate<AssignedTask> preemptionFilter(AssignedTask preemptableTask) { Predicate<AssignedTask> preemptableIsProduction = preemptableTask.getTask().isProduction() ? Predicates.<AssignedTask>alwaysTrue() : Predicates.<AssignedTask>alwaysFalse(); Predicate<AssignedTask> priorityFilter = greaterPriorityFilter(GET_PRIORITY.apply(preemptableTask)); return Predicates.or(Predicates.and(Predicates.not(preemptableIsProduction), IS_PRODUCTION), Predicates.and(isOwnedBy(getRole(preemptableTask)), priorityFilter)); }
From source file:org.artifactory.schedule.TaskServiceImpl.java
public void canBeStarted(TaskBase task) { Class<? extends TaskCallback> callbackType = task.getType(); JobCommand jobCommand = callbackType.getAnnotation(JobCommand.class); if (jobCommand == null) { throw new IllegalArgumentException("Callback type " + callbackType.getName() + " does not have the " + JobCommand.class.getName() + " annotation!"); }/* www .j a v a 2 s . c o m*/ if (task.isManuallyActivated() && jobCommand.manualUser() == TaskUser.INVALID) { throw new IllegalStateException( "Cannot start task (" + task + ") manually!" + " Manual user not defined!"); } boolean hasKey = jobCommand.keyAttributes().length != 0; if (!jobCommand.singleton() && !hasKey) { return; } EnumMap<StopStrategy, Predicate<Task>> predicatePerStrategy = getPredicatePerStrategy(callbackType, task.getKeyValues()); // Should not count myself :) Predicate<Task> notMyself = getNotMySelfPredicate(); // Only impossible are blocker here Predicate<Task> impossibleFilter = predicatePerStrategy.get(StopStrategy.IMPOSSIBLE); if (impossibleFilter != null) { for (TaskBase activeTask : getActiveTasks(Predicates.and(notMyself, impossibleFilter))) { if (task.isManuallyActivated()) { if (activeTask.processActive()) { throw new IllegalStateException("Cannot start task (" + task + ") manually!" + " Task " + activeTask + " is active!"); } if (activeTask.isManuallyActivated() && !activeTask.wasCompleted()) { throw new IllegalStateException("Cannot start task (" + task + ") manually!" + " Another manual task " + activeTask + " exists and is not completed!"); } } else { // Starting impossible filter of same type means singleton or key based singleton match if (activeTask.getType().equals(callbackType)) { if (activeTask.isManuallyActivated()) { if (!activeTask.wasCompleted()) { throw new IllegalStateException("Cannot schedule task (" + task + ")!" + " Another manual task of same type and key " + activeTask + " exists and is not completed!"); } } else { throw new IllegalStateException( "Cannot schedule task (" + task + ")!" + " Another task of same type and key " + activeTask + " is already scheduled!"); } } } } } }
From source file:org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog.java
/** returns best version, as defined by {@link BrooklynCatalog#getCatalogItem(String, String)} */ private String getBestVersion(String symbolicName) { Iterable<CatalogItem<Object, Object>> versions = getCatalogItems( Predicates.and(CatalogPredicates.disabled(false), CatalogPredicates.symbolicName(Predicates.equalTo(symbolicName)))); Collection<CatalogItem<Object, Object>> orderedVersions = sortVersionsDesc(versions); if (!orderedVersions.isEmpty()) { return orderedVersions.iterator().next().getVersion(); } else {//from ww w . j av a 2 s . com return null; } }
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"); }// w ww. ja v a 2s .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))))); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.candidacy.CandidacyProcessDA.java
protected Collection<IndividualCandidacyProcess> getChildProcesses(final CandidacyProcess process, HttpServletRequest request) {//www .j a v a 2s . com HideCancelledCandidaciesBean hideCancelledCandidacies = getHideCancelledCandidaciesValue(request); Predicate<IndividualCandidacyProcess> predicate = Predicates.and(CAN_EXECUTE_ACTIVITY_PREDICATE, getChildProcessSelectionPredicate(process, request)); if (hideCancelledCandidacies.getValue()) { predicate = Predicates.and(IS_CANDIDACY_CANCELED_PREDICATE, predicate); } return Collections2.filter(process.getChildProcessesSet(), predicate); }