Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:org.kaaproject.kaa.server.common.dao.service.EventClassServiceImpl.java

@Override
public List<EventClassDto> findEventClassesByFamilyIdVersionAndType(String ecfId, int version,
        EventClassType type) {//from  w w w .j  ava  2  s .c  o  m
    List<EventClassDto> eventClasses = new ArrayList<>();
    if (isValidSqlId(ecfId)) {
        LOG.debug("Find event classes by family id [{}] version [{}] and type [{}]", ecfId, version, type);
        EventClassFamily ecf = eventClassFamilyDao.findById(ecfId);
        Optional<EventClassFamilyVersion> ecfv = ecf.getSchemas().stream()
                .filter(s -> s.getVersion() == version).findFirst();

        if (type == null) {
            ecfv.ifPresent(e -> eventClasses.addAll(convertDtoList(e.getRecords())));
        } else {
            ecfv.ifPresent(e -> eventClasses.addAll(convertDtoList(
                    e.getRecords().stream().filter(ec -> ec.getType() == type).collect(Collectors.toList()))));
        }
    } else {
        throw new IncorrectParameterException("Incorrect event class family id: " + ecfId);
    }
    return eventClasses;
}

From source file:org.kie.workbench.common.dmn.backend.DMNMarshallerTest.java

@Test
public void test_function_java_WB_model() throws IOException {
    final DMNMarshaller m = getDMNMarshaller();

    @SuppressWarnings("unchecked")
    final Graph<?, Node<?, ?>> g = m.unmarshall(null, this.getClass().getResourceAsStream("/DROOLS-2372.dmn"));

    final Stream<Node<?, ?>> stream = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(g.nodes().iterator(), Spliterator.ORDERED), false);
    final Optional<Decision> wbDecision = stream.filter(n -> n.getContent() instanceof ViewImpl)
            .map(n -> (ViewImpl) n.getContent()).filter(n -> n.getDefinition() instanceof Decision)
            .map(n -> (Decision) n.getDefinition()).findFirst();

    wbDecision.ifPresent(d -> {
        assertTrue(d.getExpression() instanceof FunctionDefinition);
        final FunctionDefinition wbFunction = (FunctionDefinition) d.getExpression();

        //This is what the WB expects
        assertEquals(FunctionDefinition.Kind.JAVA, wbFunction.getKind());
    });/*  w w w  .j a va  2s.co m*/

    final DMNRuntime runtime = roundTripUnmarshalMarshalThenUnmarshalDMN(
            this.getClass().getResourceAsStream("/DROOLS-2372.dmn"));
    final DMNModel dmnModel = runtime.getModels().get(0);

    final BusinessKnowledgeModelNode bkmNode = dmnModel.getBusinessKnowledgeModels().iterator().next();
    final org.kie.dmn.model.api.FunctionDefinition dmnFunction = bkmNode.getBusinessKnowledModel()
            .getEncapsulatedLogic();
    assertEquals(FunctionKind.JAVA, dmnFunction.getKind());
}

From source file:org.kie.workbench.common.migration.cli.MigrationApp.java

private void validateTarget(Path target) {
    Optional<String> errorMessage = Optional.empty();
    try {//from   w  ww.  j  a  v  a  2  s.c o m
        File dirFile = target.toFile();
        if (!dirFile.exists()) {
            errorMessage = Optional.of(String.format("The target path does not exist: %s", target));
        } else if (!dirFile.isDirectory()) {
            errorMessage = Optional.of(String.format("The target path is not a directory: %s", target));
        }
    } catch (UnsupportedOperationException e) {
        errorMessage = Optional.of(String.format("The target path must be a file: %s", target));
    }

    errorMessage.ifPresent(msg -> {
        system.err().println(msg);
        system.exit(1);
    });
}

From source file:org.matonto.catalog.impl.SimpleCatalogManager.java

