Example usage for java.lang String join

List of usage examples for java.lang String join

Introduction

In this page you can find the example usage for java.lang String join.

Prototype

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) 

Source Link

Document

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter .

Usage

From source file:org.createnet.raptor.auth.service.services.AclDeviceService.java

@Retryable(maxAttempts = 3, value = AclManagerService.AclManagerException.class, backoff = @Backoff(delay = 500, multiplier = 3))
public void register(Device device) {

    User owner = device.getOwner();//from w  w w.  ja  v a  2 s  . c o  m
    List<Permission> permissions = list(device, owner);
    Sid sid = new UserSid(owner);

    logger.debug("Found {} permissions for {}", permissions.size(), owner.getUuid());

    if (permissions.isEmpty()) {

        logger.debug("Set default permission");
        List<Permission> newPerms = Arrays.stream(defaultPermissions).collect(Collectors.toList());

        if (owner.getId().equals(device.getOwner().getId())) {
            newPerms.add(RaptorPermission.ADMINISTRATION);
        }

        try {
            aclManagerService.addPermissions(Device.class, device.getId(), sid, newPerms, device.getParentId());
        } catch (AclManagerService.AclManagerException ex) {
            logger.warn("Failed to store default permission for {} ({}): {}", device.getId(), sid,
                    ex.getMessage());
            throw ex;
        }

        permissions.addAll(newPerms);
    } else {
        aclManagerService.setParent(device.getClass(), device.getId(), device.getParentId());
    }

    String perms = String.join(", ", RaptorPermission.toLabel(permissions));
    logger.debug("Permission set for device {} to {} - {}", device.getUuid(), device.getOwner().getUuid(),
            perms);

}

From source file:com.thoughtworks.go.apiv5.plugininfos.PluginInfosControllerV5.java

public String index(Request request, Response response) throws IOException {
    List<CombinedPluginInfo> pluginInfos = new ArrayList<>();
    String pluginType = request.queryParams("type");
    Boolean includeBad = Boolean.valueOf(request.queryParams("include_bad"));

    if (StringUtils.isNotBlank(pluginType)
            && !extensionsRegistry.allRegisteredExtensions().contains(pluginType)) {
        throw new UnprocessableEntityException(
                String.format("Invalid plugin type '%s'. It has to be one of '%s'.", pluginType,
                        String.join(", ", extensionsRegistry.allRegisteredExtensions())));
    }//from   w ww.ja  v  a 2s.  c o m

    Collection<CombinedPluginInfo> validPluginInfos = this.pluginInfoFinder.allPluginInfos(pluginType).stream()
            .filter(pluginInfo -> !hasUnsupportedExtensionType(pluginInfo)).collect(Collectors.toList());

    pluginInfos.addAll(validPluginInfos);

    if (includeBad) {
        List<BadPluginInfo> badPluginInfos = defaultPluginManager.plugins().stream()
                .filter(GoPluginDescriptor::isInvalid).map(BadPluginInfo::new).collect(toList());

        pluginInfos.addAll(badPluginInfos);
    }

    pluginInfos
            .sort(Comparator.comparing((CombinedPluginInfo pluginInfos1) -> pluginInfos1.getDescriptor().id()));
    String etag = etagFor(pluginInfos);

    if (fresh(request, etag)) {
        return notModified(response);
    }
    setEtagHeader(response, etag);
    return writerForTopLevelObject(request, response,
            writer -> PluginInfosRepresenter.toJSON(writer, pluginInfos));

}

From source file:gov.nist.healthcare.ttt.webapp.api.GetCCDAFolderTest.java

public static String getLink(String[] path) {
    String link = String.join("/", path).replace(" ", "%20");
    link = "https://raw.githubusercontent.com/siteadmin/2015-Certification-C-CDA-Test-Data/master/" + link;
    return link;//ww  w .j av a  2s.  com
}

From source file:uk.ac.kcl.itemProcessors.GateDocumentItemProcessor.java

