Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

In this page you can find the example usage for java.util Set stream.

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:org.arrow.model.process.SubProcess.java

/**
 * Finishes the event sub process instance.
 *
 * @param execution the execution instance
 * @param service   the execution service instance
 * @return Future//from   w  w  w  . j av  a  2s  .c  o  m
 */
private Future<Iterable<EventMessage>> finishEventSubProcess(Execution execution, ExecutionService service) {

    super.finishNode(execution, service);
    execution.setState(State.SUCCESS);

    // notify threads if process is suspended
    // and sub process was triggered by event
    // **************************************
    final ProcessInstance pi = execution.getProcessInstance();
    service.fetchEntity(pi);

    if (isTriggeredByEvent() && pi.isSuspend()) {
        EventMessage msg1 = Messages.terminateToken(execution);
        EventMessage msg2 = Messages.forceEndEvent(execution);

        return FutureUtil.result(msg1, msg2);
    }
    service.saveEntity(execution);
    Set<Execution> executions = service.data().execution().findEndEventExecutionsInWaitState(pi.getId());

    // invoke the end event
    List<EventMessage> result = executions.stream().map(Messages::finishAndContinue)
            .collect(Collectors.toList());
    return FutureUtil.result(result);
}

From source file:ddf.catalog.metrics.CatalogMetrics.java

private boolean isFederated(QueryRequest queryRequest) {
    Set<String> sourceIds = queryRequest.getSourceIds();

    if (queryRequest.isEnterprise()) {
        return true;
    } else if (sourceIds == null) {
        return false;
    } else {/*  w  w  w. jav a  2s  . co m*/
        return (sourceIds.size() > 1)
                || (sourceIds.size() == 1 && sourceIds.stream().noneMatch(StringUtils::isEmpty)
                        && !sourceIds.contains(SystemInfo.getSiteName()));
    }
}

From source file:com.haulmont.cuba.core.sys.dbupdate.DbUpdaterEngine.java

protected boolean initializedByOwnScript(Set<String> executedScripts, String dirName) {
    boolean found = executedScripts.stream().anyMatch(s -> s.substring(s.lastIndexOf('/') + 1)
            .equalsIgnoreCase("01." + dirName.substring(3) + "-create-db.sql"));
    if (found)/*from   w w w.ja  v  a  2 s.c o m*/
        log.debug("Found executed '01." + dirName.substring(3) + "-create-db.sql' script");
    return found;
}

From source file:net.morimekta.idltool.cmd.RemoteStatus.java

/**
 * Show standard status for a remote.//from w  w w.j  ava 2  s .c  o  m
 *
 * @param first          If this is the first remote to print diffs.
 * @param sourceSha1sums The remote file to sha1sum map.
 * @param targetSha1sums The local file to sha1sum map.
 * @return If the next remote is the first to print diffs.
 */
private boolean showStatus(boolean first, @Nonnull String remoteName, @Nonnull File sourceDirectory,
        @Nonnull Map<String, String> sourceSha1sums, @Nonnull File targetDirectory,
        @Nonnull Map<String, String> targetSha1sums) throws IOException {
    Set<String> removedFiles = new TreeSet<>(targetSha1sums.keySet());
    removedFiles.removeAll(sourceSha1sums.keySet());

    Set<String> addedFiles = new TreeSet<>(sourceSha1sums.keySet());
    addedFiles.removeAll(targetSha1sums.keySet());

    Set<String> updatedFiles = new TreeSet<>(sourceSha1sums.keySet());
    updatedFiles.removeAll(addedFiles);

    updatedFiles = updatedFiles.stream().filter(f -> !targetSha1sums.get(f).equals(sourceSha1sums.get(f)))
            .collect(Collectors.toSet());

    Set<String> allFiles = new TreeSet<>();
    allFiles.addAll(removedFiles);
    allFiles.addAll(addedFiles);
    allFiles.addAll(updatedFiles);

    if (allFiles.size() == 0) {
        return first;
    }

    int longestName = allFiles.stream().mapToInt(String::length).max().orElse(0);
    int diffSeparatorLength = Math.max(72, longestName + 6 + remoteName.length());

    if (!first) {
        System.out.println();
    }
    System.out.println(String.format("%sUpdates on %s%s", Color.BOLD, remoteName, Color.CLEAR));
    for (String file : allFiles) {
        String paddedFile = StringUtils.rightPad(file, longestName);
        File sourceFile = new File(sourceDirectory, file);
        File targetFile = new File(targetDirectory, file);

        if (diff) {
            System.out.println();
            System.out.println(Color.DIM + Strings.times("#", diffSeparatorLength) + Color.CLEAR);
            paddedFile = remoteName + "/" + paddedFile;
        }

        if (removedFiles.contains(file)) {
            System.out.println(String.format("  %s%s%s (%sD%s)%s", Color.YELLOW, paddedFile, Color.CLEAR,
                    Color.RED, Color.CLEAR, getDiffStats(sourceFile, targetFile)));
        } else if (addedFiles.contains(file)) {
            System.out.println(String.format("  %s%s%s (%sA%s)%s", Color.YELLOW, paddedFile, Color.CLEAR,
                    Color.GREEN, Color.CLEAR, getDiffStats(sourceFile, targetFile)));
        } else {
            System.out.println(String.format("  %s%s%s    %s", Color.YELLOW, paddedFile, Color.CLEAR,
                    getDiffStats(sourceFile, targetFile)));
        }
        if (diff) {
            System.out.println(Color.DIM + Strings.times("-", diffSeparatorLength) + Color.CLEAR);
            printDiffLines(sourceFile, targetFile);
            System.out.println(Color.DIM + Strings.times("#", diffSeparatorLength) + Color.CLEAR);
        }
    }

    return false;
}