@Override
public PaginatedSearchResults<Record> findRecord(Resource catalogId, PaginatedSearchParams searchParams)
        throws MatOntoException {
    try (RepositoryConnection conn = repository.getConnection()) {
        Optional<Resource> typeParam = searchParams.getTypeFilter();
        Optional<String> searchTextParam = searchParams.getSearchText();

        // Get Total Count
        TupleQuery countQuery = conn.prepareTupleQuery(COUNT_RECORDS_QUERY);
        countQuery.setBinding(CATALOG_BINDING, catalogId);
        typeParam.ifPresent(resource -> countQuery.setBinding(TYPE_FILTER_BINDING, resource));
        searchTextParam.ifPresent(s -> countQuery.setBinding(SEARCH_BINDING, vf.createLiteral(s)));

        TupleQueryResult countResults = countQuery.evaluate();

        int totalCount;
        BindingSet countBindingSet;/*from w  w w  . ja v a 2s  .  c o m*/
        if (countResults.hasNext()
                && (countBindingSet = countResults.next()).getBindingNames().contains(RECORD_COUNT_BINDING)) {
            totalCount = Bindings.requiredLiteral(countBindingSet, RECORD_COUNT_BINDING).intValue();
            countResults.close();
        } else {
            countResults.close();
            conn.close();
            return SearchResults.emptyResults();
        }

        log.debug("Record count: " + totalCount);

        // Prepare Query
        int limit = searchParams.getLimit();
        int offset = searchParams.getOffset();

        if (offset > totalCount) {
            throw new MatOntoException("Offset exceeds total size");
        }

        String sortBinding;
        Resource sortByParam = searchParams.getSortBy();
        if (sortingOptions.get(sortByParam) != null) {
            sortBinding = sortingOptions.get(sortByParam);
        } else {
            log.warn("sortBy parameter must be in the allowed list. Sorting by modified date instead.");
            sortBinding = "modified";
        }

        String querySuffix;
        Optional<Boolean> ascendingParam = searchParams.getAscending();
        if (ascendingParam.isPresent() && ascendingParam.get()) {
            querySuffix = String.format("\nORDER BY ?%s\nLIMIT %d\nOFFSET %d", sortBinding, limit, offset);
        } else {
            querySuffix = String.format("\nORDER BY DESC(?%s)\nLIMIT %d\nOFFSET %d", sortBinding, limit,
                    offset);
        }

        String queryString = FIND_RECORDS_QUERY + querySuffix;
        TupleQuery query = conn.prepareTupleQuery(queryString);
        query.setBinding(CATALOG_BINDING, catalogId);
        typeParam.ifPresent(resource -> query.setBinding(TYPE_FILTER_BINDING, resource));
        searchTextParam.ifPresent(searchText -> query.setBinding(SEARCH_BINDING, vf.createLiteral(searchText)));

        log.debug("Query String:\n" + queryString);
        log.debug("Query Plan:\n" + query);

        // Get Results
        TupleQueryResult result = query.evaluate();

        List<Record> records = new ArrayList<>();
        BindingSet resultsBindingSet;
        while (result.hasNext()
                && (resultsBindingSet = result.next()).getBindingNames().contains(RECORD_BINDING)) {
            Resource resource = vf
                    .createIRI(Bindings.requiredResource(resultsBindingSet, RECORD_BINDING).stringValue());
            Record record = processRecordBindingSet(resultsBindingSet, resource);
            records.add(record);
        }

        result.close();
        conn.close();

        log.debug("Result set size: " + records.size());

        int pageNumber = (offset / limit) + 1;

        if (records.size() > 0) {
            return new SimpleSearchResults<>(records, totalCount, limit, pageNumber);
        } else {
            return SearchResults.emptyResults();
        }
    } catch (RepositoryException e) {
        throw new MatOntoException("Error in repository connection.", e);
    }
}

From source file:org.matonto.platform.config.impl.state.SimpleStateManager.java

@Override
public Map<Resource, Model> getStates(String username, String applicationId, Set<Resource> subjects)
        throws MatOntoException {
    User user = engineManager.retrieveUser(RdfEngine.COMPONENT_NAME, username)
            .orElseThrow(() -> new MatOntoException("User not found"));
    Optional<Application> app = applicationManager.getApplication(applicationId);
    Map<Resource, Model> states = new HashMap<>();
    try (RepositoryConnection conn = repository.getConnection()) {
        TupleQuery statesQuery = app.isPresent() ? conn.prepareTupleQuery(GET_APPLICATION_STATES_QUERY)
                : conn.prepareTupleQuery(GET_STATES_QUERY);
        app.ifPresent(application -> statesQuery.setBinding(APPLICATION_BINDING, application.getResource()));
        statesQuery.setBinding(USER_BINDING, user.getResource());
        TupleQueryResult results = statesQuery.evaluate();

        BindingSet bindings;/*from www  .j  a  v a 2s  .co  m*/
        while (results.hasNext() && (bindings = results.next()).getBindingNames().contains(STATE_ID_BINDING)) {
            Resource stateId = Bindings.requiredResource(bindings, STATE_ID_BINDING);
            bindings.getBinding(RESOURCES_BINDING).ifPresent(binding -> {
                Set<Resource> resources = Arrays
                        .stream(StringUtils.split(binding.getValue().stringValue(), ","))
                        .map(factory::createIRI).collect(Collectors.toSet());

                if (subjects.isEmpty() || resources.containsAll(subjects)) {
                    Model stateModel = modelFactory.createModel();
                    resources.forEach(
                            resource -> conn.getStatements(resource, null, null).forEach(stateModel::add));
                    states.put(stateId, stateModel);
                }
            });
        }
    }
    return states;
}

From source file:org.mskcc.shenkers.control.alignment.chain.ChainGFFAlignmentSource1.java

