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:io.github.jeddict.orm.generator.service.ClassGenerator.java

protected T initClassDef(String packageName, JavaClass javaClass) {
    ClassHelper classHelper = new ClassHelper(javaClass.getClazz());
    classHelper.setPackageName(packageName);
    classDef.setClassName(classHelper.getFQClassName());
    classDef.setAbstractClass(javaClass.getAbstract());
    classDef.setTypeParameters(javaClass.getRuntimeTypeParameters());

    if (!(javaClass instanceof DefaultClass)) { // custom interface support skiped for IdClass/EmbeddedId
        Set<ReferenceClass> interfaces = new LinkedHashSet<>(javaClass.getRootElement().getInterfaces());
        interfaces.addAll(javaClass.getInterfaces());
        interfaces.addAll(javaClass.getRuntimeInterfaces());
        classDef.setInterfaces(interfaces.stream().filter(ReferenceClass::isEnable).map(ReferenceClass::getName)
                .collect(toList()));/*from  w w  w  .ja v a2s.c  om*/
    }

    classDef.setJSONBSnippets(getJSONBClassSnippet(javaClass));
    classDef.setAnnotation(getAnnotationSnippet(javaClass.getAnnotation()));
    classDef.getAnnotation().putAll(getAnnotationSnippet(javaClass.getRuntimeAnnotation()));

    Set<ClassSnippet> snippets = new LinkedHashSet<>(javaClass.getRootElement().getSnippets());
    snippets.addAll(javaClass.getSnippets());
    snippets.addAll(javaClass.getRuntimeSnippets());

    VetoPropertyRuntimeSnippet vetoPropertySnippet = new VetoPropertyRuntimeSnippet();
    snippets.addAll(vetoPropertySnippet.getClassSnippet(classDef.isPropertyChangeSupport(),
            classDef.isVetoableChangeSupport()));

    classDef.setCustomSnippet(buildCustomSnippet(snippets));

    classDef.setVariableDefs(new ArrayList<>(variables.values()));

    classDef.setConstructors(getConstructorSnippets(javaClass));
    classDef.setHashcodeMethod(
            getHashcodeMethodSnippet(javaClass, getClassMembers(javaClass, javaClass.getHashCodeMethod())));
    classDef.setEqualsMethod(
            getEqualsMethodSnippet(javaClass, getClassMembers(javaClass, javaClass.getEqualsMethod())));
    classDef.setToStringMethod(
            getToStringMethodSnippet(javaClass, getClassMembers(javaClass, javaClass.getToStringMethod())));

    if (javaClass.getSuperclass() != null) {
        classDef.setSuperClassName(javaClass.getSuperclass().getFQN());
    } else if (javaClass.getSuperclassRef() != null) {
        classDef.setSuperClassName(javaClass.getSuperclassRef().getName());
    } else if (javaClass.getRuntimeSuperclassRef() != null) {
        classDef.setSuperClassName(javaClass.getRuntimeSuperclassRef().getName());
    }
    return classDef;
}

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

@Transactional
public Set<DeviceClassEquipmentVO> createEquipment(@NotNull Long classId,
        @NotNull Set<DeviceClassEquipmentVO> equipments) {
    DeviceClassWithEquipmentVO deviceClass = deviceClassDao.find(classId);
    Set<String> existingCodesSet = deviceClass.getEquipment().stream().map(DeviceClassEquipmentVO::getCode)
            .collect(Collectors.toSet());
    Set<String> newCodeSet = equipments.stream().map(DeviceClassEquipmentVO::getCode)
            .collect(Collectors.toSet());

    newCodeSet.retainAll(existingCodesSet);
    if (!newCodeSet.isEmpty()) {
        String codeSet = StringUtils.join(newCodeSet, ",");
        throw new HiveException(String.format(Messages.DUPLICATE_EQUIPMENT_ENTRY, codeSet, classId),
                FORBIDDEN.getStatusCode());
    }//from www .  j  av  a  2  s.  com

    deviceClass.getEquipment().addAll(equipments);

    deviceClass = deviceClassDao.merge(deviceClass);

    //TODO [rafa] duuumb, and lazy, in case of several equipments linked to the class two for loops is fine.
    for (DeviceClassEquipmentVO equipment : equipments) {
        for (DeviceClassEquipmentVO s : deviceClass.getEquipment()) {
            if (equipment.getCode().equals(s.getCode())) {
                equipment.setId(s.getId());
            }
        }
    }

    return equipments;
}

