Example usage for org.apache.commons.lang3 StringUtils splitPreserveAllTokens

List of usage examples for org.apache.commons.lang3 StringUtils splitPreserveAllTokens

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils splitPreserveAllTokens.

Prototype

public static String[] splitPreserveAllTokens(final String str, final String separatorChars) 

Source Link

Document

Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators.

Usage

From source file:com.daraf.projectdarafprotocol.clienteapp.ingresos.IngresoFacturaRQ.java

@Override
public void build(String input) {
    if (validate(input)) {
        //            if (input.length() == 1 && input.equals("2")) {
        //                //no se ha registrado correctamente la factura
        ////from  w  w  w. jav  a2 s . c  om
        //            } else 
        if (input.length() < 2000) {
            input = StringUtils.rightPad(input, 2000);
        }
        try {
            String facturaValues[] = MyStringUtil.splitByFixedLengths(input,
                    new int[] { 10, 20, 4, 8, 10, 1948 });
            this.idFactura = facturaValues[0];
            this.identificacion = facturaValues[1];
            this.numeroDetalles = facturaValues[2];
            this.fecha = facturaValues[3];
            this.total = facturaValues[4];
            int numFacturas = Integer.parseInt(this.numeroDetalles);
            String detalleValues[] = StringUtils.splitPreserveAllTokens(facturaValues[5], FIELD_SEPARATOR_CHAR);

            if (detalles == null) {
                detalles = new ArrayList<>();
            } else {
                detalles.clear();
            }
            int stringIndex = 0;

            DetalleFacturaAppRQ f = null;
            for (int i = 0; i < numFacturas; i++) {
                f = new DetalleFacturaAppRQ();
                f.setIdProducto(detalleValues[stringIndex].trim());
                stringIndex++;
                f.setCantidad(detalleValues[stringIndex].trim());
                stringIndex++;
                this.detalles.add(f);
            }
        } catch (Exception ex) {
            Logger.getLogger(IngresoFacturaRQ.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:de.unentscheidbar.validation.builtin.EmailAddressValidator.java

@Override
protected void validateNonEmptyString(ValidationResult problems, String model) {

    String[] nameAndHost = StringUtils.splitPreserveAllTokens(model, '@');
    switch (nameAndHost.length) {
    case 0://from   ww w.j av  a2  s.  c o m
        // String is empty - cannot happen in validateNonEmptyString
        throw new AssertionError();
    case 1:
        problems.add(Id.NO_AT_SYMBOL, model);
        break;
    case 2:
        validateLocalPart(nameAndHost[0], model, problems);
        validateGlobalPart(nameAndHost[1], model, problems);
        break;
    default:
        assert nameAndHost.length > 2;
        problems.add(Id.EMAIL_HAS_MORE_THAN_ONE_AT_SYMBOL, model);
        break;
    }

}

From source file:de.bmarwell.j9kwsolver.util.ResponseUtils.java

/**
 * @param response the response sent by the server.
 * @return the number of credits assigned by the server for solving.
 *//*from  w w  w. j  a  v  a 2  s.c om*/
private static int parseCredits(final String response) {
    int credits = 0;

    if (StringUtils.isEmpty(response)) {
        return credits;
    }

    String[] splitresponse = StringUtils.splitPreserveAllTokens(response, '|');

    if (splitresponse.length != 2) {
        LOG.error("Response doesn't contain two items: {}.", ToStringBuilder.reflectionToString(splitresponse));
        return credits;
    }

    // TODO: Enum for numbered field.
    String stringCredits = splitresponse[1];

    if (NumberUtils.isDigits(stringCredits)) {
        credits = NumberUtils.toInt(stringCredits, 0);
        LOG.debug("Found reward: {} credits.", credits);
    }

    return credits;
}

From source file:com.khartec.waltz.jobs.sample.BusinessRegionProductHierarchyGenerator.java

private static Set<String> readRegions() throws IOException {
    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/regions.csv"));
    Map<String, Map<String, Set<String>>> regionHierarchy = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ","))
            .filter(cells -> notEmpty(cells[0]) && notEmpty(cells[6]) && notEmpty(cells[5]))
            .map(cells -> Tuple.tuple(cells[0], cells[6], cells[5]))
            .collect(groupingBy(t -> t.v3, groupingBy(t -> t.v2, mapping(t -> t.v1, toSet()))));

    return regionHierarchy.keySet();
}

From source file:ch.cyberduck.core.openstack.SwiftAuthenticationService.java

public Set<? extends AuthenticationRequest> getRequest(final Host host, final LoginCallback prompt)
        throws LoginCanceledException {
    final Credentials credentials = host.getCredentials();
    final StringBuilder url = new StringBuilder();
    url.append(host.getProtocol().getScheme().toString()).append("://");
    url.append(host.getHostname());/*from   www .  j  ava2s  .co m*/
    if (!(host.getProtocol().getScheme().getPort() == host.getPort())) {
        url.append(":").append(host.getPort());
    }
    final String context = PathNormalizer.normalize(host.getProtocol().getContext());
    // Custom authentication context
    url.append(context);
    if (host.getProtocol().getDefaultHostname().endsWith("identity.api.rackspacecloud.com")
            || host.getHostname().endsWith("identity.api.rackspacecloud.com")) {
        return Collections.singleton(new Authentication20RAXUsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword(), null));
    }
    final LoginOptions options = new LoginOptions(host.getProtocol()).password(false).anonymous(false)
            .publickey(false);
    if (context.contains("1.0")) {
        return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword()));
    } else if (context.contains("1.1")) {
        return Collections.singleton(new Authentication11UsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword()));
    } else if (context.contains("2.0")) {
        // Prompt for tenant
        final String user;
        final String tenant;
        if (StringUtils.contains(credentials.getUsername(), ':')) {
            final String[] parts = StringUtils.splitPreserveAllTokens(credentials.getUsername(), ':');
            tenant = parts[0];
            user = parts[1];
        } else {
            user = credentials.getUsername();
            tenant = prompt
                    .prompt(host, credentials.getUsername(),
                            LocaleFactory.localizedString("Provide additional login credentials",
                                    "Credentials"),
                            LocaleFactory.localizedString("Tenant Name", "Mosso"),
                            options.usernamePlaceholder(LocaleFactory.localizedString("Tenant Name", "Mosso")))
                    .getUsername();
            // Save tenant in username
            credentials.setUsername(String.format("%s:%s", tenant, credentials.getUsername()));
        }
        final Set<AuthenticationRequest> requests = new LinkedHashSet<AuthenticationRequest>();
        requests.add(new Authentication20UsernamePasswordRequest(URI.create(url.toString()), user,
                credentials.getPassword(), tenant));
        requests.add(new Authentication20UsernamePasswordTenantIdRequest(URI.create(url.toString()), user,
                credentials.getPassword(), tenant));
        requests.add(new Authentication20AccessKeySecretKeyRequest(URI.create(url.toString()), user,
                credentials.getPassword(), tenant));
        return requests;
    } else if (context.contains("3")) {
        // Prompt for project
        final String user;
        final String project;
        final String domain;
        if (StringUtils.contains(credentials.getUsername(), ':')) {
            final String[] parts = StringUtils.splitPreserveAllTokens(credentials.getUsername(), ':');
            if (parts.length == 3) {
                project = parts[0];
                domain = parts[1];
                user = parts[2];
            } else {
                project = parts[0];
                user = parts[1];
                domain = prompt
                        .prompt(host, credentials.getUsername(),
                                LocaleFactory.localizedString("Provide additional login credentials",
                                        "Credentials"),
                                LocaleFactory.localizedString("Project Domain Name", "Mosso"),
                                options.usernamePlaceholder(
                                        LocaleFactory.localizedString("Project Domain Name", "Mosso")))
                        .getUsername();
                // Save project name and domain in username
                credentials.setUsername(String.format("%s:%s:%s", project, domain, credentials.getUsername()));
            }
        } else {
            user = credentials.getUsername();
            final Credentials projectName = prompt.prompt(host, credentials.getUsername(),
                    LocaleFactory.localizedString("Provide additional login credentials", "Credentials"),
                    LocaleFactory.localizedString("Project Name", "Mosso"),
                    options.usernamePlaceholder(LocaleFactory.localizedString("Project Name", "Mosso")));
            if (StringUtils.contains(credentials.getUsername(), ':')) {
                final String[] parts = StringUtils.splitPreserveAllTokens(projectName.getUsername(), ':');
                project = parts[0];
                domain = parts[1];
            } else {
                project = projectName.getUsername();
                domain = prompt
                        .prompt(host, credentials.getUsername(),
                                LocaleFactory.localizedString("Provide additional login credentials",
                                        "Credentials"),
                                LocaleFactory.localizedString("Project Domain Name", "Mosso"),
                                options.usernamePlaceholder(
                                        LocaleFactory.localizedString("Project Domain Name", "Mosso")))
                        .getUsername();
            }
            // Save project name and domain in username
            credentials.setUsername(String.format("%s:%s:%s", project, domain, credentials.getUsername()));
        }
        final Set<AuthenticationRequest> requests = new LinkedHashSet<AuthenticationRequest>();
        requests.add(new Authentication3UsernamePasswordProjectRequest(URI.create(url.toString()), user,
                credentials.getPassword(), project, domain));
        return requests;
    } else {
        log.warn(String.format("Unknown context version in %s. Default to v1 authentication.", context));
        // Default to 1.0
        return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword()));
    }
}

