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.testeditor.fixture.host.HostDriverFixture.java

private void takeScreenshot(String filenameBase) {
    String testcase = getCurrentTestCase();
    String filename = filenameHelper.constructFilename(pathName, testcase, filenameBase, type);
    String filePath = StringUtils.substringBeforeLast(filename, "/");
    try {//from  www .  j  a  v  a2 s .c  o  m
        FileUtils.mkdir(new File(filePath), true);
    } catch (IOException e) {
        logger.warn("Something went wrong while creating screenshot for file {} :", filePath + filename);
    }
    Command command = new Command("PrintText", "PrintText html modi " + filename);
    Result result = connection.doCommand("PrintText html modi " + filename, command);
    if (result.getResultOfCommand().equals("ok")) {
        logger.trace("Wrote screenshot to file='{}'.", filename);
    } else {
        logger.warn("An Error occured while taking screenshots. Could not write screenshot to file='{}'.",
                filePath + filename);
    }
}

From source file:org.whispersystems.textsecuregcm.auth.AuthorizationHeader.java

public static AuthorizationHeader fromUserAndPassword(String user, String password)
        throws InvalidAuthorizationHeaderException {
    try {/*from w w w .  j  ava2 s  .com*/

        final String id = StringUtils.substringAfterLast(user, ".");
        if (StringUtils.isNumeric(id)) {
            return new AuthorizationHeader(StringUtils.substringBeforeLast(user, "."), Long.parseLong(id),
                    password);
        } else {
            return new AuthorizationHeader(user, 1, password);
        }

    } catch (NumberFormatException nfe) {
        throw new InvalidAuthorizationHeaderException(nfe);
    }
}

From source file:org.xlrnet.tibaija.FileSystemCodeProvider.java

@NotNull
public static String stripFilename(@NotNull String filename) {
    if (filename.contains("."))
        return StringUtils.substringBeforeLast(filename, ".").toUpperCase();
    return filename.toUpperCase();
}

From source file:org.xwiki.contrib.mailarchive.utils.internal.MailUtils.java

@Override
public IMAUser parseUser(final String user, final boolean isMatchLdap) {
    logger.debug("parseUser {}, {}", user, isMatchLdap);

    MAUser maUser = new MAUser();
    maUser.setOriginalAddress(user);/*from   ww  w  .  j av  a 2s  .co  m*/

    if (StringUtils.isBlank(user)) {
        return maUser;
    }

    String address = null;
    String personal = null;
    // Do our best to extract an address and a personal
    try {
        InternetAddress ia = null;
        InternetAddress[] result = InternetAddress.parse(user, true);
        if (result != null && result.length > 0) {
            ia = result[0];
            if (!StringUtils.isBlank(ia.getAddress())) {
                address = ia.getAddress();
            }
            if (!StringUtils.isBlank(ia.getPersonal())) {
                personal = ia.getPersonal();
            }
        }
    } catch (AddressException e) {
        logger.info("Email Address does not follow standards : " + user);
    }
    if (StringUtils.isBlank(address)) {
        String[] substrs = StringUtils.substringsBetween(user, "<", ">");
        if (substrs != null && substrs.length > 0) {
            address = substrs[0];
        } else {
            // nothing matches, we suppose recipient only contains email address
            address = user;
        }
    }
    if (StringUtils.isBlank(personal)) {
        if (user.contains("<")) {
            personal = StringUtils.substringBeforeLast(user, "<");
            if (StringUtils.isBlank(personal)) {
                personal = StringUtils.substringBefore(address, "@");
            }
        }

    }
    maUser.setAddress(address);
    maUser.setDisplayName(personal);

    // Now to match a wiki profile
    logger.debug("parseUser extracted email {}", address);
    String parsedUser = null;
    if (!StringUtils.isBlank(address)) {
        // to match "-external" emails and old mails with '@gemplus.com'...
        String pattern = address.toLowerCase();
        pattern = pattern.replace("-external", "").replaceAll("^(.*)@.*[.]com$", "$1%@%.com");
        logger.debug("parseUser pattern applied {}", pattern);
        // Try to find a wiki profile with this email as parameter.
        // TBD : do this in the loading phase, and only try to search db if it was not found ?
        String xwql = "select doc.fullName from Document doc, doc.object(XWiki.XWikiUsers) as user where LOWER(user.email) like :pattern";

        List<String> profiles = null;
        try {
            profiles = queryManager.createQuery(xwql, Query.XWQL).bindValue("pattern", pattern).execute();
        } catch (QueryException e) {
            logger.warn("parseUser Query threw exception", e);
            profiles = null;
        }
        if (profiles == null || profiles.size() == 0) {
            logger.debug("parseUser found no wiki profile from db");
            return maUser;
        } else {
            if (isMatchLdap) {
                logger.debug("parseUser Checking for LDAP authenticated profile(s) ...");
                // If there exists one, we prefer the user that's been authenticated through LDAP
                for (String usr : profiles) {
                    if (bridge.exists(usr, "XWiki.LDAPProfileClass")) {
                        parsedUser = usr;
                        logger.debug("parseUser Found LDAP authenticated profile {}", parsedUser);
                    }
                }
                if (parsedUser != null) {
                    maUser.setWikiProfile(parsedUser);
                    logger.debug("parseUser return {}", maUser);
                    return maUser;
                }
            }
        }

        // If none has authenticated from LDAP, we return the first user found
        maUser.setWikiProfile(profiles.get(0));
        logger.debug("parseUser return {}", maUser);
        return maUser;

    } else {
        logger.debug("parseUser No email found to match");
        return maUser;
    }

}