@Override
public Document process(final Document doc) throws Exception {
    LOG.debug("starting " + this.getClass().getSimpleName() + " on doc " + doc.getDocName());
    long startTime = System.currentTimeMillis();
    int contentLength = doc.getAssociativeArray().keySet().stream()
            .filter(k -> fieldsToGate.contains(k.toLowerCase()))
            .mapToInt(k -> ((String) doc.getAssociativeArray().get(k)).length()).sum();

    HashMap<String, Object> newMap = new HashMap<>();
    newMap.putAll(doc.getAssociativeArray());
    List<String> failedFieldsList = new ArrayList<String>(fieldsToGate);

    newMap.put(fieldName, new HashMap<String, Object>());

    doc.getAssociativeArray().forEach((k, v) -> {
        if (fieldsToGate.contains(k.toLowerCase())) {
            gate.Document gateDoc = null;
            try {
                gateDoc = Factory.newDocument((String) v);
                LOG.info("Going to process key: {} in document PK: {}, content length: {}", k,
                        doc.getPrimaryKeyFieldValue(), ((String) v).length());
                gateService.processDoc(gateDoc);
                ((HashMap<String, Object>) newMap.get(fieldName)).put(k, gateService.convertDocToJSON(gateDoc));

                // Remove the key from the list if GATE is successful
                failedFieldsList.remove(k.toLowerCase());
            } catch (Exception e) {
                LOG.warn("gate failed on doc {} (PK: {}): {}", doc.getDocName(), doc.getPrimaryKeyFieldValue(),
                        e);/*from ww w.j  ava 2 s  . c  o m*/
                ArrayList<LinkedHashMap<Object, Object>> al = new ArrayList<LinkedHashMap<Object, Object>>();
                LinkedHashMap<Object, Object> hm = new LinkedHashMap<Object, Object>();
                hm.put("error", "see logs");
                al.add(hm);
                ((HashMap<String, Object>) newMap.get(fieldName)).put(k, hm);
            } finally {
                Factory.deleteResource(gateDoc);
            }
        }
    });
    if (failedFieldsList.size() == 0) {
        newMap.put("X-TL-GATE", "Success");
    } else {
        newMap.put("X-TL-GATE", "Failed fields: " + String.join(", ", failedFieldsList));
    }
    doc.getAssociativeArray().clear();
    doc.getAssociativeArray().putAll(newMap);
    long endTime = System.currentTimeMillis();
    LOG.info("{};Primary-Key:{};Total-Content-Length:{};Time:{} ms", this.getClass().getSimpleName(),
            doc.getPrimaryKeyFieldValue(), contentLength, endTime - startTime);
    LOG.debug("finished " + this.getClass().getSimpleName() + " on doc " + doc.getDocName());
    return doc;
}

From source file:fi.hsl.parkandride.itest.HubsAndFacilitiesReportITest.java

private void checkHubsAndFacilities_hubInfo(Workbook workbook) {
    final Sheet hubs = workbook.getSheetAt(0);
    assertThat(hubs.getPhysicalNumberOfRows()).isEqualTo(2);

    final List<String> hubInfo = getDataFromRow(hubs, 1);
    assertThat(hubInfo).containsExactly(hub.name.fi,
            String.join(", ",
                    toArray(hub.address.streetAddress.fi, hub.address.postalCode, hub.address.city.fi)),
            String.format(Locale.ENGLISH, "%.4f", hub.location.getX()),
            String.format(Locale.ENGLISH, "%.4f", hub.location.getY()),
            "" + facility1.builtCapacity.entrySet().stream()
                    .filter(entry -> asList(motorCapacities).contains(entry.getKey()))
                    .mapToInt(entry -> entry.getValue()).sum(),
            "" + facility1.builtCapacity.entrySet().stream()
                    .filter(entry -> asList(bicycleCapacities).contains(entry.getKey()))
                    .mapToInt(entry -> entry.getValue()).sum(),
            "" + facility1.builtCapacity.getOrDefault(CAR, 0),
            "" + facility1.builtCapacity.getOrDefault(DISABLED, 0),
            "" + facility1.builtCapacity.getOrDefault(ELECTRIC_CAR, 0),
            "" + facility1.builtCapacity.getOrDefault(MOTORCYCLE, 0),
            "" + facility1.builtCapacity.getOrDefault(BICYCLE, 0),
            "" + facility1.builtCapacity.getOrDefault(BICYCLE_SECURE_SPACE, 0), facility1.name.fi);
}

From source file:net.dataforte.commons.resources.ClassUtils.java

private static String joinParts(String separator, String... paths) {
    Vector<String> trimmed = new Vector<String>();
    int pos = 0;//from  w  w  w  .  j a  v a2  s .co  m
    int last = paths.length - 1;
    for (String path : paths) {
        String trimmedPath;
        if (pos == 0)
            trimmedPath = StringUtils.stripEnd(path, separator);
        else if (pos == last)
            trimmedPath = StringUtils.stripStart(path, separator);
        else
            trimmedPath = StringUtils.strip(path, separator);
        trimmed.add(trimmedPath);
        pos += 1;
    }
    String joined = String.join(separator, trimmed);
    return joined;
}

From source file:com.github.blindpirate.gogradle.task.go.test.PlainGoTestResultExtractor.java