From source file:com.flipkart.flux.client.runtime.LocalContext.java

/**
 * Checks if the given definition already exists as part of the current state machine.
 * Also, throws an <code>IllegalInvocationException</code> when it encounters that the given definition's
 * name is already used by another definition with a different type
 *//*from  w  ww  .ja  v  a 2 s . com*/
public EventDefinition checkExistingDefinition(final EventDefinition givenDefinition) {
    /* This may seem like an expensive operation, we can optimise if necessary */
    final StateMachineDefinition stateMachineDefinition = this.stateMachineDefinition.get();
    Set<EventDefinition> allDefinitions = new HashSet<>();
    stateMachineDefinition.getStates().stream()
            .map(new Function<StateDefinition, Collection<EventDefinition>>() {
                @Override
                public Collection<EventDefinition> apply(StateDefinition stateDefinition) {
                    return stateDefinition.getDependencies();
                }
            }).forEach(allDefinitions::addAll);
    final Optional<EventDefinition> searchResult = allDefinitions.stream()
            .filter(eventDefinition -> givenDefinition.getName().equals(eventDefinition.getName())).findFirst();
    if (!searchResult.isPresent()) {
        return null;
    }
    final EventDefinition eventDefinitionWithMatchingName = searchResult.get();
    if (eventDefinitionWithMatchingName.getType().equals(givenDefinition.getType())) {
        return eventDefinitionWithMatchingName;
    }
    throw new IllegalInvocationException("Cannot invoke two parameters with the same name & different types!");
}

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchAlerter.java

private synchronized void update() {
    final Set<TriggerKey> existingKeys = queryFutures.keySet();
    final Set<TriggerKey> activeKeys = activeTriggers.keySet();

    Set<TriggerKey> newKeys = new HashSet<>();
    Set<TriggerKey> canceledKeys = new HashSet<>();

    Set<TriggerKey> updatedKeys = new HashSet<>(activeKeys);
    updatedKeys.retainAll(activeKeys);// w  ww.ja  v a2  s.  co m

    activeKeys.stream().filter(key -> !existingKeys.contains(key)).forEach(key -> newKeys.add(key));
    existingKeys.stream().filter(key -> !activeKeys.contains(key)).forEach(key -> canceledKeys.add(key));

    log.debugf("newKeys %s", newKeys);
    log.debugf("updatedKeys %s", updatedKeys);
    log.debugf("canceledKeys %s", canceledKeys);

    canceledKeys.stream().forEach(key -> {
        ScheduledFuture canceled = queryFutures.remove(key);
        if (canceled != null) {
            canceled.cancel(false);
        }
    });
    updatedKeys.stream().forEach(key -> {
        ScheduledFuture updated = queryFutures.remove(key);
        if (updated != null) {
            updated.cancel(false);
        }
    });

    if (scheduledExecutor == null) {
        scheduledExecutor = new ScheduledThreadPoolExecutor(THREAD_POOL_SIZE);
    }

    newKeys.addAll(updatedKeys);

    for (TriggerKey key : newKeys) {
        Trigger t = activeTriggers.get(key);
        String interval = t.getContext().get(INTERVAL) == null ? INTERVAL_DEFAULT
                : t.getContext().get(INTERVAL);
        queryFutures.put(key,
                scheduledExecutor.scheduleAtFixedRate(new ElasticsearchQuery(t, defaultProperties, alerts), 0L,
                        getIntervalValue(interval), getIntervalUnit(interval)));

    }
}

From source file:io.subutai.plugin.appscale.impl.AppScaleImpl.java

@Override
public List<String> getClusterList(Environment name) {
    List<String> c = new ArrayList();
    Set<EnvironmentContainerHost> containerHosts = name.getContainerHosts();
    containerHosts.stream().forEach((ech) -> {
        c.add(ech.toString());/*from  w  w  w  . ja  v a  2s. co  m*/
    });
    return c;
}

