Example usage for org.apache.commons.lang StringUtils substringBeforeLast

List of usage examples for org.apache.commons.lang StringUtils substringBeforeLast

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBeforeLast.

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:mitm.application.djigzo.james.matchers.SubjectPhoneNumber.java

@Override
public Collection<MailAddress> matchMail(Mail mail) throws MessagingException {
    List<MailAddress> matchingRecipients = null;

    String phoneNumber = null;/*from   ww  w  .j a  va 2  s  .c o m*/

    MimeMessage message = mail.getMessage();

    /*
     * We need to check whether the original subject is stored in the mail attributes because
     * the check for the telephone number should be done on the original subject. The reason
     * for this is that the current subject can result in the detection of an incorrect
     * telephone number because the subject was changed because the subject trigger was
     * removed. 
     * 
     * Example:
     *  
     * original subject is: "test 123 [encrypt] 123456". The subject is: "test 123 123456" after
     * the trigger has been removed. The telephone nr 123123456 is detected instead of 123456.
     * 
     * See bug report: https://jira.djigzo.com/browse/GATEWAY-11
     * 
     */
    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    String originalSubject = mailAttributes.getOriginalSubject();

    if (originalSubject == null) {
        originalSubject = message.getSubject();
    }

    if (StringUtils.isNotBlank(originalSubject)) {
        Matcher matcher = phoneNumberPattern.matcher(originalSubject);

        if (matcher.find()) {
            phoneNumber = matcher.group();

            /*
             * Remove the match and set the subject without the number. 
             * 
             * Note: the match should be removed from the current subject!!
             * 
             * Note2: using substringBeforeLast is only correct if the pattern matches the end
             * of the subject (which is the default). If the pattern matches something in the
             * middle, substringBeforeLast should not be used.
             */
            message.setSubject(StringUtils.substringBeforeLast(message.getSubject(), phoneNumber));
        }
    }

    if (StringUtils.isNotBlank(phoneNumber)) {
        matchingRecipients = MailAddressUtils.getRecipients(mail);

        int nrOfRecipients = CollectionUtils.getSize(matchingRecipients);

        if (nrOfRecipients == 1) {
            try {
                boolean added = addPhoneNumber(mail, matchingRecipients.get(0), phoneNumber);

                if (!added) {
                    /* 
                     * addPhoneNumbers has more thorough checks to see if the phone 
                     * number is valid and if not, there will be no matcj
                     */
                    matchingRecipients = Collections.emptyList();
                }
            } catch (DatabaseException e) {
                throw new MessagingException("Exception adding phone numbers.", e);
            }
        } else {
            /*
             * A telephone number was found but we cannot add the number to a users account
             * because we do not known to which recipient the number belongs. We will however
             * return all the recipients.
             */
            logger.warn("Found " + nrOfRecipients + " recipients but only one is supported.");
        }
    }

    if (matchingRecipients == null) {
        matchingRecipients = Collections.emptyList();
    }

    return matchingRecipients;
}

From source file:de.awtools.basic.file.AWToolsFileUtils.java

/**
 * Extrahiert aus einem Dateibezeichner den Verzeichnispfad. Beispiel:<br/>
 * Der Parameter <code>temp/ab/db/text.txt</code> fhrt zu der Rckgabe
 * <code>/temp/ab/db</code>. hnliches versucht die Methode
 * <code>File.getParent()</code>, kann aber z.B. die zwei Pfade
 * 'temp/test.txt' und '/temp/test.txt' nicht auf Gleichheit prfen.
 *
 * @param fileName Der Dateibezeichner dessen Verzeichnispfad ermittelt
 *  werden soll.//w  w  w .  j  a  v a 2s .  c o m
 * @return Der Verzeichnispfad.
 */
public static String getParent(final String fileName) {
    String tmp = AWToolsFileUtils.normalizePath(fileName);
    if (StringUtils.contains(tmp, "/")) {
        return StringUtils.substringBeforeLast(tmp, "/");
    } else {
        return "";
    }
}

From source file:com.hexin.core.dao.BaseDaoSupport.java

