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:com.gargoylesoftware.htmlunit.libraries.PrototypeTestBase.java

private String getExpectations(final BrowserVersion browserVersion, final String filename) throws IOException {
    final String fileNameBase = StringUtils.substringBeforeLast(filename, ".");
    final String baseName = "src/test/resources/libraries/prototype/" + getVersion() + "/expected."
            + fileNameBase;//from  www  .  j av a 2 s .  com

    File expectationsFile = null;
    // version specific to this browser (or browser group)?
    String browserSuffix = "." + browserVersion.getNickname();
    while (!browserSuffix.isEmpty()) {
        final File file = new File(baseName + browserSuffix + ".txt");
        if (file.exists()) {
            expectationsFile = file;
            break;
        }
        browserSuffix = browserSuffix.substring(0, browserSuffix.length() - 1);
    }

    // generic version
    if (expectationsFile == null) {
        expectationsFile = new File(baseName + ".txt");
        if (!expectationsFile.exists()) {
            throw new FileNotFoundException("Can't find expectations file (" + expectationsFile.getName()
                    + ") for test " + filename + "(" + browserVersion.getNickname() + ")");
        }
    }

    return FileUtils.readFileToString(expectationsFile, "UTF-8");
}

From source file:blue.lapis.pore.ap.event.EventVerifierProcessor.java

private void verifyName(TypeElement type) {
    TypeElement bukkitEvent = (TypeElement) ((DeclaredType) type.getSuperclass()).asElement();

    String poreName = StringUtils.removeStart(type.getQualifiedName().toString(), PORE_PREFIX);
    String porePackage = StringUtils.substringBeforeLast(poreName, ".");
    poreName = StringUtils.substringAfterLast(poreName, ".");

    String bukkitName = StringUtils.removeStart(bukkitEvent.getQualifiedName().toString(), BUKKIT_PREFIX);
    String bukkitPackage = StringUtils.substringBeforeLast(bukkitName, ".");
    bukkitName = StringUtils.substringAfterLast(bukkitName, ".");

    String expectedName = "Pore" + bukkitName;

    if (!poreName.equals(expectedName)) {
        processingEnv.getMessager().printMessage(SEVERITY, poreName + " should be called " + expectedName,
                type);//from  w w w .java 2 s.  c  om
    }
    if (!porePackage.equals(bukkitPackage)) {
        processingEnv.getMessager().printMessage(SEVERITY,
                poreName + " is in wrong package: should be in " + PORE_PREFIX + bukkitPackage, type);
    }
}

From source file:net.ripe.ipresource.Ipv6Address.java

private static String getIpv6AddressWithIpv4SectionInIpv6Notation(String ipAddressString) {
    String ipv6Section = StringUtils.substringBeforeLast(ipAddressString, ":");
    String ipv4Section = StringUtils.substringAfterLast(ipAddressString, ":");
    try {/*from www  .jav a 2  s .  com*/
        String ipv4SectionInIpv6Notation = StringUtils.join(
                new Ipv6Address(Ipv4Address.parse(ipv4Section).getValue()).toString().split(":"), ":", 2, 4);
        return ipv6Section + ":" + ipv4SectionInIpv6Notation;
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Embedded Ipv4 in IPv6 address is invalid: " + ipAddressString, e);
    }
}

From source file:com.neatresults.mgnltweaks.ui.action.SaveConfigAddNodeDialogAction.java

