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:info.magnolia.cms.filters.Mapping.java

/**
 * See SRV.11.2 Specification of Mappings in the Servlet Specification for the syntax of
 * mappings. Additionally, you can also use plain regular expressions to map your servlets, by
 * prefix the mapping by "regex:". (in which case anything in the request url following the
 * expression's match will be the pathInfo - if your pattern ends with a $, extra pathInfo won't
 * match)/* w  w  w  . ja  v a  2s .  c o m*/
 */
public void addMapping(final String mapping) {
    final String pattern;

    // we're building a Pattern with 3 groups: (1) servletPath (2) ignored (3) pathInfo

    if (isDefaultMapping(mapping)) {
        // the mapping is exactly '/*', the servlet path should be
        // an empty string and everything else should be the path info
        pattern = "^()(/)(" + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
    } else if (isPathMapping(mapping)) {
        // the pattern ends with /*, escape out metacharacters for
        // use in a regex, and replace the ending * with MULTIPLE_CHAR_PATTERN
        final String mappingWithoutSuffix = StringUtils.removeEnd(mapping, "/*");
        pattern = "^(" + escapeMetaCharacters(mappingWithoutSuffix) + ")(/)("
                + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
    } else if (isExtensionMapping(mapping)) {
        // something like '*.jsp', everything should be the servlet path
        // and the path info should be null
        final String regexedMapping = StringUtils.replace(mapping, "*.",
                SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + "\\.");
        pattern = "^(" + regexedMapping + ")$";
    } else if (isRegexpMapping(mapping)) {
        final String mappingWithoutPrefix = StringUtils.removeStart(mapping, "regex:");
        pattern = "^(" + mappingWithoutPrefix + ")($|/)(" + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
    } else {
        // just literal text, ensure metacharacters are escaped, and that only
        // the exact string is matched.
        pattern = "^(" + escapeMetaCharacters(mapping) + ")$";
    }
    log.debug("Adding new mapping for {}", mapping);

    mappings.add(Pattern.compile(pattern));
}

From source file:jenkins.plugins.git.AbstractGitSCMSource.java

@CheckForNull
@Override/*  w  ww  .j  a va 2 s.  c o  m*/
protected SCMRevision retrieve(@NonNull SCMHead head, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    String cacheEntry = getCacheEntry();
    Lock cacheLock = getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
        File cacheDir = getCacheDir(cacheEntry);
        Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir);
        GitClient client = git.getClient();
        client.addDefaultCredentials(getCredentials());
        if (!client.hasGitRepo()) {
            listener.getLogger().println("Creating git repository in " + cacheDir);
            client.init();
        }
        String remoteName = getRemoteName();
        listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
        client.setRemoteUrl(remoteName, getRemote());
        listener.getLogger().println("Fetching " + remoteName + "...");
        List<RefSpec> refSpecs = getRefSpecs();
        client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
        // we don't prune remotes here, as we just want one head's revision
        for (Branch b : client.getRemoteBranches()) {
            String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
            if (branchName.equals(head.getName())) {
                return new SCMRevisionImpl(head, b.getSHA1String());
            }
        }
        return null;
    } finally {
        cacheLock.unlock();
    }
}

From source file:hudson.plugins.openid.OpenIdLoginService.java

private String getFinishUrl() {
    StaplerRequest req = Stapler.getCurrentRequest();
    String contextPath = req.getContextPath();
    if (StringUtils.isBlank(contextPath) || "/".equals(contextPath)) {
        return "federatedLoginService/openid/finish";
    } else {/*from   w w w. j  a  va 2  s.  c  o  m*/
        // hack alert... work around some less than consistent servlet containers
        return StringUtils.removeEnd(StringUtils.removeStart(contextPath, "/"), "/")
                + "/federatedLoginService/openid/finish";
    }
}

From source file:com.google.gdt.eclipse.designer.uibinder.refactoring.UiFieldRenameParticipant.java

/**
 * Adds {@link TextEdit}s into existing Java file {@link Change}.
 *//* w  w w .j  a  v a 2  s  .  c  o m*/
private void addHandlerMethodChanges(CompositeChange compositeChange, IProgressMonitor pm) throws Exception {
    TextChange change = new CompilationUnitChange("(No matter)", m_field.getCompilationUnit());
    change.setEdit(new MultiTextEdit());
    // update handler methods
    String oldMethodPrefix = "on" + StringUtils.capitalize(m_oldName);
    String newMethodPrefix = "on" + StringUtils.capitalize(m_newName);
    IType type = (IType) m_field.getParent();
    for (IMethod method : type.getMethods()) {
        // prepare @UiHandler annotation
        IAnnotation annotation = getHandlerAnnotation(method);
        if (annotation == null) {
            continue;
        }
        // update @UiHandler name
        {
            ISourceRange annoRange = annotation.getSourceRange();
            ISourceRange nameRange = annotation.getNameRange();
            int nameEnd = nameRange.getOffset() + nameRange.getLength();
            int annoEnd = annoRange.getOffset() + annoRange.getLength();
            change.addEdit(new ReplaceEdit(nameEnd, annoEnd - nameEnd, "(\"" + m_newName + "\")"));
        }
        // rename method
        String methodName = method.getElementName();
        if (methodName.startsWith(oldMethodPrefix)) {
            String newName = newMethodPrefix + StringUtils.removeStart(methodName, oldMethodPrefix);
            Change renameChange = createRenameChange(method, newName, pm);
            compositeChange.add(renameChange);
            RefactoringUtils.mergeTextChange(this, renameChange);
        }
    }
    // merge edits into existing (rename) change
    RefactoringUtils.mergeTextChange(this, change);
}

From source file:net.jonbuck.texteditor.dialog.TextEditorDialog.java

