Example usage for java.util Optional filter

List of usage examples for java.util Optional filter

Introduction

In this page you can find the example usage for java.util Optional filter.

Prototype

public Optional<T> filter(Predicate<? super T> predicate) 

Source Link

Document

If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional .

Usage

From source file:org.cyclop.service.cassandra.intern.QueryServiceImpl.java

@Override
public boolean checkTableExists(CqlTable table) {
    Validate.notNull(table, "null CqlTable");

    StringBuilder cql = new StringBuilder("select columnfamily_name from system.schema_columnfamilies");
    cql.append(" where columnfamily_name='").append(table.partLc).append("' allow filtering");

    Optional<ResultSet> result = executeSilent(cql.toString());
    boolean tableExists = result.filter(r -> !r.isExhausted()).isPresent();
    return tableExists;
}

From source file:org.jbb.security.impl.password.DefaultPasswordService.java

@Override
@Transactional(readOnly = true)//from  w ww. ja va  2  s  . com
public boolean verifyFor(Long memberId, Password typedPassword) {
    Validate.notNull(memberId, MEMBER_NOT_NULL_MESSAGE);
    Validate.notNull(typedPassword, "Password cannot be null");

    Optional<PasswordEntity> currentPasswordEntity = passwordRepository.findTheNewestByMemberId(memberId);
    return currentPasswordEntity.filter(passwordEntity -> passwordEqualsMatcher.matches(typedPassword,
            passwordEntity.getPasswordValueObject())).isPresent();
}

From source file:org.jboss.errai.ui.rebind.TemplatedCodeDecorator.java

@Override
public void generateDecorator(final Decorable decorable, final FactoryController controller) {
    final MetaClass declaringClass = decorable.getDecorableDeclaringType();

    final Templated anno = (Templated) decorable.getAnnotation();
    final Class<?> templateProvider = anno.provider();
    final boolean customProvider = templateProvider != Templated.DEFAULT_PROVIDER.class;
    final Optional<String> styleSheetPath = getTemplateStyleSheetPath(declaringClass);
    final boolean explicitStyleSheetPresent = styleSheetPath
            .filter(path -> Thread.currentThread().getContextClassLoader().getResource(path) != null)
            .isPresent();//from   w  w  w.  ja v  a2s  .c  o m

    if (declaringClass.isAssignableTo(Composite.class)) {
        logger.warn(
                "The @Templated class, {}, extends Composite. This will not be supported in future versions.",
                declaringClass.getFullyQualifiedName());
    }
    if (styleSheetPath.isPresent() && !explicitStyleSheetPresent) {
        throw new GenerationException("@Templated class [" + declaringClass.getFullyQualifiedName()
                + "] declared a stylesheet [" + styleSheetPath + "] that could not be found.");
    }

    final List<Statement> initStmts = new ArrayList<>();

    generateTemplatedInitialization(decorable, controller, initStmts, customProvider);

    if (customProvider) {
        final Statement init = Stmt.invokeStatic(TemplateUtil.class, "provideTemplate", templateProvider,
                getTemplateUrl(declaringClass),
                Stmt.newObject(TemplateRenderingCallback.class).extend()
                        .publicOverridesMethod("renderTemplate", Parameter.of(String.class, "template", true))
                        .appendAll(initStmts).finish().finish());

        controller.addInitializationStatements(Collections.singletonList(init));
    } else {
        controller.addInitializationStatements(initStmts);
    }

    controller.addDestructionStatements(generateTemplateDestruction(decorable));
    controller.addInitializationStatementsToEnd(Collections.<Statement>singletonList(
            invokeStatic(StyleBindingsRegistry.class, "get").invoke("updateStyles", Refs.get("instance"))));
}

From source file:org.jboss.errai.ui.rebind.TemplatedCodeDecorator.java

/**
 * Generate the actual construction logic for our {@link Templated} component
 * @param styleSheet/*from  w  w  w.  j  a va  2s. com*/
 */
