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:edu.umd.umiacs.clip.tools.classifier.LibSVMUtils.java

public static List<String> filter(List<String> training, int threshold) {
    Set<Integer> filtered = training.stream().flatMap(line -> Stream.of(line.split(" ")).skip(1))
            .map(pair -> new Integer(pair.substring(0, pair.indexOf(":"))))
            .collect(groupingBy(i -> i, counting())).entrySet().stream()
            .filter(entry -> entry.getValue() >= threshold).map(Entry::getKey).collect(toSet());
    return training.stream().map(line -> line.split(" "))
            .map(fields -> fields[0] + " "
                    + String.join(" ", Stream.of(fields).skip(1).filter(
                            pair -> filtered.contains(new Integer(pair.substring(0, pair.indexOf(":")))))
                            .collect(toList())))
            .map(String::trim).collect(toList());
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.google.GoogleProviderUtils.java

private static void waitOnOperation(Supplier<Operation> operationSupplier) {
    Operation operation = operationSupplier.get();
    while (!operation.getStatus().equals("DONE")) {
        if (operation.getError() != null) {
            throw new HalException(FATAL, String.join("\n", operation.getError().getErrors().stream()
                    .map(e -> e.getCode() + ": " + e.getMessage()).collect(Collectors.toList())));
        }/* w  w w.j ava2  s  .c o  m*/
        operation = operationSupplier.get();
        DaemonTaskHandler.safeSleep(TimeUnit.SECONDS.toMillis(1));
    }
}

From source file:com.asakusafw.runtime.io.text.directio.AbstractTextStreamFormatTest.java

static byte[] serialize(String[][] fields) {
    return Arrays.stream(fields).map(ss -> String.join(":", ss)).collect(Collectors.joining("\n"))
            .getBytes(StandardCharsets.UTF_8);
}

From source file:lu.list.itis.dkd.aig.template.TemplateService.java

protected Response generateItems(final ServletContext context, final String name, final String jsonInput,
        final String folder, final int maxNumberOfItems) {

    final Gson gson = new Gson();
    final Type mapType = new TypeToken<HashMap<String, String>>() {
    }.getType();//w ww.  j  a va  2s .  c  o m

    final HashMap<String, String> input = gson.fromJson(jsonInput, mapType);

    String template;
    try {
        template = TemplateManager.fetch(context, name, folder);
    } catch (final IOException e) {
        Logger.getLogger(TemplateService.class.getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
        return Response.serverError().entity(
                "An error occured while trying to retrieve the template!\n" + ExceptionUtils.getStackTrace(e)) //$NON-NLS-1$
                .build();
    }

    if (null == template) {
        return Response.status(412).entity("The named template could not be found. No items generated!") //$NON-NLS-1$
                .build();
    }

    final ItemFactoryBuilder itemFactoryBuilder = new ItemFactoryBuilder();
    try {
        itemFactoryBuilder.withTemplate(template);
    } catch (final TemplateParseException e) {
        return Response.status(500)
                .entity("The provided template contained errors and could not be used to build items!\n" //$NON-NLS-1$
                        + ExceptionUtils.getStackTrace(e))
                .build();
    }
    itemFactoryBuilder.withItemLimit(maxNumberOfItems);
    itemFactoryBuilder.withInput(input);
    ItemFactory factory = null;
    try {
        factory = itemFactoryBuilder.build();
    } catch (final TemplateParseException e) {
        return Response.status(500).entity(
                "Internal server error. Internal state conflicted due to logical fallacy! Contact your administrator!\n" //$NON-NLS-1$
                        + ExceptionUtils.getStackTrace(e))
                .build();
    } catch (final ResolutionException e) {
        return Response.status(500).entity(
                "The inputs could not be interpreted or were not provided!\n" + ExceptionUtils.getStackTrace(e)) //$NON-NLS-1$
                .build();
    } catch (final NotImplementedException e) {
        return Response.status(500).entity("The initialization of a required component (process) failed!\n" //$NON-NLS-1$
                + ExceptionUtils.getStackTrace(e)).build();
    } catch (final TemplateConsistencyException e) {
        return Response.status(500).entity(
                "Inconsistencies in the provided variables, their identifiers, or their mapping caused an exception while trying to construct an item!\n" //$NON-NLS-1$
                        + ExceptionUtils.getStackTrace(e))
                .build();
    }

    List<String> items;
    try {
        items = factory.buildItems();
    } catch (final TemplateParseException e) {
        return Response.status(500)
                .entity("Variables could not be resolved to the template!\n" + ExceptionUtils.getStackTrace(e)) //$NON-NLS-1$
                .build();
    } catch (final TemplateConsistencyException e) {
        return Response.status(500)
                .entity("Variables could not be resolved as by their specification in the template!\n" //$NON-NLS-1$
                        + ExceptionUtils.getStackTrace(e))
                .build();
    } catch (final ResolutionException e) {
        return Response.status(500)
                .entity("The resolution of one or more variables failed!\n" + ExceptionUtils.getStackTrace(e)) //$NON-NLS-1$
                .build();
    }

    return Response.status(200).type(MediaType.TEXT_XML)
            .entity("<layers>" + String.join("", items) + "</layers>").build(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testEventIdformulaformfields01()./* w  w w .j  av a  2 s .com*/
 * no variables
 * @throws Exception Exception
 */
@Test
public void testEventIdformulaformfields01() throws Exception {
    // given
    String formUUID = UUID.randomUUID().toString();
    String param81 = "Test[" + formUUID + "]";
    FormJSON testform = TestDataBuilder.createSimpleForm();

    // when
    expect(this.flow.getData()).andReturn(this.mockarchive);
    expect(this.request.getParameter("83")).andReturn(param81);
    expect(this.mockarchive.getForm(formUUID)).andReturn(testform);

    replayAll();
    FormJSONField field = this.ws.eventIdformulaformfields(this.flow, this.request);

    // verify
    verifyAll();

    assertEquals("", String.join(",", field.getOptions()));
}

From source file:com.seleniumtests.connectors.selenium.SeleniumRobotGridConnector.java

/**
 * Send keys to desktop/*from  ww  w.  j a v  a 2 s . c  o m*/
 * @param keys
 */
@Override
public void sendKeysWithKeyboard(List<Integer> keyCodes) {
    if (nodeUrl == null) {
        throw new ScenarioException(
                "You cannot use keyboard before driver has been created and corresponding node instanciated");
    }

    String keyCodeString = String.join(",",
            keyCodes.stream().map(k -> Integer.toString(k)).collect(Collectors.toList()));

    logger.info("sending keys: " + keyCodes);
    try {
        Unirest.post(String.format("%s%s", nodeUrl, NODE_TASK_SERVLET)).queryString("action", "sendKeys")
                .queryString("keycodes", keyCodeString).asString();
    } catch (UnirestException e) {
        logger.warn(String.format("Could send keys: %s", e.getMessage()));
    }
}

From source file:ddf.catalog.registry.converter.RegistryPackageConverter.java

private static void parseRegistryPerson(PersonType person, MetacardImpl metacard)
        throws RegistryConversionException {

    validateIdentifiable(person);//w  ww  .  j  a  v  a 2  s . c o  m

    String name = "no name";
    String phone = "no telephone number";
    String email = "no email address";

    if (person.isSetPersonName()) {
        PersonNameType personName = person.getPersonName();
        List<String> nameParts = new ArrayList<>();
        if (StringUtils.isNotBlank(personName.getFirstName())) {
            nameParts.add(personName.getFirstName());
        }
        if (StringUtils.isNotBlank(personName.getLastName())) {
            nameParts.add(personName.getLastName());
        }

        if (CollectionUtils.isNotEmpty(nameParts)) {
            name = String.join(" ", nameParts);
        }
    }

    if (person.isSetTelephoneNumber()) {
        List<TelephoneNumberType> phoneNumbers = person.getTelephoneNumber();
        if (CollectionUtils.isNotEmpty(phoneNumbers)) {
            phone = getPhoneNumberString(phoneNumbers.get(0));
        }
    }

    if (person.isSetEmailAddress()) {
        List<EmailAddressType> emailAddresses = person.getEmailAddress();

        if (CollectionUtils.isNotEmpty(emailAddresses)) {
            EmailAddressType emailAddress = emailAddresses.get(0);

            if (StringUtils.isNotBlank(emailAddress.getAddress())) {
                email = emailAddress.getAddress();
            }
        }
    }

    String metacardPoc = String.format("%s, %s, %s", name, phone, email);
    metacard.setAttribute(Metacard.POINT_OF_CONTACT, metacardPoc);

}

From source file:com.excelsiorjet.api.util.Utils.java

public static String deriveFourDigitVersion(String version) {
    String[] versions = version.split("\\.");
    String[] finalVersions = new String[] { "0", "0", "0", "0" };
    for (int i = 0; i < Math.min(versions.length, 4); ++i) {
        try {//from   www.  ja  v  a 2s  . c om
            finalVersions[i] = Integer.decode(versions[i]).toString();
        } catch (NumberFormatException e) {
            int minusPos = versions[i].indexOf('-');
            if (minusPos > 0) {
                String v = versions[i].substring(0, minusPos);
                try {
                    finalVersions[i] = Integer.decode(v).toString();
                } catch (NumberFormatException ignore) {
                }
            }
        }
    }
    return String.join(".", (CharSequence[]) finalVersions);
}

From source file:grakn.core.console.ConsoleSession.java

/**
 * Open the user's preferred editor to write a query
 *
 * @return the string written in the editor
 *///from w  w w. ja  v  a2s .c  o  m
private String openTextEditor() throws IOException, InterruptedException {
    File tempFile = new File(System.getProperty("java.io.tmpdir") + EDITOR_FILE);
    tempFile.createNewFile();

    ProcessBuilder builder;

    if (isWindows()) {
        String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(WINDOWS_EDITOR_DEFAULT);
        builder = new ProcessBuilder("cmd", "/c", editor + " " + tempFile.getAbsolutePath());
    } else {
        String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(UNIX_EDITOR_DEFAULT);
        // Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql
        builder = new ProcessBuilder("/bin/bash", "-c",
                editor + " </dev/tty >/dev/tty " + tempFile.getAbsolutePath());
    }

    builder.start().waitFor();
    return String.join("\n", Files.readAllLines(tempFile.toPath()));
}

From source file:com.baifendian.swordfish.dao.mapper.ExecutionFlowMapperProvider.java

/**
 * ??/*from www  . jav a 2s .c  om*/
 */
public String sumByFlowIdAndTimesAndStatus(Map<String, Object> parameter) {
    List<FlowStatus> flowStatuses = (List<FlowStatus>) parameter.get("status");
    List<String> workflowList = (List<String>) parameter.get("workflowList");
    List<String> workflowList2 = new ArrayList<>();

    Date startDate = (Date) parameter.get("startDate");
    Date endDate = (Date) parameter.get("endDate");

    if (CollectionUtils.isNotEmpty(workflowList)) {
        for (String workflow : workflowList) {
            workflowList2.add("\"" + workflow + "\"");
        }
    }

    List<String> flowStatusStrList = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(flowStatuses)) {
        for (FlowStatus status : flowStatuses) {
            flowStatusStrList.add(String.valueOf(status.ordinal()));
        }
    }

    String where = String.join(",", flowStatusStrList);

    return new SQL() {
        {
            SELECT("count(0)");

            FROM(TABLE_NAME + " e_f");

            JOIN("project_flows p_f on e_f.flow_id = p_f.id");
            JOIN("project p on p_f.project_id = p.id");

            WHERE("p.name = #{projectName}");

            if (CollectionUtils.isNotEmpty(workflowList)) {
                WHERE("p_f.name in (" + String.join(",", workflowList2) + ")");
            }

            if (startDate != null && endDate != null) {
                WHERE("start_time >= #{startDate}");
                WHERE("start_time <= #{endDate}");
            }

            if (CollectionUtils.isNotEmpty(flowStatuses)) {
                WHERE("`status` in (" + where + ") ");
            }
        }
    }.toString();
}