Example usage for java.util.stream Collectors toMap

List of usage examples for java.util.stream Collectors toMap

Introduction

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

Prototype

public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper) 

Source Link

Document

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

Usage

From source file:com.epam.ta.reportportal.database.dao.ProjectRepositoryCustomImpl.java

@Override
public Map<String, ProjectRole> findProjectRoles(String login) {
    final Query q = Query.query(userExists(login));
    q.fields().include("users");
    return mongoTemplate.find(q, Project.class).stream()
            .collect(Collectors.toMap(Project::getName, p -> p.getUsers().get(login).getProjectRole()));
}

From source file:fi.helsinki.opintoni.service.portfolio.PortfolioService.java

public Map<String, String> getUserPortfolioPath(Long userId) {
    return portfolioRepository.findByUserId(userId).collect(
            Collectors.toMap(portfolio -> portfolio.portfolioRole.getRole(), portfolio -> portfolio.path));
}

From source file:io.helixservice.feature.configuration.cloudconfig.CloudConfigResourceLocator.java

private InputStream extractProperties(InputStream inputStream) throws IOException {
    YamlPropertiesLoader yamlPropertiesLoader = new YamlPropertiesLoader(inputStream);
    Map<String, Object> flattenedProperties = yamlPropertiesLoader.getFlattenedProperties();

    Map<String, Object> filteredProperties = flattenedProperties.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(PROPERTY_SOURCES_YAML_PREFIX))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    String yamlDocument = new Yaml().dumpAsMap(filteredProperties);

    return new ByteArrayInputStream(yamlDocument.getBytes());
}

From source file:io.knotx.knot.action.domain.FormEntity.java

private static Map<String, String> getSignalToUrlMapping(Document scriptDocument) {
    return scriptDocument.getElementsByAttributeStarting(FORM_SIGNAL_ATTR_PREFIX).stream()
            .flatMap(element -> element.attributes().asList().stream())
            .filter(allAttr -> allAttr.getKey().startsWith(FORM_SIGNAL_ATTR_PREFIX)).collect(Collectors.toMap(
                    e -> e.getKey().replace(FORM_SIGNAL_ATTR_PREFIX, StringUtils.EMPTY), Entry::getValue));
}

From source file:csv.sorting.PrepareWeatherData.java

private static Map<String, csv.model.Station> getStationMap(Path path) {
    try (Stream<csv.model.Station> stationStream = getStations(path)) {
        return stationStream.collect(Collectors.toMap(csv.model.Station::getWban, x -> x));
    }//from   w ww .  j a  va 2 s . c  om
}

From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBeanTest.java

public void testGetCreateXslExport() throws AccessDeniedException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    AdminUser user = new AdminUser();
    user.setRoles(/*from  w w  w  .  j av  a 2 s  .co m*/
            AdminRoleHome.findAll().stream().collect(Collectors.toMap(AdminRole::getKey, Function.identity())));
    Utils.registerAdminUserWithRigth(request, user, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);

    _instance.init(request, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);
    assertNotNull(_instance.getCreateXslExport(request));
}

From source file:com.leonarduk.finance.chart.PieChartFactory.java

@SuppressWarnings("unchecked")
public Map<String, Double> getValueMap() {
    return (Map<String, Double>) this.dataset.getKeys().stream()
            .collect(Collectors.toMap(key -> key, key -> (Double) this.dataset.getValue((String) key)));
}

From source file:org.obiba.mica.core.service.SchemaFormContentFileService.java

private Map<String, JSONArray> getPathFilesMap(DocumentContext context, Object json) {
    DocumentContext reader = new JsonContext(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES))
            .parse(json);//from  ww w .j ava 2s  .  c  om

    JSONArray paths = null;
    try {
        paths = context.read("$..obibaFiles");
    } catch (PathNotFoundException e) {
        return null;
    }

    return paths.stream()
            .collect(Collectors.toMap(Object::toString, p -> (JSONArray) reader.read(p.toString())));
}

From source file:ch.cyberduck.core.sds.SDSMissingFileKeysSchedulerFeature.java