@SuppressWarnings("serial")
private void generateTemplatedInitialization(final Decorable decorable, final FactoryController controller,
        final List<Statement> initStmts, final boolean customProvider) {

    final Map<MetaClass, BuildMetaClass> constructed = getConstructedTemplateTypes(decorable);
    final MetaClass declaringClass = decorable.getDecorableDeclaringType();

    if (!constructed.containsKey(declaringClass)) {
        final String templateVarName = "templateFor" + decorable.getDecorableDeclaringType().getName();
        final Optional<String> resolvedStylesheetPath = getResolvedStyleSheetPath(
                getTemplateStyleSheetPath(declaringClass), declaringClass);
        final boolean lessStylesheet = resolvedStylesheetPath.filter(path -> path.endsWith(".less"))
                .isPresent();

        /*
         * Generate this component's ClientBundle resource if necessary
         */
        final boolean generateCssBundle = resolvedStylesheetPath.isPresent() && !lessStylesheet;
        if (!customProvider || generateCssBundle) {
            generateTemplateResourceInterface(decorable, declaringClass, customProvider,
                    resolvedStylesheetPath.filter(path -> path.endsWith(".css")));

            /*
             * Instantiate the ClientBundle Template resource
             */
            initStmts.add(declareVariable(constructed.get(declaringClass)).named(templateVarName)
                    .initializeWith(invokeStatic(GWT.class, "create", constructed.get(declaringClass))));

            if (generateCssBundle) {
                controller.addFactoryInitializationStatements(
                        singletonList(castTo(constructed.get(declaringClass),
                                invokeStatic(GWT.class, "create", constructed.get(declaringClass)))
                                        .invoke("getStyle").invoke("ensureInjected")));
            }
        }

        /*
         * Compile LESS stylesheet to CSS and generate StyleInjector code
         */
        if (resolvedStylesheetPath.isPresent() && lessStylesheet) {
            try {
                final URL lessURL = Thread.currentThread().getContextClassLoader()
                        .getResource(resolvedStylesheetPath.get());
                final HttpResource lessResource = new HttpResource(lessURL.toURI());
                final LessSource source = new LessSource(lessResource);
                final LessCompiler compiler = new LessCompiler();
                final String compiledCss = compiler.compile(source);

                controller.addFactoryInitializationStatements(
                        singletonList(invokeStatic(StyleInjector.class, "inject", loadLiteral(compiledCss))));
            } catch (URISyntaxException | IOException | LessException e) {
                throw new RuntimeException("Error while attempting to compile the LESS stylesheet ["
                        + resolvedStylesheetPath.get() + "].", e);
            }
        }

        /*
         * Get root Template Element
         */
        final String parentOfRootTemplateElementVarName = "parentElementForTemplateOf"
                + decorable.getDecorableDeclaringType().getName();
        initStmts.add(Stmt.declareVariable(Element.class).named(parentOfRootTemplateElementVarName)
                .initializeWith(Stmt.invokeStatic(TemplateUtil.class, "getRootTemplateParentElement",
                        (customProvider) ? Variable.get("template")
                                : Stmt.loadVariable(templateVarName).invoke("getContents").invoke("getText"),
                        getTemplateFileName(declaringClass), getTemplateFragmentName(declaringClass))));

        final Statement rootTemplateElement = Stmt.invokeStatic(TemplateUtil.class, "getRootTemplateElement",
                Stmt.loadVariable(parentOfRootTemplateElementVarName));

        /*
         * If i18n is enabled for this module, translate the root template element here
         */
        if (!customProvider) {
            translateTemplate(decorable, initStmts, rootTemplateElement);
        }

        /*
         * Get a reference to the actual Composite component being created
         */
        final Statement component = Refs.get("instance");

        /*
         * Get all of the data-field Elements from the Template
         */
        final String dataFieldElementsVarName = "dataFieldElements";
        initStmts.add(Stmt.declareVariable(dataFieldElementsVarName, new TypeLiteral<Map<String, Element>>() {
        }, Stmt.invokeStatic(TemplateUtil.class, "getDataFieldElements", rootTemplateElement)));

        final String dataFieldMetasVarName = "dataFieldMetas";
        initStmts.addAll(generateDataFieldMetas(dataFieldMetasVarName, decorable));

        /*
         * Attach Widget field children Elements to the Template DOM
         */
        final String fieldsMapVarName = "templateFieldsMap";

        /*
         * The Map<String, Widget> to store actual component field references.
         */
        initStmts.add(declareVariable(fieldsMapVarName, new TypeLiteral<Map<String, Widget>>() {
        }, newObject(new TypeLiteral<LinkedHashMap<String, Widget>>() {
        })));
        final Statement fieldsMap = Stmt.loadVariable(fieldsMapVarName);

        generateComponentCompositions(decorable, initStmts, component, rootTemplateElement,
                loadVariable(dataFieldElementsVarName), fieldsMap, loadVariable(dataFieldMetasVarName));

        generateEventHandlerMethodClasses(decorable, controller, initStmts, dataFieldElementsVarName,
                fieldsMap);
    }
}

