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.thruzero.common.core.support.EntityPath.java

/**
 * Construct an instance from the given {@code entityPath}, which must begin but not end with a "/".
 *//*from   w  w w  . ja  v a2 s .com*/
public EntityPath(String entityPath) {
    if (StringUtils.isEmpty(entityPath)) {
        throw new RuntimeException("Invalid entity path. Path can't be empty.");
    }

    // Ensure path begins with CONTAINER_PATH_SEPARATOR
    if (!entityPath.startsWith(ContainerPath.CONTAINER_PATH_SEPARATOR)) {
        entityPath = ContainerPath.CONTAINER_PATH_SEPARATOR + entityPath;
    }

    // split container and name
    String containerPathAsString = StringUtils.substringBeforeLast(entityPath,
            ContainerPath.CONTAINER_PATH_SEPARATOR);
    rootDataStorePath = null;
    containerPath = new ContainerPath(
            StringUtils.isEmpty(containerPathAsString) ? ContainerPath.CONTAINER_PATH_SEPARATOR
                    : containerPathAsString + ContainerPath.CONTAINER_PATH_SEPARATOR);
    entityName = StringUtils.substringAfterLast(entityPath, ContainerPath.CONTAINER_PATH_SEPARATOR);
}

From source file:io.wcm.handler.url.suffix.impl.UrlSuffixUtil.java

/**
 * Split suffix/*from  w  w w.  ja v a 2 s  .c om*/
 * @param suffix Suffix
 * @return Suffix parts
 */
public static String[] splitSuffix(String suffix) {
    String theSuffix = suffix;

    String[] parts;
    if (StringUtils.isBlank(theSuffix)) {
        // no suffix given - return empty list
        parts = new String[0];
    } else {
        // remove leading slash
        if (theSuffix.startsWith(ESCAPED_SLASH)) {
            theSuffix = theSuffix.substring(ESCAPED_SLASH.length());
        }

        // remove file extension
        theSuffix = StringUtils.substringBeforeLast(theSuffix, ".");

        // split the suffix to extract the paths of the selected components
        parts = StringUtils.split(theSuffix, SUFFIX_PART_DELIMITER);
    }

    return parts;
}

From source file:com.epam.dlab.module.aws.S3FileList.java

private Stream<? extends String> lastFileForBillingPeriod(Map.Entry<String, List<S3ObjectSummary>> entry) {
    final List<S3ObjectSummary> assemblyIds = entry.getValue();
    final S3ObjectSummary lastBillingFile = assemblyIds.stream()
            .max(Comparator.comparing(S3ObjectSummary::getLastModified))
            .orElseThrow(() -> new IllegalStateException("AssemblyId does not contains any file"));
    return assemblyIds.stream()
            .filter(s -> s.getKey().startsWith(StringUtils.substringBeforeLast(lastBillingFile.getKey(), "/")))
            .map(S3ObjectSummary::getKey);
}

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

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param servletRequest              The servlet request. Must not be
 *                        {@code null}.//ww  w  .  j a v a2 s  .co  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 servletRequest, final long maxEntityLength)
        throws IOException {

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

    String urlString = reconstructRequestURLString(servletRequest);

    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(servletRequest.getContentType());

    } catch (ParseException e) {

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

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

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

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

        request.setQuery(servletRequest.getQueryString());

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

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

        Map<String, String[]> parameterMap = servletRequest.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 = servletRequest.getReader();
            reader.reset();
            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.reset();
            // reader.close();

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

    return request;
}

From source file:com.vip.saturn.job.console.domain.RegistryCenterConfiguration.java

public void initNameAndNamespace(String nameAndNamespace) {
    this.namespace = StringUtils.substringAfterLast(nameAndNamespace, SLASH);
    this.name = StringUtils.substringBeforeLast(nameAndNamespace, SLASH);
}

From source file:info.magnolia.security.app.dialog.field.AccessControlList.java

private Entry doGetEntryFromNode(Node entryNode) throws RepositoryException {
    long permissions = entryNode.getProperty(PERMISSIONS_PROPERTY_NAME).getLong();
    String path = entryNode.getProperty(PATH_PROPERTY_NAME).getString();

    long accessType;

    if (path.endsWith("/*")) {
        accessType = ACCESS_TYPE_CHILDREN;
        path = path.equals("/*") ? "/" : StringUtils.substringBeforeLast(path, "/*");
    } else {/*from ww  w .j  a  va  2 s.  co m*/
        accessType = ACCESS_TYPE_NODE;
        path = path.equals("/") ? path : StringUtils.removeEnd(path, "/");
    }

    return new Entry(permissions, accessType, path);
}

From source file:de.blizzy.documentr.markdown.macro.GroovyMacroScanner.java

List<String> listMacros() {
    List<File> files = Lists.newArrayList(findGroovyMacroFiles());
    Function<File, String> function = new Function<File, String>() {
        @Override//  w w  w .  j  a v a 2s .c o m
        public String apply(File file) {
            return StringUtils.substringBeforeLast(file.getName(), ".groovy"); //$NON-NLS-1$
        }
    };
    List<String> result = Lists.newArrayList(Lists.transform(files, function));
    Collections.sort(result, new Comparator<String>() {
        @Override
        public int compare(String name1, String name2) {
            return name1.compareToIgnoreCase(name2);
        }
    });
    return result;
}