From source file:org.xwiki.filter.test.integration.FilterTest.java

private InputSource getInputSource(TestConfiguration testConfiguration, String value) throws FilterException {
    InputSource source;/*  www.j  a v a2 s . co m*/

    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 FilterException("Resource [" + sourceString + "] does not exist");
        }

        source = new DefaultURLInputSource(url);
    }

    return source;
}

From source file:org.xwiki.lesscss.internal.compiler.less4j.TemplateLESSSource.java

/**
 * Get the parent folder of a path using "/" as file separator.
 * @param templateName name of the template
 * @return the parent folder path//w  w  w  .  j  a v  a  2s.  c o  m
 */
private static String getParentFolder(String templateName) {
    return StringUtils.substringBeforeLast(templateName, FILE_SEPARATOR);
}

From source file:org.xwiki.officeimporter.internal.builder.DefaultPresentationBuilder.java

@Override
public XDOMOfficeDocument build(InputStream officeFileStream, String officeFileName,
        DocumentReference documentReference) throws OfficeImporterException {
    // Invoke OpenOffice document converter.
    Map<String, byte[]> artifacts = importPresentation(officeFileStream, officeFileName);

    // Create presentation HTML.
    String html = buildPresentationHTML(artifacts, StringUtils.substringBeforeLast(officeFileName, "."));

    // Clear and adjust presentation HTML (slide image URLs are updated to point to the corresponding attachments).
    html = cleanPresentationHTML(html, documentReference);

    // Create the XDOM.
    XDOM xdom = buildPresentationXDOM(html, documentReference);

    return new XDOMOfficeDocument(xdom, artifacts, componentManager);
}

From source file:org.xwiki.officeimporter.internal.builder.DefaultXHTMLOfficeDocumentBuilder.java

@Override
public XHTMLOfficeDocument build(InputStream officeFileStream, String officeFileName,
        DocumentReference reference, boolean filterStyles) throws OfficeImporterException {
    // Invoke OpenOffice document converter.
    Map<String, InputStream> inputStreams = new HashMap<String, InputStream>();
    inputStreams.put(officeFileName, officeFileStream);
    Map<String, byte[]> artifacts;
    // The OpenOffice converter uses the output file name extension to determine the output format/syntax.
    String outputFileName = StringUtils.substringBeforeLast(officeFileName, ".") + ".html";
    try {//from  w  w  w  .  j ava2  s.c o m
        artifacts = officeManager.getConverter().convert(inputStreams, officeFileName, outputFileName);
    } catch (OpenOfficeConverterException ex) {
        String message = "Error while converting document [%s] into html.";
        throw new OfficeImporterException(String.format(message, officeFileName), ex);
    }

    // Prepare the parameters for HTML cleaning.
    Map<String, String> params = new HashMap<String, String>();
    params.put("targetDocument", entityReferenceSerializer.serialize(reference));
    if (filterStyles) {
        params.put("filterStyles", "strict");
    }

    // Parse and clean the HTML output.
    InputStream htmlStream = new ByteArrayInputStream(artifacts.remove(outputFileName));
    InputStreamReader htmlReader = null;
    Document xhtmlDoc = null;
    try {
        htmlReader = new InputStreamReader(htmlStream, "UTF-8");
        HTMLCleanerConfiguration configuration = this.ooHtmlCleaner.getDefaultConfiguration();
        configuration.setParameters(params);
        xhtmlDoc = this.ooHtmlCleaner.clean(htmlReader, configuration);
    } catch (UnsupportedEncodingException ex) {
        throw new OfficeImporterException("Error: Could not encode html office content.", ex);
    } finally {
        IOUtils.closeQuietly(htmlReader);
        IOUtils.closeQuietly(htmlStream);
    }

    // Return a new XHTMLOfficeDocument instance.
    return new XHTMLOfficeDocument(xhtmlDoc, artifacts);
}