public <T> Page<T> findMySqlPageWithBlob(JdbcTemplate jdbcTemplate, String sql, Class<T> dtoClass,
        PageCondition pageCondition, Object... args) throws SecurityException, IllegalArgumentException,
        SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, IOException {

    Page<T> page = new Page<T>();
    StringBuffer countSqlBuf = new StringBuffer();
    int currentPage = 1;
    int pageSize = 10;
    String camelSortBy = "";
    String underlineSortBy = "";
    String orderBy = "";
    long total;/*from w ww  .j  av  a 2  s.c om*/
    long totalPage;
    List<T> resultList = null;

    // distinct
    countSqlBuf.append("select count(*) from (");
    countSqlBuf.append(StringUtils.substringBeforeLast(sql, "order "));
    countSqlBuf.append(") tmp_table");
    debugSql(countSqlBuf.toString(), args);

    // 
    total = jdbcTemplate.queryForObject(countSqlBuf.toString(), Long.class, args);
    page.setTotal(total);

    StringBuffer pageSqlBuf = new StringBuffer();
    pageSqlBuf.append("select * from (");
    pageSqlBuf.append(sql);
    pageSqlBuf.append(") t ");

    if (pageCondition != null) {
        currentPage = pageCondition.getPage();
        pageSize = pageCondition.getRows();
        camelSortBy = pageCondition.getSort();
        orderBy = pageCondition.getOrder();

        // ????
        underlineSortBy = IcpObjectUtil.camelToUnderline(camelSortBy);
    }

    if (StringUtils.isNotEmpty(underlineSortBy) && StringUtils.isNotEmpty(orderBy)) {
        pageSqlBuf.append(" order by ");
        pageSqlBuf.append(underlineSortBy).append(" ").append(orderBy).append(" ");
    }
    pageSqlBuf.append(" limit ");
    pageSqlBuf.append((currentPage - 1) * pageSize);
    pageSqlBuf.append(" ,");
    pageSqlBuf.append(pageSize);
    pageSqlBuf.append(" ");

    debugSql(pageSqlBuf.toString(), args);

    resultList = findListWithBlob(pageSqlBuf.toString(), dtoClass, args);

    long mod = total % pageSize;
    if (mod == 0) {
        totalPage = total / pageSize;
    } else {
        totalPage = total / pageSize + 1;
    }

    page.setRows(resultList);
    page.setCurrentPage(currentPage);
    page.setPageSize(pageSize);
    page.setTotalPage(totalPage);
    page.setPageIndex(PageIndex.getPageIndex(Constants.PAGE_RANGE, pageSize, totalPage));

    return page;
}

From source file:fr.dutra.confluence2wordpress.wp.WordpressClient.java

/**
 * @param file//w  w w  .  j av  a2  s .com
 * @return
 * @throws WordpressXmlRpcException
 */
public Future<WordpressFile> uploadFile(final WordpressFile file) {

    return pool.submit(new Callable<WordpressFile>() {

        @Override
        public WordpressFile call() throws Exception {

            Vector<Object> params = new Vector<Object>();
            params.add(wordpressConnection.getBlogId());
            params.add(wordpressConnection.getUsername());
            params.add(wordpressConnection.getPassword());

            Hashtable<String, Object> map = new Hashtable<String, Object>();
            map.put("name", file.getFileName());
            map.put("type", file.getMimeType());
            map.put("bits", file.getData());
            // see http://core.trac.wordpress.org/ticket/17604
            map.put("overwrite", true);
            params.add(map);

            Map<String, ?> response = invoke(UPLOAD_FILE_METHOD_NAME, params);

            file.setFileName((String) response.get("file"));
            file.setMimeType((String) response.get("type"));
            file.setUrl((String) response.get("url"));

            String baseUrl = StringUtils.substringBeforeLast(file.getUrl(), "/");

            if (response.get("meta") != null && response.get("meta") instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, ?> meta = (Map<String, ?>) response.get("meta");
                if (meta != null) {
                    if (meta.containsKey("height")) {
                        file.setHeight((Integer) meta.get("height"));
                    }
                    if (meta.containsKey("width")) {
                        file.setWidth((Integer) meta.get("width"));
                    }
                    @SuppressWarnings("unchecked")
                    Map<String, ?> sizes = (Map<String, ?>) meta.get("sizes");
                    if (sizes != null) {
                        for (Entry<String, ?> entry : sizes.entrySet()) {
                            @SuppressWarnings("unchecked")
                            Map<String, ?> value = (Map<String, ?>) entry.getValue();
                            WordpressFile alternative = createAlternative(value, file.getMimeType(), baseUrl);
                            file.putAlternative(entry.getKey(), alternative);
                        }
                    }
                }
            }
            return file;
        }
    });

}

From source file:adalid.util.velocity.SecondBaseBuilder.java