From source file:com.espe.distribuidas.pmaldito.servidorbdd.operaciones.Consultar.java

/**
 * Reconoce los campos regulares de la tabla detalle
 *
 * @param tabla//w w w .  j  a  va  2  s  .c o  m
 * @param numColumna
 * @param valorColumna
 * @return
 */
public ArrayList campoRegularFact(String tabla, Integer numColumna, String valorColumna) {
    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
    ArrayList<String> datosRegistro = new ArrayList<>();
    String string;

    try {
        FileReader fr = new FileReader(tabla);
        BufferedReader br = new BufferedReader(fr);
        while ((string = br.readLine()) != null) {
            if (string.length() > 0) {
                String registro[] = StringUtils.splitPreserveAllTokens(string, "|");
                if (registro[numColumna].equalsIgnoreCase(valorColumna)) {
                    datosRegistro.addAll(Arrays.asList(registro));
                    //break;    
                }
            } else {
                break;
            }
        }
        br.close();
    } catch (FileNotFoundException e) {
        System.err.println(e);
    } catch (IOException e1) {
        System.err.println(e1);
    }
    return datosRegistro;
}

From source file:Exporters.ExportToWord.java

private void replaceParagraph(String placeholder, String textToAdd, WordprocessingMLPackage template,
        ContentAccessor addTo) {//from w ww.  ja v  a 2  s .  c o m
    // 1. get the paragraph
    List<Object> paragraphs = getAllElementFromObject(template.getMainDocumentPart(), P.class);

    P toReplace = null;
    for (Object p : paragraphs) {
        List<Object> texts = getAllElementFromObject(p, Text.class);
        for (Object t : texts) {
            Text content = (Text) t;
            if (content.getValue().equals(placeholder)) {
                toReplace = (P) p;
                break;
            }
        }
    }

    // we now have the paragraph that contains our placeholder: toReplace
    // 2. split into seperate lines
    String as[] = StringUtils.splitPreserveAllTokens(textToAdd, '\n');

    for (int i = 0; i < as.length; i++) {
        String ptext = as[i];

        // 3. copy the found paragraph to keep styling correct
        P copy = (P) XmlUtils.deepCopy(toReplace);

        // replace the text elements from the copy
        List texts = getAllElementFromObject(copy, Text.class);
        if (texts.size() > 0) {
            Text textToReplace = (Text) texts.get(0);
            textToReplace.setValue(ptext);
        }

        // add the paragraph to the document
        addTo.getContent().add(copy);
    }

    // 4. remove the original one
    ((ContentAccessor) toReplace.getParent()).getContent().remove(toReplace);

}

