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.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsMessageConversionDelegate.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void resolvePerRecordContentType(KStream<?, ?> outboundBindTarget,
        PerRecordContentTypeHolder perRecordContentTypeHolder) {
    outboundBindTarget.process(() -> new Processor() {

        ProcessorContext context;/*from  w w w. j a va  2 s .  c  om*/

        @Override
        public void init(ProcessorContext context) {
            this.context = context;
        }

        @Override
        public void process(Object key, Object value) {
            final Headers headers = this.context.headers();
            final Iterable<Header> contentTypes = headers.headers(MessageHeaders.CONTENT_TYPE);
            if (contentTypes != null && contentTypes.iterator().hasNext()) {
                final String contentType = new String(contentTypes.iterator().next().value());
                //remove leading and trailing quotes
                final String cleanContentType = StringUtils.replace(contentType, "\"", "");
                perRecordContentTypeHolder.setContentType(cleanContentType);
            }
        }

        @Override
        public void close() {

        }
    });
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Retrieve files that match the given path pattern,
 * checking the given directory and its subdirectories.
 * @param rootDir the directory to start from
 * @param pattern the pattern to match against,
 * relative to the root directory//w ww. ja  va2  s .  c  om
 * @return a mutable Set of matching Resource instances
 * @throws IOException if directory contents could not be retrieved
 */
protected Set<File> retrieveMatchingFiles(File rootDir, String pattern) throws IOException {
    if (!rootDir.exists()) {
        // Silently skip non-existing directories.
        if (logger.isDebugEnabled()) {
            logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
        }
        return Collections.emptySet();
    }
    if (!rootDir.isDirectory()) {
        // Complain louder if it exists but is no directory.
        if (logger.isWarnEnabled()) {
            logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
        }
        return Collections.emptySet();
    }
    if (!rootDir.canRead()) {
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath()
                    + "] because the application is not allowed to read the directory");
        }
        return Collections.emptySet();
    }
    String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/");
    if (!pattern.startsWith("/")) {
        fullPattern += "/";
    }
    fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
    Set<File> result = new LinkedHashSet<>(8);
    doRetrieveMatchingFiles(fullPattern, rootDir, result);
    return result;
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Recursively retrieve files that match the given pattern,
 * adding them to the given result list.
 * @param fullPattern the pattern to match against,
 * with prepended root directory path//www  .java  2 s  .c o m
 * @param dir the current directory
 * @param result the Set of matching File instances to add to
 * @throws IOException if directory contents could not be retrieved
 */
protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Searching directory [" + dir.getAbsolutePath() + "] for files matching pattern ["
                + fullPattern + "]");
    }
    File[] dirContents = dir.listFiles();
    if (dirContents == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]");
        }
        return;
    }
    Arrays.sort(dirContents);
    for (File content : dirContents) {
        String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/");
        if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
            if (!content.canRead()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Skipping subdirectory [" + dir.getAbsolutePath()
                            + "] because the application is not allowed to read the directory");
                }
            } else {
                doRetrieveMatchingFiles(fullPattern, content, result);
            }
        }
        if (getPathMatcher().match(fullPattern, currPath)) {
            result.add(content);
        }
    }
}

From source file:org.springframework.data.hadoop.fs.HdfsResourceLoader.java

/**
 * Retrieve files that match the given path pattern,
 * checking the given directory and its subdirectories.
 *
 * @param rootDir the directory to start from
 * @param pattern the pattern to match against,  * relative to the root directory
 * @return the Set of matching Path instances
 * @throws IOException if directory contents could not be retrieved
 *//*from  ww  w . jav a 2s. co m*/
@SuppressWarnings("deprecation")
protected Set<Path> retrieveMatchingFiles(Path rootDir, String pattern) throws IOException {
    boolean exists = fs.exists(rootDir);
    if (!exists) {
        // Silently skip non-existing directories.
        if (log.isDebugEnabled()) {
            log.debug("Skipping [" + rootDir.toUri().getPath() + "] because it does not exist");
        }
        return Collections.emptySet();
    }
    // previous exists() should make sure we don't
    // get FileNotFoundException
    FileStatus fileStatus = fs.getFileStatus(rootDir);
    if (!fileStatus.isDir()) {
        // Complain louder if it exists but is no directory.
        if (log.isWarnEnabled()) {
            log.warn("Skipping [" + rootDir.toUri().getPath() + "] because it does not denote a directory");
        }
        return Collections.emptySet();
    }
    String fullPattern = StringUtils.replace(rootDir.toUri().getPath(), File.separator, "/");
    if (!pattern.startsWith("/")) {
        fullPattern += "/";
    }
    fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
    Set<Path> result = new LinkedHashSet<Path>(8);
    doRetrieveMatchingFiles(fullPattern, rootDir, result);
    return result;
}

