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

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

Introduction

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

Prototype

public static String stripStart(String str, String stripChars) 

Source Link

Document

Strips any of a set of characters from the start of a String.

Usage

From source file:com.gemstone.gemfire.internal.security.GeodeSecurityUtil.java

private static void authorize(String resource, String operation, String regionName, String key) {
    regionName = StringUtils.stripStart(regionName, "/");
    authorize(new GeodePermission(resource, operation, regionName, key));
}

From source file:ch.cyberduck.core.ftp.FTPPath.java

@Override
public AttributedList<Path> list(final AttributedList<Path> children) {
    try {/*from  w  w  w  .j a  v a  2s  .  c  o m*/
        this.getSession().check();
        this.getSession().message(MessageFormat
                .format(Locale.localizedString("Listing directory {0}", "Status"), this.getName()));

        // Cached file parser determined from SYST response with the timezone set from the bookmark
        final FTPFileEntryParser parser = this.getSession().getFileParser();
        boolean success = false;
        try {
            if (this.getSession().isStatListSupportedEnabled()) {
                int response = this.getSession().getClient().stat(this.getAbsolute());
                if (FTPReply.isPositiveCompletion(response)) {
                    String[] reply = this.getSession().getClient().getReplyStrings();
                    final List<String> result = new ArrayList<String>(reply.length);
                    for (final String line : reply) {
                        //Some servers include the status code for every line.
                        if (line.startsWith(String.valueOf(response))) {
                            try {
                                result.add(line.substring(line.indexOf(response) + line.length() + 1).trim());
                            } catch (IndexOutOfBoundsException e) {
                                log.error(String.format("Failed parsing line %s", line), e);
                            }
                        } else {
                            result.add(StringUtils.stripStart(line, null));
                        }
                    }
                    success = this.parseListResponse(children, parser, result);
                } else {
                    this.getSession().setStatListSupportedEnabled(false);
                }
            }
        } catch (IOException e) {
            log.warn("Command STAT failed with I/O error:" + e.getMessage());
            this.getSession().interrupt();
            this.getSession().check();
        }
        if (!success || children.isEmpty()) {
            success = this.data(new DataConnectionAction() {
                @Override
                public boolean run() throws IOException {
                    if (!getSession().getClient().changeWorkingDirectory(getAbsolute())) {
                        throw new FTPException(getSession().getClient().getReplyString());
                    }
                    if (!getSession().getClient().setFileType(FTPClient.ASCII_FILE_TYPE)) {
                        // Set transfer type for traditional data socket file listings. The data transfer is over the
                        // data connection in type ASCII or type EBCDIC.
                        throw new FTPException(getSession().getClient().getReplyString());
                    }
                    boolean success = false;
                    // STAT listing failed or empty
                    if (getSession().isMlsdListSupportedEnabled()
                            // Note that there is no distinct FEAT output for MLSD.
                            // The presence of the MLST feature indicates that both MLST and MLSD are supported.
                            && getSession().getClient().isFeatureSupported(FTPCommand.MLST)) {
                        success = parseMlsdResponse(children, getSession().getClient().list(FTPCommand.MLSD));
                        if (!success) {
                            getSession().setMlsdListSupportedEnabled(false);
                        }
                    }
                    if (!success) {
                        // MLSD listing failed or not enabled
                        if (getSession().isExtendedListEnabled()) {
                            try {
                                success = parseListResponse(children, parser,
                                        getSession().getClient().list(FTPCommand.LIST, "-a"));
                            } catch (FTPException e) {
                                getSession().setExtendedListEnabled(false);
                            }
                        }
                        if (!success) {
                            // LIST -a listing failed or not enabled
                            success = parseListResponse(children, parser,
                                    getSession().getClient().list(FTPCommand.LIST));
                        }
                    }
                    return success;
                }
            });
        }
        for (Path child : children) {
            if (child.attributes().isSymbolicLink()) {
                if (this.getSession().getClient().changeWorkingDirectory(child.getAbsolute())) {
                    child.attributes().setType(SYMBOLIC_LINK_TYPE | DIRECTORY_TYPE);
                } else {
                    // Try if CWD to symbolic link target succeeds
                    if (this.getSession().getClient()
                            .changeWorkingDirectory(child.getSymlinkTarget().getAbsolute())) {
                        // Workdir change succeeded
                        child.attributes().setType(SYMBOLIC_LINK_TYPE | DIRECTORY_TYPE);
                    } else {
                        child.attributes().setType(SYMBOLIC_LINK_TYPE | FILE_TYPE);
                    }
                }
            }
        }
        if (!success) {
            // LIST listing failed
            log.error("No compatible file listing method found");
        }
    } catch (IOException e) {
        log.warn("Listing directory failed:" + e.getMessage());
        children.attributes().setReadable(false);
        if (!session.cache().containsKey(this.getReference())) {
            this.error(e.getMessage(), e);
        }
    }
    return children;
}

