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:io.spring.initializr.metadata.InitializrConfiguration.java

private static String unsplitWords(String text) {
    return String.join("",
            Arrays.stream(text.split("(_|-| |:)+")).map(StringUtils::capitalize).toArray(String[]::new));
}

From source file:org.mycontroller.standalone.api.jaxrs.json.RoleJson.java

@JsonIgnore
public void mapResources(Role role) {
    this.id = role.getId();
    this.name = role.getName();
    this.description = role.getDescription();
    this.permission = role.getPermission().getText();
    //TODO: map resources
    List<RoleUserMap> roleUserMaps = DaoUtils.getRoleUserMapDao().getByRoleId(this.id);
    users = new ArrayList<Integer>();
    for (RoleUserMap userMap : roleUserMaps) {
        users.add(userMap.getUser().getId());
    }//from   ww  w.j a v a2s .  c om
    if (role.getPermission() == PERMISSION_TYPE.USER) {
        //GatewayTable map
        List<RoleGatewayMap> roleGatewayMaps = DaoUtils.getRoleGatewayMapDao().getByRoleId(this.id);
        gateways = new ArrayList<Integer>();
        for (RoleGatewayMap gatewayMap : roleGatewayMaps) {
            gateways.add(gatewayMap.getGatewayTable().getId());
        }
        //Node map
        List<RoleNodeMap> roleNodeMaps = DaoUtils.getRoleNodeMapDao().getByRoleId(this.id);
        nodes = new ArrayList<Integer>();
        for (RoleNodeMap nodeMap : roleNodeMaps) {
            nodes.add(nodeMap.getNode().getId());
        }
        //Sensor map
        List<RoleSensorMap> roleSensorMaps = DaoUtils.getRoleSensorMapDao().getByRoleId(this.id);
        sensors = new ArrayList<Integer>();
        for (RoleSensorMap sensorMap : roleSensorMaps) {
            sensors.add(sensorMap.getSensor().getId());
        }
    } else if (role.getPermission() == PERMISSION_TYPE.MQTT_USER) {
        //update mqtt
        RoleMqttMap roleMqttMap = DaoUtils.getRoleMqttMapDao().getByRoleId(this.id);
        if (roleMqttMap != null) {
            if (roleMqttMap.getPublish() != null) {
                topicsPublish = String.join(", ", roleMqttMap.getPublish());
            }
            if (roleMqttMap.getSubscribe() != null) {
                topicsSubscribe = String.join(", ", roleMqttMap.getSubscribe());
            }
        }
    }
}

From source file:com.hortonworks.streamline.streams.runtime.storm.bolt.query.WindowedQueryBolt.java

static String convertToStreamLineKeys(String commaSeparatedKeys) {
    String[] keyNames = commaSeparatedKeys.replaceAll("\\s+", "").split(",");

    String[] prefixedKeys = new String[keyNames.length];

    for (int i = 0; i < keyNames.length; i++) {
        FieldSelector fs = new FieldSelector(keyNames[i]);
        if (fs.getStreamName() == null) {
            prefixedKeys[i] = EVENT_PREFIX + String.join(".", fs.getField());
        } else {//from   w  ww  .j a  va  2s. c o m
            prefixedKeys[i] = fs.getStreamName() + ":" + EVENT_PREFIX + String.join(".", fs.getField());
        }
    }

    return String.join(", ", prefixedKeys);
}

From source file:io.github.retz.cli.CommandRun.java

