Search in sources :

Example 31 with Predicate

use of java.util.function.Predicate in project sling by apache.

the class ValidationServiceImplTest method testValidateResourceRecursively.

@Test()
public void testValidateResourceRecursively() throws Exception {
    modelBuilder.resourceProperty(propertyBuilder.build("field1"));
    final ValidationModel vm1 = modelBuilder.build("resourcetype1", "some source");
    modelBuilder = new ValidationModelBuilder();
    modelBuilder.resourceProperty(propertyBuilder.build("field2"));
    final ValidationModel vm2 = modelBuilder.build("resourcetype2", "some source");
    // set model retriever
    validationService.modelRetriever = new ValidationModelRetriever() {

        @Override
        @CheckForNull
        public ValidationModel getValidationModel(@Nonnull String resourceType, String resourcePath, boolean considerResourceSuperTypeModels) {
            if (resourceType.equals("resourcetype1")) {
                return vm1;
            } else if (resourceType.equals("resourcetype2")) {
                return vm2;
            } else {
                return null;
            }
        }
    };
    ResourceResolver rr = context.resourceResolver();
    // resource is lacking the required field (is invalid)
    Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", "resourcetype1", JcrConstants.NT_UNSTRUCTURED, true);
    // child1 is valid
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    properties.put("field2", "test");
    rr.create(testResource, "child1", properties);
    // child2 is invalid
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    rr.create(testResource, "child2", properties);
    // child3 has no model (but its resource type is ignored)
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype3");
    rr.create(testResource, "child3", properties);
    final Predicate<Resource> ignoreResourceType3Filter = new Predicate<Resource>() {

        @Override
        public boolean test(final Resource resource) {
            return !"resourcetype3".equals(resource.getResourceType());
        }
    };
    ValidationResult vr = validationService.validateResourceRecursively(testResource, true, ignoreResourceType3Filter, false);
    Assert.assertFalse("resource should have been considered invalid", vr.isValid());
    Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1"), new DefaultValidationFailure("child2", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field2")));
}
Also used : HashMap(java.util.HashMap) ValidationModelRetriever(org.apache.sling.validation.model.spi.ValidationModelRetriever) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Predicate(java.util.function.Predicate) ValidationModel(org.apache.sling.validation.model.ValidationModel) CheckForNull(javax.annotation.CheckForNull) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) Test(org.junit.Test)

Example 32 with Predicate

use of java.util.function.Predicate in project helios by spotify.

the class HostsResource method list.

/**
   * Returns the list of hostnames of known hosts/agents.
   * @return The list of hostnames.
   */
@GET
@Produces(APPLICATION_JSON)
@Timed
@ExceptionMetered
public List<String> list(@QueryParam("namePattern") final String namePattern, @QueryParam("selector") final List<String> hostSelectors) {
    List<String> hosts = model.listHosts();
    if (namePattern != null) {
        final Predicate<String> matchesPattern = Pattern.compile(namePattern).asPredicate();
        hosts = hosts.stream().filter(matchesPattern).collect(Collectors.toList());
    }
    if (!hostSelectors.isEmpty()) {
        // check that all supplied selectors are parseable/valid
        final List<HostSelector> selectors = hostSelectors.stream().map(selectorStr -> {
            final HostSelector parsed = HostSelector.parse(selectorStr);
            if (parsed == null) {
                throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid host selector: " + selectorStr).build());
            }
            return parsed;
        }).collect(Collectors.toList());
        final Map<String, Map<String, String>> hostsAndLabels = getLabels(hosts);
        final HostMatcher matcher = new HostMatcher(hostsAndLabels);
        hosts = matcher.getMatchingHosts(selectors);
    }
    return hosts;
}
Also used : Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) SetGoalResponse(com.spotify.helios.common.protocol.SetGoalResponse) HostRegisterResponse(com.spotify.helios.common.protocol.HostRegisterResponse) Valid(javax.validation.Valid) QueryParam(javax.ws.rs.QueryParam) Optional(com.google.common.base.Optional) JobUndeployResponse(com.spotify.helios.common.protocol.JobUndeployResponse) Map(java.util.Map) INVALID_ID(com.spotify.helios.common.protocol.JobUndeployResponse.Status.INVALID_ID) Deployment(com.spotify.helios.common.descriptors.Deployment) DefaultValue(javax.ws.rs.DefaultValue) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) HostStillInUseException(com.spotify.helios.master.HostStillInUseException) JobDeployResponse(com.spotify.helios.common.protocol.JobDeployResponse) DELETE(javax.ws.rs.DELETE) HostMatcher(com.spotify.helios.master.HostMatcher) Responses.notFound(com.spotify.helios.master.http.Responses.notFound) JobDoesNotExistException(com.spotify.helios.master.JobDoesNotExistException) FORBIDDEN(com.spotify.helios.common.protocol.JobUndeployResponse.Status.FORBIDDEN) Predicate(java.util.function.Predicate) JOB_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.JOB_NOT_FOUND) Collectors(java.util.stream.Collectors) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) JobPortAllocationConflictException(com.spotify.helios.master.JobPortAllocationConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) Responses.badRequest(com.spotify.helios.master.http.Responses.badRequest) Pattern(java.util.regex.Pattern) JobId(com.spotify.helios.common.descriptors.JobId) PathParam(javax.ws.rs.PathParam) HOST_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.HOST_NOT_FOUND) GET(javax.ws.rs.GET) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) OK(com.spotify.helios.common.protocol.JobUndeployResponse.Status.OK) PATCH(com.spotify.helios.master.http.PATCH) Function(java.util.function.Function) Responses.forbidden(com.spotify.helios.master.http.Responses.forbidden) HostSelector(com.spotify.helios.common.descriptors.HostSelector) EMPTY_TOKEN(com.spotify.helios.common.descriptors.Job.EMPTY_TOKEN) HostStatus(com.spotify.helios.common.descriptors.HostStatus) HostNotFoundException(com.spotify.helios.master.HostNotFoundException) JobAlreadyDeployedException(com.spotify.helios.master.JobAlreadyDeployedException) MasterModel(com.spotify.helios.master.MasterModel) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) HostDeregisterResponse(com.spotify.helios.common.protocol.HostDeregisterResponse) Maps(com.google.common.collect.Maps) TokenVerificationException(com.spotify.helios.master.TokenVerificationException) PUT(javax.ws.rs.PUT) JobNotDeployedException(com.spotify.helios.master.JobNotDeployedException) WebApplicationException(javax.ws.rs.WebApplicationException) HostSelector(com.spotify.helios.common.descriptors.HostSelector) Map(java.util.Map) HostMatcher(com.spotify.helios.master.HostMatcher) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 33 with Predicate

