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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:net.sf.jabb.util.web.WebApplicationConfiguration.java

/**
 * Scan all the beans for menu items/*  www.j a va 2  s  . c o m*/
 */
public void scanForMenuItems() {
    Map<String, Map<String, MenuItemExt>> allMenuItems = new PutIfAbsentMap<String, Map<String, MenuItemExt>>(
            new HashMap<String, Map<String, MenuItemExt>>(),
            new MapValueFactory<String, Map<String, MenuItemExt>>() {
                @Override
                public Map<String, MenuItemExt> createValue(String key) {
                    return new TreeMap<String, MenuItemExt>();
                }
            });
    //new HashMap<String, Map<String, MenuItemExt>>();   // <menuName, <path, MenuItemExt>>

    // Get all beans that may have menu items defined
    Map<String, Object> beans = appContext.getBeansWithAnnotation(WebMenu.class);
    beans.putAll(appContext.getBeansWithAnnotation(RequestMapping.class));

    // Find all menu items 
    for (Object bean : beans.values()) {
        Class<?> beanClass;
        if (bean instanceof Advised) { // if EnhancerBySpringCGLIB
            beanClass = ((Advised) bean).getTargetClass();
        } else {
            beanClass = bean.getClass();
        }

        // Check class level annotations first
        RequestMapping classRequestMapping = beanClass.getAnnotation(RequestMapping.class);
        WebMenu classWebMenu = beanClass.getAnnotation(WebMenu.class);
        if (true) {//classWebMenu != null && classWebMenu.value().length() != 0){   // not hidden
            MenuItemExt classMenuItem = new MenuItemExt(classWebMenu, classRequestMapping);

            String basePath = classMenuItem.path != null ? classMenuItem.path : "";
            if (classMenuItem.title != null && classMenuItem.title.length() > 0) { // it is also a visible menu item
                MenuItemExt existing = allMenuItems.get(classMenuItem.menuName).put(basePath, classMenuItem);
                if (existing != null) {
                    log.error("Duplicated web menu item definitions in " + beanClass.getName()
                            + ".\n\tExisting: " + existing + "\n\tCurrent: " + classMenuItem);
                }
            }

            // Then look into all the methods
            for (Method method : beanClass.getDeclaredMethods()) {
                RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
                WebMenu methodWebMenu = method.getAnnotation(WebMenu.class);
                if (methodWebMenu != null && methodWebMenu.value().length() != 0) { // not hidden
                    MenuItemExt methodMenuItem = new MenuItemExt(methodWebMenu, methodRequestMapping,
                            classMenuItem);

                    if (methodMenuItem.menuName != null) {
                        MenuItemExt existing = allMenuItems.get(methodMenuItem.menuName)
                                .put(methodMenuItem.path, methodMenuItem);
                        if (existing != null) {
                            log.error("Duplicated web menu item definitions in " + beanClass.getName() + "."
                                    + method.toGenericString() + ".\n\tExisting: " + existing + "\n\tCurrent: "
                                    + methodMenuItem);
                        }
                    }
                }
            }
        }
    }

    // construct menu trees
    menus = new HashMap<String, WebMenuItem>();
    menuItemPaths = new HashMap<String, Map<String, WebMenuItem>>();

    for (Map.Entry<String, Map<String, MenuItemExt>> menuItems : allMenuItems.entrySet()) {
        String menuName = menuItems.getKey();
        Map<String, MenuItemExt> items = menuItems.getValue();
        WebMenuItem root = new WebMenuItem();
        root.title = menuName; // for the root, set its title as menu name
        root.breadcrumbs = new ArrayList<WebMenuItem>(1);
        root.breadcrumbs.add(root); // root is the first in breadcrumbs
        menus.put(menuName, root);
        menuItemPaths.put(menuName, new HashMap<String, WebMenuItem>());
        for (MenuItemExt itemExt : items.values()) {
            String path = itemExt.path;
            WebMenuItem parent = null;
            do {
                path = StringUtils.substringBeforeLast(path, "/");
                if (path == null || path.indexOf('/') == -1) {
                    parent = root;
                    break;
                }
                parent = items.get(path);
            } while (parent == null);
            parent.addSubItem(itemExt);
        }

        // clean up the tree
        cleanUpMenuTree(root, menuName);
        log.info("Menu '" + menuName + "' loaded:\n" + root);
    }
}