@Override
public int handle(ClientCLIConfig fileConfig, boolean verbose) throws Throwable {
    Properties envProps = SubCommand.parseKeyValuePairs(envs);

    if (ports < 0 || 1000 < ports) {
        LOG.error("--ports must be within 0 to 1000: {} given.", ports);
        return -1;
    }/*from w ww .j a va  2  s. c  om*/

    if ("-".equals(remoteCmd)) {
        List<String> lines = IOUtils.readLines(System.in, StandardCharsets.UTF_8);
        remoteCmd = String.join("\n", lines);
    }

    Job job = new Job(appName, remoteCmd, envProps, cpu, mem, disk, gpu, ports);
    job.setPriority(priority);
    job.setName(name);
    job.addTags(tags);
    job.setAttributes(attributes);

    if (verbose) {
        LOG.info("Job: {}", job);
    }

    try (Client webClient = Client.newBuilder(fileConfig.getUri())
            .setAuthenticator(fileConfig.getAuthenticator()).checkCert(!fileConfig.insecure())
            .setVerboseLog(verbose).build()) {

        if (verbose) {
            LOG.info("Sending job {} to App {}", job.cmd(), job.appid());
        }
        Response res = webClient.schedule(job);

        if (!(res instanceof ScheduleResponse)) {
            LOG.error(res.status());
            return -1;
        }

        Date start = Calendar.getInstance().getTime();
        Callable<Boolean> timedout;
        if (timeout > 0) {
            LOG.info("Timeout = {} minutes", timeout);
            timedout = () -> {
                Date now = Calendar.getInstance().getTime();
                long diff = now.getTime() - start.getTime();
                return diff / 1000 > timeout * 60;
            };
        } else {
            timedout = () -> false;
        }

        Job scheduled = ((ScheduleResponse) res).job();
        if (verbose) {
            LOG.info("job {} scheduled", scheduled.id(), scheduled.state());
        }

        try {
            Job running = ClientHelper.waitForStart(scheduled, webClient, timedout);
            if (verbose) {
                LOG.info("job {} started: {}", running.id(), running.state());
            }

            LOG.info("============ stdout of job {} sandbox start ===========", running.id());
            Optional<Job> finished = ClientHelper.getWholeFileWithTerminator(webClient, running.id(), "stdout",
                    true, System.out, timedout);
            LOG.info("============ stdout of job {} sandbox end ===========", running.id());

            if (stderr) {
                LOG.info("============ stderr of job {} sandbox start ===========", running.id());
                Optional<Job> j = ClientHelper.getWholeFileWithTerminator(webClient, running.id(), "stderr",
                        false, System.err, null);
                LOG.info("============ stderr of job {} sandbox end ===========", running.id());
            }

            if (finished.isPresent()) {
                LOG.debug(finished.get().toString());
                LOG.info("Job(id={}, cmd='{}') finished in {} seconds. status: {}", running.id(), job.cmd(),
                        TimestampHelper.diffMillisec(finished.get().finished(), finished.get().started())
                                / 1000.0,
                        finished.get().state());
                return finished.get().result();
            } else {
                LOG.error("Failed to fetch last state of job id={}", running.id());
            }
        } catch (TimeoutException e) {
            webClient.kill(scheduled.id());
            LOG.error("Job(id={}) has been killed due to timeout after {} minute(s)", scheduled.id(), timeout);
        }
    }
    return -1;
}

From source file:org.opentestsystem.ap.irs.client.IvsClient.java

/**
 * Generates a comma separated string.  The values in the generated string are the values in the 'ids' list with the
 * bnankkey prefixed to it.  The format is bankkey-id.  For example 187-100001.
 * <p>//from   www  .  j  a  va2 s .  com
 * An example result is "187-100001,187-200002"
 *
 * @param bankKey The bank key to prefix the ids with.
 * @param ids     The ids to be prefixed.
 * @return A comma separated string.
 */
public String generateIdString(final String bankKey, final List<String> ids) {
    final Function<String, String> appendBankKey = id -> String.format("%s-%s", bankKey, id);
    final List<String> newIds = ids.stream().map(appendBankKey).collect(toList());
    return String.join(",", newIds);
}

From source file:ninja.eivind.hotsreplayuploader.window.nodes.BattleLobbyNode.java

public String base64EncodeBattleLobby(Replay replay) {
    Base64.Encoder encoder = Base64.getEncoder();
    List<String> asString = replay
            .getReplayDetails().getPlayers().stream().map(player -> player.getBattleNetRegionId() + "#"
                    + player.getShortName() + "#" + player.getBattleTag() + "#" + player.getTeam())
            .collect(Collectors.toList());
    try {//from   w  w w. ja  v  a2  s.co m
        byte[] data = String.join(",", asString).getBytes("UTF-8");
        return encoder.encodeToString(data);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.spinnaker.fiat.controllers.RolesController.java

@RequestMapping(value = "/sync", method = RequestMethod.POST)
public long sync(HttpServletResponse response, @RequestBody(required = false) List<String> specificRoles)
        throws IOException {
    if (specificRoles == null) {
        log.info("Full role sync invoked by web request.");
        long count = syncer.syncAndReturn();
        if (count == 0) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "Error occurred syncing permissions. See Fiat Logs.");
        }/*from  w ww  .  j a  v  a 2  s.  c om*/
        return count;
    }

    log.info("Web request role sync of roles: " + String.join(",", specificRoles));
    Map<String, UserPermission> affectedUsers = permissionsRepository.getAllByRoles(specificRoles);
    if (affectedUsers.size() == 0) {
        log.info("No users found with specified roles");
        return 0;
    }
    return syncer.updateUserPermissions(affectedUsers);
}

From source file:io.spring.initializr.metadata.InitializrConfiguration.java

private static String splitCamelCase(String text) {
    return String.join("", Arrays.stream(text.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"))
            .map((it) -> StringUtils.capitalize(it.toLowerCase())).toArray(String[]::new));
}

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

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

    User owner = token.getUser();//from w  w w.ja v a 2  s  .com
    List<Permission> permissions = list(token, 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(token.getUser().getId())) {
            newPerms.add(RaptorPermission.ADMINISTRATION);
        }

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

        permissions.addAll(newPerms);
    }

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

}