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:org.xwiki.webjars.internal.FilesystemResourceReferenceCopier.java

private void processCSSfile(String resourcePrefix, String targetPrefix, JarEntry entry, JarFile jar,
        FilesystemExportContext exportContext) throws Exception {
    // Limitation: we only support url() constructs located on a single line
    try (BufferedReader br = new BufferedReader(new InputStreamReader(jar.getInputStream(entry), "UTF-8"))) {
        String line;//from w  ww . j  av  a 2 s. c  om
        while ((line = br.readLine()) != null) {
            Matcher matcher = URL_PATTERN.matcher(line);
            while (matcher.find()) {
                String url = matcher.group(1);
                // Determine if URL is relative
                if (isRelativeURL(url)) {
                    // Remove any query string part and any fragment part too
                    url = StringUtils.substringBefore(url, "?");
                    url = StringUtils.substringBefore(url, "#");
                    // Normalize paths
                    String resourceName = String.format(CONCAT_PATH_FORMAT,
                            StringUtils.substringBeforeLast(entry.getName(), "/"), url);
                    resourceName = new URI(resourceName).normalize().getPath();
                    resourceName = resourceName.substring(resourcePrefix.length() + 1);
                    // Copy to filesystem
                    copyResourceFromJAR(resourcePrefix, resourceName, targetPrefix, exportContext);
                }
            }
        }
    }
}

From source file:org.xwiki.wikistream.test.integration.TestDataParser.java

private void addExpect(TestResourceData data, String typeId, StringBuilder buffer,
        Map<String, String> configuration) {
    ExpectTestConfiguration expectTestConfiguration = new ExpectTestConfiguration();

    // expect//from  ww w .  ja v a  2 s.  c o  m

    InputSource expect;

    String expectPath = configuration.get(WikiStreamConstants.PROPERTY_SOURCE);
    if (expectPath == null) {
        expect = new StringInputSource(buffer.toString());
    } else {
        if (!expectPath.startsWith("/")) {
            expectPath = StringUtils.substringBeforeLast(data.resourceName, "/") + '/' + expectPath;
        }

        expect = new DefaultURLInputSource(getClass().getResource(expectPath));
    }

    expectTestConfiguration.expect = expect;

    // output

    OutputTestConfiguration outputConfiguration = new OutputTestConfiguration(typeId);

    // Default properties
    outputConfiguration.setEncoding("UTF-8");
    outputConfiguration.setFormat(true);

    outputConfiguration.putAll(configuration);

    expectTestConfiguration.output = outputConfiguration;

    data.expects.add(expectTestConfiguration);
}

From source file:org.xwiki.wikistream.test.integration.WikiStreamTest.java

private InputSource getInputSource(TestConfiguration testConfiguration, String value)
        throws WikiStreamException {
    InputSource source;//from   www  .ja v  a2  s .c om

    String sourceString = TestDataParser.interpret(value);

    File file = new File(sourceString);

    if (file.exists()) {
        // It's a file

        source = new DefaultFileInputSource(file);
    } else {
        // If not a file it's probably a resource

        if (!sourceString.startsWith("/")) {
            sourceString = StringUtils.substringBeforeLast(testConfiguration.resourceName, "/") + '/'
                    + sourceString;
        }

        URL url = getClass().getResource(sourceString);

        if (url == null) {
            throw new WikiStreamException("Resource [" + sourceString + "] does not exist");
        }

        source = new DefaultURLInputSource(url);
    }

    return source;
}

From source file:org.xwiki.wysiwyg.filter.ConversionFilter.java

private void handleConversionErrors(Map<String, Throwable> errors, Map<String, String> output,
        MutableServletRequest mreq, ServletResponse res) throws IOException {
    ServletRequest req = mreq.getRequest();
    if (req instanceof HttpServletRequest
            && "XMLHttpRequest".equals(((HttpServletRequest) req).getHeader("X-Requested-With"))) {
        // If this is an AJAX request then we should simply send back the error.
        StringBuilder errorMessage = new StringBuilder();
        // Aggregate all error messages (for all fields that have conversion errors).
        for (Map.Entry<String, Throwable> entry : errors.entrySet()) {
            errorMessage.append(entry.getKey()).append(": ");
            errorMessage.append(entry.getValue().getLocalizedMessage()).append('\n');
        }/*  ww  w  . j  ava  2s  . c o m*/
        ((HttpServletResponse) res).sendError(400, errorMessage.substring(0, errorMessage.length() - 1));
        return;
    }
    // Otherwise, if this is a normal request, we have to redirect the request back and provide a key to
    // access the exception and the value before the conversion from the session.
    // Redirect to the error page specified on the request.
    String redirectURL = mreq.getParameter("xerror");
    if (redirectURL == null) {
        // Redirect to the referrer page.
        redirectURL = mreq.getReferer();
    }
    // Extract the query string.
    String queryString = StringUtils.substringAfterLast(redirectURL, String.valueOf('?'));
    // Remove the query string.
    redirectURL = StringUtils.substringBeforeLast(redirectURL, String.valueOf('?'));
    // Remove the previous key from the query string. We have to do this since this might not be the first
    // time the conversion fails for this redirect URL.
    queryString = queryString.replaceAll("key=.*&?", "");
    if (queryString.length() > 0 && !queryString.endsWith(String.valueOf('&'))) {
        queryString += '&';
    }
    // Save the output and the caught exceptions on the session.
    queryString += "key=" + save(mreq, output, errors);
    mreq.sendRedirect(res, redirectURL + '?' + queryString);
}