From source file:io.github.swagger2markup.Swagger2MarkupMojo.java

private String getInputDirStructurePath(Swagger2MarkupConverter converter) {
    /*/*w  w  w  .  j  a v a2  s  . c  o  m*/
     * When the Swagger input is a local folder (e.g. /Users/foo/) you'll want to group the generated output in the
     * configured output directory. The most obvious approach is to replicate the folder structure from the input
     * folder to the output folder. Example:
     * - swaggerInput is set to /Users/foo
     * - there's a single Swagger file at /Users/foo/bar-service/v1/bar.yaml
     * - outputDir is set to /tmp/asciidoc
     * -> markdown files from bar.yaml are generated to /tmp/asciidoc/bar-service/v1
     */
    String swaggerFilePath = new File(converter.getContext().getSwaggerLocation()).getAbsolutePath(); // /Users/foo/bar-service/v1/bar.yaml
    String swaggerFileFolder = StringUtils.substringBeforeLast(swaggerFilePath, File.separator); // /Users/foo/bar-service/v1
    return StringUtils.remove(swaggerFileFolder, getSwaggerInputAbsolutePath()); // /bar-service/v1
}

From source file:de.blizzy.documentr.markdown.macro.impl.NeighborsMacroTest.java

private void setupPage(String pagePath) throws IOException {
    String parentPagePath = pagePath.contains("/") ? //$NON-NLS-1$
            StringUtils.substringBeforeLast(pagePath, "/") : //$NON-NLS-1$
            null;/*from   ww w.  j av a  2  s. co m*/
    Page page = Page.fromText(pagePath, "text"); //$NON-NLS-1$
    TestPageUtil.setParentPagePath(page, parentPagePath);
    when(pageStore.getPage(PROJECT, BRANCH, pagePath, false)).thenReturn(page);
}

From source file:com.netflix.spinnaker.clouddriver.ecs.provider.view.EcsServerClusterProvider.java

private Map<String, Set<EcsServerCluster>> findClustersForRegion(Map<String, Set<EcsServerCluster>> clusterMap,
        AmazonCredentials credentials, AmazonCredentials.AWSRegion awsRegion, String application) {

    Collection<Service> services = serviceCacheClient.getAll(credentials.getName(), awsRegion.getName());
    Collection<Task> allTasks = taskCacheClient.getAll(credentials.getName(), awsRegion.getName());

    for (Service service : services) {
        String applicationName = service.getApplicationName();
        String serviceName = service.getServiceName();

        if (application != null && !applicationName.equals(application)) {
            continue;
        }//  w  ww . j  av a2 s . co m

        Set<LoadBalancer> loadBalancers = new HashSet<>(
                ecsLoadbalancerCacheClient.find(credentials.getName(), awsRegion.getName()));

        Set<Instance> instances = allTasks.stream()
                .filter(task -> task.getGroup().equals("service:" + serviceName))
                .map(task -> convertToEcsTask(credentials.getName(), awsRegion.getName(), serviceName, task))
                .collect(Collectors.toSet());

        String taskDefinitionKey = Keys.getTaskDefinitionKey(credentials.getName(), awsRegion.getName(),
                service.getTaskDefinition());
        com.amazonaws.services.ecs.model.TaskDefinition taskDefinition = taskDefinitionCacheClient
                .get(taskDefinitionKey);
        if (taskDefinition == null) {
            continue;
        }

        EcsServerGroup ecsServerGroup = buildEcsServerGroup(credentials.getName(), awsRegion.getName(),
                serviceName, service.getDesiredCount(), instances, service.getCreatedAt(),
                service.getClusterName(), taskDefinition);

        if (ecsServerGroup == null) {
            continue;
        }

        if (clusterMap.containsKey(applicationName)) {
            String escClusterName = StringUtils.substringBeforeLast(ecsServerGroup.getName(), "-");
            boolean found = false;

            for (EcsServerCluster cluster : clusterMap.get(applicationName)) {
                if (cluster.getName().equals(escClusterName)) {
                    cluster.getServerGroups().add(ecsServerGroup);
                    found = true;
                    break;
                }
            }

            if (!found) {
                EcsServerCluster spinnakerCluster = buildSpinnakerServerCluster(credentials, loadBalancers,
                        ecsServerGroup);
                clusterMap.get(applicationName).add(spinnakerCluster);
            }
        } else {
            EcsServerCluster spinnakerCluster = buildSpinnakerServerCluster(credentials, loadBalancers,
                    ecsServerGroup);
            clusterMap.put(applicationName, Sets.newHashSet(spinnakerCluster));
        }
    }

    return clusterMap;
}

