Example usage for org.springframework.util StringUtils replace

List of usage examples for org.springframework.util StringUtils replace

Introduction

In this page you can find the example usage for org.springframework.util StringUtils replace.

Prototype

public static String replace(String inString, String oldPattern, @Nullable String newPattern) 

Source Link

Document

Replace all occurrences of a substring within a string with another string.

Usage

From source file:org.dbist.dml.impl.DmlJdbc.java

private List<TableColumn> getTableColumnList(Table table) {
    String sql = "view".equals(table.getType()) ? getQueryViewColumns() : getQueryColumns();
    if (sql == null)
        throw new IllegalArgumentException(ValueUtils.populate(MSG_QUERYNOTFOUND,
                ValueUtils.toMap("queryName: table columns", "dbType:" + getDbType())));

    sql = StringUtils.replace(sql, "${domain}", toFirstDomainName(table.getDomain()));
    String tableName = table.getName();

    return jdbcOperations.query(sql, new Object[] { tableName }, TABLECOLUMN_ROWMAPPER);
}

From source file:org.dbist.dml.impl.DmlJdbc.java

private void addColumn(Table table, Field field) {
    Ignore ignoreAnn = field.getAnnotation(Ignore.class);
    if (ignoreAnn != null)
        return;/*from w w  w .j  a va 2  s  .  c  o  m*/

    Column column = table.addColumn(new Column());
    column.setField(field);
    column.setGetter(ReflectionUtils.getGetter(table.getClazz(), field.getName(), field.getType()));
    column.setSetter(ReflectionUtils.getSetter(table.getClazz(), field.getName(), field.getType()));

    Relation relAnn = field.getAnnotation(Relation.class);
    if (relAnn != null) {
        if (relAnn.field().length == 0)
            throw new DbistRuntimeException("@Relation of " + table.getClazz().getName() + "." + field.getName()
                    + " requires linked field value.");
        column.setRelation(relAnn);

        Class<?> linkedClass = field.getType();
        Table linkedTable = getTable(linkedClass);

        if (relAnn.field().length != linkedTable.getPkColumnNameList().size())
            throw new DbistRuntimeException("@Relation.field.length of " + table.getClazz().getName() + "."
                    + field.getName() + " must same with the primary key size of " + table.getName());

        column.setTable(linkedTable);
        table.setContainsLinkedTable(true);

        column.setName(ValueUtils.toDelimited(field.getName(), '_'));
        for (Column linkedColumn : linkedTable.getColumnList()) {
            if (!ValueUtils.isEmpty(linkedColumn.getColumnList()))
                continue;
            column.addColumn(linkedColumn);
        }
        return;
    }

    String tableName = table.getName();

    // Column
    {
        String sql = "view".equals(table.getType()) ? getQueryViewColumn() : getQueryColumn();
        if (sql == null)
            throw new IllegalArgumentException(ValueUtils.populate(MSG_QUERYNOTFOUND,
                    ValueUtils.toMap("queryName: table column", "dbType:" + getDbType())));

        sql = StringUtils.replace(sql, "${domain}", toFirstDomainName(table.getDomain()));
        org.dbist.annotation.Column columnAnn = field.getAnnotation(org.dbist.annotation.Column.class);
        TableColumn tabColumn = null;

        if (columnAnn != null) {
            if (!ValueUtils.isEmpty(columnAnn.name())) {
                try {
                    tabColumn = jdbcOperations.queryForObject(sql, TABLECOLUMN_ROWMAPPER, tableName,
                            columnAnn.name().toLowerCase());
                } catch (EmptyResultDataAccessException e) {
                    throw new DbistRuntimeException(ValueUtils.populate(MSG_COLUMNNOTFOUND, ValueUtils.toMap(
                            "column:" + columnAnn.name(), "table:" + table.getDomain() + "." + tableName)));
                }
            }
            column.setType(ValueUtils.toNull(columnAnn.type().value()));
            if (!ValueUtils.isEmpty(columnAnn.generator()))
                table.getValueGeneratorByFieldMap().put(field, getValueGenerator(columnAnn.generator()));
        }
        if (tabColumn == null) {
            List<String> columnNameCandidates = new ArrayList<String>(3);
            String candidate1 = ValueUtils.toDelimited(field.getName(), '_').toLowerCase();
            columnNameCandidates.add(candidate1);
            String candidate2 = ValueUtils.toDelimited(field.getName(), '_', true);
            if (!columnNameCandidates.contains(candidate2))
                columnNameCandidates.add(candidate2);
            String candidate3 = field.getName().toLowerCase();
            if (!columnNameCandidates.contains(candidate3))
                columnNameCandidates.add(candidate3);
            Set<String> checkedSet = new HashSet<String>();
            for (String columnName : columnNameCandidates) {
                if (checkedSet.contains(columnName))
                    continue;
                try {
                    tabColumn = jdbcOperations.queryForObject(sql, TABLECOLUMN_ROWMAPPER, tableName,
                            columnName);
                } catch (EmptyResultDataAccessException e) {
                    checkedSet.add(columnName);
                    continue;
                }
                break;
            }
            if (tabColumn == null)
                throw new DbistRuntimeException(ValueUtils.populate(MSG_COLUMNNOTFOUND,
                        ValueUtils.toMap("column:" + mapOr(columnNameCandidates),
                                "table:" + table.getDomain() + "." + tableName)));
        }

        column.setName(tabColumn.getName());
        column.setPrimaryKey(table.getPkColumnNameList().contains(tabColumn.getName()));
        column.setDataType(tabColumn.getDataType().toLowerCase());
    }

    // Identity / Sequence
    org.dbist.annotation.Sequence seqAnn = field.getAnnotation(org.dbist.annotation.Sequence.class);
    if (seqAnn != null) {
        Sequence seq = new Sequence();
        column.setSequence(seq);

        {
            String sql = getQueryCountIdentity();
            if (!ValueUtils.isEmpty(sql)) {
                sql = StringUtils.replace(sql, "${domain}", toFirstDomainName(table.getDomain()));
                if (jdbcOperations.queryForInt(sql, table.getName(), column.getName()) > 0)
                    seq.setAutoIncrement(true);
            }
        }

        if (!seq.isAutoIncrement() && !ValueUtils.isEmpty(seqAnn.name())) {
            String sql = getQueryCountSequence();
            if (ValueUtils.isEmpty(sql)) {
                seq.setAutoIncrement(true);
            } else {
                List<String> domainNameList = ValueUtils.isEmpty(seqAnn.domain()) ? this.domainList
                        : ValueUtils.toList(seqAnn.domain());
                String name = seqAnn.name().toLowerCase();

                boolean populated = false;
                for (String domainName : domainNameList) {
                    domainName = domainName.toLowerCase();
                    String _sql = StringUtils.replace(sql, "${domain}", toFirstDomainName(domainName));
                    if (jdbcOperations.queryForInt(_sql, name) > 0) {
                        seq.setDomain(domainName);
                        seq.setName(name);
                        populated = true;
                        break;
                    }
                }

                if (!populated) {
                    String errMsg = "Couldn't find sequence[${sequence}] from this(these) domain(s)[${domain}]";
                    throw new IllegalArgumentException(ValueUtils.populate(errMsg,
                            ValueUtils.toMap("domain:" + mapOr(domainNameList), "sequence:" + name)));
                }
            }
        }
    }
}