From source file:org.xwiki.wysiwyg.server.filter.ConversionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    // Take the list of request parameters that require HTML conversion.
    String[] parametersRequiringHTMLConversion = req.getParameterValues(REQUIRES_HTML_CONVERSION);
    if (parametersRequiringHTMLConversion != null) {
        MutableServletRequestFactory mreqFactory = (MutableServletRequestFactory) Utils
                .getComponent(MutableServletRequestFactory.class, req.getProtocol());
        // Wrap the current request in order to be able to change request parameters.
        MutableServletRequest mreq = mreqFactory.newInstance(req);
        // Remove the list of request parameters that require HTML conversion to avoid recurrency.
        mreq.removeParameter(REQUIRES_HTML_CONVERSION);
        // Try to convert each parameter from the list and save caught exceptions.
        Map<String, Throwable> errors = new HashMap<String, Throwable>();
        // Save also the output to prevent loosing data in case of conversion exceptions.
        Map<String, String> output = new HashMap<String, String>();
        for (int i = 0; i < parametersRequiringHTMLConversion.length; i++) {
            String parameterName = parametersRequiringHTMLConversion[i];
            if (StringUtils.isEmpty(parameterName)) {
                continue;
            }/*from w ww . j a v  a2  s .co  m*/
            // Remove the syntax parameter from the request to avoid interference with further request processing.
            String syntax = mreq.removeParameter(parameterName + "_syntax");
            try {
                HTMLConverter converter = Utils.getComponent(HTMLConverter.class);
                mreq.setParameter(parameterName, converter.fromHTML(req.getParameter(parameterName), syntax));
            } catch (Exception e) {
                LOGGER.error(e.getLocalizedMessage(), e);
                errors.put(parameterName, e);
            }
            // If the conversion fails the output contains the value before the conversion.
            output.put(parameterName, mreq.getParameter(parameterName));
        }

        if (!errors.isEmpty()) {
            // In case of a conversion exception we have to redirect the request back and provide a key to access
            // the exception and the value before the conversion from the session.
            // Redirect to the error page specified on the request.
            String redirectURL = mreq.getParameter("xerror");
            if (redirectURL == null) {
                // Redirect to the referrer page.
                redirectURL = mreq.getReferer();
            }
            // Extract the query string.
            String queryString = StringUtils.substringAfterLast(redirectURL, String.valueOf('?'));
            // Remove the query string.
            redirectURL = StringUtils.substringBeforeLast(redirectURL, String.valueOf('?'));
            // Remove the previous key from the query string. We have to do this since this might not be the first
            // time the conversion fails for this redirect URL.
            queryString = queryString.replaceAll("key=.*&?", "");
            if (queryString.length() > 0 && !queryString.endsWith(String.valueOf('&'))) {
                queryString += '&';
            }
            // Save the output and the caught exceptions on the session.
            queryString += "key=" + save(mreq, output, errors);
            mreq.sendRedirect(res, redirectURL + '?' + queryString);
        } else {
            chain.doFilter(mreq, res);
        }
    } else {
        chain.doFilter(req, res);
    }
}

From source file:pl.bcichecki.rms.client.android.services.clients.restful.AbstractRestClient.java

protected String getAbsoluteAddress(String... resourceSuffixes) {
    StringBuilder absoluteAddress = new StringBuilder();
    absoluteAddress.append(HttpConstants.PROTOCOL_HTTPS).append(host).append(HttpConstants.COLON).append(port)
            .append(webServiceContextPath);
    for (String resourceSuffix : resourceSuffixes) {
        if (!resourceSuffix.startsWith(HttpConstants.PATH_SEPARATOR)) {
            absoluteAddress.append(HttpConstants.PATH_SEPARATOR);
        }//  w  ww. ja  v a  2  s . c o  m
        if (resourceSuffix.endsWith(HttpConstants.PATH_SEPARATOR)) {
            resourceSuffix = StringUtils.substringBeforeLast(resourceSuffix, HttpConstants.PATH_SEPARATOR);
        }
        absoluteAddress.append(resourceSuffix);
    }
    return absoluteAddress.toString();
}

