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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:org.xwiki.users.internal.WikiUserManagerTest.java

private void setupMocks(final String passedIdentifier, final String targetSpace, final String targetUserWiki,
        final boolean existing) {
    final DocumentReference targetUser = new DocumentReference(targetUserWiki, "XWiki", "Admin");
    when(this.configuration.getProperty("users.defaultWiki", "local")).thenReturn("users");
    when(this.modelContext.getCurrentEntityReference())
            .thenReturn(new DocumentReference("local", "Main", "WebHome"));

    when(this.bridge.exists(new DocumentReference("xwiki", targetSpace, "Admin"))).thenReturn(false);
    when(this.bridge.exists(new DocumentReference("users", targetSpace, "Admin"))).thenReturn(false);
    when(this.bridge.exists(new DocumentReference("local", targetSpace, "Admin"))).thenReturn(false);
    when(this.bridge.exists(targetUser)).thenReturn(existing);

    when(this.referenceResolver.resolve(new EntityReference("XWikiUsers", EntityType.DOCUMENT,
            new EntityReference("XWiki", EntityType.SPACE)), EntityType.DOCUMENT, targetUser))
                    .thenReturn(new DocumentReference(targetUserWiki, "XWiki", "XWikiUsers"));

    when(this.serializer.serialize(targetUser, new Object[0]))
            .thenReturn(targetUserWiki + ":" + targetSpace + "." + StringUtils
                    .defaultIfEmpty(StringUtils.substringAfterLast(passedIdentifier, "."), passedIdentifier));

    if (passedIdentifier.startsWith(targetUserWiki + ":")) {
        when(this.nameResolver.resolve(passedIdentifier, EntityType.DOCUMENT,
                new EntityReference("XWiki", EntityType.SPACE, new WikiReference("local"))))
                        .thenReturn(targetUser);
    } else {/*from   w  ww . j a  v  a 2s  .  c  o  m*/
        when(this.nameResolver.resolve(passedIdentifier, EntityType.DOCUMENT,
                new EntityReference("XWiki", EntityType.SPACE, new WikiReference("xwiki"))))
                        .thenReturn(new DocumentReference("xwiki", targetSpace, "Admin"));
        when(this.nameResolver.resolve(passedIdentifier, EntityType.DOCUMENT,
                new EntityReference("XWiki", EntityType.SPACE, new WikiReference("users"))))
                        .thenReturn(new DocumentReference("users", targetSpace, "Admin"));
        when(this.nameResolver.resolve(passedIdentifier, EntityType.DOCUMENT,
                new EntityReference("XWiki", EntityType.SPACE, new WikiReference("local"))))
                        .thenReturn(new DocumentReference("local", targetSpace, "Admin"));
    }
}

From source file:org.xwiki.wikistream.instance.internal.output.XWikiDocumentOutputWikiStream.java

@Override
public void beginWikiClassProperty(String name, String type, FilterEventParameters parameters)
        throws WikiStreamException {
    ComponentManager componentManager = this.componentManagerProvider.get();

    PropertyClassProvider provider;//from w ww.  j  av a  2 s.co  m

    // First try to use the specified class type as hint.
    try {
        if (componentManager.hasComponent(PropertyClassProvider.class, type)) {
            provider = componentManager.getInstance(PropertyClassProvider.class, type);
        } else {
            // In previous versions the class type was the full Java class name of the property class
            // implementation. Extract the hint by removing the Java package prefix and the Class suffix.
            String classType = StringUtils.removeEnd(StringUtils.substringAfterLast(type, "."), "Class");
            provider = componentManager.getInstance(PropertyClassProvider.class, classType);
        }
    } catch (ComponentLookupException e) {
        throw new WikiStreamException(
                String.format("Failed to get instance of the property class provider for type [%s]", type), e);
    }

    this.currentClassPropertyMeta = provider.getDefinition();

    // We should use PropertyClassInterface (instead of PropertyClass, its default implementation) but it
    // doesn't have the set methods and adding them would breaks the backwards compatibility. We make the
    // assumption that all property classes extend PropertyClass.
    this.currentClassProperty = (PropertyClass) provider.getInstance();
    this.currentClassProperty.setName(name);
    this.currentClassProperty.setObject(this.currentXClass);

    this.currentXClass.safeput(name, this.currentClassProperty);
}

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');
        }/*from www .  j  av a  2 s  .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   www  .  j  ava  2 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:org.xwiki.wysiwyg.server.internal.plugin.importer.XWikiImportService.java

/**
 * @param fileName a file name// ww  w. j a  v a2  s  .  c  o m
 * @return {@code true} if the specified file is an office presentation, {@code false} otherwise
 */