@Override
public List<LocalAlignment> getAlignment(GenomeSpan span1, GenomeSpan span2) {
    try {//w  ww.  j av  a 2 s  .c  o m

        logger.info("querying alignment file");
        CloseableTribbleIterator<ChainContext> itt = alignments.query(span1.getChr(), span1.getStart(),
                span1.getEnd());

        List<LocalAlignment> chainIntersections = new ArrayList<>();

        // find all overlapping chains
        logger.info("iterating alignments");
        while (itt.hasNext()) {
            ChainContext next = itt.next();
            logger.info("alignment from {}:{}-{} to {}:{}-{}", next.getChr(), next.getStart(), next.getEnd(),
                    next.getTargetChr(), next.getTargetStart(), next.getTargetEnd());
            // check for intersections with the displayed interval
            // retaining only those blocks that intersect
            Optional<LocalAlignment> alignedBlocks = getAlignedBlocks(next, span1);
            logger.info("aligned blocks? {}", alignedBlocks.isPresent());
            alignedBlocks.ifPresent(l -> chainIntersections.add(l));
        }

        return chainIntersections;
    } catch (IOException ex) {
        logger.error("error parsing alignment file", ex);
        throw new RuntimeException(ex);
    }
}

From source file:org.onosproject.store.ecmap.EventuallyConsistentMapImpl.java

private MapValue<V> removeInternal(K key, Optional<V> value, Optional<MapValue<V>> tombstone) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);/*from  www . j  a  va  2 s . c om*/
    checkNotNull(value, ERROR_NULL_VALUE);
    tombstone.ifPresent(v -> checkState(v.isTombstone()));

    counter.incrementCount();
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue<V>> previousValue = new AtomicReference<>();
    items.compute(key, (k, existing) -> {
        boolean valueMatches = true;
        if (value.isPresent() && existing != null && existing.isAlive()) {
            valueMatches = Objects.equals(value.get(), existing.get());
        }
        if (existing == null) {
            log.trace("ECMap Remove: Existing value for key {} is already null", k);
        }
        if (valueMatches) {
            if (existing == null) {
                updated.set(tombstone.isPresent());
            } else {
                updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing));
            }
        }
        if (updated.get()) {
            previousValue.set(existing);
            return tombstone.orElse(null);
        } else {
            return existing;
        }
    });
    if (updated.get()) {
        if (persistent) {
            if (tombstone.isPresent()) {
                persistentStore.update(key, tombstone.get());
            } else {
                persistentStore.remove(key);
            }
        }
    }
    return previousValue.get();
}

From source file:org.onosproject.store.primitives.impl.EventuallyConsistentMapImpl.java

private MapValue<V> removeInternal(K key, Optional<V> value, Optional<MapValue<V>> tombstone) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);/*from  ww w .j  av a  2s.c  o m*/
    checkNotNull(value, ERROR_NULL_VALUE);
    tombstone.ifPresent(v -> checkState(v.isTombstone()));

    counter.incrementCount();
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue<V>> previousValue = new AtomicReference<>();
    items.compute(key, (k, existing) -> {
        boolean valueMatches = true;
        if (value.isPresent() && existing != null && existing.isAlive()) {
            valueMatches = Objects.equals(value.get(), existing.get());
        }
        if (existing == null) {
            log.trace("ECMap Remove: Existing value for key {} is already null", k);
        }
        if (valueMatches) {
            if (existing == null) {
                updated.set(tombstone.isPresent());
            } else {
                updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing));
            }
        }
        if (updated.get()) {
            previousValue.set(existing);
            return tombstone.orElse(null);
        } else {
            return existing;
        }
    });
    return previousValue.get();
}

From source file:org.openhab.io.transport.modbus.internal.ModbusManagerImpl.java

private void invalidate(ModbusSlaveEndpoint endpoint, Optional<ModbusSlaveConnection> connection) {
    KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> pool = connectionPool;
    if (pool == null) {
        return;//from   w  w  w .  j  a va  2s  .  c o  m
    }
    long start = System.currentTimeMillis();
    connection.ifPresent(con -> {
        try {
            pool.invalidateObject(endpoint, con);
        } catch (Exception e) {
            logger.warn("Error invalidating connection in pool for endpoint {}. Error was: {} {}", endpoint,
                    e.getClass().getName(), e.getMessage(), e);
        }
    });
    logger.trace("invalidating connection for endpoint {} took {} ms", endpoint,
            System.currentTimeMillis() - start);
}

From source file:org.openhab.io.transport.modbus.internal.ModbusManagerImpl.java

private void returnConnection(ModbusSlaveEndpoint endpoint, Optional<ModbusSlaveConnection> connection) {
    KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> pool = connectionPool;
    if (pool == null) {
        return;//from   ww  w  . j a  v  a  2 s .  c o m
    }
    long start = System.currentTimeMillis();
    connection.ifPresent(con -> {
        try {
            pool.returnObject(endpoint, con);
            logger.trace("returned connection to pool for endpoint {}", endpoint);
        } catch (Exception e) {
            logger.warn("Error returning connection to pool for endpoint {}. Error was: {} {}", endpoint,
                    e.getClass().getName(), e.getMessage(), e);
        }
    });
    logger.trace("returning connection for endpoint {} took {} ms", endpoint,
            System.currentTimeMillis() - start);
}