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

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

Introduction

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

Prototype

public static String substringBefore(final String str, final String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.google.dart.java2dart.engine.EngineSemanticProcessor.java

static void useImportPrefix(final Context context, final ASTNode rootNode, final String prefixName,
        final String[] packageNames) {
    rootNode.accept(new RecursiveASTVisitor<Void>() {
        @Override//from   w  w w . j a v a2 s. c  om
        public Void visitPropertyAccess(PropertyAccess node) {
            super.visitPropertyAccess(node);
            Expression target = node.getTarget();
            Object binding0 = context.getNodeBinding(target);
            if (binding0 instanceof ITypeBinding) {
                ITypeBinding binding = (ITypeBinding) binding0;
                String shortName = binding.getName();
                shortName = StringUtils.substringBefore(shortName, "<");
                if (isPrefixPackage(binding)) {
                    SemanticProcessor.replaceNode(target, identifier(prefixName, shortName));
                    return null;
                }
            }
            return null;
        }

        @Override
        public Void visitTypeName(TypeName node) {
            ITypeBinding binding = context.getNodeTypeBinding(node);
            if (binding != null) {
                String shortName = binding.getName();
                shortName = StringUtils.substringBefore(shortName, "<");
                if (isPrefixPackage(binding)) {
                    node.setName(identifier(prefixName, shortName));
                    return null;
                }
            }
            return super.visitTypeName(node);
        }

        private boolean isPrefixPackage(ITypeBinding binding) {
            String typeName = binding.getQualifiedName();
            for (String packageName : packageNames) {
                if (typeName.startsWith(packageName)) {
                    return true;
                }
            }
            return false;
        }
    });
}

From source file:de.blizzy.documentr.web.page.PageController.java

@RequestMapping(value = "/saveRange/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/"
        + "{branchName:" + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{path:"
        + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}/json", method = RequestMethod.POST)
@ResponseBody/*  ww  w .j  a  v  a 2  s .  com*/
@PreAuthorize("hasPagePermission(#projectName, #branchName, #path, EDIT_PAGE)")
public Map<String, Object> savePageRange(@PathVariable String projectName, @PathVariable String branchName,
        @PathVariable String path, @RequestParam String markdown, @RequestParam String range,
        @RequestParam String commit, Authentication authentication, HttpServletRequest request)
        throws IOException {

    path = Util.toRealPagePath(path);

    markdown = markdown.replaceAll("[\\r\\n]+$", StringUtils.EMPTY); //$NON-NLS-1$
    int rangeStart = Integer.parseInt(StringUtils.substringBefore(range, ",")); //$NON-NLS-1$
    int rangeEnd = Integer.parseInt(StringUtils.substringAfter(range, ",")); //$NON-NLS-1$

    Page page = pageStore.getPage(projectName, branchName, path, commit, true);
    String text = ((PageTextData) page.getData()).getText();
    rangeEnd = Math.min(rangeEnd, text.length());

    String oldMarkdown = text.substring(rangeStart, rangeEnd);
    String cleanedOldMarkdown = oldMarkdown.replaceAll("[\\r\\n]+$", StringUtils.EMPTY); //$NON-NLS-1$
    rangeEnd -= oldMarkdown.length() - cleanedOldMarkdown.length();

    String newText = text.substring(0, rangeStart) + markdown
            + text.substring(Math.min(rangeEnd, text.length()));

    page.setData(new PageTextData(newText));
    User user = userStore.getUser(authentication.getName());
    MergeConflict conflict = pageStore.savePage(projectName, branchName, path, page, commit, user);

    Map<String, Object> result = Maps.newHashMap();
    if (conflict != null) {
        result.put("conflict", Boolean.TRUE); //$NON-NLS-1$
        HttpSession session = request.getSession();
        session.setAttribute("conflict", conflict); //$NON-NLS-1$
        session.setAttribute("conflict.projectName", projectName); //$NON-NLS-1$
        session.setAttribute("conflict.branchName", branchName); //$NON-NLS-1$
        session.setAttribute("conflict.path", path); //$NON-NLS-1$
    } else {
        String newCommit = pageStore.getPageMetadata(projectName, branchName, path).getCommit();
        String contextPath = request.getContextPath();
        String html = pageRenderer.getHtml(projectName, branchName, path, authentication, contextPath);
        html = markdownProcessor.processNonCacheableMacros(html, projectName, branchName, path, authentication,
                contextPath);
        result.put("html", html); //$NON-NLS-1$
        result.put("commit", newCommit); //$NON-NLS-1$
    }
    return result;
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static Geopoint parseCoords(final String location) {
    final String latitude = StringUtils.substringBefore(location, SEPARATOR_STRING);
    final String longitude = StringUtils.substringAfter(location, SEPARATOR_STRING);
    if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
        return new Geopoint(latitude, longitude);
    }/*from www  .jav a  2  s  . com*/

    return null;
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static void setLocation(final Geocache cache, final String location) {
    final String latitude = StringUtils.substringBefore(location, SEPARATOR_STRING);
    final String longitude = StringUtils.substringAfter(location, SEPARATOR_STRING);
    cache.setCoords(new Geopoint(latitude, longitude));
}

From source file:com.google.dart.tools.ui.internal.text.SemanticHighlightingTest.java

/**
 * Asserts that {@link #positions} contains position with given ID, at offset of "pattern" and
 * with length of the first space-separate word.
 *///w  w w.jav  a2  s .  c o m
private void assertHasWordPosition(String id, String pattern) throws Exception {
    int offset = findOffset(pattern);
    String word = StringUtils.substringBefore(pattern, " ");
    assertHasPosition(id, offset, word.length());
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

private boolean checkIfIsTheLastest(String webappName) {
    try {/* w  w w  .j  av a  2  s. co  m*/
        String baseName = StringUtils.substringBefore(webappName, "##");
        for (TomcatManager.DeployedApp app : tomcat.listDeployedApplications(baseName)) {
            if (app.name.compareTo(webappName) > 0)
                return false;
        }
        return true;

    } catch (Exception ex) {
        logger.error("Unable to query TomcatManager", ex);
        return false;
    }
}

From source file:com.xpn.xwiki.XWiki.java

/**
 * Return the XWiki object (as in "the Wiki API") corresponding to the requested wiki.
 * /*from   ww w .  ja v  a 2  s  .c  o m*/
 * @param context the current context
 * @return an XWiki object configured for the wiki corresponding to the current request
 * @throws XWikiException if the requested URL does not correspond to a real wiki, or if there's an error in the
 *             storage
 */
public static XWiki getXWiki(XWikiContext context) throws XWikiException {
    XWiki xwiki = getMainXWiki(context);
    if (!xwiki.isVirtualMode()) {
        return xwiki;
    }

    // Host is full.host.name in DNS-based multiwiki, and wikiname in path-based multiwiki.
    String host = "";
    // Canonical name of the wiki (database)
    String wikiName = "";
    // wikiDefinition should be the document holding the definition of the virtual wiki, a document in the main
    // wiki with a XWiki.XWikiServerClass object attached to it
    DocumentReference wikiDefinition;

    XWikiRequest request = context.getRequest();
    try {
        URL requestURL = context.getURL();
        host = requestURL.getHost();
    } catch (Exception e) {
    }

    // In path-based multi-wiki, the wiki name is an element of the request path.
    // The url is in the form /xwiki (app name)/wiki (servlet name)/wikiname/
    if ("1".equals(xwiki.Param("xwiki.virtual.usepath", "0"))) {
        String uri = request.getRequestURI();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Request uri is: " + uri);
        }
        // Remove the (eventual) context path from the URI, usually /xwiki
        uri = stripSegmentFromPath(uri, request.getContextPath());
        // Remove the (eventual) servlet path from the URI, usually /wiki
        String servletPath = request.getServletPath();
        uri = stripSegmentFromPath(uri, servletPath);

        if (servletPath.equals("/" + xwiki.Param("xwiki.virtual.usepath.servletpath", "wiki"))) {
            // Requested path corresponds to a path-based wiki, now the wiki name is between the first and
            // second "/"
            host = StringUtils.substringBefore(StringUtils.removeStart(uri, "/"), "/");
        }
    }

    if (StringUtils.isEmpty(host) || host.equals(context.getMainXWiki())) {
        // Can't find any wiki name, return the main wiki
        return xwiki;
    }

    wikiDefinition = xwiki.findWikiServer(host, context);

    if (wikiDefinition == null) {
        // No definition found based on the full domain name/path wiki name, try to use the first part of the domain
        // name as the wiki name
        String servername = StringUtils.substringBefore(host, ".");

        // As a convenience, allow sites starting with www, localhost or using an
        // IP address not to have to create a XWikiServerXwiki page since we consider
        // in that case that they're pointing to the main wiki.
        if (!"0".equals(xwiki.Param("xwiki.virtual.autowww")) && (servername.equals("www")
                || host.equals("localhost") || host.matches("[0-9]{1,3}(?:\\.[0-9]{1,3}){3}"))) {
            return xwiki;
        }

        wikiDefinition = new DocumentReference(DEFAULT_MAIN_WIKI, SYSTEM_SPACE,
                "XWikiServer" + StringUtils.capitalize(servername));
    }

    // Check if this wiki definition exists in the Database
    XWikiDocument doc = xwiki.getDocument(wikiDefinition, context);
    if (doc.isNew()) {
        throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_DOES_NOT_EXIST,
                "The wiki " + host + " does not exist");
    }

    // Set the wiki owner
    String wikiOwner = doc.getStringValue(VIRTUAL_WIKI_DEFINITION_CLASS_REFERENCE, "owner");
    if (wikiOwner.indexOf(':') == -1) {
        wikiOwner = xwiki.getDatabase() + ":" + wikiOwner;
    }
    context.setWikiOwner(wikiOwner);
    context.setWikiServer(doc);

    wikiName = StringUtils.removeStart(wikiDefinition.getName(), "XWikiServer").toLowerCase();
    context.setDatabase(wikiName);
    context.setOriginalDatabase(wikiName);

    try {
        // Let's make sure the virtual wikis are upgraded to the latest database version
        xwiki.updateDatabase(wikiName, false, context);
    } catch (HibernateException ex) {
        // Just report it, hopefully the database is in a good enough state
        LOGGER.error("Failed to upgrade database: " + wikiName, ex);
    }
    return xwiki;
}

From source file:com.google.dart.tools.ui.internal.text.SemanticHighlightingTest.java

/**
 * Asserts that {@link #positions} has no position with given ID, at offset of "pattern" and with
 * length of the first space-separate word.
 *//*from   w ww .j ava  2 s .  c  om*/
private void assertNoWordPosition(String id, String pattern) throws Exception {
    int offset = findOffset(pattern);
    String word = StringUtils.substringBefore(pattern, " ");
    assertNoPosition(id, offset, word.length());
}

From source file:de.micromata.genome.util.types.Converter.java

/**
 * convert delimited string to map.//  w w w.ja  va2 s  .  c o m
 *
 * @param str String to Convert
 * @param d1 Delimiter zwischen den Eintrgen
 * @param d2 Delimiter zwischen den key=value Paaren
 * @return the map
 */
public static Map<String, String> delimitedStringToMap(String str, String d1, String d2) {
    String[] fields = StringUtils.split(str, d1);
    Map<String, String> map = new HashMap<String, String>();
    for (String fld : fields) {
        String key = StringUtils.substringBefore(fld, d2);
        String val = StringUtils.substringAfter(fld, d2);
        map.put(key, val);
    }
    return map;
}

From source file:de.blizzy.documentr.web.page.PageController.java

@RequestMapping(value = "/cherryPick/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/"
        + "{branchName:" + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{path:"
        + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}", method = RequestMethod.POST)
@PreAuthorize("hasPagePermission(#projectName, #branchName, #path, VIEW)")
public String cherryPick(@PathVariable String projectName, @PathVariable String branchName,
        @PathVariable String path, @RequestParam String version1, @RequestParam String version2,
        @RequestParam("branch") Set<String> targetBranches, @RequestParam boolean dryRun, WebRequest request,
        Model model, Authentication authentication, Locale locale) throws IOException {

    path = Util.toRealPagePath(path);

    for (String targetBranch : targetBranches) {
        if (!permissionEvaluator.hasPagePermission(authentication, projectName, targetBranch, path,
                Permission.EDIT_PAGE)) {

            return ErrorController.forbidden();
        }//from  w  w w.  j  a  va 2 s  .  c om
    }

    List<String> commits = cherryPicker.getCommitsList(projectName, branchName, path, version1, version2);
    if (commits.isEmpty()) {
        throw new IllegalArgumentException("no commits to cherry-pick"); //$NON-NLS-1$
    }

    User user = userStore.getUser(authentication.getName());

    Map<String, String[]> params = request.getParameterMap();
    Set<CommitCherryPickConflictResolve> resolves = Sets.newHashSet();
    for (Map.Entry<String, String[]> entry : params.entrySet()) {
        String name = entry.getKey();
        if (name.startsWith("resolveText_")) { //$NON-NLS-1$
            String branchCommit = StringUtils.substringAfter(name, "_"); //$NON-NLS-1$
            String branch = StringUtils.substringBefore(branchCommit, "/"); //$NON-NLS-1$
            String commit = StringUtils.substringAfter(branchCommit, "/"); //$NON-NLS-1$
            String text = entry.getValue()[0];
            CommitCherryPickConflictResolve resolve = new CommitCherryPickConflictResolve(branch, commit, text);
            resolves.add(resolve);
        }
    }

    Map<String, List<CommitCherryPickResult>> results = cherryPicker.cherryPick(projectName, branchName, path,
            commits, targetBranches, resolves, dryRun, user, locale);
    if (results.keySet().size() != targetBranches.size()) {
        throw new IllegalStateException();
    }

    if (!dryRun) {
        boolean allOk = true;
        loop: for (List<CommitCherryPickResult> branchResults : results.values()) {
            for (CommitCherryPickResult result : branchResults) {
                if (result.getStatus() != CommitCherryPickResult.Status.OK) {
                    allOk = false;
                    break loop;
                }
            }
        }

        if (allOk) {
            return "redirect:/page/" + projectName + "/" + branchName + //$NON-NLS-1$ //$NON-NLS-2$
                    "/" + Util.toUrlPagePath(path); //$NON-NLS-1$
        }
    }

    model.addAttribute("cherryPickResults", results); //$NON-NLS-1$
    model.addAttribute("version1", version1); //$NON-NLS-1$
    model.addAttribute("version2", version2); //$NON-NLS-1$
    model.addAttribute("resolves", resolves); //$NON-NLS-1$
    return "/project/branch/page/cherryPick"; //$NON-NLS-1$
}