From source file:dk.dma.ais.sentence.CommentBlockLine.java

public void parse(String line) throws CommentBlockException {
    parameterMap = new HashMap<>();
    int start = -1;
    int end = -1;
    checksum = 0;/*from   w  w  w. j  av  a2 s.c  o m*/
    // Find start, end, checksum and fields
    for (int i = 0; i < line.length(); i++) {
        char c = line.charAt(i);
        if (c == '*') {
            end = i;
            break;
        }
        if (start >= 0) {
            checksum ^= c;
        }
        if (c == '\\') {
            if (start < 0) {
                start = i;
            }
        }
    }
    if (start < 0) {
        throw new CommentBlockException("No comment block found");
    }
    if (end < 0) {
        throw new CommentBlockException("Malformed comment block");
    }

    // Check checksum
    try {
        String given = line.substring(end + 1, end + 3);
        String calculated = Integer.toString(checksum, 16).toUpperCase();
        if (checksum != Integer.parseInt(given, 16)) {
            throw new CommentBlockException("Wrong checksum " + given + " calculated " + calculated);
        }
    } catch (IndexOutOfBoundsException e) {
        throw new CommentBlockException("Missing checksum in comment block");
    } catch (NumberFormatException e) {
        throw new CommentBlockException("Invalid checksum");
    }

    // Split into fields
    StringBuilder tmpStr = new StringBuilder(16);
    List<String> fields = new ArrayList<>();
    for (int i = start + 1; i < end; i++) {
        if (line.charAt(i) == ',' || line.charAt(i) == ':') {
            fields.add(tmpStr.toString());
            tmpStr.setLength(0);
        } else {
            tmpStr.append(line.charAt(i));
        }
    }
    if (start + 1 < end) {
        fields.add(tmpStr.toString());
    }

    if (fields.size() % 2 != 0) {
        throw new CommentBlockException("Malformed comment block");
    }

    for (int i = 0; i < fields.size(); i += 2) {
        String parameterCode = fields.get(i);
        String value = fields.get(i + 1);

        // Check for grouping parameter code
        int groupCharIndex;
        if ((groupCharIndex = parameterCode.indexOf('G')) >= 0) {
            try {
                lineNumber = Integer.parseInt(parameterCode.substring(0, groupCharIndex));
                totalLines = Integer
                        .parseInt(parameterCode.substring(groupCharIndex + 1, parameterCode.length()));
            } catch (NumberFormatException e) {
                throw new CommentBlockException("Invalid group tag: " + parameterCode);
            }
            groupId = value;
        }
        // Check for tag block group
        if (parameterCode.equals("g")) {
            String[] tagGroupParts = StringUtils.splitPreserveAllTokens(value, '-');
            if (tagGroupParts.length != 3) {
                throw new CommentBlockException("Invalid TAG block g parameter: " + value);
            }
            try {
                lineNumber = Integer.parseInt(tagGroupParts[0]);
                totalLines = Integer.parseInt(tagGroupParts[1]);
            } catch (NumberFormatException e) {
                throw new CommentBlockException("Invalid TAG block g parameter: " + value);
            }
            groupId = tagGroupParts[2];
        }
        parameterMap.put(parameterCode, value);
    }
}