private boolean isPresentation(String fileName) {
    String fileExtension = StringUtils.substringAfterLast(fileName, ".");
    return PRESENTATION_FORMAT_EXTENSIONS.contains(fileExtension);
}

From source file:org.xwiki.xar.internal.XarObjectPropertySerializerManager.java

/**
 * @param type the property type for which to find a serializer
 * @return the property serializer, if none could be found for the provided type the default one is returned
 * @throws ComponentLookupException when failing to lookup property serializer
 *//*from  w ww.  j  a  va 2 s .  c  o  m*/
public XarObjectPropertySerializer getPropertySerializer(String type) throws ComponentLookupException {
    if (type != null) {
        ComponentManager componentManager = this.componentManagerProvider.get();

        if (componentManager.hasComponent(XarObjectPropertySerializer.class, type)) {
            // First try to use the specified class type as hint.
            return getInstance(type, componentManager);
        } else {
            // In previous versions the class type was the full Java class name of the property class
            // implementation. Extract the hint by removing the Java package prefix and the Class suffix.
            String simpleType = StringUtils.removeEnd(StringUtils.substringAfterLast(type, "."), "Class");

            if (componentManager.hasComponent(XarObjectPropertySerializer.class, simpleType)) {
                return getInstance(simpleType, componentManager);
            }
        }
    }

    return this.defaultPropertySerializer;
}

From source file:password.pwm.http.servlet.peoplesearch.PeopleSearchResourcesServlet.java

@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    response.sendRedirect(String.format(
            // Build a relative URL with place holders:
            "%s%s/resources/app/fonts/%s",

            // Place holder values:
            request.getContextPath(), PwmConstants.URL_PREFIX_PUBLIC,
            StringUtils.substringAfterLast(request.getRequestURI(), "/")));
}

From source file:pcgen.io.ExportUtilities.java

/**
 * Retrieve the extension that should be used for the output file. This is base don the template name.  
 * @param templateFilename The filename of the export template.
 * @param isPdf Is this an export to a PDF file?
 * @return The output filename extension.
 *///from ww w. ja v a  2 s  .  c  om
public static String getOutputExtension(String templateFilename, boolean isPdf) {
    if (isPdf) {
        return "pdf";
    }

    if (templateFilename.endsWith(".ftl")) {
        templateFilename = templateFilename.substring(0, templateFilename.length() - 4);
    }
    String extension = StringUtils.substringAfterLast(templateFilename, ".");
    if (StringUtils.isEmpty(extension)) {
        extension = StringUtils.substringAfterLast(templateFilename, "-");
    }

    return extension;
}

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

private static void printRepo(String owner, String repo) {
    JSONArray array = null;//from  ww  w .j  a v  a2  s. c  o m
    try {
        array = Unirest.get("https://api.github.com/repos/" + owner + "/" + repo + "/releases")
                //               .basicAuth("thirdy", "quicksandisunderratedbandandofcthisisnotmyrealpassword") // note that basic auth is optional but you'll be limited to 60 request per hour
                .asJson().getBody().getArray();

        for (int i = 0; i < array.length(); i++) {

            JSONObject object = (JSONObject) array.get(i);
            String tag_name = object.getString("tag_name");
            String html_url = object.getString("html_url");

            JSONArray assets = (JSONArray) object.get("assets");

            for (int j = 0; j < assets.length(); j++) {
                JSONObject asset = (JSONObject) assets.get(j);
                String browser_download_url = asset.getString("browser_download_url");
                int download_count = asset.getInt("download_count");
                String created_at = asset.getString("created_at");

                print(created_at, owner, repo, html_url, tag_name,
                        StringUtils.substringAfterLast(browser_download_url, "/"), download_count);
            }

        }

    } catch (UnirestException e) {
        e.printStackTrace();
    }

}

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

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