From source file:com.smartitengineering.util.bean.PropertiesLocator.java

protected void loadFromReader(Properties props, Reader reader) throws IOException {
    BufferedReader in = new BufferedReader(reader);
    while (true) {
        String line = in.readLine();
        if (line == null) {
            return;
        }//from   w w w. j  av  a  2 s  .  c  o m
        line = StringUtils.stripStart(line, null);
        if (line.length() > 0) {
            char firstChar = line.charAt(0);
            if (firstChar != '#' && firstChar != '!') {
                while (endsWithContinuationMarker(line)) {
                    String nextLine = in.readLine();
                    line = line.substring(0, line.length() - 1);
                    if (nextLine != null) {
                        line += StringUtils.stripStart(nextLine, null);
                    }
                }
                int separatorIndex = line.indexOf("=");
                if (separatorIndex == -1) {
                    separatorIndex = line.indexOf(":");
                }
                String key = (separatorIndex != -1 ? line.substring(0, separatorIndex) : line);
                String value = (separatorIndex != -1) ? line.substring(separatorIndex + 1) : "";
                key = StringUtils.stripEnd(key, null);
                value = StringUtils.stripStart(value, null);
                props.put(unescape(key), unescape(value));
            }
        }
    }
}

From source file:au.org.ala.delta.translation.PrintFile.java

private void writeJustifiedText(String text, int completionAction, boolean addSpaceIfRequired) {
    text = doSubstitutions(text);/* w w w.j  a v  a2s  . c  om*/

    if (_capitalise) {
        text = capitaliseFirstWord(text);
    }

    if (needsLineWrap() == false) {
        printBufferLine(_indentOnLineWrap);
    }

    // Insert a space if one is required.
    if (addSpaceIfRequired && !text.startsWith(" ")) {
        insertTrailingSpace();
    }

    _outputBuffer.append(text);

    while (needsLineWrap() == false) {

        int wrappingPos = findWrapPosition();

        String trailingText = _outputBuffer.substring(wrappingPos);
        _outputBuffer.delete(wrappingPos, _outputBuffer.length());
        printBufferLine(_indentOnLineWrap);

        if (_trim) {
            trailingText = trailingText.trim();
        } else if (_trimLeadingSpacesOnLineWrap) {
            trailingText = StringUtils.stripStart(trailingText, null);
        }
        _outputBuffer.append(trailingText);
    }
    complete(completionAction);
}

From source file:com.fortify.processrunner.RunProcessRunnerFromCLI.java

/**
 * This method iterates over the given args array, and matches each argument against the given
 * {@link CLIOptionDefinitions}. If an argument matches with a {@link CLIOptionDefinition},
 * the argument value is added to the result {@link ContextWithUnknownCLIOptionsList} (or in case
 * of a flag option, "true" is added to the result). Any unknown options will be added to the
 * unknown options set.  //  ww  w . ja v a 2 s . co  m
 * 
 * @param cliOptionDefinitions
 * @param args
 * @return
 */
private ContextWithUnknownCLIOptionsList parseContextFromCLI(CLIOptionDefinitions cliOptionDefinitions,
        String[] args) {
    ContextWithUnknownCLIOptionsList result = new ContextWithUnknownCLIOptionsList();
    for (int i = 0; i < args.length; i++) {
        String optionName = StringUtils.stripStart(args[i], "-");
        if (cliOptionDefinitions.containsCLIOptionDefinitionName(optionName)) {
            if (cliOptionDefinitions.getCLIOptionDefinitionByName(optionName).isFlag()) {
                result.put(optionName, "true");
            } else {
                result.put(optionName, args[++i]);
            }
        } else {
            result.addUnknowCLIOption(optionName);
            // Skip next argument if it looks like a value for the unknown option
            if (args.length > i + 1 && !args[i + 1].startsWith("-")) {
                i++;
            }
        }
    }
    return result;
}