From source file:org.springframework.data.hadoop.fs.HdfsResourceLoader.java

/**
 * Recursively retrieve files that match the given pattern,
 * adding them to the given result list.
 *
 * @param fullPattern the pattern to match against, with prepended root directory path
 * @param dir the current directory/*from  ww  w  .j a v  a  2s.  co m*/
 * @param result the Set of matching File instances to add to
 * @throws IOException if directory contents could not be retrieved
 */
@SuppressWarnings("deprecation")
protected void doRetrieveMatchingFiles(String fullPattern, Path dir, Set<Path> result) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Searching directory [" + dir.toUri().getPath() + "] for files matching pattern ["
                + fullPattern + "]");
    }

    FileStatus[] dirContents = null;
    try {
        dirContents = fs.listStatus(dir);
    } catch (IOException ex) {
        // ignore (likely security exception)
    }

    if (dirContents == null) {
        if (log.isWarnEnabled()) {
            log.warn("Could not retrieve contents of directory [" + dir.toUri().getPath() + "]");
        }
        return;
    }
    for (FileStatus content : dirContents) {
        String currPath = StringUtils.replace(content.getPath().toUri().getPath(), File.separator, "/");
        if (content.isDir() && pathMatcher.matchStart(fullPattern, currPath + "/")) {
            doRetrieveMatchingFiles(fullPattern, content.getPath(), result);
        }
        if (pathMatcher.match(fullPattern, currPath)) {
            result.add(content.getPath());
        }
    }
}

From source file:org.springframework.data.hadoop.store.strategy.naming.UuidFileNamingStrategy.java

@Override
public Path init(Path path) {
    path = super.init(path);
    log.debug("Init using path=[" + path + "]");
    if (path != null && isEnabled()) {
        String oldName = path.getName();
        String newName = StringUtils.replace(oldName, prefix + uuid, "");
        if (!StringUtils.hasText(newName)) {
            path = null;/* w w  w .j  a  v a 2  s .  c  o  m*/
            log.debug("Removed last handled name part, returning null");
        } else if (!ObjectUtils.nullSafeEquals(oldName, newName)) {
            path = new Path(path.getParent(), newName);
            log.debug("Removed handled prefix, path is now " + newName);
        }
    }
    return path;
}

From source file:org.springframework.instrument.classloading.ShadowingClassLoader.java

private Class<?> doLoadClass(String name) throws ClassNotFoundException {
    String internalName = StringUtils.replace(name, ".", "/") + ".class";
    InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
    if (is == null) {
        throw new ClassNotFoundException(name);
    }/*from   w ww .  j a  v a  2 s  . c o m*/
    try {
        byte[] bytes = FileCopyUtils.copyToByteArray(is);
        bytes = applyTransformers(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;
    } catch (IOException ex) {
        throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
    }
}

From source file:org.springframework.instrument.classloading.ShadowingClassLoader.java

private byte[] applyTransformers(String name, byte[] bytes) {
    String internalName = StringUtils.replace(name, ".", "/");
    try {//from w  w  w  .j a v  a  2 s.c o m
        for (ClassFileTransformer transformer : this.classFileTransformers) {
            byte[] transformed = transformer.transform(this, internalName, null, null, bytes);
            bytes = (transformed != null ? transformed : bytes);
        }
        return bytes;
    } catch (IllegalClassFormatException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:org.springframework.integration.jdbc.JdbcMessageStore.java

/**
 * Replace patterns in the input to produce a valid SQL query. This implementation lazily initializes a
 * simple map-based cache, only replacing the table prefix on the first access to a named query. Further
 * accesses will be resolved from the cache.
 *
 * @param base the SQL query to be transformed
 * @return a transformed query with replacements
 *///from   w  ww  .  j  ava2 s.  co  m
protected String getQuery(Query base) {
    String query = queryCache.get(base);

    if (query == null) {
        query = StringUtils.replace(base.getSql(), "%PREFIX%", tablePrefix);
        queryCache.put(base, query);
    }

    return query;
}

From source file:org.springframework.integration.jdbc.store.JdbcChannelMessageStore.java

/**
 * Replace patterns in the input to produce a valid SQL query. This implementation lazily initializes a
 * simple map-based cache, only replacing the table prefix on the first access to a named query. Further
 * accesses will be resolved from the cache.
 *
 * @param sqlQuery the SQL query to be transformed
 * @return a transformed query with replacements
 */// w w  w. ja  v a  2 s.  c o m
protected String getQuery(String sqlQuery) {
    String query = queryCache.get(sqlQuery);

    if (query == null) {
        query = StringUtils.replace(sqlQuery, "%PREFIX%", tablePrefix);
        queryCache.put(sqlQuery, query);
    }

    return query;
}