@Override
public void execute() throws ActionExecutionException {
    // First Validate
    validator.showValidation(true);//from ww w.j a va  2s.c  o m
    if (validator.isValid()) {

        // we support only JCR item adapters
        if (!(item instanceof JcrItemAdapter)) {
            return;
        }

        // don't save if no value changes occurred on adapter
        if (!((JcrItemAdapter) item).hasChangedProperties()) {
            return;
        }

        if (item instanceof AbstractJcrNodeAdapter) {
            // Saving JCR Node, getting updated node first
            AbstractJcrNodeAdapter nodeAdapter = (AbstractJcrNodeAdapter) item;
            try {
                String nodePath = ((String) nodeAdapter.getItemProperty("path").getValue()).trim();
                String nodeType = NodeTypes.ContentNode.NAME;
                if (nodeAdapter.getItemProperty("nodeType") != null) {
                    nodeType = ((String) nodeAdapter.getItemProperty("nodeType").getValue()).trim();
                }
                String parentNodeType = NodeTypes.Content.NAME;
                if (nodeAdapter.getItemProperty("parentNodeType") != null) {
                    parentNodeType = ((String) nodeAdapter.getItemProperty("parentNodeType").getValue()).trim();
                }
                Node node = nodeAdapter.getJcrItem();
                String propertyName = null;
                if (nodePath.contains("@")) {
                    propertyName = StringUtils.substringAfter(nodePath, "@").trim();
                    if (StringUtils.isEmpty(propertyName)) {
                        propertyName = null;
                    }
                    nodePath = StringUtils.substringBefore(nodePath, "@");
                }
                String nodeName = nodePath;
                if (nodePath.contains("/")) {
                    nodeName = StringUtils.substringAfterLast(nodePath, "/");
                    String parentPath = StringUtils.substringBeforeLast(nodePath, "/");
                    for (String parentName : parentPath.split("/")) {
                        node = JcrUtils.getOrAddNode(node, parentName, parentNodeType);
                    }
                }
                node = node.addNode(nodeName, nodeType);
                if (propertyName != null) {
                    String value = "";
                    if (nodeAdapter.getItemProperty("value") != null) {
                        value = ((String) nodeAdapter.getItemProperty("value").getValue());
                    }
                    node.setProperty(propertyName, value == null ? "" : value);
                }
                node.getSession().save();
                Location location = subAppContext.getLocation();
                String param = location.getParameter();
                param = node.getPath() + (propertyName != null ? ("@" + propertyName) : "") + ":"
                        + StringUtils.substringAfter(param, ":");
                location = new DefaultLocation(location.getAppType(), location.getAppName(),
                        location.getSubAppId(), param);
                adminEventBus.fireEvent(new LocationChangedEvent(location));
            } catch (RepositoryException e) {
                log.error("Could not save changes to node", e);
            }
            callback.onSuccess(getDefinition().getName());
        } else if (item instanceof JcrPropertyAdapter) {
            super.execute();
        }
    } else {
        log.debug("Validation error(s) occurred. No save performed.");
    }
}

From source file:de.vandermeer.skb.base.utils.Skb_STUtils.java

/**
 * Returns the name of the STGroup.//from  w  ww. ja v  a  2 s  .co m
 * Any file extension will be removed from the returned name.
 * @param stg STGroup
 * @return name of the group or null
 */
public static final String getStgName(STGroup stg) {
    String ret = null;
    if (stg instanceof STGroupFile) {
        ret = ((STGroupFile) stg).fileName;
    } else if (stg instanceof STGroupString) {
        ret = ((STGroupString) stg).sourceName;
    } else if (stg instanceof STGroupDir) {
        ret = ((STGroupDir) stg).groupDirName;
    }
    return StringUtils.substringBeforeLast(ret, ".");
}

From source file:net.sibcolombia.sibsp.model.Source.java

/**
 * This method normalises a file name by removing certain reserved characters and converting all file name characters
 * to lowercase.// ww  w .ja  v  a2 s  . c  o m
 * The reserved characters are:
 * <ul>
 * <li>All whitespace characters</li>
 * <li>All slash character</li>
 * <li>All backslash character</li>
 * <li>All question mark character</li>
 * <li>All percent character</li>
 * <li>All asterik character</li>
 * <li>All colon character</li>
 * <li>All pipe character</li>
 * <li>All less than character</li>
 * <li>All greater than character</li>
 * <li>All quote character</li>
 * </ul>
 * 
 * @param name to normalise, may be null
 * @return normalised name
 */
public static String normaliseName(@Nullable String name) {
    if (name == null) {
        return null;
    }
    return StringUtils.substringBeforeLast(name, ".").replaceAll("[\\s.:/\\\\*?%|><\"]+", "").toLowerCase();
}

From source file:info.magnolia.ui.contentapp.detail.DetailEditorPresenter.java