From source file:de.cismet.cids.custom.objecteditors.utils.VermessungUmleitungPanel.java

/**
 * DOCUMENT ME!//from   w w w. jav a  2 s  .  co  m
 *
 * @param   rissNummer  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 */
private boolean checkIfRissExists(final String rissNummer) {
    try {
        if (rissNummer.startsWith(PLATZHALTER_PREFIX)) {
            return true;
        }
        final String[] props = parsePropertiesFromLink(rissNummer);
        final MetaClass MB_MC = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "vermessung_riss",
                getConnectionContext());
        String query = "SELECT " + MB_MC.getID() + ", " + MB_MC.getPrimaryKey() + " ";
        query += "FROM " + MB_MC.getTableName();
        query += " WHERE schluessel ilike '" + props[0] + "' and gemarkung=" + props[1] + " and flur ilike '"
                + props[2] + "' and blatt ilike '" + StringUtils.stripStart(props[3], "0") + "'";
        final MetaObject[] metaObjects = SessionManager.getProxy().getMetaObjectByQuery(query, 0,
                getConnectionContext());
        return (metaObjects != null) && (metaObjects.length == 1) && (metaObjects[0] != null);
    } catch (ConnectionException ex) {
        LOG.error("Error while checkig if riss exists", ex);
        return false;
    }
}

From source file:edu.ku.brc.specify.ui.BaseUIFieldFormatter.java

@Override
public Object formatToUI(Object... datas) {
    Object data = datas[0];/* www. ja  v a  2s. c o  m*/
    if (isNumericCatalogNumber) {
        if (data != null) {
            if (isNumericCatalogNumber && data instanceof String && StringUtils.isEmpty(data.toString())) {
                return pattern;
            }
            return StringUtils.stripStart(data.toString(), "0"); //$NON-NLS-1$
        }
    }
    return data;
}

From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java

private String normalizeUrlPart(String urlPart) {
    // remove slashes at the beginning and end of the URL part
    // and return null if it empty or contains only whitespace
    urlPart = StringUtils.stripStart(urlPart, "/");
    urlPart = StringUtils.stripEnd(urlPart, "/");
    return StringUtils.defaultIfBlank(urlPart, null);
}

From source file:com.doculibre.constellio.wicket.panels.results.DefaultSearchResultPanel.java

public DefaultSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) {
    super(id);/*from   www .  j  av  a  2s  .c om*/

    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
    SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils
            .getSearchInterfaceConfigServices();

    String collectionName = dataProvider.getSimpleSearch().getCollectionName();

    RecordCollection collection = collectionServices.get(collectionName);
    Record record = recordServices.get(doc);
    if (record != null) {
        SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get();

        IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
        IndexField defaultSearchField = collection.getDefaultSearchIndexField();
        IndexField urlField = collection.getUrlIndexField();
        IndexField titleField = collection.getTitleIndexField();

        if (urlField == null) {
            urlField = uniqueKeyField;
        }
        if (titleField == null) {
            titleField = urlField;
        }

        final String recordURL = record.getUrl();
        final String displayURL;

        if (record.getDisplayUrl().startsWith("/get?file=")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            displayURL = ContextUrlUtils.getContextUrl(req) + record.getDisplayUrl();

        } else {
            displayURL = record.getDisplayUrl();
        }

        String title = record.getDisplayTitle();

        final String protocol = StringUtils.substringBefore(displayURL, ":");
        boolean linkEnabled = isLinkEnabled(protocol);

        // rcupration des champs highlight  partir de la cl unique
        // du document, dans le cas de Nutch c'est l'URL
        QueryResponse response = dataProvider.getQueryResponse();
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL);

        String titleHighlight = getTitleFromHighlight(titleField.getName(), fieldsHighlighting);
        if (titleHighlight != null) {
            title = titleHighlight;
        }

        String excerpt = null;
        String description = getDescription(record);
        String summary = getSummary(record);

        if (StringUtils.isNotBlank(description) && searchInterfaceConfig.isDescriptionAsExcerpt()) {
            excerpt = description;
        } else {
            excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting);
            if (excerpt == null) {
                excerpt = description;
            }
        }

        toggleSummaryLink = new WebMarkupContainer("toggleSummaryLink");
        add(toggleSummaryLink);
        toggleSummaryLink.setVisible(StringUtils.isNotBlank(summary));
        toggleSummaryLink.add(new AttributeModifier("onclick", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                return "toggleSearchResultSummary('" + summaryLabel.getMarkupId() + "')";
            }
        }));

        summaryLabel = new Label("summary", summary);
        add(summaryLabel);
        summaryLabel.setOutputMarkupId(true);
        summaryLabel.setVisible(StringUtils.isNotBlank(summary));

        ExternalLink titleLink;
        if (displayURL.startsWith("file://")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            String newDisplayURL = ContextUrlUtils.getContextUrl(req) + "app/getSmbFile?"
                    + SmbServletPage.RECORD_ID + "=" + record.getId() + "&" + SmbServletPage.COLLECTION + "="
                    + collectionName;
            titleLink = new ExternalLink("titleLink", newDisplayURL);
        } else {
            titleLink = new ExternalLink("titleLink", displayURL);
        }

        final RecordModel recordModel = new RecordModel(record);
        AttributeModifier computeClickAttributeModifier = new AttributeModifier("onmousedown", true,
                new LoadableDetachableModel() {
                    @Override
                    protected Object load() {
                        Record record = recordModel.getObject();
                        SimpleSearch simpleSearch = dataProvider.getSimpleSearch();
                        WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest();
                        HttpServletRequest httpRequest = webRequest.getHttpServletRequest();
                        return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch,
                                record);
                    }
                });
        titleLink.add(computeClickAttributeModifier);
        titleLink.setEnabled(linkEnabled);

        boolean resultsInNewWindow;
        PageParameters params = RequestCycle.get().getPageParameters();
        if (params != null && params.getString(POPUP_LINK) != null) {
            resultsInNewWindow = params.getBoolean(POPUP_LINK);
        } else {
            resultsInNewWindow = searchInterfaceConfig.isResultsInNewWindow();
        }
        titleLink.add(new SimpleAttributeModifier("target", resultsInNewWindow ? "_blank" : "_self"));

        // Add title
        title = StringUtils.remove(title, "\n");
        title = StringUtils.remove(title, "\r");
        if (StringUtils.isEmpty(title)) {
            title = StringUtils.defaultString(displayURL);
            title = StringUtils.substringAfterLast(title, "/");
            title = StringUtils.substringBefore(title, "?");
            try {
                title = URLDecoder.decode(title, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (title.length() > 120) {
                title = title.substring(0, 120) + " ...";
            }
        }

        Label titleLabel = new Label("title", title);
        titleLink.add(titleLabel.setEscapeModelStrings(false));
        add(titleLink);

        Label excerptLabel = new Label("excerpt", excerpt);
        add(excerptLabel.setEscapeModelStrings(false));
        // add(new ExternalLink("url", url,
        // url).add(computeClickAttributeModifier).setEnabled(linkEnabled));
        if (displayURL.startsWith("file://")) {
            // Creates a Windows path for file URLs
            String urlLabel = StringUtils.substringAfter(displayURL, "file:");
            urlLabel = StringUtils.stripStart(urlLabel, "/");
            urlLabel = "\\\\" + StringUtils.replace(urlLabel, "/", "\\");
            try {
                urlLabel = URLDecoder.decode(urlLabel, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            add(new Label("url", urlLabel));
        } else {
            add(new Label("url", displayURL));
        }

        final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>(
                collection);
        add(new ListView("searchResultFields", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                RecordCollection collection = collectionModel.getObject();
                return collection.getSearchResultFields();
            }

            /**
             * Detaches from the current request. Implement this method with
             * custom behavior, such as setting the model object to null.
             */
            protected void onDetach() {
                recordModel.detach();
                collectionModel.detach();
            }
        }) {
            @Override
            protected void populateItem(ListItem item) {
                SearchResultField searchResultField = (SearchResultField) item.getModelObject();
                IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                Record record = recordModel.getObject();
                IndexField indexField = searchResultField.getIndexField();
                Locale locale = getLocale();
                String indexFieldTitle = indexField.getTitle(locale);
                if (StringUtils.isBlank(indexFieldTitle)) {
                    indexFieldTitle = indexField.getName();
                }
                StringBuffer fieldValueSb = new StringBuffer();
                List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField);
                Map<String, String> defaultLabelledValues = indexFieldServices
                        .getDefaultLabelledValues(indexField, locale);
                for (Object fieldValue : fieldValues) {
                    if (fieldValueSb.length() > 0) {
                        fieldValueSb.append("\n");
                    }
                    String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale);
                    if (fieldValueLabel == null) {
                        fieldValueLabel = defaultLabelledValues.get("" + fieldValue);
                    }
                    if (fieldValueLabel == null) {
                        fieldValueLabel = "" + fieldValue;
                    }
                    fieldValueSb.append(fieldValueLabel);
                }

                item.add(new Label("indexField", indexFieldTitle));
                item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString()));
                item.setVisible(fieldValueSb.length() > 0);
            }

            @SuppressWarnings("unchecked")
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject();
                    visible = !searchResultFields.isEmpty();
                }
                return visible;
            }
        });

        // md5
        ConstellioSession session = ConstellioSession.get();
        ConstellioUser user = session.getUser();
        // TODO Provide access to unauthenticated users ?
        String md5 = "";
        if (user != null) {
            IntelliGIDServiceInfo intelligidServiceInfo = ConstellioSpringUtils.getIntelliGIDServiceInfo();
            if (intelligidServiceInfo != null) {
                Collection<Object> md5Coll = doc.getFieldValues(IndexField.MD5);
                if (md5Coll != null) {
                    for (Object md5Obj : md5Coll) {
                        try {
                            String md5Str = new String(Hex.encodeHex(Base64.decodeBase64(md5Obj.toString())));
                            InputStream is = HttpClientHelper
                                    .get(intelligidServiceInfo.getIntelligidUrl() + "/connector/checksum",
                                            "md5=" + URLEncoder.encode(md5Str, "ISO-8859-1"),
                                            "username=" + URLEncoder.encode(user.getUsername(), "ISO-8859-1"),
                                            "password=" + URLEncoder.encode(Base64.encodeBase64String(
                                                    ConstellioSession.get().getPassword().getBytes())),
                                            "ISO-8859-1");
                            try {
                                Document xmlDocument = new SAXReader().read(is);
                                Element root = xmlDocument.getRootElement();
                                for (Iterator<Element> it = root.elementIterator("fichier"); it.hasNext();) {
                                    Element fichier = it.next();
                                    String url = fichier.attributeValue("url");
                                    md5 += "<a href=\"" + url + "\">" + url + "</a> ";
                                }
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        Label md5Label = new Label("md5", md5) {
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    visible = StringUtils.isNotBlank(this.getModelObjectAsString());
                }
                return visible;
            }
        };
        md5Label.setEscapeModelStrings(false);
        add(md5Label);

        add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch()));
    } else {
        setVisible(false);
    }
}

From source file:hudson.plugins.clearcase.AbstractClearCaseScm.java

/**
 * Return string array containing the paths in the view that should be used when polling for changes.
 * @param variableResolver TODO//from w w w  . j  av a 2  s  .  c o  m
 * @param build TODO
 * @param launcher TODO
 * @return string array that will be used by the lshistory command and for constructing the config spec, etc.
 * @throws InterruptedException
 * @throws IOException
 */
public String[] getViewPaths(VariableResolver<String> variableResolver, AbstractBuild build, Launcher launcher)
        throws IOException, InterruptedException {
    String loadRules = getLoadRules(variableResolver);
    if (StringUtils.isBlank(loadRules)) {
        return null;
    }

    String[] rules = loadRules.split("[\\r\\n]+");
    for (int i = 0; i < rules.length; i++) {
        String rule = rules[i];
        // Remove "load " from the string, just in case.
        rule = StringUtils.removeStart(rule, "load ");
        // Remove "\\", "\" or "/" from the load rule. (bug#1706) Only if
        // the view is not dynamic
        // the user normally enters a load rule beginning with those chars
        rule = StringUtils.stripStart(rule, "\\/");
        rules[i] = rule;
    }
    return rules;
}