From source file:org.easyrec.plugin.profileduke.duke.datasource.utils.EasyrecXMLFormatParser.java

/**
 * Takes an XML string with the profile and creates statements out
 * of the properties for the StatementHandler
 *
 * @param xmlString string with the profile XML
 * @param tenantId tenantId of the actual tenant
 * @param itemId itemId of the item with the profile
 * @param itemType itemType of the item with the profile
 *///  w ww  .ja  v  a  2s. c  o m

private void xmlParser(String xmlString, int tenantId, int itemId, int itemType) {

    String idString = Integer.toString(tenantId) + Integer.toString(itemId) + Integer.toString(itemType);

    try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xmlString));

        String subject = idString;
        handler.statement(subject, "ID", idString, true);
        handler.statement(subject, "ItemID", Integer.toString(itemId), true);

        Document doc = dBuilder.parse(is);
        doc.getDocumentElement().normalize();

        ProfileDukeGenerator.logger
                .debug("File: " + idString + " Root element: " + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("profile");

        // create a map of props to check later if the properties from the profile are
        // also in the duke configuration
        HashMap<String, Property> propertyList = new HashMap<String, Property>(props.size());
        for (Property property : props)
            propertyList.put(property.getName(), property);

        for (int i = 0; i < nList.getLength(); i++) {

            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;

                NodeList propertyNodes = element.getElementsByTagName("*");
                for (int j = 0; j < propertyNodes.getLength(); j++) {
                    String propertyName = propertyNodes.item(j).getNodeName();
                    NodeList childNodes = propertyNodes.item(j).getChildNodes();
                    String propertyValue;
                    if (childNodes.getLength() > 0) {
                        propertyValue = childNodes.item(0).getNodeValue();
                    } else {
                        continue;
                    }
                    if (propertyList.containsKey(propertyName)) {
                        if (propertyList.get(propertyName).isConcatenateMultiValues())
                            propertyValue = StringUtils.replace(propertyValue, " ", "~");
                        handler.statement(subject, propertyName, propertyValue, true);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("An error occurred!", e);
    }
}

From source file:org.kuali.rice.core.api.util.ShadowingInstrumentableClassLoader.java

private Class<?> loadAndInstrumentClass(String name) throws ClassNotFoundException {
    String internalName = StringUtils.replace(name, ".", "/") + ".class";
    attempted.add(name);//from w  w w .j  a v a 2 s  .  co m
    attempted.add(internalName);
    InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
    if (is == null) {
        throw new ClassNotFoundException(name);
    }
    byte[] bytes;
    try {
        bytes = ByteStreams.toByteArray(is);
    } catch (IOException e) {
        throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", e);
    } finally {
        Closeables.closeQuietly(is);
    }
    bytes = weavingTransformer.transformIfNecessary(name, bytes);
    Class<?> cls = defineClass(name, bytes, 0, bytes.length);
    // Additional check for defining the package, if not defined yet.
    if (cls.getPackage() == null) {
        int packageSeparator = name.lastIndexOf('.');
        if (packageSeparator != -1) {
            String packageName = name.substring(0, packageSeparator);
            definePackage(packageName, null, null, null, null, null, null, null);
        }
    }
    this.classCache.put(name, cls);
    return cls;
}

From source file:org.rill.bpm.common.mail.support.TemplateMailSenderSupport.java

@SuppressWarnings("unchecked")
protected MimeMessageHelper processMultipart(Map<String, Object> model, MimeMessageHelper messageHelper)
        throws MessagingException {

    // Handle multipart
    if (isMultipart(model)) {
        List<AttachmentWarper> list = new ArrayList<AttachmentWarper>();
        Object attachments = model.get(TemplateMailSender.ATTACHMENT_KEY);
        if (attachments.getClass().isArray()) {
            AttachmentWarper[] awArrays = ((AttachmentWarper[]) attachments);
            list.addAll(Arrays.asList(awArrays));
        } else if (attachments instanceof Collection) {
            Collection<AttachmentWarper> c = (Collection<AttachmentWarper>) attachments;
            list.addAll(c);/*from  ww w .j  a  va2  s.  co m*/
        } else {
            list.add(((AttachmentWarper) attachments));
        }

        for (AttachmentWarper aw : list) {
            if (aw.getContentType() == null)
                messageHelper.addAttachment(aw.getAttachmentFileName(), aw.getInputStreamSource());
            else
                messageHelper.addAttachment(aw.getAttachmentFileName(), aw.getInputStreamSource(),
                        aw.getContentType());
        }
    }

    // Handle multipart
    if (isMultipart(model)) {
        List<AttachmentWarper> list = new ArrayList<AttachmentWarper>();
        Object inline = model.get(TemplateMailSender.INLINE_KEY);
        if (inline.getClass().isArray()) {
            AttachmentWarper[] awArrays = ((AttachmentWarper[]) inline);
            list.addAll(Arrays.asList(awArrays));
        } else if (inline instanceof Collection) {
            Collection<AttachmentWarper> c = (Collection<AttachmentWarper>) inline;
            list.addAll(c);
        } else {
            list.add(((AttachmentWarper) inline));
        }

        for (AttachmentWarper aw : list) {
            String cid = StringUtils.replace(aw.getAttachmentFileName(), ".", "_");
            if (aw.getContentType() == null)
                messageHelper.addInline(cid, aw.getInputStreamSource(),
                        messageHelper.getFileTypeMap().getContentType(aw.getAttachmentFileName()));
            else
                messageHelper.addInline(cid, aw.getInputStreamSource(), aw.getContentType());
        }
    }

    return messageHelper;
}

From source file:org.springframework.aop.aspectj.AspectJExpressionPointcut.java

/**
 * If a pointcut expression has been specified in XML, the user cannot
 * write {@code and} as "&&" (though &amp;&amp; will work).
 * We also allow {@code and} between two pointcut sub-expressions.
 * <p>This method converts back to {@code &&} for the AspectJ pointcut parser.
 *//*from  w w w . j a  va  2s. c om*/
private String replaceBooleanOperators(String pcExpr) {
    String result = StringUtils.replace(pcExpr, " and ", " && ");
    result = StringUtils.replace(result, " or ", " || ");
    result = StringUtils.replace(result, " not ", " ! ");
    return result;
}

From source file:org.springframework.batch.sample.MultilineJobFunctionalTests.java

@Test
public void testJobLaunch() throws Exception {
    jobLauncherTestUtils.launchJob();//from  w w  w .ja  v  a  2s.com
    assertEquals(EXPECTED_RESULT, StringUtils.replace(IOUtils.toString(output.getInputStream()),
            System.getProperty("line.separator"), ""));
}

From source file:org.springframework.batch.sample.MultilineOrderJobFunctionalTests.java

/**
 * Read the output file and compare it with expected string
 * @throws IOException //from  w  w  w  .j av  a  2 s .c o  m
 */
protected void validatePostConditions() throws Exception {
    assertEquals(EXPECTED_OUTPUT, StringUtils.replace(IOUtils.toString(fileOutputLocator.getInputStream()),
            System.getProperty("line.separator"), ""));
}

From source file:org.springframework.cloud.config.server.resource.GenericResourceRepository.java

/**
 * Process the given resource path.// w  w  w.j a  va  2 s.c  o  m
 * <p>
 * The default implementation replaces:
 * <ul>
 * <li>Backslash with forward slash.
 * <li>Duplicate occurrences of slash with a single slash.
 * <li>Any combination of leading slash and control characters (00-1F and 7F) with a
 * single "/" or "". For example {@code "  / // foo/bar"} becomes {@code "/foo/bar"}.
 * </ul>
 * @since 3.2.12
 */
protected String processPath(String path) {
    path = StringUtils.replace(path, "\\", "/");
    path = cleanDuplicateSlashes(path);
    return cleanLeadingSlash(path);
}

From source file:org.springframework.cloud.dataflow.server.controller.AboutController.java

private String constructUrl(String url, String version) {
    final String VERSION_TAG = "{version}";
    final String REPOSITORY_TAG = "{repository}";
    if (url.contains(VERSION_TAG)) {
        url = StringUtils.replace(url, VERSION_TAG, version);
        url = StringUtils.replace(url, REPOSITORY_TAG, repoSelector(version));
    }/*www.  jav a  2  s  .c o  m*/
    return url;
}