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

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

Introduction

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

Prototype

public static String substring(final String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start/end n characters from the end of the String.

The returned substring starts with the character in the start position and ends before the end position.

Usage

From source file:ch.cyberduck.core.Permission.java

public String getSymbol() {
    final StringBuilder symbolic = new StringBuilder();
    symbolic.append(setuid ? user.implies(Action.execute) ? StringUtils.substring(user.symbolic, 0, 2) + "s"
            : StringUtils.substring(user.symbolic, 0, 2) + "S" : user.symbolic);
    symbolic.append(setgid ? group.implies(Action.execute) ? StringUtils.substring(group.symbolic, 0, 2) + "s"
            : StringUtils.substring(group.symbolic, 0, 2) + "S" : group.symbolic);
    symbolic.append(sticky ? other.implies(Action.execute) ? StringUtils.substring(other.symbolic, 0, 2) + "t"
            : StringUtils.substring(other.symbolic, 0, 2) + "T" : other.symbolic);
    return symbolic.toString();
}

From source file:com.dgtlrepublic.anitomyj.ParserHelper.java

/**
 * Builds an element an adds it to the internal element list.
 *
 * @param category       the element category
 * @param keepDelimiters delimiters to keep in the element content.
 * @param tokens         the tokens used to create the element content value.
 *///from  w  w  w .j  av a2  s  .  c  o  m
public void buildElement(ElementCategory category, boolean keepDelimiters, List<Token> tokens) {
    StringBuilder element = new StringBuilder();

    for (ListIterator<Token> iter = tokens.listIterator(); iter.hasNext();) {
        Token token = iter.next();
        switch (token.getCategory()) {
        case kUnknown:
            element.append(token.getContent());
            token.setCategory(kIdentifier);
            break;
        case kBracket:
            element.append(token.getContent());
            break;
        case kDelimiter: {
            String delimiter = "";
            if (StringUtils.isNotEmpty(token.getContent())) {
                delimiter = StringUtils.substring(token.getContent(), 0, 1);
            }

            if (keepDelimiters) {
                element.append(delimiter);
            } else if (iter.hasPrevious() && iter.hasNext()) {
                switch (delimiter) {
                case ",":
                case "&":
                    element.append(delimiter);
                    break;
                default:
                    element.append(' ');
                    break;
                }
            }
            break;
        }
        }
    }

    if (!keepDelimiters) {
        element = new StringBuilder(StringHelper.trimAny(element.toString(), kDashesWithSpace));
    }

    if (!element.toString().isEmpty()) {
        parser.getElements().add(new Element(category, element.toString()));
    }
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseMetadataDialog.java

/**
 * Generates a SELECT query from a map of table names with column names.
 * /*from w  w  w.  j av a  2s.  c o m*/
 * @param metaData
 *            A map of String table names to List<String> column names
 * @return The generated SELECT query
 */
@SuppressWarnings("unchecked")
public String createQueryFromMetaData(Map<String, Object> metaData) {
    if (metaData == null) {
        return null;
    }

    Set<String> tables = new LinkedHashSet<String>();
    Set<String> aliases = new LinkedHashSet<String>();
    Set<String> columns = new LinkedHashSet<String>();

    for (Entry<String, Object> entry : metaData.entrySet()) {
        String table = entry.getKey().trim();

        for (String column : (List<String>) entry.getValue()) {
            column = column.trim();
            String alias = table + "_" + column;

            if (alias.length() > MAX_ALIAS_LENGTH) {
                alias = column;
            }

            if (alias.length() > MAX_ALIAS_LENGTH) {
                alias = StringUtils.substring(alias, 0, MAX_ALIAS_LENGTH);
            }

            int i = 2;
            String originalAlias = alias;

            /*
             * If the column alias already exists, then append a counter to the end of the
             * alias, keeping it under MAX_ALIAS_LENGTH, until we have a new unique alias.
             */
            while (aliases.contains(alias)) {
                alias = originalAlias + i;

                if (alias.length() > MAX_ALIAS_LENGTH) {
                    alias = StringUtils.substring(originalAlias, 0,
                            MAX_ALIAS_LENGTH - String.valueOf(i).length()) + i;
                }

                i++;
            }

            tables.add(table);
            aliases.add(alias);
            columns.add(table + "." + column + " AS " + alias);
        }
    }

    return "SELECT " + StringUtils.join(columns, ", ") + "\nFROM " + StringUtils.join(tables, ", ");
}

From source file:io.lavagna.service.NotificationService.java

private void sendEmailToUser(User user, List<Event> events, MailConfig mailConfig)
        throws MustacheException, IOException {

    Set<Integer> userIds = new HashSet<>();
    userIds.add(user.getId());// w  w  w  . j  a  v a 2  s . c  o m
    Set<Integer> cardIds = new HashSet<>();
    Set<Integer> cardDataIds = new HashSet<>();
    Set<Integer> columnIds = new HashSet<>();

    for (Event e : events) {
        cardIds.add(e.getCardId());
        userIds.add(e.getUserId());

        addIfNotNull(userIds, e.getValueUser());
        addIfNotNull(cardIds, e.getValueCard());

        addIfNotNull(cardDataIds, e.getDataId());
        addIfNotNull(cardDataIds, e.getPreviousDataId());

        addIfNotNull(columnIds, e.getColumnId());
        addIfNotNull(columnIds, e.getPreviousColumnId());
    }

    final ImmutableTriple<String, String, String> subjectAndText = composeEmailForUser(
            new EventsContext(events, userRepository.findByIds(userIds), cardRepository.findAllByIds(cardIds),
                    cardDataRepository.findDataByIds(cardDataIds), boardColumnRepository.findByIds(columnIds)));

    mailConfig.send(user.getEmail(), StringUtils.substring("Lavagna: " + subjectAndText.getLeft(), 0, 78),
            subjectAndText.getMiddle(), subjectAndText.getRight());
}

From source file:com.github.ferstl.depgraph.AbstractGraphMojo.java

private StyleResource getCustomStyleResource() throws MojoFailureException {
    StyleResource customStyleResource;//  www. j a v  a  2s  . c o m
    if (StringUtils.startsWith(this.customStyleConfiguration, "classpath:")) {
        String resourceName = StringUtils.substring(this.customStyleConfiguration, 10,
                this.customStyleConfiguration.length());
        customStyleResource = new ClasspathStyleResource(resourceName, getClass().getClassLoader());
    } else {
        customStyleResource = new FileSystemStyleResource(Paths.get(this.customStyleConfiguration));
    }

    if (!customStyleResource.exists()) {
        throw new MojoFailureException(
                "Custom configuration '" + this.customStyleConfiguration + "' does not exist.");
    }

    return customStyleResource;
}

From source file:com.gargoylesoftware.htmlunit.html.XmlSerializer.java

/**
 * Computes the best file to save the response to the given URL.
 * @param url the requested URL// ww w . j a  v  a 2  s  .  c  om
 * @param extension the preferred extension
 * @return the file to create
 * @throws IOException if a problem occurs creating the file
 */
private File createFile(final String url, final String extension) throws IOException {
    String name = url.replaceFirst("/$", "");
    name = CREATE_FILE_PATTERN.matcher(name).replaceAll("");
    name = StringUtils.substringBefore(name, "?"); // remove query
    name = StringUtils.substringBefore(name, ";"); // remove additional info
    name = StringUtils.substring(name, 0, 30); // many file systems have a limit at 255, let's limit it
    name = com.gargoylesoftware.htmlunit.util.StringUtils.sanitizeForFileName(name);
    if (!name.endsWith(extension)) {
        name += extension;
    }
    int counter = 0;
    while (true) {
        final String fileName;
        if (counter != 0) {
            fileName = StringUtils.substringBeforeLast(name, ".") + "_" + counter + "."
                    + StringUtils.substringAfterLast(name, ".");
        } else {
            fileName = name;
        }
        outputDir_.mkdirs();
        final File f = new File(outputDir_, fileName);
        if (f.createNewFile()) {
            return f;
        }
        counter++;
    }
}

From source file:com.gargoylesoftware.htmlunit.util.DebuggingWebConnection.java

/**
 * Computes the best file to save the response to the given URL.
 * @param url the requested URL//  w w w. j  a v a  2s  .c  om
 * @param extension the preferred extension
 * @return the file to create
 * @throws IOException if a problem occurs creating the file
 */
private File createFile(final URL url, final String extension) throws IOException {
    String name = url.getPath().replaceFirst("/$", "").replaceAll(".*/", "");
    name = StringUtils.substringBefore(name, "?"); // remove query
    name = StringUtils.substringBefore(name, ";"); // remove additional info
    name = StringUtils.substring(name, 0, 30); // avoid exceptions due to too long file names
    name = com.gargoylesoftware.htmlunit.util.StringUtils.sanitizeForFileName(name);
    if (!name.endsWith(extension)) {
        name += extension;
    }
    int counter = 0;
    while (true) {
        final String fileName;
        if (counter != 0) {
            fileName = StringUtils.substringBeforeLast(name, ".") + "_" + counter + "."
                    + StringUtils.substringAfterLast(name, ".");
        } else {
            fileName = name;
        }
        final File f = new File(reportFolder_, fileName);
        if (f.createNewFile()) {
            return f;
        }
        counter++;
    }
}

From source file:hu.bme.mit.sette.tools.spf.SpfParser.java

@Override
protected void parseSnippet(Snippet snippet, SnippetInputsXml inputsXml) throws Exception {
    File outputFile = RunnerProjectUtils.getSnippetOutputFile(getRunnerProjectSettings(), snippet);
    File errorFile = RunnerProjectUtils.getSnippetErrorFile(getRunnerProjectSettings(), snippet);

    if (errorFile.exists()) {

        // TODO make this section simple and clear

        List<String> lines = FileUtils.readLines(errorFile);

        String firstLine = lines.get(0);

        if (firstLine.startsWith("java.lang.RuntimeException: ## Error: Operation not supported!")) {
            inputsXml.setResultType(ResultType.NA);
        } else if (firstLine.startsWith("java.lang.NullPointerException")) {
            inputsXml.setResultType(ResultType.EX);
        } else if (firstLine
                .startsWith("java.lang.RuntimeException: ## Error: symbolic log10 not implemented")) {
            inputsXml.setResultType(ResultType.NA);
        } else if (firstLine.startsWith("***********Warning: everything false")) {
            // TODO enhance
            // now skip
        } else if (snippet.getMethod().toString().contains("_Constants")
                || snippet.getMethod().toString().contains(".always()")) {
            // TODO JPF/SPF compilation differences between javac and ecj:
            // https://groups.google.com/forum/#!topic/java-pathfinder/jhOkvLx-SKE
            // now just accept
        } else {//from   ww w  .j  a v  a  2  s.  c  o m
            // TODO error handling

            // this is debug (only if unhandled error)
            System.err.println("=============================");
            System.err.println(snippet.getMethod());
            System.err.println("=============================");

            for (String line : lines) {
                System.err.println(line);
            }
            System.err.println("=============================");

            // TODO error handling
            throw new RuntimeException("PARSER PROBLEM, UNHANDLED ERROR");
        }
    }

    if (inputsXml.getResultType() == null) {
        // TODO enhance
        inputsXml.setResultType(ResultType.S);

        if (snippet.getMethod().toString().contains("_Constants")
                || snippet.getMethod().toString().contains(".always()")) {
            // TODO JPF/SPF compilation differences between javac and ecj:
            // https://groups.google.com/forum/#!topic/java-pathfinder/jhOkvLx-SKE
            // now just accept

            // no inputs for constant tests, just call them once
            inputsXml.getGeneratedInputs().add(new InputElement());
        } else {
            LineIterator lines = FileUtils.lineIterator(outputFile);

            // find input lines

            List<String> inputLines = new ArrayList<>();
            boolean shouldCollect = false;
            while (lines.hasNext()) {
                String line = lines.next();
                if (line.trim()
                        .equals("====================================================== Method Summaries")) {
                    shouldCollect = true;
                } else if (shouldCollect) {
                    if (line.startsWith("======================================================")) {
                        // start of next section
                        shouldCollect = false;
                        break;
                    } else {
                        if (!StringUtils.isBlank(line)) {
                            inputLines.add(line.trim());
                        }
                    }
                }
            }

            // close iterator
            lines.close();

            // remove duplicates
            inputLines = new ArrayList<>(new LinkedHashSet<>(inputLines));

            System.out.println(snippet.getMethod());

            String firstLine = inputLines.get(0);
            assert (firstLine.startsWith("Inputs: "));
            firstLine = firstLine.substring(7).trim();
            String[] parameterStrings = StringUtils.split(firstLine, ',');
            ParameterType[] parameterTypes = new ParameterType[parameterStrings.length];

            if (inputLines.size() == 2 && inputLines.get(1).startsWith("No path conditions for")) {
                InputElement input = new InputElement();
                for (int i = 0; i < parameterStrings.length; i++) {
                    // no path conditions, only considering the "default"
                    // inputs
                    Class<?> type = snippet.getMethod().getParameterTypes()[i];
                    parameterTypes[i] = getParameterType(type);
                    input.getParameters()
                            .add(new ParameterElement(parameterTypes[i], getDefaultParameterString(type)));
                }
                inputsXml.getGeneratedInputs().add(input);
            } else {
                // parse parameter types

                Class<?>[] paramsJavaClass = snippet.getMethod().getParameterTypes();

                for (int i = 0; i < parameterStrings.length; i++) {
                    String parameterString = parameterStrings[i];
                    Class<?> pjc = ClassUtils.primitiveToWrapper(paramsJavaClass[i]);

                    if (parameterString.endsWith("SYMINT")) {
                        if (pjc == Boolean.class) {
                            parameterTypes[i] = ParameterType.BOOLEAN;
                        } else if (pjc == Byte.class) {
                            parameterTypes[i] = ParameterType.BYTE;
                        } else if (pjc == Short.class) {
                            parameterTypes[i] = ParameterType.SHORT;
                        } else if (pjc == Integer.class) {
                            parameterTypes[i] = ParameterType.INT;
                        } else if (pjc == Long.class) {
                            parameterTypes[i] = ParameterType.LONG;
                        } else {
                            // int for something else
                            parameterTypes[i] = ParameterType.INT;
                        }
                    } else if (parameterString.endsWith("SYMREAL")) {
                        if (pjc == Float.class) {
                            parameterTypes[i] = ParameterType.FLOAT;
                        } else if (pjc == Float.class) {
                            parameterTypes[i] = ParameterType.DOUBLE;
                        } else {
                            // int for something else
                            parameterTypes[i] = ParameterType.DOUBLE;
                        }
                    } else if (parameterString.endsWith("SYMSTRING")) {
                        parameterTypes[i] = ParameterType.EXPRESSION;
                    } else {
                        // TODO error handling
                        // int for something else
                        System.err.println(parameterString);
                        throw new RuntimeException("PARSER PROBLEM");
                    }
                }

                // example
                // inheritsAPIGuessTwoPrimitives(11,-2147483648(don't care))
                // -->
                // "java.lang.IllegalArgumentException..."
                // inheritsAPIGuessTwoPrimitives(9,11) -->
                // "java.lang.IllegalArgumentException..."
                // inheritsAPIGuessTwoPrimitives(7,9) -->
                // "java.lang.RuntimeException: Out of range..."
                // inheritsAPIGuessTwoPrimitives(4,1) --> Return Value: 1
                // inheritsAPIGuessTwoPrimitives(0,0) --> Return Value: 0
                // inheritsAPIGuessTwoPrimitives(9,-88) -->
                // "java.lang.IllegalArgumentException..."
                // inheritsAPIGuessTwoPrimitives(-88,-2147483648(don't
                // care))
                // --> "java.lang.IllegalArgumentException..."

                String ps = String.format("^%s\\((.*)\\)\\s+-->\\s+(.*)$", snippet.getMethod().getName());

                // ps = String.format("^%s(.*)\\s+-->\\s+(.*)$",
                // snippet.getMethod()
                // .getName());
                ps = String.format("^(%s\\.)?%s(.*)\\s+-->\\s+(.*)$",
                        snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName());
                Pattern p = Pattern.compile(ps);

                // parse inputs
                int i = -1;
                for (String line : inputLines) {
                    i++;

                    if (i == 0) {
                        // first line
                        continue;
                    } else if (StringUtils.isEmpty(line)) {
                        continue;
                    }

                    Matcher m = p.matcher(line);

                    if (m.matches()) {
                        String paramsString = StringUtils.substring(m.group(2).trim(), 1, -1);
                        String resultString = m.group(3).trim();

                        paramsString = StringUtils.replace(paramsString, "(don't care)", "");

                        String[] paramsStrings = StringUtils.split(paramsString, ',');

                        InputElement input = new InputElement();

                        // if index error -> lesser inputs than parameters
                        for (int j = 0; j < parameterTypes.length; j++) {
                            if (parameterTypes[j] == ParameterType.BOOLEAN
                                    && paramsStrings[j].contains("-2147483648")) {
                                // don't care -> 0
                                paramsStrings[j] = "false";
                            }

                            ParameterElement pe = new ParameterElement(parameterTypes[j],
                                    paramsStrings[j].trim());

                            try {
                                // just check the type format
                                pe.validate();
                            } catch (Exception e) {
                                // TODO error handling
                                System.out.println(parameterTypes[j]);
                                System.out.println(paramsStrings[j]);
                                System.out.println(pe.getType());
                                System.out.println(pe.getValue());
                                e.printStackTrace();

                                System.err.println("=============================");
                                System.err.println(snippet.getMethod());
                                System.err.println("=============================");
                                for (String lll : inputLines) {
                                    System.err.println(lll);
                                }
                                System.err.println("=============================");

                                System.exit(-1);
                            }

                            input.getParameters().add(pe);
                        }

                        if (resultString.startsWith("Return Value:")) {
                            // has retval, nothing to do
                        } else {
                            // exception; example (" is present inside the
                            // string!!!):
                            // "java.lang.ArithmeticException: div by 0..."
                            // "java.lang.IndexOutOfBoundsException: Index: 1, Size: 5..."

                            int pos = resultString.indexOf(':');
                            if (pos < 0) {
                                // not found :, search for ...
                                pos = resultString.indexOf("...");
                            }

                            String ex = resultString.substring(1, pos);
                            input.setExpected(ex);

                            // System.err.println(resultString);
                            // System.err.println(ex);
                            // // input.setExpected(expected);
                        }

                        inputsXml.getGeneratedInputs().add(input);
                    } else {
                        System.err.println("NO MATCH");
                        System.err.println(ps);
                        System.err.println(line);
                        throw new Exception("NO MATCH: " + line);
                    }
                }
            }
        }
        inputsXml.validate();
    }
}

From source file:com.zhumeng.dream.orm.PropertyFilter.java

private void init(final String filterName, final Object value, String propertyNameStr) {
    String firstPart = StringUtils.substringBefore(filterName, "_");

    String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);

    String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());

    try {//from  w w w.j a v a 2s.  com
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    // String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    Assert.isTrue(StringUtils.isNotBlank(propertyNameStr),
            "filter??" + filterName + ",??.");

    propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR);

}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Write the Record object to the output files.
 *
 * @param record - the <code>Record</code> object
 *///  ww w. j  av a 2s  . c o m
public final void write(final Record record) {
    /* get control field 001 */
    String ppn = record.getControlNumber();

    if (ppn5) {
        // Nur Daten mit 5 vor der PPN-Prfziffer ausgeben;
        // das reduziert den Datenumfang auf ca. 10 %
        if (!StringUtils.substring(ppn, -2, -1).equals("5")) {
            return;
        }
    }

    try {
        validateIsbn10(ppn);
        bibWriter.write(withoutCheckdigit(ppn));
        bibWriter.write("\t");
        toXml(ppn, record);
        bibWriter.write("\n");
    } catch (Exception e) {
        throw new MarcException("Control field 001 (PPN): " + ppn, e);
    }
}