From source file:org.silverpeas.core.admin.service.Admin.java

@Override
public String[] getUserManageableSpaceRootIds(String sUserId) throws AdminException {
    try {/*  w w w  .j  a  v a  2s  .  c  om*/
        // Get user manageable space ids from database
        List<String> groupIds = getAllGroupsOfUser(sUserId);
        Integer[] asManageableSpaceIds = userManager.getManageableSpaceIds(sUserId, groupIds);

        // retain only root spaces
        List<String> manageableRootSpaceIds = new ArrayList<>();
        for (Integer asManageableSpaceId : asManageableSpaceIds) {
            Optional<SpaceInstLight> space = treeCache.getSpaceInstLight(asManageableSpaceId);
            space.filter(SpaceInstLight::isRoot)
                    .ifPresent(s -> manageableRootSpaceIds.add(asManageableSpaceId.toString()));
        }
        return manageableRootSpaceIds.toArray(new String[0]);

    } catch (Exception e) {
        throw new AdminException(failureOnGetting("root spaces manageable by user", sUserId), e);
    }
}

From source file:org.silverpeas.core.admin.service.Admin.java

@Override
public List<ComponentInstLight> getComponentsWithParameter(String paramName, String paramValue) {
    try {//from  w  w  w  .  j  a v a  2s .c o m
        final Parameter param = new Parameter();
        param.setName(paramName);
        param.setValue(paramValue);
        final List<Integer> componentIds = componentManager.getComponentIds(param);
        final List<ComponentInstLight> components = new ArrayList<>();
        for (Integer id : componentIds) {
            ComponentInst component = getComponentInst(id, null);
            // check TreeCache to know if component is not removed neither into a removed space
            Optional<ComponentInstLight> componentLight = treeCache.getComponent(component.getId());
            componentLight.filter(c -> !c.isRemoved()).ifPresent(components::add);
        }
        return components;
    } catch (Exception e) {
        SilverLogger.getLogger(this).error(e);
        return Collections.emptyList();
    }
}

From source file:org.springframework.web.reactive.function.server.RequestPredicates.java

/**
 * Return a {@code RequestPredicate} that tests the request's query parameter of the given name
 * against the given predicate.//from   w ww .  j a  v  a2  s .  c  om
 * @param name the name of the query parameter to test against
 * @param predicate predicate to test against the query parameter value
 * @return a predicate that matches the given predicate against the query parameter of the given name
 * @see ServerRequest#queryParam(String)
 */
public static RequestPredicate queryParam(String name, Predicate<String> predicate) {
    return request -> {
        Optional<String> s = request.queryParam(name);
        return s.filter(predicate).isPresent();
    };
}

From source file:org.trellisldp.http.impl.HttpUtils.java