From source file:com.adeptj.runtime.core.RuntimeInitializer.java

/**
 * {@inheritDoc}/*from   ww w . j a  v  a  2s.  com*/
 */
@Override
public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    if (startupAwareClasses == null || startupAwareClasses.isEmpty()) {
        logger.error("No @HandlesTypes(StartupAware) on classpath!!");
        throw new IllegalStateException("No @HandlesTypes(StartupAware) on classpath!!");
    } else {
        ServletContextHolder.getInstance().setServletContext(context);
        startupAwareClasses.stream().sorted(new StartupAwareComparator()).forEach(startupAwareClass -> {
            logger.info("@HandlesTypes: [{}]", startupAwareClass);
            try {
                ((StartupAware) ConstructorUtils.invokeConstructor(startupAwareClass)).onStartup(context);
            } catch (Exception ex) { // NOSONAR
                logger.error("Exception while executing StartupAware#onStartup!!", ex);
                throw new InitializationException(ex.getMessage(), ex);
            }
        });
        context.addListener(FrameworkShutdownHandler.class);
    }
}

From source file:com.baidu.rigel.biplatform.ma.ds.service.impl.DataSourceServiceImpl.java

/**
 * ????idname???/*w  ww. j  a v a 2 s .  c om*/
 * 
 * @param idOrName
 * @return
 */
private String getDatasourceDefineNameByIdOrName(String productLine, String idOrName) {
    String dir = getDsFileStoreDir(productLine);
    String[] ds = null;
    try {
        ds = fileService.ls(dir);
    } catch (FileServiceException e1) {
        logger.debug(e1.getMessage(), e1);
    }
    if (ds == null || ds.length == 0) {
        String msg = "can not get ds define by id : " + idOrName;
        logger.error(msg);
        return null;
    }
    Set<String> tmp = new HashSet<String>();
    Collections.addAll(tmp, ds);
    Set<String> dict = new HashSet<String>();
    tmp.stream().forEach((String s) -> {
        dict.add(s.substring(0, s.indexOf("_")));
        dict.add(s.substring(s.indexOf("_") + 1));
    });
    if (!dict.contains(idOrName)) {
        return null;
    }

    String fileName = null;
    for (String dsFileName : ds) {
        if (dsFileName.contains(idOrName)) {
            fileName = dsFileName;
            break;
        }
    }
    return fileName;
}

From source file:com.epam.catgenome.manager.protein.ProteinSequenceManager.java

private Map<Variation, List<Gene>> findIntersections(final Track<Variation> variations,
        final Set<Gene> allCds) {
    Map<Variation, List<Gene>> intersections = new HashMap<>();
    for (Variation variation : variations.getBlocks()) {
        List<Gene> currIntersections = allCds.stream()
                .filter(geneFeature -> variation.getStartIndex() >= geneFeature.getStartIndex()
                        && variation.getStartIndex() <= geneFeature.getEndIndex())
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(currIntersections)) {
            intersections.put(variation, currIntersections);
        }/*  ww w  . j av a  2s  . com*/
    }
    return intersections;
}

From source file:com.devicehive.service.DeviceClassServiceTest.java