From source file:poe.trade.assist.Main.java

private List<CSVRecord> loadCSVRaw() {
    List<CSVRecord> records = null;
    try {//  ww w. j  a  v a 2  s . c  o  m
        String searchFileFromTextField = StringUtils.trimToEmpty(searchFileTextField.getText());
        if (searchFileFromTextField.isEmpty()
                || searchFileFromTextField.equalsIgnoreCase(LOCAL_SEARCH_FILE_NAME)) {
            File file = getSearchFile();
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                CSVParser csvParser = CSVFormat.RFC4180.withHeader().parse(br);
                records = csvParser.getRecords();
            }
        } else {
            String url = searchFileFromTextField;
            if (url.contains("google") && url.contains("/edit")) {
                // handle google spreadsheet url that is not an export url
                // https://docs.google.com/spreadsheets/d/1V8r0mIn5njpmVYwFWpqnptAMI6udrIaqhCby1i79UGw/edit#gid=0
                url = StringUtils.substringBeforeLast(url, "/edit");
                url += "/export?gid=0&format=csv";
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
                CSVParser csvParser = CSVFormat.RFC4180.withHeader().parse(br);
                records = csvParser.getRecords();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        Dialogs.showError(e);
    }
    return records;
}

From source file:randori.compiler.internal.utils.AnnotationUtils.java

public static String toEnumQualifiedName(String type) {
    if (type.indexOf(".") == -1)
        return type;
    return StringUtils.substringBeforeLast(type, ".");
}

From source file:reconf.server.services.security.SecurityAccessDecisionManager.java

@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (!(object instanceof FilterInvocation)) {
        return;/*from  w  w  w  . java2  s  .c  o  m*/
    }
    if (authentication == null) {
        return;
    }
    FilterInvocation filterInvocation = (FilterInvocation) object;

    String url = filterInvocation.getRequestUrl();
    if (url.endsWith("/")) {
        url = StringUtils.substringBeforeLast(url, "/");
    }

    AntPathMatcher antMatcher = new AntPathMatcher();
    if (antMatcher.match("/crud/product", url)) {
        if (userDetailsManager.userExists(authentication.getName())) {
            return;
        }
    }
    if (antMatcher.match("/crud/product/{product}", url)) {
        if (continueToProduct(authentication, antMatcher, "/crud/product/{product}", url)) {
            return;
        }
    }
    if (antMatcher.match("/crud/product/{product}/**", url)) {
        if (continueToProduct(authentication, antMatcher, "/crud/product/{product}/**", url)) {
            return;
        }
    }
    if (antMatcher.match("/crud/user", url)) {
        if (userDetailsManager.userExists(authentication.getName())) {
            return;
        }
    }
    if (antMatcher.match("/crud/user/**", url)) {
        if (ApplicationSecurity.isRoot(authentication)) {
            return;
        }
    }
    throw new AccessDeniedException("Forbidden");
}

From source file:therian.buildweaver.StandardOperatorsProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {//from   w  ww  . j a va2s.c o  m
        final FileObject resource = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT,
                StringUtils.substringBeforeLast(TARGET_CLASSNAME, ".").replace('.', '/'),
                StringUtils.substringAfterLast(TARGET_CLASSNAME, ".") + ".class");

        if (resource.getLastModified() > 0L) {
            processingEnv.getMessager().printMessage(Kind.NOTE,
                    String.format("%s already generated", TARGET_CLASSNAME));
            return false;
        }
    } catch (IOException e1) {
        // expected, swallow
    }
    try {
        ClassUtils.getClass(TARGET_CLASSNAME);
        processingEnv.getMessager().printMessage(Kind.ERROR,
                String.format("%s exists on classpath", TARGET_CLASSNAME));
        return false;
    } catch (ClassNotFoundException e) {
        // expected, swallow
    }

    if (roundEnv.processingOver()) {
        write();
        return true;
    }
    for (TypeElement ann : annotations) {
        final Set<? extends Element> standardOperatorElements = roundEnv.getElementsAnnotatedWith(ann);
        originatingElements.addAll(standardOperatorElements);

        for (Element element : standardOperatorElements) {
            Validate.validState(isValidStandardOperator(element), "%s is not a valid @StandardOperator",
                    appendTo(new StringBuilder(), element).toString());

            if (element.getKind() == ElementKind.CLASS) {
                operators.add(appendTo(new StringBuilder("new "), element).append("()").toString());
            }
            if (element.getKind() == ElementKind.METHOD) {
                operators.add(appendTo(new StringBuilder(), element).append("()").toString());
            }
            if (element.getKind() == ElementKind.FIELD) {
                operators.add(appendTo(new StringBuilder(), element).toString());
            }
        }
    }
    return true;
}