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:edu.usu.sdl.openstorefront.service.io.HelpImporter.java

/**
 * Accept a stream pointed to markdown//from w  w  w  .  ja va  2 s  . co  m
 *
 * @param in
 * @return
 */
public List<HelpSection> processHelp(InputStream in) {
    List<HelpSection> helpSections = new ArrayList<>();

    String data = "";
    try (BufferedReader bin = new BufferedReader(new InputStreamReader(in))) {
        data = bin.lines().collect(Collectors.joining("\n"));
    } catch (IOException e) {

    }

    PegDownProcessor pegDownProcessor = new PegDownProcessor(PROCESSING_TIMEOUT);
    String html = pegDownProcessor.markdownToHtml(data);
    Document doc = Jsoup.parse(html);
    Elements elements = doc.getAllElements();

    Set<String> headerTags = new HashSet<>();
    headerTags.add("h1");
    headerTags.add("h2");
    headerTags.add("h3");
    headerTags.add("h4");
    headerTags.add("h5");
    headerTags.add("h6");

    boolean capture = false;
    HelpSection helpSection = null;
    for (Element element : elements) {
        if (headerTags.contains(element.tagName().toLowerCase()) == false && capture) {
            if (helpSection != null) {
                if (helpSection.getContent().contains(element.outerHtml()) == false) {
                    helpSection.setContent(helpSection.getContent() + element.outerHtml());
                }
            }
        }

        if (headerTags.contains(element.tagName().toLowerCase())) {
            String title = element.html();

            if (helpSection != null) {
                //save old section
                addHelpSection(helpSections, helpSection);
            }

            String titleSplit[] = title.split(" ");

            helpSection = new HelpSection();
            helpSection.setTitle(title);
            helpSection.setHeaderLevel(Convert.toInteger(element.tagName().toLowerCase().replace("h", "")));
            helpSection.setSectionNumber(titleSplit[0]);
            helpSection.setContent("");

            if (title.contains("*")) {
                helpSection.setAdminSection(true);
            } else {
                helpSection.setAdminSection(false);
            }

            capture = true;
        }
    }
    //Add last section
    if (helpSection != null) {
        addHelpSection(helpSections, helpSection);
    }

    return helpSections;
}

From source file:com.example.audit.CSVAuditLogger.java

/**
 * Write a CSV record in the audit log for the supplied audit event,
 * including additional information specific to the sub-type of the audit
 * event.//from  ww w.  j av  a  2  s.  c  o  m
 *
 * @param event an audit event.
 * @param type specific type of the audit event.
 * @param detail information specific to this audit event type.
 */
private void writeAuditLog(final IAuditEvent event, final String type, final String detail) {
    final String logEntry = CSV_FORMAT.format(event.getTimestamp(), event.getUser(), type,
            event.getUserSecurityGroups().stream().collect(Collectors.joining(", ")),
            event.getClientIPAddress(), event.getClientUserAgent(), detail);
    mLogWriter.writeAuditLog(logEntry);
}

From source file:net.kemitix.checkstyle.ruleset.builder.CheckstyleWriter.java

private String formatProperties(final Map<String, String> properties) {
    return MapStream.of(properties).map((k, v) -> String.format("<property name=\"%s\" value=\"%s\"/>", k, v))
            .collect(Collectors.joining(NEWLINE));
}

From source file:org.eclipse.hawkbit.simulator.DeviceSimulatorUpdater.java

/**
 * Starting an simulated update process of an simulated device.
 *
 * @param tenant/*www . j  a va2s  . co  m*/
 *            the tenant of the device
 * @param id
 *            the ID of the simulated device
 * @param actionId
 *            the actionId from the hawkbit update server to start the
 *            update.
 * @param modules
 *            the software module version from the hawkbit update server
 * @param swVersion
 *            the software version as static value in case modules is null
 * @param targetSecurityToken
 *            the target security token for download authentication
 * @param callback
 *            the callback which gets called when the simulated update
 *            process has been finished
 */
public void startUpdate(final String tenant, final String id, final long actionId, final String swVersion,
        final List<DmfSoftwareModule> modules, final String targetSecurityToken,
        final UpdaterCallback callback) {
    AbstractSimulatedDevice device = repository.get(tenant, id);

    // plug and play - non existing device will be auto created
    if (device == null) {
        device = repository
                .add(deviceFactory.createSimulatedDevice(id, tenant, Protocol.DMF_AMQP, 1800, null, null));
    }

    device.setProgress(0.0);

    if (modules == null || modules.isEmpty()) {
        device.setSwversion(swVersion);
    } else {
        device.setSwversion(
                modules.stream().map(DmfSoftwareModule::getModuleVersion).collect(Collectors.joining(", ")));
    }
    device.setTargetSecurityToken(targetSecurityToken);
    eventbus.post(new InitUpdate(device));

    threadPool.schedule(new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, threadPool,
            callback, modules), 2_000, TimeUnit.MILLISECONDS);
}