private boolean copyTextFiles() {
    Collection<File> files = FileUtils.listFiles(projectFolder, textFileFilter(), textDirFilter());
    //      ColUtils.sort(files);
    String source, target, targetParent;
    boolean java, jrxml, properties, sh, bat, xml;
    String[] precedingWords = { "extends", "import", "new", "@see", "@throws" };
    SmallFile smallSource;/*from   www . j  ava 2  s  . c om*/
    List<String> sourceLines;
    List<String> targetLines = new ArrayList<>();
    for (File file : files) {
        source = file.getPath();
        java = StringUtils.endsWithIgnoreCase(source, ".java");
        jrxml = StringUtils.endsWithIgnoreCase(source, ".jrxml");
        properties = StringUtils.endsWithIgnoreCase(source, ".properties");
        sh = StringUtils.endsWithIgnoreCase(source, ".sh");
        bat = StringUtils.endsWithIgnoreCase(source, ".bat");
        xml = StringUtils.endsWithIgnoreCase(source, ".xml");
        target = source.replace(projectFolderPath, velocityTemplatesTargetFolderPath) + VM;
        targetParent = StringUtils.substringBeforeLast(target, FS);
        targetLines.clear();
        FilUtils.mkdirs(targetParent);
        smallSource = new SmallFile(source);
        sourceLines = smallSource.read();
        check(smallSource);
        if (smallSource.isNotEmpty()) {
            for (String line : sourceLines) {
                if (StringUtils.isNotBlank(line)) {
                    if (java && line.matches(PACKAGE_REGEX)) {
                        line = "package $package;";
                    } else {
                        line = line.replace("$", "${dollar}");
                        line = line.replace("#", "${pound}");
                        line = line.replace("\\", "${backslash}");
                        line = line.replace(project, PROJECT_ALIAS);
                        line = line.replace(PROJECT, PROJECT_ALIAS_UPPER_CASE);
                        if (java) {
                            for (String word : precedingWords) {
                                line = replaceAliasWithRootPackageName(line, word + " ", ".");
                            }
                            line = replaceAliasWithRootPackageName(line, "String BASE_NAME = ", ".");
                            line = replaceAliasWithRootPackageName(line, "new ResourceBundleHandler(", ".");
                        }
                        if (jrxml) {
                            line = replaceAliasWithRootPackageName(line, "<import value=\"", ".");
                        }
                        if (properties) {
                            line = StrUtils.replaceAfter(line, PROJECT_ALIAS + ".", ROOT_PACKAGE_NAME + ".",
                                    "${pound}");
                            line = StrUtils.replaceAfter(line, PROJECT_ALIAS + ".", ROOT_PACKAGE_NAME + ".",
                                    "file.resource.loader.class");
                            line = replaceAliasWithRootPackageName(line, "log4j.category.", "=");
                            line = replaceAliasWithRootPackageName(line, "log4j.additivity.", "=");
                        }
                        if (sh) {
                            line = StrUtils.replaceAfter(line, PROJECT_ALIAS, DATABASE_NAME, "dbname=");
                        }
                        if (bat) {
                            line = StrUtils.replaceAfter(line, PROJECT_ALIAS, DATABASE_NAME, "dbname=");
                        }
                        if (xml) {
                            line = replaceAliasWithDatabaseName(line, "jdbc/", "");
                            line = replaceAliasWithDatabaseName(line, "localhost:5432/", "");
                            line = StrUtils.replaceAfter(line, PROJECT_ALIAS + "-pool", DATABASE_NAME + "-pool",
                                    "pool-name=");
                            line = replaceAliasWithRootPackageName(line, "<logger category=\"", "\">");
                        }
                    }
                }
                targetLines.add(line);
            }
        }
        if (write(target, targetLines, WINDOWS_CHARSET)) {
            textFilesCopied++;
            createTextFilePropertiesFile(source, target);
        }
    }
    return true;
}

From source file:info.magnolia.module.admininterface.AdminTreeMVCHandler.java