From source file:com.zht.common.codegen.util.HiberStrUtil.java

public static void handlerProperty_Double$Float$BigDecimal(GenEntityProperty prop) {

    StringBuffer hiberColumnStr = new StringBuffer("");
    StringBuffer hiberValidateStr = new StringBuffer("");

    String clumnName = prop.getColumnName();
    Integer precision = prop.getPrecision();
    Integer scale = prop.getScale();

    Boolean nullAble = prop.getNullable();
    Boolean unique = prop.getUnique();

    //-------hiberValidateStr---------
    Double min = prop.getMinValue();
    Double max = prop.getMaxValue();

    if (min != null) {
        hiberValidateStr.append("@javax.validation.constraints.DecimalMin(\"" + min + "\") \r\t");
    }//w  ww.  jav a 2 s  . c  o  m
    if (max != null) {
        hiberValidateStr.append("@javax.validation.constraints.DecimalMax(\"" + max + "\") \r\t");
    }
    if (nullAble != null && nullAble == false) {
        hiberValidateStr.append("@javax.validation.constraints.NotNull \r\t");
    }
    //-------hiberValidateStr---------
    hiberColumnStr.append("name = \"" + clumnName + "\",");
    if (precision != null) {
        hiberColumnStr.append("precision = " + precision + ",");
    }
    if (scale != null) {
        hiberColumnStr.append("scale = " + scale + ",");
    }

    if (unique != null) {
        hiberColumnStr.append("unique = " + unique + ",");
    }
    if (nullAble != null) {
        hiberColumnStr.append("nullable = " + nullAble + ",");
    }
    String sd = hiberColumnStr.toString().trim();
    if (sd.endsWith(",")) {
        sd = StringUtils.substringBeforeLast(sd, ",");
    }
    sd = "@javax.persistence.Column(" + sd + ")";

    prop.setGeneratedHibernateModelOfPropertyStr(hiberValidateStr + sd);

}

From source file:com.projectsontracks.model.CaribooKey.java

/**
 * Encrypts the AES key into a password protected ZIP file
 *
 * @param outputFile//from w  ww . ja  v  a 2s.c o m
 * @param password
 * @throws java.io.IOException
 * @throws java.security.GeneralSecurityException
 * @throws net.lingala.zip4j.exception.ZipException
 * @throws com.projectsontracks.model.CaribooException
 */
public void saveKey(String outputFile, String password)
        throws IOException, GeneralSecurityException, ZipException, CaribooException {

    // write AES key
    String tmpFileName = StringUtils.substringBeforeLast(outputFile, ".") + "." + KEY_FILE_EXTENSION;
    FileOutputStream os = new FileOutputStream(tmpFileName);
    os.write(key);
    os.close();

    // Initiate ZipFile object with the path/name of the zip file.
    ZipFile zipFile = new ZipFile(outputFile);

    // Initiate Zip Parameters which define various properties such
    // as compression method, etc. More parameters are explained in other
    // examples
    ZipParameters parameters = new ZipParameters();
    parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to store compression

    // Set the compression level. This value has to be in between 0 to 9
    // Several predefined compression levels are available
    // DEFLATE_LEVEL_FASTEST - Lowest compression level but higher speed of compression
    // DEFLATE_LEVEL_FAST - Low compression level but higher speed of compression
    // DEFLATE_LEVEL_NORMAL - Optimal balance between compression level/speed
    // DEFLATE_LEVEL_MAXIMUM - High compression level with a compromise of speed
    // DEFLATE_LEVEL_ULTRA - Highest compression level but low speed
    parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

    // Set the encryption flag to true
    // If this is set to false, then the rest of encryption properties are ignored
    parameters.setEncryptFiles(true);

    // Set the encryption method to AES Zip Encryption
    parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);

    // Set AES Key strength. Key strengths available for AES encryption are:
    // AES_STRENGTH_128 - For both encryption and decryption
    // AES_STRENGTH_192 - For decryption only
    // AES_STRENGTH_256 - For both encryption and decryption
    // Key strength 192 cannot be used for encryption. But if a zip file already has a
    // file encrypted with key strength of 192, then Zip4j can decrypt this file
    parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);

    // Set password
    parameters.setPassword(password);

    // Now add files to the zip file
    // Note: To add a single file, the method addFile can be used
    // Note: If the zip file already exists and if this zip file is a split file
    // then this method throws an exception as Zip Format Specification does not
    // allow updating split zip files
    zipFile.addFile(new File(tmpFileName), parameters);

    // delete the key file
    FileUtils.deleteTempFile(tmpFileName);
}

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

private void parseLocation(InputStream is, HttpClient httpClient, SitemapURLAdder sitemapURLAdder,
        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, sitemapURLAdder, resolvedLocations);
                parseState.loc = false;/*from   w  w  w  .j a  va2  s .c o m*/
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLAdder, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}