Example usage for java.util.stream Collectors joining

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

Introduction

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

Prototype

public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) 

Source Link

Document

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

Usage

From source file:com.haulmont.cuba.web.widgets.CubaTimeField.java

protected void updateResolution() {
    this.timeFormat = getResolutionsHigherOrEqualTo(getResolution()).map(this::getResolutionFormat)
            .collect(Collectors.joining(":"));

    // By default, only visual representation is updated after the resolution is changed.
    // As a result, the actual value and the visual representation are different values.
    // Since we want to update the field value and fire value change event, we reset the value,
    // taking into account the fact that the  setValue(LocalTime, boolean) method applies current
    // resolution to value.
    if (getValue() != null) {
        setValue(getValue(), true);/*from   ww w.  j  a v  a 2s .  c o m*/
    }

    updateTimeFormat();
}

From source file:me.rkfg.xmpp.bot.plugins.CoolStoryPlugin.java

@Override
public String getManual() {
    return Stream.concat(Stream.of(HELP_AVAILABLE_COMMANDS), Arrays.stream(WEBSITES).map(Website::getHelp))
            .collect(Collectors.joining("\n"));
}

From source file:io.gravitee.management.idp.repository.authentication.RepositoryAuthenticationProvider.java

private UserDetails mapUserEntityToUserDetails(UserEntity userEntity) {
    List<GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;
    if (userEntity.getRoles() != null && userEntity.getRoles().size() > 0) {

        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
                userEntity.getRoles().stream().collect(Collectors.joining(",")));
    }/*  w ww  .  ja v  a2s  .c  o m*/
    return new User(userEntity.getUsername(), "unknown", authorities);
}

From source file:com.esri.geoportal.harvester.api.defs.EntityDefinition.java

@Override
public String toString() {
    return String.format("%s[%s]", type,
            properties.entrySet().stream()
                    .map(e -> String.format("%s=%s", e.getKey(),
                            P_CRED_PASSWORD.equals(e.getKey()) ? "*****" : e.getValue()))
                    .collect(Collectors.joining(", ")));
}

From source file:com.epam.catgenome.manager.vcf.VcfFileManager.java

/**
 * Delete vcf file metadata from database and corresponding vcf samples.
 *
 * @param vcfFile file to delete//from  ww  w  .  ja v a  2  s.  c o  m
 */
@Transactional(propagation = Propagation.REQUIRED)
public void deleteVcfFile(final VcfFile vcfFile) {
    Assert.notNull(vcfFile, MessagesConstants.ERROR_INVALID_PARAM);
    Assert.notNull(vcfFile.getId(), MessagesConstants.ERROR_INVALID_PARAM);

    List<Project> projectsWhereFileInUse = projectDao.loadProjectsByBioDataItemId(vcfFile.getBioDataItemId());
    Assert.isTrue(projectsWhereFileInUse.isEmpty(), MessageHelper.getMessage(
            MessagesConstants.ERROR_FILE_IN_USE, vcfFile.getName(), vcfFile.getId(),
            projectsWhereFileInUse.stream().map(BaseEntity::getName).collect(Collectors.joining(", "))));

    vcfFileDao.deleteVcfFile(vcfFile.getId());
    biologicalDataItemDao.deleteBiologicalDataItem(vcfFile.getIndex().getId());
    biologicalDataItemDao.deleteBiologicalDataItem(vcfFile.getBioDataItemId());
}

From source file:com.marand.thinkmed.medications.connector.impl.rest.RestMedicationsConnector.java

@Override
public Map<String, PatientDisplayWithLocationDto> getPatientDisplayWithLocationMap(
        final Collection<String> careProviderIds, final Collection<String> patientIds) {
    final String patientsListJson;
    if (patientIds != null) {
        if (patientIds.isEmpty()) {
            return Collections.emptyMap();
        }//from   w  w w .  j a va 2s.c o m
        final String patientIdsString = patientIds.stream().collect(Collectors.joining(","));
        patientsListJson = restClient.getPatientsSummariesList(patientIdsString);
    } else {
        Preconditions.checkArgument(careProviderIds != null, "Both patientIds and careProviderId are null");
        final String careProviderIdsString = careProviderIds.stream().collect(Collectors.joining(","));
        patientsListJson = restClient.getCareProvidersPatientsSummariesList(careProviderIdsString);
    }
    final List<PatientDisplayWithLocationDto> patientsList = Arrays
            .asList(JsonUtil.fromJson(patientsListJson, PatientDisplayWithLocationDto[].class));

    return patientsList.stream()
            .collect(Collectors.toMap(p -> p.getPatientDisplayDto().getId(), Function.identity()));
}

From source file:com.github.kaklakariada.aws.sam.PluginTest.java

private String readStream(InputStream input) {
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
        return buffer.lines().collect(Collectors.joining("\n"));
    } catch (final IOException e) {
        throw new AssertionError("Error reading input stream", e);
    }//from w  ww .  jav a  2s  .co  m
}

From source file:org.apache.nifi.minifi.c2.provider.nifi.rest.NiFiRestConfigurationProvider.java