/**
 * {@inheritDoc}//from  w ww . jav  a 2 s  .c o m
 */
@Override
protected Control createDialogArea(Composite parent) {

    getShell().setText(TextEditorMessages.shellTitle);

    Composite contents = (Composite) super.createDialogArea(parent);
    final GridLayout gridLayout = new GridLayout();
    gridLayout.verticalSpacing = 0;
    gridLayout.marginWidth = 0;
    gridLayout.marginHeight = 0;
    gridLayout.horizontalSpacing = 0;
    contents.setLayout(gridLayout);

    final Browser browser = new Browser(contents, SWT.NONE);
    browser.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    URL url = FileLocator.find(Activator.getDefault().getBundle(), new Path("/html/editor.html"), null);

    StringBuilder editorContent = new StringBuilder();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            editorContent.append(inputLine);
        }

    } catch (IOException e1) {
        e1.printStackTrace();
    }

    try {
        browser.setUrl(FileLocator.resolve(url).toExternalForm());
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Add text to control if text is being edited
    if (StringUtils.isNotEmpty(this.content)) {
        browser.addProgressListener(new ProgressListener() {

            public void changed(ProgressEvent event) {
            }

            public void completed(ProgressEvent event) {
                String htmlcontent = StringUtils.replace(content, "\"", "'");
                htmlcontent = StringUtils.replace(htmlcontent, "\r", "");
                htmlcontent = StringUtils.replace(htmlcontent, "\n", "");
                String method = "document.forms[0].content.value=\"" + htmlcontent + "\"";
                if (!browser.execute(method)) {
                    System.out.println("Script was not executed");
                }
            }
        });
    }

    browser.addStatusTextListener(new StatusTextListener() {
        public void changed(StatusTextEvent event) {
            if (event.text.startsWith(identifier)) {
                content = StringUtils.removeStart(event.text, identifier);
                content = content.replaceAll("[\\n\\r]", "");
                browser.removeStatusTextListener(this);
                setReturnCode(OK);
                close();
            }
        }
    });

    return contents;
}

From source file:br.com.nordestefomento.jrimum.utilix.StringUtil.java

/**
 * <p>//from w w  w .ja  v  a 2  s.  c o m
 * Remove os zeros iniciais de uma <code>String</code>, seja ela numrica ou
 * no.
 * </p>
 * <p>
 * <code>removeStartWithZeros("00000") => 0</code><br />
 * <code>removeStartWithZeros("00023") => 23</code><br />
 * <code>removeStartWithZeros("02003") => 2003</code>
 * <p>
 * 
 * @param str
 * @return a string sem zeros inicias ou um nico zero.
 * 
 * @since 0.2
 */

public static String removeStartWithZeros(final String str) {

    String withoutZeros = StringUtils.EMPTY;
    final String zero = "0";

    if (isNotNull(str)) {

        if (StringUtils.startsWith(str, zero)) {

            withoutZeros = StringUtils.removeStart(str, zero);

            while (StringUtils.startsWith(withoutZeros, zero)) {
                withoutZeros = StringUtils.removeStart(withoutZeros, zero);
            }

            if (withoutZeros.trim().length() == 0) {
                withoutZeros = zero;
            }

        } else {
            withoutZeros = str;
        }
    }

    return withoutZeros;
}

From source file:com.huawei.streaming.config.ConfVariable.java

private void parseVariableConf(String value) {
    //trim???/*from   ww w .j a v a  2  s.  c  om*/
    String variable = StringUtils
            .removeEnd(StringUtils.removeStart(value, CONF_VARIABLE_PREFIX), CONF_VARIABLE_POSTFIX).trim();
    if (Strings.isNullOrEmpty(variable)) {
        return;
    }

    if (variable.toLowerCase(Locale.US).startsWith(SYSTEM_PREFIX)) {
        parseSystemVariable(variable);
        return;
    }

    if (variable.toLowerCase(Locale.US).startsWith(CQLCONF_PREFIX)) {
        parseConfVariable(variable);
        return;
    }
}

From source file:com.google.gdt.eclipse.designer.model.widgets.panels.DockLayoutPanelInfo.java

public String getEdge(WidgetInfo widget) {
    if (widget.getAssociation() instanceof InvocationChildAssociation) {
        InvocationChildAssociation association = (InvocationChildAssociation) widget.getAssociation();
        String methodName = association.getInvocation().getName().getIdentifier();
        String edge = StringUtils.removeStart(methodName, "add");
        if (edge.length() == 0) {
            return "CENTER";
        }//from  w w  w  .  j  a  va  2 s .com
        return edge.toUpperCase(Locale.ENGLISH);
    }
    return "UNKNOWN";
}

From source file:info.magnolia.cms.util.ContentUtil.java

public static Content createPath(HierarchyManager hm, String path, ItemType type)
        throws AccessDeniedException, PathNotFoundException, RepositoryException {
    // remove leading /
    path = StringUtils.removeStart(path, "/");

    String[] names = path.split("/"); //$NON-NLS-1$
    Content node = hm.getRoot();//  ww w  .  j  a  v  a2  s . c o m
    for (int i = 0; i < names.length; i++) {
        String name = names[i];
        if (node.hasContent(name)) {
            node = node.getContent(name);
        } else {
            node = node.createContent(name, type);
        }
    }
    return node;
}

From source file:gobblin.compaction.mapreduce.MRCompactorTimeBasedJobPropCreator.java

private DateTime getFolderTime(Path path) {
    int startPos = path.toString().indexOf(this.topicInputDir.toString())
            + this.topicInputDir.toString().length();
    return this.timeFormatter.parseDateTime(StringUtils.removeStart(path.toString().substring(startPos), "/"));
}