public View start(String nodePath, DetailView.ViewType viewType, ContentConnector contentConnector,
        String versionName) {//w ww.ja v  a 2s . c o  m
    this.contentConnector = contentConnector;
    this.nodePath = nodePath;

    view.setListener(this);
    Object itemId = contentConnector.getItemIdByUrlFragment(nodePath);

    if (contentConnector.canHandleItem(itemId)) {
        if (StringUtils.isNotEmpty(versionName) && DetailView.ViewType.VIEW.equals(viewType)
                && contentConnector instanceof SupportsVersions) {
            itemId = ((SupportsVersions) contentConnector).getItemVersion(itemId, versionName);
        }
    } else {
        if (contentConnector instanceof SupportsCreation) {
            Object parentId = contentConnector
                    .getItemIdByUrlFragment(StringUtils.substringBeforeLast(nodePath, "/"));
            itemId = ((SupportsCreation) contentConnector).getNewItemId(parentId,
                    editorDefinition.getNodeType().getName());
        }
    }

    // editor
    if (editorDefinition != null && editorDefinition.getForm() != null) {
        DetailView itemView = detailPresenter.start(editorDefinition, viewType, itemId);
        view.setItemView(itemView);
        detailPresenter.addShortcut(new CloseEditorAfterConfirmationShortcutListener(KeyCode.ESCAPE, itemView));
        detailPresenter.addShortcut(new CommitDialogShortcutListener(KeyCode.ENTER));
        if (editorDefinition.isWide()) {
            itemView.setWide(true);
        }
    } else {
        log.warn(
                "DetailPresenter expected an editor and a form definition, but no such definitions are currently configured.");
        view.setItemView(new StubView("icon-warning-l"));
        return view;
    }

    // actionbar
    actionbarPresenter.setListener(this);
    ActionbarView actionbar = actionbarPresenter.start(subAppDescriptor.getActionbar(),
            subAppDescriptor.getActions());
    view.setActionbarView(actionbar);

    return view;
}

From source file:ambroafb.clients.dialog.ClientDialogController.java

private void changeSceneVisualAsPerson(String delimiter) {
    first_name.setText(conf.getTitleFor("first_name"));
    last_name.setText(conf.getTitleFor("last_name"));

    VBox lastNameVBox = new VBox(last_name, lastName);
    namesRootPane.getChildren().add(1, lastNameVBox);
    lastNameVBox.getStyleClass().add("couple");

    setStylesForNamesPaneElements("oneThirds", "couple", "couple");

    String firmDescrip = firstName.getText();
    String firstNameText = StringUtils.substringBeforeLast(firmDescrip, delimiter);
    String lastNameText = StringUtils.substringAfterLast(firmDescrip, delimiter);
    firstName.setText(firstNameText.trim());
    lastName.setText(lastNameText.trim());
}

From source file:com.eryansky.common.orm.core.PageRequest.java

/**
 * ?Order By?sql//from w w  w  . j ava  2s. c om
 * @return String
 */
public String getOrderSortString() {
    List<Sort> list = this.getSort();
    StringBuffer buffer = new StringBuffer();
    for (Iterator<Sort> it = list.iterator(); it.hasNext();) {
        Sort sort = it.next();
        buffer.append(sort.property + " " + sort.dir).append(",");
    }

    return StringUtils.substringBeforeLast(buffer.toString(), ",");
}

From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param sr              The servlet request. Must not be
 *                        {@code null}./* w w  w .ja v a2  s.c  o  m*/
 * @param maxEntityLength The maximum entity length to accept, -1 for
 *                        no limit.
 *
 * @return The HTTP request.
 *
 * @throws IllegalArgumentException The the servlet request method is
 *                                  not GET, POST, PUT or DELETE or the
 *                                  content type header value couldn't
 *                                  be parsed.
 * @throws IOException              For a POST or PUT body that
 *                                  couldn't be read due to an I/O
 *                                  exception.
 */
public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength)
        throws IOException {

    HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase());

    String urlString = reconstructRequestURLString(sr);

    URL url;

    try {
        url = new URL(urlString);

    } catch (MalformedURLException e) {

        throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e);
    }

    HTTPRequest request = new HTTPRequest(method, url);

    try {
        request.setContentType(sr.getContentType());

    } catch (ParseException e) {

        throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e);
    }

    Enumeration<String> headerNames = sr.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        request.setHeader(headerName, sr.getHeader(headerName));
    }

    if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) {

        request.setQuery(sr.getQueryString());

    } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) {

        if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) {
            throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars");
        }

        Map<String, String[]> parameterMap = sr.getParameterMap();
        StringBuilder builder = new StringBuilder();

        if (!parameterMap.isEmpty()) {
            for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (value.length > 0 && value[0] != null) {
                    String encoded = URLEncoder.encode(value[0], "UTF-8");
                    builder = builder.append(key).append('=').append(encoded).append('&');
                }
            }
            String queryString = StringUtils.substringBeforeLast(builder.toString(), "&");
            request.setQuery(queryString);

        } else {
            // read body
            StringBuilder body = new StringBuilder(256);

            BufferedReader reader = sr.getReader();

            char[] cbuf = new char[256];

            int readChars;

            while ((readChars = reader.read(cbuf)) != -1) {

                body.append(cbuf, 0, readChars);

                if (maxEntityLength > 0 && body.length() > maxEntityLength) {
                    throw new IOException(
                            "Request entity body is too large, limit is " + maxEntityLength + " chars");
                }
            }

            reader.close();

            request.setQuery(body.toString());
        }
    }

    return request;
}