use of java.util.function.Predicate in project ddf by codice.

the class SubjectUtilsTest method testFilterDNDropTwo.

@Test
public void testFilterDNDropTwo() {
    Predicate<RDN> predicate = rdn -> !ImmutableSet.of(BCStyle.C, BCStyle.ST).contains(rdn.getTypesAndValues()[0].getType());
    String baseDN = SubjectUtils.filterDN(dnPrincipal, predicate);
    assertThat(baseDN, is("CN=Foo,OU=Engineering,OU=Dev,O=DDF"));
}
Also used : X509Certificate(java.security.cert.X509Certificate) CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) X500Principal(javax.security.auth.x500.X500Principal) SortedSet(java.util.SortedSet) KeyStoreException(java.security.KeyStoreException) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) Assert.assertThat(org.junit.Assert.assertThat) Attribute(org.opensaml.saml.saml2.core.Attribute) ImmutableList(com.google.common.collect.ImmutableList) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Map(java.util.Map) Is.is(org.hamcrest.core.Is.is) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) XSString(org.opensaml.core.xml.schema.XSString) Mockito.doReturn(org.mockito.Mockito.doReturn) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) Before(org.junit.Before) SimpleSession(org.apache.shiro.session.mgt.SimpleSession) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Matchers.empty(org.hamcrest.Matchers.empty) ImmutableSet(com.google.common.collect.ImmutableSet) DefaultSecurityManager(org.apache.shiro.mgt.DefaultSecurityManager) RDN(org.bouncycastle.asn1.x500.RDN) ImmutableMap(com.google.common.collect.ImmutableMap) CoreMatchers.hasItems(org.hamcrest.CoreMatchers.hasItems) Predicate(java.util.function.Predicate) IOException(java.io.IOException) KeyStore(java.security.KeyStore) Test(org.junit.Test) CertificateException(java.security.cert.CertificateException) Collectors(java.util.stream.Collectors) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Principal(java.security.Principal) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) InputStream(java.io.InputStream) XSString(org.opensaml.core.xml.schema.XSString) RDN(org.bouncycastle.asn1.x500.RDN) Test(org.junit.Test)

Example 34 with Predicate

use of java.util.function.Predicate in project ddf by codice.

the class SubjectUtilsTest method testFilterDNRemoveAll.

