Example usage for org.apache.commons.lang StringUtils removeStart

List of usage examples for org.apache.commons.lang StringUtils removeStart

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils removeStart.

Prototype

public static String removeStart(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the begining of a source string, otherwise returns the source string.

Usage

From source file:com.microsoft.alm.plugin.idea.common.utils.VcsHelper.java

public static List<Integer> getWorkItemIdsFromMessage(final String commitMessage) {
    logger.info("getWorkItemIdsFromMessage: commitMessage = " + commitMessage);
    final List<Integer> workItems = new ArrayList<Integer>(10);
    // We cache the compiled pattern for later use
    if (pattern == null) {
        pattern = Pattern.compile("#(\\d+)");
    }/*w  w  w. jav  a  2s . com*/
    final Matcher matcher = pattern.matcher(commitMessage);
    // finds all matches in the string where it is a # followed by an int
    while (matcher.find()) {
        try {
            final int workItemId = Integer.parseInt(StringUtils.removeStart(matcher.group(), "#"));
            workItems.add(workItemId);
        } catch (NumberFormatException e) {
            logger.warn("Error converting work item id into integer: " + matcher.group(1));
        }
    }
    return workItems;
}

From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractMessageWrappingController.java

/**
 * Populate directory.//from  w w  w.  ja v  a 2s.  c o m
 * 
 * @param <T>
 *            the generic type
 * @param result
 *            the result
 * @param page
 *            the page
 * @param httpServletRequest
 *            the http servlet request
 * @param directoryClazz
 *            the directory clazz
 * @return the t
 */
@SuppressWarnings("unchecked")
protected <T extends Directory> T populateDirectory(DirectoryResult<?> result, Page page,
        HttpServletRequest httpServletRequest, Class<T> directoryClazz) {

    T directory;

    try {
        directory = directoryClazz.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (result == null || result.getEntries() == null) {
        result = new DirectoryResult<Void>(new ArrayList<Void>(), true);
    }

    this.setDirectoryEntries(directory, result.getEntries());

    boolean atEnd = result.isAtEnd();
    boolean isComplete = atEnd && (page.getPage() == 0);

    String urlRoot = this.serverContext.getServerRootWithAppName();

    if (!urlRoot.endsWith("/")) {
        urlRoot = urlRoot + "/";
    }

    String pathInfo = httpServletRequest.getServletPath();

    String url = urlRoot + StringUtils.removeStart(pathInfo, "/");

    if (isComplete) {
        directory.setComplete(CompleteDirectory.COMPLETE);
    } else {
        directory.setComplete(CompleteDirectory.PARTIAL);

        if (!result.isAtEnd()) {
            directory.setNext(url + getParametersString(httpServletRequest.getParameterMap(),
                    page.getPage() + 1, page.getMaxToReturn()));
        }

        if (page.getPage() > 0) {
            directory.setPrev(url + getParametersString(httpServletRequest.getParameterMap(),
                    page.getPage() - 1, page.getMaxToReturn()));
        }
    }

    directory.setNumEntries((long) result.getEntries().size());

    return this.wrapMessage(directory, httpServletRequest);
}

From source file:com.ewcms.core.site.model.Channel.java

private String removeStartAndEndPathSeparator(final String dir) {
    String path = dir;// www . ja  v  a 2 s .co  m
    path = StringUtils.removeStart(path, PATH_SEPARATOR);
    path = StringUtils.removeEnd(path, PATH_SEPARATOR);

    return path;
}

From source file:info.magnolia.freemarker.FreemarkerServletContextWrapper.java

/**
 * Clean url and get the file./*from  www.java  2s  .  co m*/
 * @param url url to cleanup
 * @return file to url
 */
private File sanitizeToFile(URL url) {
    try {
        String fileUrl = url.getFile();
        // needed because somehow the URLClassLoader has encoded URLs, and getFile does not decode them.
        fileUrl = URLDecoder.decode(fileUrl, "UTF-8");
        // needed for Resin - for some reason, its URLs are formed as jar:file:/absolutepath/foo/bar.jar instead of
        // using the :///abs.. notation
        fileUrl = StringUtils.removeStart(fileUrl, "file:");
        fileUrl = StringUtils.removeEnd(fileUrl, "!/");
        return new File(fileUrl);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:info.magnolia.cms.module.ModuleUtil.java

/**
 * Extracts files of a jar and stores them in the magnolia file structure
 * @param names a list of resource names
 * @param prefix prefix which is not part of the magolia path (in common 'mgnl-files')
 * @throws Exception io exception//from w  ww. j a v a  2 s .  c o  m
 */
public static void installFiles(String[] names, String prefix) throws Exception {

    String root = null;
    // Try to get root
    try {
        File f = new File(SystemProperty.getProperty(SystemProperty.MAGNOLIA_APP_ROOTDIR));
        if (f.isDirectory()) {
            root = f.getAbsolutePath();
        }
    } catch (Exception e) {
        // nothing
    }

    if (root == null) {
        throw new Exception("Invalid magnolia " + SystemProperty.MAGNOLIA_APP_ROOTDIR + " path"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Loop throgh files and check writeable
    String error = StringUtils.EMPTY;
    for (int j = 0; j < names.length; j++) {
        String name = names[j];

        InputStream resourceStream = ClasspathResourcesUtil.getStream(name, false);

        File targetFile = new File(Path.getAbsoluteFileSystemPath(StringUtils.removeStart(name, prefix)));

        String s = StringUtils.EMPTY;
        if (!targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs()) {
            s = "Can't create directories for " + targetFile.getAbsolutePath(); //$NON-NLS-1$
        } else if (!targetFile.getParentFile().canWrite()) {
            s = "Can't write to " + targetFile.getAbsolutePath(); //$NON-NLS-1$
        }
        if (s.length() > 0) {
            if (error.length() > 0) {
                error += "\r\n"; //$NON-NLS-1$
            }
            error += s;
        }

        OutputStream out = new FileOutputStream(targetFile);
        IOUtils.copy(resourceStream, out);

        IOUtils.closeQuietly(resourceStream);
        IOUtils.closeQuietly(out);
    }

    if (error.length() > 0) {
        throw new Exception("Errors while installing files: " + error); //$NON-NLS-1$
    }

}

From source file:msi.gama.util.GAML.java

public static String getDocumentationOn2(final String query) {
    final String keyword = StringUtils.removeEnd(StringUtils.removeStart(query.trim(), "#"), ":");
    final THashMap<String, String> results = new THashMap<>();
    // Statements
    final SymbolProto p = DescriptionFactory.getStatementProto(keyword);
    if (p != null) {
        results.put("Statement", p.getDocumentation());
    }//from  w ww. ja v  a 2s  .  co  m
    DescriptionFactory.visitStatementProtos((name, proto) -> {
        if (proto.getFacet(keyword) != null) {
            results.put("Facet of statement " + name, proto.getFacet(keyword).getDocumentation());
        }
    });
    final Set<String> types = new HashSet<>();
    final String[] facetDoc = { "" };
    DescriptionFactory.visitVarProtos((name, proto) -> {
        if (proto.getFacet(keyword) != null && types.size() < 4) {
            if (!Types.get(name).isAgentType() || name.equals(IKeyword.AGENT)) {
                types.add(name);
            }
            facetDoc[0] = proto.getFacet(keyword).getDocumentation();
        }
    });
    if (!types.isEmpty()) {
        results.put("Facet of attribute declarations with types " + types + (types.size() == 4 ? " ..." : ""),
                facetDoc[0]);
    }
    // Operators
    final THashMap<Signature, OperatorProto> ops = IExpressionCompiler.OPERATORS.get(keyword);
    if (ops != null) {
        ops.forEachEntry((sig, proto) -> {
            results.put("Operator on " + sig.toString(), proto.getDocumentation());
            return true;
        });
    }
    // Built-in skills
    final SkillDescription sd = GamaSkillRegistry.INSTANCE.get(keyword);
    if (sd != null) {
        results.put("Skill", sd.getDocumentation());
    }
    GamaSkillRegistry.INSTANCE.visitSkills(desc -> {
        final SkillDescription sd1 = (SkillDescription) desc;
        final VariableDescription var = sd1.getAttribute(keyword);
        if (var != null) {
            results.put("Attribute of skill " + desc.getName(), var.getDocumentation());
        }
        final ActionDescription action = sd1.getAction(keyword);
        if (action != null) {
            results.put("Primitive of skill " + desc.getName(),
                    action.getDocumentation().isEmpty() ? "" : ":" + action.getDocumentation());
        }
        return true;
    });
    // Types
    final IType<?> t = Types.builtInTypes.containsType(keyword) ? Types.get(keyword) : null;
    if (t != null) {
        String tt = t.getDocumentation();
        if (tt == null) {
            tt = "type " + keyword;
        }
        results.put("Type", tt);
    }
    // Built-in species
    for (final TypeDescription td : Types.getBuiltInSpecies()) {
        if (td.getName().equals(keyword)) {
            results.put("Built-in species", ((SpeciesDescription) td).getDocumentationWithoutMeta());
        }
        final IDescription var = td.getOwnAttribute(keyword);
        if (var != null) {
            results.put("Attribute of built-in species " + td.getName(), var.getDocumentation());
        }
        final ActionDescription action = td.getOwnAction(keyword);
        if (action != null) {
            results.put("Primitive of built-in species " + td.getName(),
                    action.getDocumentation().isEmpty() ? "" : ":" + action.getDocumentation());
        }
    }
    // Constants
    final UnitConstantExpression exp = IUnits.UNITS_EXPR.get(keyword);
    if (exp != null) {
        results.put("Constant", exp.getDocumentation());
    }
    if (results.isEmpty()) {
        return "No result found";
    }
    final StringBuilder sb = new StringBuilder();
    final int max = results.keySet().stream().mapToInt(each -> each.length()).max().getAsInt();
    final String separator = StringUtils.repeat("", max + 6).concat(Strings.LN);
    results.forEachEntry((sig, doc) -> {
        sb.append("").append(separator).append("|| ");
        sb.append(StringUtils.rightPad(sig, max));
        sb.append(" ||").append(Strings.LN).append(separator);
        sb.append(toText(doc)).append(Strings.LN);
        return true;
    });

    return sb.toString();

    //
}

From source file:com.fiveamsolutions.nci.commons.validator.MultipleCriteriaMessageInterpolator.java

@SuppressWarnings("rawtypes")
private String interpolateWithDefault(String message, Validator validator,
        MessageInterpolator defaultInterpolator) {
    String toInterpolate = message;
    String key = StringUtils.removeStart(StringUtils.removeEnd(message, "}"), "{");
    if (bundle != null && bundle.containsKey(key)) {
        toInterpolate = bundle.getString(key);
    }/*from  www .  java 2  s .  c  o  m*/
    return defaultInterpolator.interpolate(toInterpolate, validator, defaultInterpolator);
}

From source file:ch.cyberduck.core.gdocs.GDPath.java

private String getDocumentId() {
    // Removing document type from resourceId gives us the documentId
    return StringUtils.removeStart(this.getResourceId(), this.getDocumentType() + ":");
}

From source file:gda.device.detector.addetector.filewriter.FileWriterBase.java

/**
 * Only if the path template starts with the datadir, return a path relative to it, otherwise
 * return an absolute path.//from www.  ja  v a 2s  .  c om
 */
protected String getFileDirRelativeToDataDirIfPossible() {
    String template = getFilePathTemplate();
    if (StringUtils.startsWith(template, "$datadir$")) {
        template = StringUtils.replace(template, "$datadir$", "");
        template = StringUtils.removeStart(template, "/");
    } else {
        //return absolute path (after substituting data directory)
        template = substituteDatadir(template);
    }
    return substituteScan(template);
}

From source file:com.gemstone.gemfire.management.internal.cli.parser.jopt.JoptOptionParser.java

public OptionSet parse(String userInput) throws CliCommandOptionException {
    OptionSet optionSet = new OptionSet();
    optionSet.setUserInput(userInput != null ? userInput.trim() : "");
    if (userInput != null) {
        TrimmedInput input = PreprocessorUtils.trim(userInput);
        String[] preProcessedInput = preProcess(input.getString());
        joptsimple.OptionSet joptOptionSet = null;
        CliCommandOptionException ce = null;
        // int factor = 0;
        try {/*from   ww  w.j av  a 2s . c  om*/
            joptOptionSet = parser.parse(preProcessedInput);
        } catch (Exception e) {
            if (e instanceof OptionException) {
                ce = processException(e);
                joptOptionSet = ((OptionException) e).getDetected();
            }
        }
        if (joptOptionSet != null) {

            // Make sure there are no miscellaneous, unknown strings that cannot be identified as
            // either options or arguments.
            if (joptOptionSet.nonOptionArguments().size() > arguments.size()) {
                String unknownString = joptOptionSet.nonOptionArguments().get(arguments.size());
                // If the first option is un-parseable then it will be returned as "<option>=<value>" since it's
                // been interpreted as an argument. However, all subsequent options will be returned as "<option>".
                // This hack splits off the string before the "=" sign if it's the first case.
                if (unknownString.matches("^-*\\w+=.*$")) {
                    unknownString = unknownString.substring(0, unknownString.indexOf('='));
                }
                ce = processException(
                        OptionException.createUnrecognizedOptionException(unknownString, joptOptionSet));
            }

            // First process the arguments
            StringBuffer argument = new StringBuffer();
            int j = 0;
            for (int i = 0; i < joptOptionSet.nonOptionArguments().size() && j < arguments.size(); i++) {
                argument = argument.append(joptOptionSet.nonOptionArguments().get(i));
                // Check for syntax of arguments before adding them to the
                // option set as we want to support quoted arguments and those
                // in brackets
                if (PreprocessorUtils.isSyntaxValid(argument.toString())) {
                    optionSet.put(arguments.get(j), argument.toString());
                    j++;
                    argument.delete(0, argument.length());
                }
            }
            if (argument.length() > 0) {
                // Here we do not need to check for the syntax of the argument
                // because the argument list is now over and this is the last
                // argument which was not added due to improper syntax
                optionSet.put(arguments.get(j), argument.toString());
            }

            // Now process the options
            for (Option option : options) {
                List<String> synonyms = option.getAggregate();
                for (String string : synonyms) {
                    if (joptOptionSet.has(string)) {
                        // Check whether the user has actually entered the
                        // full option or just the start
                        boolean present = false;
                        outer: for (String inputSplit : preProcessedInput) {
                            if (inputSplit.startsWith(SyntaxConstants.LONG_OPTION_SPECIFIER)) {
                                // Remove option prefix
                                inputSplit = StringUtils.removeStart(inputSplit,
                                        SyntaxConstants.LONG_OPTION_SPECIFIER);
                                // Remove value specifier
                                inputSplit = StringUtils.removeEnd(inputSplit,
                                        SyntaxConstants.OPTION_VALUE_SPECIFIER);
                                if (!inputSplit.equals("")) {
                                    if (option.getLongOption().equals(inputSplit)) {
                                        present = true;
                                        break outer;
                                    } else {
                                        for (String optionSynonym : option.getSynonyms()) {
                                            if (optionSynonym.equals(inputSplit)) {
                                                present = true;
                                                break outer;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (present) {
                            if (joptOptionSet.hasArgument(string)) {
                                List<?> arguments = joptOptionSet.valuesOf(string);
                                if (arguments.size() > 1
                                        && !(option.getConverter() instanceof MultipleValueConverter)
                                        && option.getValueSeparator() == null) {
                                    List<String> optionList = new ArrayList<String>(1);
                                    optionList.add(string);
                                    ce = processException(
                                            new MultipleArgumentsForOptionException(optionList, joptOptionSet));
                                } else if ((arguments.size() == 1
                                        && !(option.getConverter() instanceof MultipleValueConverter))
                                        || option.getValueSeparator() == null) {
                                    optionSet.put(option, arguments.get(0).toString().trim());
                                } else {
                                    StringBuffer value = new StringBuffer();
                                    String valueSeparator = option.getValueSeparator();
                                    for (Object object : joptOptionSet.valuesOf(string)) {
                                        if (value.length() == 0) {
                                            value.append((String) object);
                                        } else {
                                            if (valueSeparator != null) {
                                                value.append(valueSeparator + ((String) object).trim());
                                            } else {
                                                value.append(((String) object).trim());
                                            }
                                        }
                                    }
                                    optionSet.put(option, value.toString());
                                }
                            } else {
                                optionSet.put(option, option.getSpecifiedDefaultValue());
                            }
                            break;
                        }
                    }
                }
            }
        }

        // Convert the preProcessedInput into List<String>
        List<String> split = new ArrayList<String>();
        for (int i = 0; i < preProcessedInput.length; i++) {
            split.add(preProcessedInput[i]);
        }
        optionSet.setNoOfSpacesRemoved(input.getNoOfSpacesRemoved() /* + factor */);
        optionSet.setSplit(split);
        if (ce != null) {
            ce.setOptionSet(optionSet);
            throw ce;
        }
    }
    return optionSet;
}