@Override
protected List<UserFileKeySetRequest> operate(final PasswordCallback callback, final Path file)
        throws BackgroundException {
    final List<UserFileKeySetRequest> processed = new ArrayList<>();
    try {// w w w .j a v a 2s  . co  m
        // Requests a list of missing FileKeys that may be generated by the current user.
        // Clients should regularly request missing FileKeys to provide access to files for other users. The returned list is ordered by priority (Rescue Keys are returned first)
        if (!session.userAccount().isEncryptionEnabled()) {
            return processed;
        }
        final UserPrivateKey privateKey = new UserPrivateKey();
        final UserKeyPairContainer keyPairContainer = session.keyPair();
        privateKey.setPrivateKey(keyPairContainer.getPrivateKeyContainer().getPrivateKey());
        privateKey.setVersion(keyPairContainer.getPrivateKeyContainer().getVersion());
        final UserKeyPair userKeyPair = new UserKeyPair();
        userKeyPair.setUserPrivateKey(privateKey);
        final Credentials passphrase = new TripleCryptKeyPair().unlock(callback, session.getHost(),
                userKeyPair);
        final Long fileId = file != null
                ? Long.parseLong(
                        new SDSNodeIdProvider(session).getFileid(file, new DisabledListProgressListener()))
                : null;
        UserFileKeySetBatchRequest request;
        do {
            final MissingKeysResponse missingKeys = new NodesApi(session.getClient())
                    .missingFileKeys(StringUtils.EMPTY, null, null, null, fileId, null);
            final Map<Long, UserUserPublicKey> publicKeys = missingKeys.getUsers().stream()
                    .collect(Collectors.toMap(UserUserPublicKey::getId, Function.identity()));
            final Map<Long, FileFileKeys> files = missingKeys.getFiles().stream()
                    .collect(Collectors.toMap(FileFileKeys::getId, Function.identity()));
            request = new UserFileKeySetBatchRequest();
            for (UserIdFileIdItem item : missingKeys.getItems()) {
                final UserUserPublicKey publicKey = publicKeys.get(item.getUserId());
                final FileFileKeys fileKeys = files.get(item.getFileId());
                final UserFileKeySetRequest keySetRequest = new UserFileKeySetRequest().fileId(item.getFileId())
                        .userId(item.getUserId());
                processed.add(keySetRequest);
                final PlainFileKey plainFileKey = Crypto.decryptFileKey(
                        TripleCryptConverter.toCryptoEncryptedFileKey(fileKeys.getFileKeyContainer()),
                        privateKey, passphrase.getPassword());
                final EncryptedFileKey encryptFileKey = Crypto.encryptFileKey(plainFileKey,
                        TripleCryptConverter.toCryptoUserPublicKey(publicKey.getPublicKeyContainer()));
                keySetRequest.setFileKey(TripleCryptConverter.toSwaggerFileKey(encryptFileKey));
                if (log.isDebugEnabled()) {
                    log.debug(
                            String.format("Missing file key for file with id %d processed", item.getFileId()));
                }
                request.addItemsItem(keySetRequest);
            }
            if (!request.getItems().isEmpty()) {
                new NodesApi(session.getClient()).setUserFileKeys(StringUtils.EMPTY, request);
            }
        } while (!request.getItems().isEmpty());
    } catch (ApiException e) {
        throw new SDSExceptionMappingService().map(e);
    } catch (CryptoException e) {
        throw new CryptoExceptionMappingService().map(e);
    }
    return processed;
}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPlugin.java

private GoPluginApiResponse handleExecuteRequest(JsonObject requestBody) {
    final String image = requestBody.getJsonObject(CONFIG).getJsonObject(IMAGE).getString(VALUE);
    final String command = requestBody.getJsonObject(CONFIG).getJsonObject("COMMAND").getString(VALUE);
    final JsonString argumentsJson = requestBody.getJsonObject(CONFIG).getJsonObject("ARGUMENTS")
            .getJsonString(VALUE);/* ww  w .j  a v  a2 s  . co m*/
    final String[] arguments;
    if (argumentsJson != null) {
        arguments = argumentsJson.getString().split("\\r?\\n");
    } else {
        arguments = new String[0];
    }
    Map<String, String> envVars = requestBody.getJsonObject("context").getJsonObject("environmentVariables")
            .entrySet().stream()
            .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), ((JsonString) e.getValue()).getString()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    final String workingDir = requestBody.getJsonObject("context").getString("workingDirectory");
    final String pwd = Paths.get(System.getProperty("user.dir"), workingDir).toAbsolutePath().toString();

    final Map<String, Object> responseBody = new HashMap<>();
    try {
        final int exitCode = executeBuild(image, pwd, envVars, command, arguments);

        responseBody.put(MESSAGE,
                (new StringBuilder()).append("Command ")
                        .append(DockerUtils.getCommandString(command, arguments))
                        .append(" completed with status ").append(exitCode).toString());
        if (exitCode == 0) {
            responseBody.put(SUCCESS, Boolean.TRUE);
        } else {
            responseBody.put(SUCCESS, Boolean.FALSE);
        }
    } catch (DockerCleanupException dce) {
        responseBody.clear();
        responseBody.put(SUCCESS, Boolean.FALSE);
        if (dce.getNested() == null) {
            responseBody.put(MESSAGE, dce.getCause().getMessage());
        } else {
            responseBody.put(MESSAGE, dce.getNested().getMessage());
        }
    } catch (ImageNotFoundException infe) {
        responseBody.put(SUCCESS, Boolean.FALSE);
        responseBody.put(MESSAGE,
                (new StringBuilder()).append("Image '").append(image).append("' not found").toString());
    } catch (Exception e) {
        responseBody.clear();
        responseBody.put(SUCCESS, Boolean.FALSE);
        responseBody.put(MESSAGE, e.getMessage());
    }

    return DefaultGoPluginApiResponse.success(Json.createObjectBuilder(responseBody).build().toString());
}