From source file:de.unentscheidbar.validation.builtin.Ipv4AddressValidator.java

@Override
protected void validateNonEmptyString(ValidationResult result, String s) {

    String[] parts = StringUtils.splitPreserveAllTokens(s, '.');

    /*/*from  ww  w .ja v a 2 s . c o m*/
     * Number of segments ok?
     */
    if (parts.length < IPV4_SEGMENT_COUNT) {
        result.add(Id.TOO_FEW_SEGMENTS, s, parts.length);
        return;
    } else if (parts.length > IPV4_SEGMENT_COUNT) {
        result.add(Id.TOO_MANY_SEGMENTS, s, parts.length);
        return;
    }
    assert parts.length == IPV4_SEGMENT_COUNT;

    /* Handle bitmask modifier, if present (such as 10.37.0.0/16) */
    String maskStr = "";
    int maxIdx = parts.length - 1;
    int slashIndex = parts[maxIdx].lastIndexOf('/');
    if (slashIndex != -1) {
        maskStr = StringUtils.substring(parts[maxIdx], slashIndex + 1);
        parts[maxIdx] = parts[maxIdx].substring(0, slashIndex);
    }

    Integer bits = maskStr.isEmpty() ? Integer.valueOf(BITS_PER_IPV4) : Ints.tryParse(maskStr);
    if (bits == null || bits < minBits || bits > maxBits) {
        result.add(Id.BAD_SUBNET_MASK, bits == null ? maskStr : bits.toString(), minBits, maxBits);
        return;
    }
    for (int i = 0; i < parts.length; i++) {
        if (!BYTE_RANGE_VALIDATOR.wouldAcceptWithout(Severity.ERROR, parts[i])) {
            result.add(Id.SEGMENT_INVALID, i, parts[i]);
            break;
        }
    }
}

From source file:com.khartec.waltz.jobs.sample.BusinessRegionProductHierarchyGenerator.java

private static Set<String> readProducts() throws IOException {
    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/products-flat.csv"));
    Set<String> productHierarchy = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ",")).filter(cells -> notEmpty(cells[0]))
            .map(cells -> cells[0]).collect(toSet());

    return productHierarchy;
}