From source file:com.intuit.wasabi.tests.service.priority.BatchPriorityAssignmentTest.java

@Test(groups = { "batchAssign" }, dependsOnGroups = { "setup" })
public void t_batchAssign() {
    String lables = "{\"labels\": ["
            + validExperimentsLists.stream().map(s -> "\"" + s.label + "\"").collect(Collectors.joining(","))
            + "]}";
    response = apiServerConnector.doPost(
            "/assignments/applications/" + validExperimentsLists.get(0).applicationName + "/users/johnDoe",
            lables);/*ww w .ja va 2s .c o m*/
    assertReturnCode(response, HttpStatus.SC_OK);
    LOGGER.debug("status: " + response.statusCode() + "\noutput: " + response.asString());
    Type listType = new TypeToken<Map<String, ArrayList<Map<String, Object>>>>() {
    }.getType();
    Map<String, List<Map<String, Object>>> result = new Gson().fromJson(response.asString(), listType);
    List<Map<String, Object>> assignments = result.get("assignments");
    Assert.assertNotNull(assignments.get(0).get("assignment"));
    IntStream.range(1, assignments.size())
            .forEach(i -> Assert.assertNull(assignments.get(i).get("assignment")));
}

From source file:io.specto.hoverfly.junit.dsl.RequestMatcherBuilder.java

private RequestMatcher build() {
    String query = queryParams.entrySet().stream()
            .flatMap(e -> e.getValue().stream().map(v -> encodeUrl(e.getKey()) + "=" + encodeUrl(v)))
            .collect(Collectors.joining("&"));
    return new RequestMatcher(path, method, destination, scheme, query, body, headers, TEMPLATE);
}

From source file:org.fenixedu.spaces.ui.OccupationController.java

@RequestMapping(value = "create", method = RequestMethod.POST)
public String create(Model model, @RequestParam String emails, @RequestParam String subject,
        @RequestParam String description, @RequestParam String selectedSpaces, @RequestParam String config,
        @RequestParam String events, @RequestParam(required = false) OccupationRequest request) {
    List<String> parsedMails = new ArrayList<String>();
    for (String m : emails.split(",")) {
        if (isValidEmailAddress(m.trim())) {
            parsedMails.add(m);/*w  w w  .ja va 2  s  . c om*/
        }
    }
    emails = parsedMails.stream().collect(Collectors.joining(", "));
    try {
        occupationService.createOccupation(emails, subject, description, selectedSpaces, config, events,
                request, Authenticate.getUser());
        if (request != null) {
            return "redirect:/spaces/occupations/requests/" + request.getExternalId();
        }
        return "redirect:/spaces/occupations/list";
    } catch (Exception e) {
        model.addAttribute("errorMessage", e.getMessage());
        return searchSpaces(model, events, config, request, emails);
    }
}

From source file:com.cybernostics.jsp2thymeleaf.api.util.AlternateFormatStrings.java

Supplier<RuntimeException> err(Map<String, Object> values) {
    return () -> {
        StringWriter message = new StringWriter();
        message.write("Could not select format from candidates:");
        message.write(candidateFormats.stream().map(it -> it.toString()).collect(Collectors.joining(",")));
        message.write('\n');
        message.write("Given Attributes:");
        message.write(values.keySet().stream().collect(Collectors.joining(",")));
        return new RuntimeException(message.toString());
    };//w w  w  .  j a  v a  2  s . c om
}

From source file:jp.toastkid.script.Controller.java

/**
 * Load script from file./* w w w .ja  v a2 s  .c o  m*/
 * @param file
 */
private void loadScript(final File file) {
    if (file == null || !file.exists()) {
        return;
    }
    try {
        scriptName.setText(file.getCanonicalPath());
        scripterInput.replaceText(
                Files.readAllLines(file.toPath()).stream().collect(Collectors.joining(System.lineSeparator())));
    } catch (final IOException e) {
        LOGGER.error("Caught error.", e);
    }
}

From source file:org.fcrepo.client.GetBuilder.java

private String buildPrefer(final String prefer, final List<URI> includeUris, final List<URI> omitUris) {
    final StringJoiner preferJoin = new StringJoiner("; ");
    preferJoin.add("return=" + prefer);

    if (includeUris != null) {
        final String include = includeUris.stream().map(URI::toString).collect(Collectors.joining(" "));
        if (include.length() > 0) {
            preferJoin.add("include=\"" + include + "\"");
        }/*www.j ava2s  . c  o  m*/
    }

    if (omitUris != null) {
        final String omit = omitUris.stream().map(URI::toString).collect(Collectors.joining(" "));
        if (omit.length() > 0) {
            preferJoin.add("omit=\"" + omit + "\"");
        }
    }

    return preferJoin.toString();
}