From source file:org.xwiki.rendering.test.cts.TestDataParser.java

/**
 * Find {@code *.xml} files in the classpath and return the list of all resources found, without their filename
 * extensions. For example if {@code {ctsDirectoryName}/simple/bold/bold1.*.xml} is found, return
 * {@code simple/bold/bold1}./*from   w w  w  .  j a v a 2 s.  c om*/
 *
 * @param ctsRootPackageName the root of the CTS resources
 * @param packageFilter the regex to filter packages
 * @param pattern a regex to decide which {@code *.xml} resources should be found. The default should be to find
 *        them all
 * @return the list of relative test directories found
 */
public Set<String> findRelativeTestDirectoryNames(String ctsRootPackageName, String packageFilter,
        String pattern) {
    Reflections reflections = new Reflections(new ConfigurationBuilder().setScanners(new ResourcesScanner())
            .setUrls(ClasspathHelper.forPackage(ctsRootPackageName)).filterInputsBy(
                    new FilterBuilder.Include(FilterBuilder.prefix(ctsRootPackageName + DOT + packageFilter))));

    Set<String> prefixes = new TreeSet<String>();
    for (String fullTestDirectoryName : reflections.getResources(Pattern.compile(pattern))) {
        // Remove the prefix and trailing extension
        String testDirectoryName = StringUtils.substringAfter(fullTestDirectoryName,
                ctsRootPackageName + SLASH);
        testDirectoryName = StringUtils.substringBeforeLast(testDirectoryName, ".inout.xml");
        prefixes.add(testDirectoryName);
    }

    return prefixes;
}

From source file:org.xwiki.tool.xar.AbstractVerifyMojo.java

/**
 * Guess the {@code &lt;defaultLanguage&gt;} value to use for the passed file using the following algorithm:
 * <ul>/*  w  w w.jav  a2 s.  c  o m*/
 *     <li>If the page name matches one of the regexes defined by the user as content pages then check that the
 *         default language is {@link #defaultLanguage}.</li>
 *     <li>If the page name matches one of the regexes defined by the user as technial pages then check that the
 *         default language is empty. Matching technical pages have precedence over matching content pages.</li>
 *     <li>If there's no other translation of the file then consider default language to be empty to signify that
 *         it's a technical document. </li>
 *     <li>If there are other translations ("(prefix).(language).xml" format) then the default language should be
 *         {@link #defaultLanguage}</li>
 * </ul>
 * @since 5.4.1
 */
protected String guessDefaultLanguage(File file, Collection<File> xwikiXmlFiles) {
    String fileName = file.getName();

    // Note that we need to check for content pages before technical pages because some pages are both content
    // pages (Translation pages for example) and technical pages.

    // Is it in the list of defined content pages?
    String language = guessDefaultLanguageForPatterns(fileName, this.contentPagePatterns, this.defaultLanguage);
    if (language != null) {
        return language;
    }

    // Is it in the list of defined technical pages?
    language = guessDefaultLanguageForPatterns(fileName, this.technicalPagePatterns, "");
    if (language != null) {
        return language;
    }

    language = "";

    // Check if the doc is a translation
    Matcher matcher = TRANSLATION_PATTERN.matcher(fileName);
    if (matcher.matches()) {
        // We're in a translation, use the default language
        language = this.defaultLanguage;
    } else {
        // We're not in a translation, check if there are translations. First get the doc name before the extension
        String prefix = StringUtils.substringBeforeLast(fileName, EXTENSION);
        // Check for a translation now
        Pattern translationPattern = Pattern.compile(String.format("%s\\..*\\.xml", Pattern.quote(prefix)));
        for (File xwikiXmlFile : xwikiXmlFiles) {
            Matcher translationMatcher = translationPattern.matcher(xwikiXmlFile.getName());
            if (translationMatcher.matches()) {
                // Found a translation, use the default language
                language = this.defaultLanguage;
                break;
            }
        }
    }
    return language;
}