@Test
public void should_replace_equipment() {
    DeviceClassEquipmentVO initialEquipment = DeviceFixture.createEquipmentVO();
    final DeviceClassWithEquipmentVO deviceClass = DeviceFixture.createDCVO();
    deviceClass.setEquipment(Collections.singleton(initialEquipment));

    final DeviceClassWithEquipmentVO createdDC = deviceClassService.addDeviceClass(deviceClass);

    for (DeviceClassEquipmentVO deviceClassEquipmentVO : createdDC.getEquipment()) {
        if (deviceClassEquipmentVO.getCode().equals(initialEquipment.getCode())) {
            initialEquipment = deviceClassEquipmentVO;
        }//www .  ja  va  2  s .  c o  m
    }

    DeviceClassWithEquipmentVO existingDC = deviceClassService.getWithEquipment(createdDC.getId());
    Set<DeviceClassEquipmentVO> existingEquipmentSet = existingDC.getEquipment();
    assertNotNull(existingEquipmentSet);
    assertEquals(1, existingEquipmentSet.size());
    DeviceClassEquipmentVO existingEquipment = existingEquipmentSet.stream().findFirst().get();
    assertEquals(initialEquipment.getName(), existingEquipment.getName());
    assertEquals(initialEquipment.getId(), existingEquipment.getId());
    assertEquals(initialEquipment.getCode(), existingEquipment.getCode());

    DeviceClassEquipmentVO anotherEquipment = DeviceFixture.createEquipmentVO();

    DeviceClassUpdate dcu = new DeviceClassUpdate();
    HashSet<DeviceClassEquipmentVO> equipments = new HashSet<>();
    equipments.add(anotherEquipment);
    dcu.setEquipment(Optional.of(equipments));
    DeviceClassWithEquipmentVO update = deviceClassService.update(createdDC.getId(), dcu);

    existingDC = deviceClassService.getWithEquipment(createdDC.getId());
    existingEquipmentSet = existingDC.getEquipment();
    assertNotNull(existingEquipmentSet);
    assertEquals(1, existingEquipmentSet.size());

    for (DeviceClassEquipmentVO deviceClassEquipmentVO : update.getEquipment()) {
        if (deviceClassEquipmentVO.getCode().equals(anotherEquipment.getCode())) {
            anotherEquipment = deviceClassEquipmentVO;
            break;
        }
    }

    existingEquipment = existingEquipmentSet.stream().findFirst().get();
    assertEquals(anotherEquipment.getName(), existingEquipment.getName());
    assertEquals(anotherEquipment.getId(), existingEquipment.getId());
    assertEquals(anotherEquipment.getCode(), existingEquipment.getCode());
}

From source file:io.gravitee.management.service.impl.InstanceServiceImpl.java

@Override
public Collection<InstanceListItem> findInstances(boolean includeStopped) {
    Set<EventEntity> events;

    if (includeStopped) {
        events = eventService.findByType(instancesAllState);
    } else {/*  ww w . jav a 2 s  .co  m*/
        events = eventService.findByType(instancesRunningOnly);
    }

    Instant nowMinusXMinutes = Instant.now().minus(5, ChronoUnit.MINUTES);
    return events.stream().map(event -> {
        Map<String, String> props = event.getProperties();
        InstanceListItem instance = new InstanceListItem(props.get("id"));
        instance.setEvent(event.getId());
        instance.setLastHeartbeatAt(new Date(Long.parseLong(props.get("last_heartbeat_at"))));
        instance.setStartedAt(new Date(Long.parseLong(props.get("started_at"))));

        if (event.getPayload() != null) {
            try {
                InstanceInfo info = objectMapper.readValue(event.getPayload(), InstanceInfo.class);
                instance.setHostname(info.getHostname());
                instance.setIp(info.getIp());
                instance.setVersion(info.getVersion());
                instance.setTags(info.getTags());
                instance.setOperatingSystemName(info.getSystemProperties().get("os.name"));
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while getting instance informations from event payload", ioe);
            }
        }

        if (event.getType() == EventType.GATEWAY_STARTED) {
            instance.setState(InstanceState.STARTED);
            // If last heartbeat timestamp is < now - 5m, set as unknown state
            Instant lastHeartbeat = Instant.ofEpochMilli(instance.getLastHeartbeatAt().getTime());
            if (lastHeartbeat.isBefore(nowMinusXMinutes)) {
                instance.setState(InstanceState.UNKNOWN);
            }
        } else {
            instance.setState(InstanceState.STOPPED);
            instance.setStoppedAt(new Date(Long.parseLong(props.get("stopped_at"))));
        }

        return instance;
    }).collect(Collectors.toList());
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java

public static boolean removeFromSetProperty(Node node, String name, Object value, boolean weakRef) {
    try {/* w  ww . jav a  2 s  . com*/
        //            JcrVersionUtil.ensureCheckoutNode(node);

        if (node == null) {
            throw new IllegalArgumentException("Cannot remove a property from a null-node!");
        }
        if (name == null) {
            throw new IllegalArgumentException("Cannot remove a property without a provided name");
        }

        Set<Value> values = new HashSet<>();

        if (node.hasProperty(name)) {
            values = Arrays.stream(node.getProperty(name).getValues()).collect(Collectors.toSet());
        } else {
            values = new HashSet<>();
        }

        Value existingVal = createValue(node.getSession(), value,
                values.stream().anyMatch(v -> v.getType() == PropertyType.WEAKREFERENCE));
        boolean result = values.remove(existingVal);
        node.setProperty(name, (Value[]) values.stream().toArray(size -> new Value[size]));
        return result;
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to remove from set property: " + name + "->" + value, e);
    }
}