From source file:kenh.xscript.elements.Debug.java

private void list(JList c) {
    if (result == null)
        return;/*w w w .ja  v  a2 s . c  om*/

    if (StringUtils.isBlank(c.getSelectedValue().toString()))
        return;

    if (this.getEnvironment() != null) {

        String context = "";
        try {
            Object obj = this.getEnvironment().getVariable(c.getSelectedValue().toString());
            if (obj != null) {

                context = c.getSelectedValue().toString() + LINE_SEP + LINE_SEP;

                context += "-- Class: " + obj.getClass().getCanonicalName() + LINE_SEP;

                context += LINE_SEP;
                context += "-- Fields: " + LINE_SEP;
                Field[] fields = obj.getClass().getFields();

                for (Field field : fields) {
                    int i = field.getModifiers();
                    String retval = Modifier.toString(i);
                    if (StringUtils.contains(retval, "public")) {
                        context += "\t" + field.getName() + " - " + retval + LINE_SEP;
                    }
                }

                context += LINE_SEP;
                context += "-- Method: " + LINE_SEP;
                java.lang.reflect.Method[] methods = obj.getClass().getMethods();

                for (java.lang.reflect.Method method : methods) {
                    int i = method.getModifiers();
                    String retval = Modifier.toString(i);
                    if (StringUtils.contains(retval, "public")) {
                        Class[] pcs = method.getParameterTypes();
                        StringBuffer sb = new StringBuffer();

                        for (Class c_ : pcs) {
                            String s = c_.getSimpleName();
                            sb.append(s + ", ");
                        }

                        String p = StringUtils.trimToEmpty(StringUtils.substringBeforeLast(sb.toString(), ","));

                        context += "\t" + method.getName() + "(" + p + ") - " + retval + LINE_SEP;
                    }
                }

            } else {
                context = "<null>";
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            context = sw.toString();
        }

        result.setText(context);

    } else {
        result.setText(c.getSelectedValue().toString());
    }

    result.setCaretPosition(0);
    c.requestFocus();
}

From source file:com.norconex.collector.http.sitemap.impl.DefaultSitemapResolver.java

private void parseLocation(InputStream is, DefaultHttpClient httpClient, SitemapURLStore sitemapURLStore,
        Set<String> resolvedLocations, String location) throws XMLStreamException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
    ParseState parseState = new ParseState();

    String locationDir = StringUtils.substringBeforeLast(location, "/");
    int event = xmlReader.getEventType();
    while (true) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String tag = xmlReader.getLocalName();
            parseStartElement(parseState, tag);
            break;
        case XMLStreamConstants.CHARACTERS:
            String value = xmlReader.getText();
            if (parseState.sitemapIndex && parseState.loc) {
                resolveLocation(value, httpClient, sitemapURLStore, resolvedLocations);
                parseState.loc = false;//from w  w w . j a v  a  2  s.  c om
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLStore, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}

From source file:info.magnolia.ui.framework.command.ImportZipCommand.java

private String extractEntryPath(ZipArchiveEntry entry) {
    String entryName = entry.getName();
    String path = (StringUtils.contains(entryName, "/")) ? StringUtils.substringBeforeLast(entryName, "/")
            : "/";

    if (!path.startsWith("/")) {
        path = "/" + path;
    }//from  ww  w.  j  a v  a2 s .co m

    // make proper name, the path was already created
    path = StringUtils.replace(path, "/", BACKSLASH_DUMMY);
    path = Path.getValidatedLabel(path);
    path = StringUtils.replace(path, BACKSLASH_DUMMY, "/");
    return path;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.DataImporter.java

public void createMissingNode(String path, ResourceResolver rr, Map<String, CompositeVariant> row)
        throws PersistenceException {
    String parentPath = StringUtils.substringBeforeLast(path, "/");
    Resource parent = ResourceUtil.getOrCreateResource(rr, parentPath, defaultNodeType, defaultNodeType, true);
    String nodeName = StringUtils.substringAfterLast(path, "/");
    if (!row.containsKey(JCR_PRIMARY_TYPE)) {
        row.put("JCR_TYPE", new CompositeVariant(defaultNodeType));
    }/*from  w w  w .ja  v a  2s .co  m*/
    Map<String, Object> nodeProps = new HashMap(row);
    rr.refresh();
    rr.create(parent, nodeName, nodeProps);
}

From source file:com.iorga.iraj.servlet.AgglomeratorServlet.java

private void parseResource(final ServletConfig config, final String path)
        throws IOException, URISyntaxException {
    //TODO catch the modifications on the path itself
    final URL pathUrl = config.getServletContext().getResource(path);
    long lastModified = pathUrl.openConnection().getLastModified();
    final InputStream targetIS = pathUrl.openStream();
    final Document document = Jsoup.parse(targetIS, "UTF-8", "");
    final Elements elements = document.getElementsByAttribute(ATTRIBUTE_NAME);
    for (final Element element : elements) {
        // each element which defines iraj-agglomerate
        // retrieve the suffix
        final String suffix = element.attr(ATTRIBUTE_NAME);
        final String urlAttribute = element.attr(URL_ATTRIBUTE_ATTRIBUTE_NAME);
        String src = StringUtils.removeEndIgnoreCase(element.attr(urlAttribute), suffix);
        String prefix = "";
        if (!src.startsWith("/")) {
            // this is not an absolute file, let's add the prefix from the given path
            prefix = StringUtils.substringBeforeLast(path, "/") + "/";
            src = prefix + src;//  w  ww. j  av  a  2 s  . c  o  m
        }
        // searching all scripts inside the folder defined by src attribute
        lastModified = searchAndAppendAfter(config, element, src, prefix, suffix, urlAttribute, lastModified);
        // finally remove it
        element.remove();
    }

    caches.put(path, new ParsedResourceCacheEntry(path, document, lastModified));
}

From source file:com.google.dart.tools.core.internal.builder.AnalysisMarkerManager.java

/**
 * @return the {@link ErrorCode} enumeration constant for string from
 *         {@link #encodeErrorCode(ErrorCode)}.
 *//*  ww  w  . j a  va 2 s  .  c  o  m*/
private static ErrorCode decodeErrorCode(String encoding) {
    try {
        String className = StringUtils.substringBeforeLast(encoding, ".");
        String fieldName = StringUtils.substringAfterLast(encoding, ".");
        Class<?> errorCodeClass = Class.forName(className);
        return (ErrorCode) errorCodeClass.getField(fieldName).get(null);
    } catch (Throwable e) {
        return null;
    }
}