/**
 * Given a list of acceptable media types, get an RDF syntax.
 *
 * @param ioService the I/O service/*from  ww w.j  a  v a2  s  .  c  om*/
 * @param acceptableTypes the types from HTTP headers
 * @param mimeType an additional "default" mimeType to match
 * @return an RDFSyntax or null if there was an error
 */
public static Optional<RDFSyntax> getSyntax(final IOService ioService, final List<MediaType> acceptableTypes,
        final Optional<String> mimeType) {
    if (acceptableTypes.isEmpty()) {
        return mimeType.isPresent() ? empty() : of(TURTLE);
    }
    final Optional<MediaType> mt = mimeType.map(MediaType::valueOf);
    for (final MediaType type : acceptableTypes) {
        if (mt.filter(type::isCompatible).isPresent()) {
            return empty();
        }
        final Optional<RDFSyntax> syntax = ioService.supportedReadSyntaxes().stream()
                .filter(s -> MediaType.valueOf(s.mediaType()).isCompatible(type)).findFirst();
        if (syntax.isPresent()) {
            return syntax;
        }
    }
    LOGGER.debug("Valid syntax not found among {} or {}", acceptableTypes, mimeType);
    throw new NotAcceptableException();
}

From source file:org.trellisldp.http.impl.RdfUtils.java

/**
 * Given a list of acceptable media types, get an RDF syntax.
 * @param acceptableTypes the types from HTTP headers
 * @param mimeType an additional "default" mimeType to match
 * @return an RDFSyntax// www.j a  v  a  2s . c  o m
 */
public static Optional<RDFSyntax> getSyntax(final List<MediaType> acceptableTypes,
        final Optional<String> mimeType) {
    if (acceptableTypes.isEmpty()) {
        // TODO -- JDK9 refactor with Optional::or
        if (mimeType.isPresent()) {
            return empty();
        }
        return of(TURTLE);
    }
    final Optional<MediaType> mt = mimeType.map(MediaType::valueOf);
    for (final MediaType type : acceptableTypes) {
        if (mt.filter(type::isCompatible).isPresent()) {
            return empty();
        }
        final Optional<RDFSyntax> syntax = MEDIA_TYPES.stream().filter(type::isCompatible).findFirst()
                .map(MediaType::toString).flatMap(RDFSyntax::byMediaType);
        if (syntax.isPresent()) {
            return syntax;
        }
    }
    LOGGER.debug("Valid syntax not found among {} or {}", acceptableTypes, mimeType);
    throw new NotAcceptableException();
}

From source file:org.trellisldp.http.PartitionedLdpResource.java

/**
 * Perform a POST operation on a LDP Resource
 * @param req the request//  w  w w. j a  va2 s.c  o m
 * @param body the body
 * @return the response
 */
@POST
@Timed
public Response createResource(@BeanParam final LdpRequest req, final File body) {

    final String baseUrl = partitions.get(req.getPartition());
    final String path = req.getPartition() + req.getPath();
    final String identifier = "/"
            + ofNullable(req.getSlug()).orElseGet(resourceService.getIdentifierSupplier());

    final PostHandler postHandler = new PostHandler(req, identifier, body, resourceService, ioService,
            binaryService, baseUrl);

    // First check if this is a container
    final Optional<Resource> parent = resourceService.get(rdf.createIRI(TRELLIS_PREFIX + path));
    if (parent.isPresent()) {
        final Optional<IRI> ixModel = parent.map(Resource::getInteractionModel);
        if (ixModel.filter(type -> ldpResourceTypes(type).anyMatch(LDP.Container::equals)).isPresent()) {
            return resourceService.get(rdf.createIRI(TRELLIS_PREFIX + path + identifier), MAX)
                    .map(x -> status(CONFLICT)).orElseGet(postHandler::createResource).build();
        } else if (parent.filter(RdfUtils::isDeleted).isPresent()) {
            return status(GONE).build();
        }
        return status(METHOD_NOT_ALLOWED).build();
    }
    return status(NOT_FOUND).build();
}