@Test
public void testFilterDNRemoveAll() {
    Predicate<RDN> predicate = rdn -> !ImmutableSet.of(BCStyle.OU, BCStyle.CN, BCStyle.O, BCStyle.ST, BCStyle.C).contains(rdn.getTypesAndValues()[0].getType());
    String baseDN = SubjectUtils.filterDN(dnPrincipal, predicate);
    assertThat(baseDN, is(""));
}
Also used : X509Certificate(java.security.cert.X509Certificate) CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) X500Principal(javax.security.auth.x500.X500Principal) SortedSet(java.util.SortedSet) KeyStoreException(java.security.KeyStoreException) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) Assert.assertThat(org.junit.Assert.assertThat) Attribute(org.opensaml.saml.saml2.core.Attribute) ImmutableList(com.google.common.collect.ImmutableList) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Map(java.util.Map) Is.is(org.hamcrest.core.Is.is) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) XSString(org.opensaml.core.xml.schema.XSString) Mockito.doReturn(org.mockito.Mockito.doReturn) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) Before(org.junit.Before) SimpleSession(org.apache.shiro.session.mgt.SimpleSession) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Matchers.empty(org.hamcrest.Matchers.empty) ImmutableSet(com.google.common.collect.ImmutableSet) DefaultSecurityManager(org.apache.shiro.mgt.DefaultSecurityManager) RDN(org.bouncycastle.asn1.x500.RDN) ImmutableMap(com.google.common.collect.ImmutableMap) CoreMatchers.hasItems(org.hamcrest.CoreMatchers.hasItems) Predicate(java.util.function.Predicate) IOException(java.io.IOException) KeyStore(java.security.KeyStore) Test(org.junit.Test) CertificateException(java.security.cert.CertificateException) Collectors(java.util.stream.Collectors) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Principal(java.security.Principal) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) InputStream(java.io.InputStream) XSString(org.opensaml.core.xml.schema.XSString) RDN(org.bouncycastle.asn1.x500.RDN) Test(org.junit.Test)

Example 35 with Predicate

use of java.util.function.Predicate in project Gargoyle by callakrsos.

the class FilteredTreeItemExam method start.

@Override
public void start(Stage primaryStage) throws Exception {
    FilterableTreeItem<String> filterableTreeItem = new FilterableTreeItem<>("");
    filterableTreeItem.setExpanded(true);
    TreeView<String> treeView = new TreeView<>(filterableTreeItem);
    treeView.setShowRoot(false);
    treeView.setRoot(filterableTreeItem);
    BorderPane borderPane = new BorderPane(treeView);
    TextField value = new TextField();
    value.textProperty().addListener((oba, oldval, newval) -> {
        Callable<TreeItemPredicate<String>> func = () -> {
            Predicate<String> predicate = str -> str.indexOf(newval) >= 0;
            return TreeItemPredicate.<String>create(predicate);
        };
        ObjectBinding<TreeItemPredicate<String>> createObjectBinding = Bindings.createObjectBinding(func, hide);
        filterableTreeItem.predicateProperty().bind(createObjectBinding);
    });
    borderPane.setTop(value);
    Scene scene = new Scene(borderPane);
    primaryStage.setScene(scene);
    primaryStage.show();
    FilterableTreeItem<String> e = new FilterableTreeItem<>("ABC");
    //		e.getChildren().add(new FilterableTreeItem<>("DEF"));
    //		e.getChildren().add(new FilterableTreeItem<>("김aa"));
    //		e.getChildren().add(new FilterableTreeItem<>("김bb"));
    //		e.getChildren().add(new FilterableTreeItem<>("김cc"));
    //		filterableTreeItem.getChildren().add(e);
    //		filterableTreeItem.getChildren().add(new FilterableTreeItem<>("DEF"));
    //		filterableTreeItem.getChildren().add(new FilterableTreeItem<>("김DD"));
    //
    e.getSourceChildren().add(new FilterableTreeItem<>("DEF"));
    e.getSourceChildren().add(new FilterableTreeItem<>("김aa"));
    e.getSourceChildren().add(new FilterableTreeItem<>("김bb"));
    e.getSourceChildren().add(new FilterableTreeItem<>("김cc"));
    filterableTreeItem.getSourceChildren().add(e);
    filterableTreeItem.getSourceChildren().add(new FilterableTreeItem<>("DEF"));
    filterableTreeItem.getSourceChildren().add(new FilterableTreeItem<>("김DD"));
// filterableTreeItem.predicateProperty()
// .bind(Bindings.createObjectBinding(() ->
// TreeItemPredicate<String>.create(str -> str.indexOf("김") >= 0),
// hide));
}
Also used : BorderPane(javafx.scene.layout.BorderPane) FilterableTreeItem(com.kyj.fx.voeditor.visual.component.tree.FilterableTreeItem) Scene(javafx.scene.Scene) Predicate(java.util.function.Predicate) TreeItemPredicate(com.kyj.fx.voeditor.visual.component.tree.TreeItemPredicate) TreeItemPredicate(com.kyj.fx.voeditor.visual.component.tree.TreeItemPredicate) TreeView(javafx.scene.control.TreeView) TextField(javafx.scene.control.TextField)

Aggregations

Predicate (java.util.function.Predicate)120 List (java.util.List)49 Map (java.util.Map)34 Collectors (java.util.stream.Collectors)31 Test (org.junit.Test)30 IOException (java.io.IOException)28 ArrayList (java.util.ArrayList)26 Arrays (java.util.Arrays)25 Collections (java.util.Collections)23 Set (java.util.Set)15 Function (java.util.function.Function)14 Assert.assertEquals (org.junit.Assert.assertEquals)14 java.util (java.util)13 Optional (java.util.Optional)13 Supplier (java.util.function.Supplier)13 HashMap (java.util.HashMap)12 Before (org.junit.Before)12 Objects (java.util.Objects)11 InputStream (java.io.InputStream)10 AssertExtensions (io.pravega.test.common.AssertExtensions)9