private void filterNot(Properties properties, @Nullable List<String> exclusions) { if (exclusions == null) return; List<Predicate<CharSequence>> excludePredicates = Lists.transform( exclusions, new Function<String, Predicate<CharSequence>>() { @Override public Predicate<CharSequence> apply(String exclude) { return Predicates.containsPattern(exclude); } }); Predicate<CharSequence> shouldExclude = Predicates.alwaysFalse(); for (Predicate<CharSequence> predicate : excludePredicates) { shouldExclude = Predicates.or(shouldExclude, predicate); } for (String key : properties.stringPropertyNames()) { if (shouldExclude.apply(key)) { loggerBridge.debug("shouldExclude.apply(" + key + ") = " + shouldExclude.apply(key)); properties.remove(key); } } }
/** {@inheritDoc} */ @Override public void destroyLoadBalancer(final String id) { checkNotNull(id, "id"); logger.debug(">> destroying load balancer(%s)", id); final AtomicReference<LoadBalancerMetadata> loadBalancer = Atomics.newReference(); Predicate<String> tester = retry( new Predicate<String>() { public boolean apply(String input) { try { LoadBalancerMetadata md = destroyLoadBalancerStrategy.destroyLoadBalancer(id); if (md != null) loadBalancer.set(md); return true; } catch (IllegalStateException e) { logger.warn("<< illegal state destroying load balancer(%s)", id); return false; } } }, 3000, 1000, MILLISECONDS); // TODO make timeouts class like ComputeServiceconstants boolean successful = tester.apply(id) && loadBalancer.get() == null; // TODO add load // balancerTerminated // retryable predicate // (load balancer.get() == null || // load balancerTerminated.apply(load balancer.get())); logger.debug("<< destroyed load balancer(%s) success(%s)", id, successful); }
protected void scan(URL url) { Vfs.Dir dir = Vfs.fromURL(url); try { for (final Vfs.File file : dir.getFiles()) { // scan if inputs filter accepts file relative path or fqn Predicate<String> inputsFilter = configuration.getInputsFilter(); String path = file.getRelativePath(); String fqn = path.replace('/', '.'); if (inputsFilter == null || inputsFilter.apply(path) || inputsFilter.apply(fqn)) { Object classObject = null; for (Scanner scanner : configuration.getScanners()) { try { if (scanner.acceptsInput(path) || scanner.acceptResult(fqn)) { classObject = scanner.scan(file, classObject); } } catch (Exception e) { if (log != null && log.isDebugEnabled()) log.debug( "could not scan file " + file.getRelativePath() + " in url " + url.toExternalForm() + " with scanner " + scanner.getClass().getSimpleName(), e); } } } } } finally { dir.close(); } }
public Intent fromUri(URI uri) { uri = resolveUri(uri); Intent intent = new Intent("android.intent.action.VIEW", uri); Iterator iterator = conditionalComponentNameMap.keySet().iterator(); do { if (!iterator.hasNext()) { break; } Predicate predicate = (Predicate) iterator.next(); if (predicate.apply(uri)) { intent.setComponent((ComponentName) conditionalComponentNameMap.get(predicate)); } } while (true); iterator = conditionalPackageNameMap.keySet().iterator(); do { if (!iterator.hasNext()) { break; } Predicate predicate1 = (Predicate) iterator.next(); if (predicate1.apply(uri)) { intent.setPackage((String) conditionalPackageNameMap.get(predicate1)); } } while (true); return intent; }
@Test public void apply_returns_false_for_String_measure() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.FLOAT, 36.5d), FILE_COMPONENT); assertThat(underTest.apply(newMeasureBuilder().create("aaa"))).isFalse(); }
@Test public void apply_returns_false_for_LEVEL_measure() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.STRING, 36.5d), FILE_COMPONENT); assertThat(underTest.apply(newMeasureBuilder().create(Measure.Level.OK))).isFalse(); }
@Test public void apply_returns_false_if_measure_has_data_for_Boolean_Metric_and_best_value_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_TRUE, FILE_COMPONENT); assertThat(underTest.apply(newMeasureBuilder().create(true, SOME_DATA))).isFalse(); assertThat(underTest.apply(newMeasureBuilder().create(false, SOME_DATA))).isFalse(); }
@Test(enabled = true) public void testShellAccess() throws IOException { final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6); serversToDeleteAfterTheTests.add(nameOfServer); Set<Ip> availableIps = client.getIpServices().getUnassignedIpList(); Ip availableIp = Iterables.getLast(availableIps); Server createdServer = client .getServerServices() .addServer( nameOfServer, "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", "1", availableIp.getIp()); assertNotNull(createdServer); assert serverLatestJobCompleted.apply(createdServer); // get server by name Set<Server> response = client.getServerServices().getServersByName(nameOfServer); assert (response.size() == 1); createdServer = Iterables.getOnlyElement(response); Map<String, Credentials> credsMap = client.getServerServices().getServerCredentialsList(); LoginCredentials instanceCredentials = LoginCredentials.fromCredentials(credsMap.get(createdServer.getName())); assertNotNull(instanceCredentials); HostAndPort socket = HostAndPort.fromParts(createdServer.getIp().getIp(), 22); Predicate<HostAndPort> socketOpen = retry(new InetSocketAddressConnect(), 180, 5, SECONDS); socketOpen.apply(socket); SshClient sshClient = gocontext .utils() .injector() .getInstance(SshClient.Factory.class) .create(socket, instanceCredentials); sshClient.connect(); String output = sshClient.exec("df").getOutput(); assertTrue( output.contains("Filesystem"), "The output should've contained filesystem information, but it didn't. Output: " + output); sshClient.disconnect(); // check that the get credentials call is the same as this assertEquals( client.getServerServices().getServerCredentials(createdServer.getId()), instanceCredentials); try { assertEquals(client.getServerServices().getServerCredentials(Long.MAX_VALUE), null); } catch (AssertionError e) { e.printStackTrace(); } // delete the server client.getServerServices().deleteByName(nameOfServer); }
public static DescribeServicesResponseType describeService(final DescribeServicesType request) { final DescribeServicesResponseType reply = request.getReply(); Topology.touch(request); if (request.getServices().isEmpty()) { final ComponentId compId = (request.getByServiceType() != null) ? ComponentIds.lookup(request.getByServiceType().toLowerCase()) : Empyrean.INSTANCE; final boolean showEventStacks = Boolean.TRUE.equals(request.getShowEventStacks()); final boolean showEvents = Boolean.TRUE.equals(request.getShowEvents()) || showEventStacks; final Function<ServiceConfiguration, ServiceStatusType> transformToStatus = ServiceConfigurations.asServiceStatus(showEvents, showEventStacks); final List<Predicate<ServiceConfiguration>> filters = new ArrayList<Predicate<ServiceConfiguration>>() { { if (request.getByPartition() != null) { Partitions.exists(request.getByPartition()); this.add(Filters.partition(request.getByPartition())); } if (request.getByState() != null) { final Component.State stateFilter = Component.State.valueOf(request.getByState().toUpperCase()); this.add(Filters.state(stateFilter)); } if (!request.getServiceNames().isEmpty()) { this.add(Filters.name(request.getServiceNames())); } this.add(Filters.host(request.getByHost())); this.add( Filters.listAllOrInternal( request.getListAll(), request.getListUserServices(), request.getListInternal())); } }; final Predicate<Component> componentFilter = Filters.componentType(compId); final Predicate<ServiceConfiguration> configPredicate = Predicates.and(filters); List<ServiceConfiguration> replyConfigs = Lists.newArrayList(); for (final Component comp : Components.list()) { if (componentFilter.apply(comp)) { Collection<ServiceConfiguration> acceptedConfigs = Collections2.filter(comp.services(), configPredicate); replyConfigs.addAll(acceptedConfigs); } } ImmutableList<ServiceConfiguration> sortedReplyConfigs = ServiceOrderings.defaultOrdering().immutableSortedCopy(replyConfigs); final Collection<ServiceStatusType> transformedReplyConfigs = Collections2.transform(sortedReplyConfigs, transformToStatus); reply.getServiceStatuses().addAll(transformedReplyConfigs); } else { for (ServiceId s : request.getServices()) { reply.getServiceStatuses().add(TypeMappers.transform(s, ServiceStatusType.class)); } } return reply; }
@Test public void apply_returns_false_if_component_is_not_a_FILE_for_Boolean_Metric_and_best_value_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_TRUE, SOME_NON_FILE_COMPONENT); assertThat(underTest.apply(newMeasureBuilder().create(true))).isFalse(); assertThat(underTest.apply(newMeasureBuilder().create(false))).isFalse(); }
@Test public void test_filter() { Predicate<AstNode> predicate = mock(Predicate.class); assertThat((Object) select.filter(predicate)).isSameAs(AstSelectFactory.empty()); when(predicate.apply(node)).thenReturn(true); assertThat((Object) select.filter(predicate)).isSameAs(select); }
protected <STATE, STACKITEM> TraceItem<STATE, STACKITEM> traceToWithPruningStack( IPdaAdapter<STATE, STACKITEM> pda, Iterable<STATE> starts, Iterator<STACKITEM> stack, Predicate<STATE> matches, Predicate<STATE> canPass) { StackItem<STACKITEM> stackItem = createStack(stack); List<TraceItem<STATE, STACKITEM>> current = Lists.newArrayList(); Set<STATE> visited = Sets.newHashSet(starts); TraceItem<STATE, STACKITEM> result = null; for (STATE start : starts) { TraceItem<STATE, STACKITEM> item = new TraceItem<STATE, STACKITEM>(null, start, stackItem); // if (matches.apply(start)) // result = item; current.add(item); } int counter = stackItem.size() * -1; while (current.size() > 0 && counter < visited.size()) { List<TraceItem<STATE, STACKITEM>> newCurrent = Lists.newArrayList(); for (TraceItem<STATE, STACKITEM> trace : current) for (STATE follower : pda.getFollowers(trace.state)) { if (matches.apply(follower)) { TraceItem<STATE, STACKITEM> found = new TraceItem<STATE, STACKITEM>(trace, follower, trace.stackitem); if (found.stackitem == null) return found; if (result == null || result.stackitem.size() > found.stackitem.size()) { result = found; counter = result.stackitem.size() * -1; } else if (result.stackitem.size() == found.stackitem.size() && result.size() > found.size()) { result = found; counter = result.stackitem.size() * -1; } } if (canPass.apply(follower)) { STACKITEM push = pda.getPush(follower); visited.add(follower); if (push != null) { StackItem<STACKITEM> pushed = trace.stackitem.push(push); newCurrent.add(new TraceItem<STATE, STACKITEM>(trace, follower, pushed)); } else { STACKITEM pop = pda.getPop(follower); if (pop != null) { if (trace.stackitem != null && pop == trace.stackitem.peek()) { StackItem<STACKITEM> popped = trace.stackitem.pop(); newCurrent.add(new TraceItem<STATE, STACKITEM>(trace, follower, popped)); } } else newCurrent.add(new TraceItem<STATE, STACKITEM>(trace, follower, trace.stackitem)); } } } current = newCurrent; counter++; } return result; }
@Test public void testGetSensorPredicateNoWhitelist() { Object rootElement = Iterables.getOnlyElement(Yamls.parseAll(PLANS_YAML)); Predicate<String> predicate = BrooklynServiceInstanceBindingService.getSensorWhitelistPredicate(rootElement); assertNotNull(predicate); assertTrue(predicate.apply("foo.bar")); assertTrue(predicate.apply("bar.foo")); }
@Test public void testPredicteStringContains() { final Predicate<KomeaEvent> predicate = PredicateUtils.fromPredicateDto( new PredicateDto(PredicateType.STRING_CONTAINS, "eventString", "zert")); assertFalse(predicate.apply(newEvent("project_1", null, new DateTime().toDate(), 10))); assertFalse(predicate.apply(newEvent("project_1", "azety", new DateTime().toDate(), 10))); assertTrue(predicate.apply(newEvent("project_1", "azerty", new DateTime().toDate(), 10))); }
// Suggest at least 15 minutes for timeout public static String waitForPasswordOnAws( ComputeService computeService, final NodeMetadata node, long timeout, TimeUnit timeUnit) throws TimeoutException { ComputeServiceContext computeServiceContext = computeService.getContext(); AWSEC2Api ec2Client = computeServiceContext.unwrapApi(AWSEC2Api.class); final WindowsApi client = ec2Client.getWindowsApi().get(); final String region = node.getLocation().getParent().getId(); // The Administrator password will take some time before it is ready - Amazon says sometimes 15 // minutes. // So we create a predicate that tests if the password is ready, and wrap it in a retryable // predicate. Predicate<String> passwordReady = new Predicate<String>() { @Override public boolean apply(String s) { if (Strings.isNullOrEmpty(s)) return false; PasswordData data = client.getPasswordDataInRegion(region, s); if (data == null) return false; return !Strings.isNullOrEmpty(data.getPasswordData()); } }; LOG.info("Waiting for password, for " + node.getProviderId() + ":" + node.getId()); Predicate<String> passwordReadyRetryable = Predicates2.retry( passwordReady, timeUnit.toMillis(timeout), 10 * 1000, TimeUnit.MILLISECONDS); boolean ready = passwordReadyRetryable.apply(node.getProviderId()); if (!ready) throw new TimeoutException( "Password not available for " + node + " in region " + region + " after " + timeout + " " + timeUnit.name()); // Now pull together Amazon's encrypted password blob, and the private key that jclouds // generated PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey( client.getPasswordDataInRegion(region, node.getProviderId()), node.getCredentials().getPrivateKey()); // And apply it to the decryption function WindowsLoginCredentialsFromEncryptedData f = computeServiceContext .utils() .injector() .getInstance(WindowsLoginCredentialsFromEncryptedData.class); LoginCredentials credentials = f.apply(dataAndKey); return credentials.getPassword(); }
@Test(dependsOnMethods = "testCreateAndStartServer") public void testConnectivity() throws Exception { HostAndPort vncsocket = HostAndPort.fromParts(server.getVnc().getIp(), 5900); Logger.getAnonymousLogger().info("awaiting vnc: " + vncsocket); assert socketTester.apply(vncsocket) : server; HostAndPort sshsocket = HostAndPort.fromParts(server.getNics().get(0).getDhcp(), 22); Logger.getAnonymousLogger().info("awaiting ssh: " + sshsocket); assert socketTester.apply(sshsocket) : server; doConnectViaSsh(server, getSshCredentials(server)); }
@Test public void apply_returns_false_if_measure_has_anything_else_than_value_for_Boolean_Metric_and_best_value_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_TRUE, FILE_COMPONENT); for (Measure.NewMeasureBuilder builder : builders_of_non_bestValueOptimized_measures()) { assertThat(underTest.apply(builder.create(true))).isFalse(); assertThat(underTest.apply(builder.create(false))).isFalse(); } }
@Test public void verify_value_comparison_for_int_metric() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.INT, 10), FILE_COMPONENT); assertThat(underTest.apply(newMeasureBuilder().create(10))).isTrue(); assertThat(underTest.apply(newMeasureBuilder().setVariations(SOME_EMPTY_VARIATIONS).create(10))) .isTrue(); assertThat(underTest.apply(newMeasureBuilder().create(11))).isFalse(); }
@Test public void apply_returns_true_for_value_false_for_Boolean_Metric_and_best_value_not_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_FALSE, FILE_COMPONENT); assertThat(underTest.apply(newMeasureBuilder().create(true))).isFalse(); assertThat(underTest.apply(newMeasureBuilder().create(false))).isTrue(); assertThat( underTest.apply(newMeasureBuilder().setVariations(SOME_EMPTY_VARIATIONS).create(false))) .isTrue(); }
/** * 根据条件过滤集合元素 * * @param source * @param conditions * @param <T> * @return 如果全部过滤完则返回null */ public static <T> T filterByOrConditions(Collection<T> source, Predicate<T>... conditions) { for (T s : source) { for (Predicate<T> condition : conditions) { if (condition.apply(s)) return s; } } return null; }
@Test public void testImageDensityFilter() { Set<Path> filesToRemove = Filters.filterByDensity(candidates, ImmutableSet.of(Density.MDPI), false); Predicate<Path> predicate = Filters.createImageDensityFilter(candidates, ImmutableSet.of(Density.MDPI), false); assertFalse(candidates.isEmpty()); for (Path candidate : candidates) { assertEquals(!filesToRemove.contains(candidate), predicate.apply(candidate)); } }
@GET @Produces(MediaType.APPLICATION_JSON) public Response getAllSlots(@Context UriInfo uriInfo) { Predicate<RemoteSlot> slotFilter = SlotFilterBuilder.build(uriInfo); List<SlotStatusRepresentation> representations = Lists.newArrayList(); for (RemoteSlot remoteSlot : coordinator.getAllSlots()) { if (slotFilter.apply(remoteSlot)) { representations.add(SlotStatusRepresentation.from(remoteSlot.status())); } } return Response.ok(representations).build(); }
private void verifyPlacementGroup(String region, String groupName) { assert availableTester.apply(new PlacementGroup(region, groupName, "cluster", State.PENDING)) : group; Set<PlacementGroup> oneResult = client.getPlacementGroupApi().get().describePlacementGroupsInRegion(region, groupName); assertNotNull(oneResult); assertEquals(oneResult.size(), 1); group = oneResult.iterator().next(); assertEquals(group.getName(), groupName); assertEquals(group.getStrategy(), "cluster"); assert availableTester.apply(group) : group; }
/** Tests server start, reboot and deletion. Also verifies IP services and job services. */ @Test(enabled = true) public void testServerLifecycle() { int serverCountBeforeTest = client.getServerServices().getServerList().size(); final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6); serversToDeleteAfterTheTests.add(nameOfServer); Set<Ip> availableIps = client.getIpServices().getUnassignedPublicIpList(); Ip availableIp = Iterables.getLast(availableIps); String ram = Iterables.get(client.getServerServices().getRamSizes(), 0).getName(); Server createdServer = client .getServerServices() .addServer( nameOfServer, "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, availableIp.getIp()); assertNotNull(createdServer); assert serverLatestJobCompleted.apply(createdServer); // get server by name Set<Server> response = client.getServerServices().getServersByName(nameOfServer); assert (response.size() == 1); // restart the server client.getServerServices().power(nameOfServer, PowerCommand.RESTART); Set<Job> jobs = client.getJobServices().getJobsForObjectName(nameOfServer); assert ("RestartVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName())); assert serverLatestJobCompleted.apply(createdServer); int serverCountAfterAddingOneServer = client.getServerServices().getServerList().size(); assert serverCountAfterAddingOneServer == serverCountBeforeTest + 1 : "There should be +1 increase in the number of servers since the test started"; // delete the server client.getServerServices().deleteByName(nameOfServer); jobs = client.getJobServices().getJobsForObjectName(nameOfServer); assert ("DeleteVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName())); assert serverLatestJobCompleted.apply(createdServer); int serverCountAfterDeletingTheServer = client.getServerServices().getServerList().size(); assert serverCountAfterDeletingTheServer == serverCountBeforeTest : "There should be the same # of servers as since the test started"; // make sure that IP is put back to "unassigned" assert client.getIpServices().getUnassignedIpList().contains(availableIp); }
@Override public boolean tree(@Nullable final NodeRef left, @Nullable final NodeRef right) { if (!treeNodeFilter.apply(left) || !treeNodeFilter.apply(right)) { return false; } if (left == null) { addEnv(right); return false; } else if (right == null) { addEnv(left); return false; } return true; }
private void assertHasEvent( Sensor<?> sensor, Predicate<Object> componentPredicate, Predicate<? super CharSequence> descriptionPredicate) { for (SensorEvent<FailureDescriptor> event : events) { if (event.getSensor().equals(sensor) && (componentPredicate == null || componentPredicate.apply(event.getValue().getComponent())) && (descriptionPredicate == null || descriptionPredicate.apply(event.getValue().getDescription()))) { return; } } fail("No matching " + sensor + " event found; events=" + events); }
/** * Verify that some non-looping paths from {@code a} to {@code b} pass through at least one node * where {@code nodePredicate} is true. */ private boolean checkSomePathsWithoutBackEdges(DiGraphNode<N, E> a, DiGraphNode<N, E> b) { if (nodePredicate.apply(a.getValue()) && (inclusive || (a != start && a != end))) { return true; } if (a == b) { return false; } for (DiGraphEdge<N, E> e : a.getOutEdges()) { // Once we visited that edge once, we no longer need to // re-visit it again. if (e.getAnnotation() == VISITED_EDGE) { continue; } e.setAnnotation(VISITED_EDGE); if (ignoreEdge(e)) { continue; } if (e.getAnnotation() == BACK_EDGE) { continue; } DiGraphNode<N, E> next = e.getDestination(); if (checkSomePathsWithoutBackEdges(next, b)) { return true; } } return false; }
@Test public void testHistoryRunningPredicateFalse() { ReportHistory history = createTestHistory(); // history not running sut = new HistoryReadyPredicate(history); assertFalse(sut.apply(status)); }
/** For each node, update the block stack and reference collection as appropriate. */ @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName() || n.isRest() || (n.isStringKey() && parent.isObjectPattern() && !n.hasChildren())) { Var v; if (n.getString().equals("arguments")) { v = t.getScope().getArgumentsVar(); } else { v = t.getScope().getVar(n.getString()); } if (v != null) { if (varFilter.apply(v)) { addReference(v, new Reference(n, t, peek(blockStack))); } if (v.getParentNode() != null && NodeUtil.isHoistedFunctionDeclaration(v.getParentNode()) && // If we're only traversing a narrow scope, do not try to climb outside. (narrowScope == null || narrowScope.getDepth() <= v.getScope().getDepth())) { outOfBandTraversal(v); } } } if (isBlockBoundary(n, parent)) { pop(blockStack); } }
private static <T> T lookupMBean( final Map<String, String> props, final Class<T> type, final Predicate<T> tester, final long timeout) { long until = System.currentTimeMillis() + timeout; do try { final T bean = Mbeans.lookup(jdbcJmxDomain, props, type); tester.apply(bean); return bean; } catch (UndeclaredThrowableException e) { if (Exceptions.isCausedBy(e, InstanceNotFoundException.class)) { if (System.currentTimeMillis() < until) { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e1) { Thread.interrupted(); break; } LOG.debug("Waiting for MBean " + type.getSimpleName() + "/" + props); continue; } throw new NoSuchElementException(type.getSimpleName() + " " + props.toString()); } else { throw Exceptions.toUndeclared(e); } } while (System.currentTimeMillis() < until); throw new NoSuchElementException(type.getSimpleName() + " " + props.toString()); }