From source file:it.smartcommunitylab.aac.controller.AppController.java

/**
 * Retrieve the with the user data: currently on the username is added.
 * @return/* w  w w.ja v  a  2s .com*/
 */
@RequestMapping("/dev")
public ModelAndView developer() {
    Map<String, Object> model = new HashMap<String, Object>();

    String username = userManager.getUserFullName();
    model.put("username", username);
    Set<String> userRoles = userManager.getUserRoles();
    model.put("roles", userRoles);
    model.put("contexts",
            userManager.getUser().getRoles().stream().filter(r -> r.getRole().equals(Config.R_PROVIDER))
                    .map(Role::canonicalSpace).collect(Collectors.toSet()));
    String check = ":" + Config.R_PROVIDER;
    model.put("apiProvider", userRoles.stream().anyMatch(s -> s.endsWith(check)));
    return new ModelAndView("index", model);
}

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 * Merge system and user defined configuration properties based on the replacement policy of each property
 * @param hopsworksParams System/default properties
 * @param userParameters User defined properties parsed by parseSparkProperties(String sparkProps)
 * @return A map with the replacement pattern and value for each property
 *///  w  w w  . j  a  v  a 2  s  .  co m
public static Map<String, String> mergeHopsworksAndUserParams(Map<String, ConfigProperty> hopsworksParams,
        Map<String, String> userParameters, boolean isJob) {
    Map<String, String> finalParams = new HashMap<>();
    Set<String> notReplacedUserParams = new HashSet<>();

    for (Map.Entry<String, String> userParam : userParameters.entrySet()) {
        if (hopsworksParams.containsKey(userParam.getKey())) {
            ConfigProperty prop = hopsworksParams.get(userParam.getKey());
            prop.replaceValue(userParam.getValue());
            finalParams.put(prop.getReplacementPattern(), prop.getValue());
        } else {
            notReplacedUserParams.add(userParam.getKey());
            if (isJob) {
                finalParams.put(userParam.getKey(), userParam.getValue());
            }
        }
    }

    String userParamsStr = "";
    if (!notReplacedUserParams.isEmpty()) {
        StringBuilder userParamsSb = new StringBuilder();
        userParamsSb.append(",\n");
        notReplacedUserParams.stream().forEach(p -> userParamsSb.append("\"").append(p).append("\": ")
                .append("\"").append(userParameters.get(p)).append("\"," + "\n"));

        userParamsStr = userParamsSb.toString();
        // Remove last comma and add a new line char
        userParamsStr = userParamsStr.trim().substring(0, userParamsStr.length() - 2) + "\n";
    }
    finalParams.put("spark_user_defined_properties", userParamsStr);

    for (ConfigProperty configProperty : hopsworksParams.values()) {
        finalParams.putIfAbsent(configProperty.getReplacementPattern(), configProperty.getValue());
    }

    return finalParams;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.UrlAssetImport.java

protected Set<FileOrRendition> extractFilesAndFolders(List<Map<String, CompositeVariant>> fileData) {
    Set<FileOrRendition> allFiles = fileData.stream().peek(this::extractFolder).map(this::extractFile)
            .filter(t -> t != null).collect(Collectors.toSet());

    // Remove renditions from the data set and file them with their original renditions
    Set<FileOrRendition> renditions = allFiles.stream().filter(FileOrRendition::isRendition)
            .collect(Collectors.toSet());
    allFiles.removeAll(renditions);/*from w ww  .  j a v  a  2  s . c  o  m*/
    renditions.forEach(r -> {
        Optional<FileOrRendition> asset = findOriginalRendition(allFiles, r);
        if (asset.isPresent()) {
            asset.get().addRendition(r);
        } else {
            unmatchedRenditions.add(r.getProperties());
        }
    });
    return allFiles;
}

From source file:com.nike.cerberus.service.SafeDepositBoxService.java

/**
 * Queries the data store for the specific safe deposit box by ID.  The query also enforces that the specified
 * safe deposit box has a linked permission via the user groups supplied in the call.
 *
 * @param groups Set of user groups that must have at least one matching permission for the specific safe
 *               deposit box//from  w  ww. j a va2 s  .c  o  m
 * @param id The unique identifier for the safe deposit box to lookup
 * @return The safe deposit box, if found
 */
public Optional<SafeDepositBox> getAssociatedSafeDepositBox(final Set<String> groups, final String id) {
    SafeDepositBox safeDepositBox = null;
    final Optional<SafeDepositBoxRecord> safeDepositBoxRecord = safeDepositBoxDao.getSafeDepositBox(id);

    if (safeDepositBoxRecord.isPresent()) {
        final Set<UserGroupPermission> userGroupPermissions = userGroupPermissionService
                .getUserGroupPermissions(id);

        final long count = userGroupPermissions.stream().filter(perm -> groups.contains(perm.getName()))
                .count();

        if (count == 0) {
            throw ApiException.newBuilder().withApiErrors(DefaultApiError.ACCESS_DENIED).build();
        }

        String owner = null;
        final Optional<String> possibleOwner = extractOwner(userGroupPermissions);

        if (!possibleOwner.isPresent()) {
            logger.error("Detected Safe Deposit Box without owner! ID={}", id);
        } else {
            owner = possibleOwner.get();
        }

        final Set<IamRolePermission> iamRolePermissions = iamRolePermissionService.getIamRolePermissions(id);

        safeDepositBox = new SafeDepositBox();
        safeDepositBox.setId(safeDepositBoxRecord.get().getId());
        safeDepositBox.setName(safeDepositBoxRecord.get().getName());
        safeDepositBox.setDescription(safeDepositBoxRecord.get().getDescription());
        safeDepositBox.setPath(safeDepositBoxRecord.get().getPath());
        safeDepositBox.setCategoryId(safeDepositBoxRecord.get().getCategoryId());
        safeDepositBox.setCreatedBy(safeDepositBoxRecord.get().getCreatedBy());
        safeDepositBox.setLastUpdatedBy(safeDepositBoxRecord.get().getLastUpdatedBy());
        safeDepositBox.setCreatedTs(safeDepositBoxRecord.get().getCreatedTs());
        safeDepositBox.setLastUpdatedTs(safeDepositBoxRecord.get().getLastUpdatedTs());
        safeDepositBox.setOwner(owner);
        safeDepositBox.setUserGroupPermissions(userGroupPermissions);
        safeDepositBox.setIamRolePermissions(iamRolePermissions);
    }

    return Optional.ofNullable(safeDepositBox);
}

From source file:cop.raml.processor.Parameter.java

/**
 * Set enum field for current parameter. Other fields will be automatically validated. In case of any error, {@link RamlProcessingException} will
 * be thrown/*from w w w .  j  a  v a 2  s .  com*/
 *
 * @param anEnum {@link Utils#SEMICOLON} separated enum constants string
 * @throws RamlProcessingException in case of any error (and {@link Config#ramlShowExample} is set to {@code true})
 */
public void setEnum(String anEnum) {
    String[] arr = StringUtils.isNotBlank(anEnum) ? Utils.COLON.split(anEnum) : ArrayUtils.EMPTY_STRING_ARRAY;
    Set<String> items = StringUtils.isNotBlank(anEnum) ? Utils.asSet(arr) : Collections.emptySet();
    String validEnum = Utils.toEnumStr(items);

    if (items.isEmpty())
        this.anEnum.clear();
    else {
        if (def != null && !items.contains(def))
            ProblemResolver.paramDefaultIsNotInEnum(def, validEnum);
        if (pattern != null && items.stream().filter(item -> !item.matches(pattern)).count() > 0)
            ProblemResolver.paramEnumConstantIsNotMatchPattern(validEnum, pattern);
        if (arr.length > items.size())
            ProblemResolver.paramEnumConstantDuplication(String.format("[%s]", anEnum));
        if (type != Type.STRING)
            ProblemResolver.paramEnumForNotStringType(type.id);
    }

    this.anEnum.clear();

    if (validEnum != null)
        this.anEnum.addAll(items);
}