public Content copyMoveNode(String source, String destination, boolean move)
        throws ExchangeException, RepositoryException {
    // todo: ??? generic -> RequestInterceptor.java
    if (getHierarchyManager().isExist(destination)) {
        String parentPath = StringUtils.substringBeforeLast(destination, "/"); //$NON-NLS-1$
        String label = StringUtils.substringAfterLast(destination, "/"); //$NON-NLS-1$
        label = Path.getUniqueLabel(getHierarchyManager(), parentPath, label);
        destination = parentPath + "/" + label; //$NON-NLS-1$
    }//from w  ww  .j a v  a 2 s .c o m
    if (move) {
        if (destination.indexOf(source + "/") == 0) { //$NON-NLS-1$
            // todo: disable this possibility in javascript
            // move source into destinatin not possible
            return null;
        }
        this.deActivateNode(source);
        try {
            getHierarchyManager().moveTo(source, destination);
        } catch (Exception e) {
            // try to move below node data
            return null;
        }
    } else {
        // copy
        getHierarchyManager().copyTo(source, destination);
    }
    // SessionAccessControl.invalidateUser(this.getRequest());
    Content newContent = getHierarchyManager().getContent(destination);
    try {
        newContent.updateMetaData();
        newContent.getMetaData().setUnActivated();
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Exception caught: " + e.getMessage(), e); //$NON-NLS-1$
    }
    newContent.save();
    return newContent;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.renovator.Renovator.java

private void identifyStructureFromRoot(AtomicInteger visitedSourceNodes, String source, String dest,
        ResourceResolver rr, Resource res, MovingNode root) throws TraversalException {
    root.setDestinationPath(dest);/*from  w w w  . j a  va2 s .  co  m*/
    if (root instanceof MovingAsset) {
        String destFolder = StringUtils.substringBeforeLast(dest, "/");
        if (!additionalTargetFolders.contains(destFolder) && rr.getResource(destFolder) == null) {
            additionalTargetFolders.add(destFolder);
        }
    }
    moves.add(root);
    note(source, Report.misc, "Root path");
    note(source, Report.target, dest);

    TreeFilteringResourceVisitor visitor = new TreeFilteringResourceVisitor(JcrConstants.NT_FOLDER,
            JcrResourceConstants.NT_SLING_FOLDER, JcrResourceConstants.NT_SLING_ORDERED_FOLDER,
            NameConstants.NT_PAGE);

    visitor.setResourceVisitorChecked((r, level) -> buildMoveTree(r, level, root, visitedSourceNodes));
    visitor.setLeafVisitorChecked((r, level) -> buildMoveTree(r, level, root, visitedSourceNodes));

    visitor.accept(res);
    note("All scanned nodes", Report.misc, "Scanned " + visitedSourceNodes.get() + " source nodes.");
}

From source file:com.amalto.core.query.user.UserQueryHelper.java

public static List<TypedExpression> getFields(ComplexTypeMetadata type, String fieldName) {
    if (type == null) {
        throw new IllegalArgumentException("Type cannot be null."); //$NON-NLS-1$ 
    }/* w ww. j  ava 2 s  .  c  o  m*/
    // Considers attributes as elements
    // TODO This is assuming attributes are elements... which is true when these line were written.
    if (fieldName.startsWith("@")) { //$NON-NLS-1$
        fieldName = fieldName.substring(1);
    }
    int position = -1;
    if (fieldName.indexOf('[') > 0) {
        // Check if there's multiple [] in path (unsupported).
        if (fieldName.indexOf('[', fieldName.indexOf('[') + 1) > 0) {
            throw new IllegalArgumentException("Does not support multiple index in path.");
        }
        position = Integer.parseInt(fieldName.substring(fieldName.indexOf('[') + 1, fieldName.indexOf(']')))
                - 1;
        fieldName = fieldName.substring(0, fieldName.indexOf('['));
    }
    // Additional trim() (in case XPath is like "Entity/FieldName  ").
    fieldName = fieldName.trim();
    MetadataField metadataField = MetadataField.Factory.getMetadataField(fieldName);
    if (metadataField != null) {
        return Collections.singletonList(metadataField.getConditionExpression());
    }
    if (fieldName.endsWith("xsi:type") || fieldName.endsWith("tmdm:type")) { //$NON-NLS-1$ //$NON-NLS-2$
        FieldMetadata field = type.getField(StringUtils.substringBeforeLast(fieldName, "/")); //$NON-NLS-1$
        if (fieldName.endsWith("xsi:type")) { //$NON-NLS-1$
            return Collections.singletonList(alias(type(field), "xsi:type")); //$NON-NLS-1$
        } else {
            return Collections.singletonList(alias(type(field), "tmdm:type")); //$NON-NLS-1$
        }
    } else if (UserQueryBuilder.ID_FIELD.equals(fieldName)) {
        Collection<FieldMetadata> keyFields = type.getKeyFields();
        if (keyFields.isEmpty()) {
            throw new IllegalArgumentException(
                    "Can not query id on type '" + type.getName() + "' because type has no id field."); //$NON-NLS-1$//$NON-NLS-2$
        }
        List<TypedExpression> expressions = new LinkedList<TypedExpression>();
        for (FieldMetadata keyField : keyFields) {
            expressions.add(new Field(keyField));
        }
        return expressions;
    } else if ("/*".equals(fieldName)) { //$NON-NLS-1$
        List<TypedExpression> expressions = new LinkedList<TypedExpression>();
        for (FieldMetadata field : type.getFields()) {
            expressions.add(new Field(field));
        }
        return expressions;
    }
    FieldMetadata field = type.getField(fieldName);
    if (field == null) {
        throw new FieldNotFoundException(
                "Field '" + fieldName + "' does not exist in type '" + type.getName() + "'."); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
    }
    if (field instanceof ContainedTypeFieldMetadata) {
        // Field does not contain a value, expected behavior is to return empty string.
        return Collections.<TypedExpression>singletonList(
                new Alias(new StringConstant(StringUtils.EMPTY), field.getName()));
    } else {
        if (position > -1) {
            return Collections.<TypedExpression>singletonList(new IndexedField(field, position));
        } else {
            return Collections.<TypedExpression>singletonList(new Field(field));
        }
    }
}

From source file:com.fortify.bugtracker.common.src.context.AbstractSourceContextGenerator.java

/**
 * Add on-demand data to the given {@link AbstractRestConnectionQueryBuilder}
 * based on {@link ISourceContextGeneratorConfiguration#getExtraData()}.
 * //from  w ww. j  a  va2 s. c o  m
 * @param queryBuilder
 */
private final void addOnDemandData(AbstractRestConnectionQueryBuilder<?, ?> queryBuilder) {
    // TODO Remove code duplication with SourceVulnerabilityProcessorHelper
    Map<String, String> extraData = getConfig().getExtraData();
    if (extraData != null) {
        for (Map.Entry<String, String> entry : extraData.entrySet()) {
            String propertyName = entry.getKey();
            String uriString = StringUtils.substringBeforeLast(entry.getValue(), ";");
            // TODO Parse properly as properties, to allow additional properties if ever necessary
            boolean useCache = "useCache=true".equals(StringUtils.substringAfterLast(entry.getValue(), ";"));
            queryBuilder.onDemand(propertyName, uriString, useCache ? propertyName : null);
        }
    }
}

From source file:com.hexin.core.dao.BaseDaoSupport.java

public <T> Page<T> findMySqlPage(JdbcTemplate jdbcTemplate, String sql, Class<T> dtoClass,
        PageCondition pageCondition, Object... args) {

    Page<T> page = new Page<T>();
    StringBuffer countSqlBuf = new StringBuffer();
    int currentPage = 1;
    int pageSize = 10;
    String camelSortBy = "";
    String underlineSortBy = "";
    String orderBy = "";
    long total;//from  w ww. j  a va 2 s  .  c  o  m
    long totalPage;
    List<T> resultList = null;

    // distinct
    countSqlBuf.append("select count(*) from (");
    countSqlBuf.append(StringUtils.substringBeforeLast(sql, "order "));
    countSqlBuf.append(") tmp_table");
    debugSql(countSqlBuf.toString(), args);

    // 
    total = jdbcTemplate.queryForObject(countSqlBuf.toString(), Long.class, args);
    page.setTotal(total);

    StringBuffer pageSqlBuf = new StringBuffer();
    pageSqlBuf.append("select * from (");
    pageSqlBuf.append(sql);
    pageSqlBuf.append(") t ");

    if (pageCondition != null) {
        currentPage = pageCondition.getPage();
        pageSize = pageCondition.getRows();
        camelSortBy = pageCondition.getSort();
        orderBy = pageCondition.getOrder();

        // ????
        underlineSortBy = IcpObjectUtil.camelToUnderline(camelSortBy);
    }

    if (StringUtils.isNotEmpty(underlineSortBy) && StringUtils.isNotEmpty(orderBy)) {
        pageSqlBuf.append(" order by ");
        pageSqlBuf.append(underlineSortBy).append(" ").append(orderBy).append(" ");
    }
    pageSqlBuf.append(" limit ");
    pageSqlBuf.append((currentPage - 1) * pageSize);
    pageSqlBuf.append(" ,");
    pageSqlBuf.append(pageSize);
    pageSqlBuf.append(" ");

    debugSql(pageSqlBuf.toString(), args);

    RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(dtoClass);
    resultList = jdbcTemplate.query(pageSqlBuf.toString(), rowMapper, args);

    long mod = total % pageSize;
    if (mod == 0) {
        totalPage = total / pageSize;
    } else {
        totalPage = total / pageSize + 1;
    }

    page.setRows(resultList);
    page.setCurrentPage(currentPage);
    page.setPageSize(pageSize);
    page.setTotalPage(totalPage);
    page.setPageIndex(PageIndex.getPageIndex(Constants.PAGE_RANGE, pageSize, totalPage));

    return page;
}