@Override
public Configuration getConfiguration(String contentType, Integer version, Map<String, List<String>> parameters)
        throws ConfigurationProviderException {
    if (!CONTENT_TYPE.equals(contentType)) {
        throw new ConfigurationProviderException(
                "Unsupported content type: " + contentType + " supported value is " + CONTENT_TYPE);
    }//from w  w  w  .j  a  v  a2 s  . c om
    String filename = templateNamePattern;
    for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
        if (entry.getValue().size() != 1) {
            throw new InvalidParameterException(
                    "Multiple values for same parameter not supported in this provider.");
        }
        filename = filename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0));
    }
    int index = filename.indexOf("${");
    while (index != -1) {
        int endIndex = filename.indexOf("}", index);
        if (endIndex == -1) {
            break;
        }
        String variable = filename.substring(index + 2, endIndex);
        if (!"version".equals(variable)) {
            throw new InvalidParameterException("Found unsubstituted parameter " + variable);
        }
        index = endIndex + 1;
    }

    String id = null;
    if (version == null) {
        String filenamePattern = Arrays.stream(filename.split(Pattern.quote("${version}"), -1))
                .map(Pattern::quote).collect(Collectors.joining("([0-9+])"));
        Pair<String, Integer> maxIdAndVersion = getMaxIdAndVersion(filenamePattern);
        id = maxIdAndVersion.getFirst();
        version = maxIdAndVersion.getSecond();
    }
    filename = filename.replaceAll(Pattern.quote("${version}"), Integer.toString(version));
    WriteableConfiguration configuration = configurationCache.getCacheFileInfo(contentType, parameters)
            .getConfiguration(version);
    if (configuration.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Configuration " + configuration + " exists and can be served from configurationCache.");
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Configuration " + configuration
                    + " doesn't exist, will need to download and convert template.");
        }
        if (id == null) {
            try {
                String tmpFilename = templateNamePattern;
                for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
                    if (entry.getValue().size() != 1) {
                        throw new InvalidParameterException(
                                "Multiple values for same parameter not supported in this provider.");
                    }
                    tmpFilename = tmpFilename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"),
                            entry.getValue().get(0));
                }
                Pair<Stream<Pair<String, String>>, Closeable> streamCloseablePair = getIdAndFilenameStream();
                try {
                    String finalFilename = filename;
                    id = streamCloseablePair.getFirst().filter(p -> finalFilename.equals(p.getSecond()))
                            .map(Pair::getFirst).findFirst().orElseThrow(() -> new InvalidParameterException(
                                    "Unable to find template named " + finalFilename));
                } finally {
                    streamCloseablePair.getSecond().close();
                }
            } catch (IOException | TemplatesIteratorException e) {
                throw new ConfigurationProviderException("Unable to retrieve template list", e);
            }
        }

        HttpURLConnection urlConnection = httpConnector.get("/templates/" + id + "/download");

        try (InputStream inputStream = urlConnection.getInputStream()) {
            ConfigSchema configSchema = ConfigMain.transformTemplateToSchema(inputStream);
            SchemaSaver.saveConfigSchema(configSchema, configuration.getOutputStream());
        } catch (IOException e) {
            throw new ConfigurationProviderException(
                    "Unable to download template from url " + urlConnection.getURL(), e);
        } catch (JAXBException e) {
            throw new ConfigurationProviderException("Unable to convert template to yaml", e);
        } finally {
            urlConnection.disconnect();
        }
    }
    return configuration;
}

From source file:com.intuit.wasabi.tests.service.assignment.BatchAssignment.java

@Test(groups = { "batchAssign" }, dependsOnGroups = {
        "setup" }, dataProvider = "BatchAssignmentStateAndExpectedValues", dataProviderClass = AssignmentDataProvider.class)
public void t_batchAssign(String state, boolean isAssignment, String status) {
    clearAssignmentsMetadataCache();/*from w ww . jav a  2  s  .c  o  m*/

    String lables = "{\"labels\": ["
            + experimentLabels.stream().map(s -> "\"" + s + "\"").collect(Collectors.joining(",")) + "]}";
    String url = "/assignments/applications/testBatch/users/batchUser";
    for (Experiment experiment : experimentList) {
        response = apiServerConnector.doPut("/experiments/" + experiment.id, "{\"state\": \"" + state + "\"}");
        assertReturnCode(response, HttpStatus.SC_OK);
    }
    response = apiServerConnector.doPost(url, lables);
    LOGGER.debug("experiment not found State=" + state + " status=" + response.getStatusCode() + " response="
            + response.asString());
    Type listType = new TypeToken<Map<String, ArrayList<Assignment>>>() {
    }.getType();
    Map<String, List<Assignment>> batchAssignmentResult = new Gson().fromJson(response.asString(), listType);
    for (Assignment assignment : batchAssignmentResult.get("assignments")) {
        if (isAssignment) {
            Assert.assertNotNull(assignment.assignment, "Assignment should not be null for: " + assignment);
        } else {
            Assert.assertNull(assignment.assignment, "Assignment should be null for: " + assignment);
        }
        Assert.assertEquals(assignment.status, status);
    }
}

From source file:com.thoughtworks.go.apiv2.dashboard.DashboardController.java

private String calcEtag(Username username, List<GoDashboardPipelineGroup> pipelineGroups,
        List<GoDashboardEnvironment> environments) {
    final String pipelineSegment = pipelineGroups.stream().map(GoDashboardPipelineGroup::etag)
            .collect(Collectors.joining(SEP_CHAR));
    final String environmentSegment = environments.stream().map(GoDashboardEnvironment::etag)
            .collect(Collectors.joining(SEP_CHAR));
    return DigestUtils.md5Hex(
            StringUtils.joinWith(SEP_CHAR, username.getUsername(), pipelineSegment, environmentSegment));
}