private GoTestMethodResult extractOneTestMethod(String testMethodName, List<String> resultLines) {
    Pattern testEndLinePattern = Pattern
            .compile("--- (PASS|FAIL|SKIP):\\s+" + testMethodName + "\\s+\\(((\\d+)(\\.\\d+)?)s\\)");
    String message = String.join("\n", resultLines);

    for (String line : resultLines) {
        if (line.contains(TEST_PASS) || line.contains(TEST_FAIL) || line.contains(TEST_SKIP)) {
            Matcher matcher = testEndLinePattern.matcher(line);
            if (matcher.find()) {
                TestResult.ResultType resultType = RESULT_TYPE_MAP.get(matcher.group(1));
                long duration = toMilliseconds(parseDouble(matcher.group(2)));
                return createTestMethodResult(testMethodName, resultType, message, duration);
            }//from  w ww .ja  v  a2  s  .co m
        }
    }
    return createTestMethodResult(testMethodName, TestResult.ResultType.FAILURE, message, 0L);
}

From source file:io.syndesis.runtime.action.DynamicActionSqlStoredITCase.java

private static String read(final String path) {
    try {/*from ww  w .  ja  v a 2 s.  c  o  m*/
        return String.join("",
                Files.readAllLines(Paths.get(DynamicActionSqlStoredITCase.class.getResource(path).toURI())));
    } catch (IOException | URISyntaxException e) {
        throw new IllegalArgumentException("Unable to read from path: " + path, e);
    }
}

From source file:com.groupdocs.ui.servlets.ViewDocument.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {/*w w w.j a v a2 s  .com*/
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
        cssList = tempRef_cssList.argValue;

        ArrayList<String> pagesContent = new ArrayList<String>();
        for (PageHtml page : htmlPages) {
            pagesContent.add(page.getHtmlContent());
        }
        String[] htmlContent = pagesContent.toArray(new String[0]);
        result.setPageHtml(htmlContent);
        result.setPageCss(new String[] { String.join(" ", temp_cssList) });

        for (int i = 0; i < result.getPageHtml().length; i++) {
            String html = result.getPageHtml()[i];
            int indexOfScript = html.indexOf("script");
            if (indexOfScript > 0) {
                result.getPageHtml()[i] = html.substring(0, indexOfScript);
            }
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}

From source file:com.ggvaidya.scinames.ui.DatasetImporterController.java

private void displayPreview() {
    filePreviewTextArea.setText("");
    if (currentFile == null)
        return;//from   w  ww . jav a 2 s . c  o  m

    if (currentFile.getName().endsWith("xls") || currentFile.getName().endsWith("xlsx")) {
        // Excel files are special! We need to load it special and then preview it.
        ExcelImporter imp;

        String excelPreviewText;
        try {
            imp = new ExcelImporter(currentFile);
            List<Sheet> sheets = imp.getWorksheets();

            StringBuffer preview = new StringBuffer();
            preview.append("Excel file version " + imp.getWorkbook().getSpreadsheetVersion() + " containing "
                    + sheets.size() + " sheets.\n");
            for (Sheet sh : sheets) {
                preview.append(
                        " - " + sh.getSheetName() + " contains " + sh.getPhysicalNumberOfRows() + " rows.\n");

                // No rows?
                if (sh.getPhysicalNumberOfRows() == 0)
                    continue;

                // Header row?
                Row headerRow = sh.getRow(0);
                boolean headerEmitted = false;

                for (int rowIndex = 1; rowIndex < sh.getPhysicalNumberOfRows(); rowIndex++) {
                    if (rowIndex >= 10)
                        break;

                    Row row = sh.getRow(rowIndex);

                    if (!headerEmitted) {
                        preview.append(
                                "  - " + String.join("\t", ExcelImporter.getCellsAsValues(headerRow)) + "\n");
                        headerEmitted = true;
                    }
                    preview.append("  - " + String.join("\t", ExcelImporter.getCellsAsValues(row)) + "\n");
                }

                preview.append("\n");
            }

            excelPreviewText = preview.toString();
        } catch (IOException ex) {
            excelPreviewText = "Could not open '" + currentFile + "': " + ex;
        }

        filePreviewTextArea.setText(excelPreviewText);

        return;
    }

    // If we're here, then this is some sort of text file, so let's preview the text content directly.
    try {
        LineNumberReader reader = new LineNumberReader(new BufferedReader(new FileReader(currentFile)));

        // Load the first ten lines.
        StringBuffer head = new StringBuffer();
        for (int x = 0; x < 10; x++) {
            head.append(reader.readLine());
            head.append('\n');
        }

        reader.close();
        filePreviewTextArea.setText(head.toString());
    } catch (IOException ex) {
        filePreviewTextArea.setBackground(BACKGROUND_RED);
        filePreviewTextArea.setText("ERROR: Could not load file '" + currentFile + "': " + ex);
    }
}