Example usage for org.springframework.core.io.support PathMatchingResourcePatternResolver getResources

List of usage examples for org.springframework.core.io.support PathMatchingResourcePatternResolver getResources

Introduction

In this page you can find the example usage for org.springframework.core.io.support PathMatchingResourcePatternResolver getResources.

Prototype

@Override
    public Resource[] getResources(String locationPattern) throws IOException 

Source Link

Usage

From source file:org.ktunaxa.referral.shapereader.ShapeReaderServiceImpl.java

/**
 * <p>// w w  w  . j  a  v a  2  s .c  o m
 * Retrieve a list of available shape files to chose from. The idea is that
 * in some location a list of shape files can be retrieved, of which we want
 * to upload one.
 * </p>
 * <p>
 * This implementation uses a "base path" (system folder) to look for shape
 * files.
 * </p>
 * 
 * @param subDirectory extra path element to indicate sub-package/directory
 * @return Returns the full list of available shape files available on the
 *         configured base path.
 * @throws IOException
 *             Thrown if something goes wrong while retrieving available
 *             shape files.
 */
public File[] getAllFiles(String subDirectory) throws IOException {
    if (basePath.startsWith("classpath:")) {
        String fullPath = basePath.substring(10);
        if (subDirectory != null && subDirectory.trim().length() > 0) {
            fullPath = fullPath + "/" + subDirectory;
        }
        PathMatchingResourcePatternResolver pmrpr = new PathMatchingResourcePatternResolver();
        Resource[] resources = pmrpr.getResources(fullPath + File.separator + "*.shp");
        int length = resources.length;
        File[] files = new File[length];
        for (int i = 0; i < length; i++) {
            files[i] = resources[i].getFile();
        }
        return files;
    } else {
        String fullPath = basePath;
        if (subDirectory != null && subDirectory.trim().length() > 0) {
            fullPath = fullPath + File.separator + subDirectory;
        }
        File folder = new File(fullPath); // We don't have to check for folder==null.
        if (!folder.isDirectory()) {
            throw new IOException(
                    "Configured base path is not a directory: " + basePath + " translated to " + fullPath);
        }
        return folder.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.endsWith(".shp");
            }
        });
    }

}

From source file:in.mycp.service.WorkflowImpl4Jbpm.java

public void setupProcessDefinitions() {

    try {/* w  w  w  . j  a  v a  2s .  c  o m*/

        PathMatchingResourcePatternResolver matchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource resource[] = matchingResourcePatternResolver.getResources("classpath*:jbpm/**/*.jpdl.xml");

        if (resource != null && resource.length > 0) {
            for (int i = 0; i < resource.length; i++) {

                NewDeployment deployment = repositoryService.createDeployment();
                deployment.addResourceFromUrl(resource[i].getURL());
                deployment.deploy();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.info("IOException occurred: ", e);
        throw new RuntimeException("An error occured while trying to deploy a process definition", e);
    }
}

From source file:com.foilen.smalltools.upgrader.tasks.AbstractFlywayMigrateOffUpgradeTask.java

@Override
public void execute() {
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(
            jdbcTemplate.getDataSource());

    // Check if the schema_version table exists
    List<String> tableNames = mysqlTablesFindAll();
    List<String> executed;
    if (tableNames.contains("schema_version")) {
        executed = jdbcTemplate.queryForList("SELECT script FROM schema_version WHERE success = 1",
                String.class);
        jdbcTemplate.update("DELETE FROM schema_version WHERE success = 0");
    } else {/*from   ww w. j  a  v  a 2  s .c  om*/
        executed = new ArrayList<>();
        logger.info("Flyway table does not exists. Creating it");
        updateFromResource("flyway-schema_version.sql", AbstractFlywayMigrateOffUpgradeTask.class);
    }

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    AntPathMatcher pathMatcher = new AntPathMatcher();
    resolver.setPathMatcher(pathMatcher);
    Resource[] resources;
    try {
        resources = resolver.getResources("classpath:db/migration/*.sql");
    } catch (IOException e) {
        throw new SmallToolsException("Problem getting the sql files", e);
    }

    int rank = executed.size() + 1;
    List<String> scriptNames = Arrays.asList(resources).stream() //
            .map(Resource::getFilename) //
            .sorted() //
            .collect(Collectors.toList());
    for (String scriptName : scriptNames) {
        boolean needRetry = true;
        if (executed.contains(scriptName)) {
            logger.info("[{}] Already executed. Skip", scriptName);
        } else {
            logger.info("[{}] To execute", scriptName);
            for (int retryCount = 0; needRetry; ++retryCount) {
                needRetry = false;
                TransactionStatus transactionStatus = transactionManager
                        .getTransaction(new DefaultTransactionDefinition());
                try {
                    // Do the update
                    updateFromResource("/db/migration/" + scriptName);

                    // Save in schema_version
                    jdbcTemplate.update("INSERT INTO schema_version " //
                            + "(version_rank, installed_rank, version, description, type, script, installed_by, execution_time, success) " //
                            + "VALUES (?,?,?,'','SQL',?,'upgrader',1, 1)", //
                            rank, rank, //
                            scriptName.substring(0, Math.min(50, scriptName.length())), //
                            scriptName //
                    );
                    ++rank;
                    transactionManager.commit(transactionStatus);
                } catch (Exception e) {
                    logger.warn("[{}] Problem executing script. Will purge the connections and retry",
                            scriptName);
                    transactionManager.rollback(transactionStatus);
                    needRetry = true;
                    purgeConnections();
                    if (retryCount > 5) {
                        throw new SmallToolsException("Problem executing script: " + scriptName, e);
                    }
                }

            }
        }
    }

    if (deleteSchemaTable) {
        logger.info("Deleting the Flyway schema_version table");
        jdbcTemplate.update("DROP TABLE schema_version");
    }

}

From source file:se.ivankrizsan.messagecowboy.services.transport.MuleTransportService.java

/**
 * Builds a string containing the Mule configuration resources the transport
 * service is to be configured with.//from www .  j a va2s .  c  om
 *
 * @return Configuration resources string, or empty string if no configuration
 * resources.
 * @throws IOException If error occurs discovering configuration resource.
 */
protected String buildMuleConfigResourcesString() throws IOException {
    final StringBuffer theMuleConfigResource = new StringBuffer();
    final PathMatchingResourcePatternResolver theConnectorsResolver = new PathMatchingResourcePatternResolver();

    for (String theConfigRsrcsLocationPattern : mConfigResourcesLocationPatterns) {
        final Resource[] theConnectorsConfigurations = theConnectorsResolver
                .getResources(theConfigRsrcsLocationPattern);

        LOGGER.debug("Found {} connector configuration files using the pattern {}",
                theConnectorsConfigurations.length, theConfigRsrcsLocationPattern);

        if (theConnectorsConfigurations.length > 0) {
            for (Resource theResource : theConnectorsConfigurations) {
                /* Only comma-separate if there already is an entry. */
                if (theMuleConfigResource.length() > 0) {
                    theMuleConfigResource.append(",");
                }
                theMuleConfigResource.append(theResource.getURL());
            }
        }
    }
    return theMuleConfigResource.toString();
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetFactory.java

private Map<String, DatasetDescriptionImpl> loadFromYaml() throws IOException {
    // Scan for locators
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] locators = resolver.getResources("classpath:META-INF/org.dkpro.core/datasets.txt");

    // Read locators
    Set<String> patterns = new LinkedHashSet<>();
    for (Resource locator : locators) {
        try (InputStream is = locator.getInputStream()) {
            IOUtils.lineIterator(is, "UTF-8").forEachRemaining(l -> patterns.add(l));
        }//from   www  .j a  v a 2s  .c o  m
    }

    // Scan for YAML dataset descriptions
    List<Resource> resources = new ArrayList<>();
    for (String pattern : patterns) {
        for (Resource r : resolver.getResources(pattern)) {
            resources.add(r);
        }
    }

    // Configure YAML deserialization
    Constructor datasetConstructor = new Constructor(DatasetDescriptionImpl.class);
    TypeDescription datasetDesc = new TypeDescription(DatasetDescriptionImpl.class);
    datasetDesc.putMapPropertyType("artifacts", String.class, ArtifactDescriptionImpl.class);
    datasetDesc.putListPropertyType("licenses", LicenseDescriptionImpl.class);
    datasetConstructor.addTypeDescription(datasetDesc);
    TypeDescription artifactDesc = new TypeDescription(ArtifactDescriptionImpl.class);
    artifactDesc.putListPropertyType("actions", ActionDescriptionImpl.class);
    datasetConstructor.addTypeDescription(artifactDesc);
    Yaml yaml = new Yaml(datasetConstructor);

    // Ensure that there is a fixed order (at least if toString is correctly implemented)
    Collections.sort(resources, (a, b) -> {
        return a.toString().compareTo(b.toString());
    });

    // Load the YAML descriptions
    Map<String, DatasetDescriptionImpl> sets = new LinkedHashMap<>();
    for (Resource res : resources) {
        LOG.debug("Loading [" + res + "]");
        try (InputStream is = res.getInputStream()) {
            String id = FilenameUtils.getBaseName(res.getFilename());
            DatasetDescriptionImpl ds = yaml.loadAs(is, DatasetDescriptionImpl.class);
            ds.setId(id);
            ds.setOwner(this);

            // Inject artifact names into artifacts
            for (Entry<String, ArtifactDescription> e : ds.getArtifacts().entrySet()) {
                ((ArtifactDescriptionImpl) e.getValue()).setName(e.getKey());
            }

            sets.put(ds.getId(), ds);
        }
    }

    return sets;
}

From source file:ru.emdev.ldap.util.EmDevSchemaLdifExtractor.java

/**
 * Extracts the LDIF files from a Jar file or copies exploded LDIF resources.
 *
 * @param overwrite over write extracted structure if true, false otherwise
 * @throws IOException if schema already extracted and on IO errors
 *///from  w w  w.java 2 s. c om
public void extractOrCopy(boolean overwrite) throws IOException {
    if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
        throw new IOException("Directory Creation Failed: " + outputDirectory.getAbsolutePath());
    }

    File schemaDirectory = new File(outputDirectory, SCHEMA_SUBDIR);

    if (!schemaDirectory.exists()) {
        if (!schemaDirectory.mkdirs()) {
            throw new IOException(I18n.err("Directory Creation Failed: " + schemaDirectory.getAbsolutePath()));
        }
    } else if (!overwrite) {
        throw new IOException(I18n.err(I18n.ERR_08001, schemaDirectory.getAbsolutePath()));
    }

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    for (Resource resource : resolver.getResources("classpath:/schema/**/*.ldif")) {
        LOG.debug("Schema Found: " + resource.getURL().toString());

        String path = "schema/" + resource.getURL().toString().split("/schema/")[1];
        LOG.info("Extracting from path: " + path);

        extractFromJar(path);
    }
}

From source file:se.ivankrizsan.messagecowboy.services.transport.AbstractXmlConfigurerdTransportService.java

/**
 * Retrieves configuration resource information for the currently configured
 * XML configuration resources.//w  ww . ja  v  a 2s . co  m
 *
 * @return List of configuration resource information.
 * @throws IOException If error occurs discovering or accessing configuration resource.
 */
protected List<XmlConfigurationResourceInfo> retrieveXmlConfigResourceInfos() throws IOException {
    final PathMatchingResourcePatternResolver theConnectorsResolver = new PathMatchingResourcePatternResolver();
    final List<XmlConfigurationResourceInfo> theConfigRsrcInfos = new ArrayList<XmlConfigurationResourceInfo>();

    for (String theConfigRsrcsLocationPattern : mConfigResourcesLocationPatterns) {
        final Resource[] theConnectorsConfigurations = theConnectorsResolver
                .getResources(theConfigRsrcsLocationPattern);

        LOGGER.debug("Found {} connector configuration files using the pattern {}",
                theConnectorsConfigurations.length, theConfigRsrcsLocationPattern);

        if (theConnectorsConfigurations.length > 0) {
            for (Resource theResource : theConnectorsConfigurations) {

                final byte[] theConfigRsrcContents = FileCopyUtils
                        .copyToByteArray(theResource.getInputStream());
                final String theConfigRsrcName = theResource.getFilename();
                final String theConfigRsrcChecksum = DigestUtils.md5Hex(theConfigRsrcContents);

                final XmlConfigurationResourceInfo theConfigRsrcInfo = new XmlConfigurationResourceInfo(
                        theConfigRsrcName, theConfigRsrcChecksum);
                theConfigRsrcInfos.add(theConfigRsrcInfo);
            }
        }
    }
    return theConfigRsrcInfos;
}

From source file:org.red5.spring.ExtendedPropertyPlaceholderConfigurer.java

/**
 * String[] of wildcard locations of properties that are converted to
 * Resource[] using using {@link PathMatchingResourcePatternResolver}
 * /*from   w w  w . j ava 2 s  . co  m*/
 * @param locations
 *            String[]
 * @throws IOException
 */
public void setWildcardLocations(String[] locations) throws IOException {

    List<Resource> resources = new ArrayList<Resource>();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
            this.getClass().getClassLoader());

    for (String location : locations) {
        logger.debug("Loading location {}", location);
        try {
            // Get all Resources for a wildcard location
            Resource[] configs = resolver.getResources(location);
            if (configs != null && configs.length > 0) {
                List<Resource> resourceGroup = new ArrayList<Resource>();
                for (Resource resource : configs) {
                    logger.debug("Loading {} for location {}", resource.getFilename(), location);
                    resourceGroup.add(resource);
                }
                // Sort all Resources for a wildcard location by filename
                Collections.sort(resourceGroup, new ResourceFilenameComparator());

                // Add to master List
                resources.addAll(resourceGroup);

            } else {
                logger.info("Wildcard location does not exist: {}", location);
            }
        } catch (IOException ioException) {
            logger.error("Failed to resolve location: {} - {}", location, ioException);
        }
    }
    this.setLocations(resources.toArray(new Resource[resources.size()]));
}

From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java

@Override
protected Resource[] getConfigResources() {
    List<Resource> resources = new ArrayList<Resource>();
    if (includeDefault) {
        try {/* w w w.  j a v  a2s .  co m*/
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                    Thread.currentThread().getContextClassLoader());

            Collections.addAll(resources, resolver.getResources(DEFAULT_CFG_FILE));

            Resource[] exts = resolver.getResources(DEFAULT_EXT_CFG_FILE);
            for (Resource r : exts) {
                InputStream is = r.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line = rd.readLine();
                while (line != null) {
                    if (!"".equals(line)) {
                        resources.add(resolver.getResource(line));
                    }
                    line = rd.readLine();
                }
                is.close();
            }

        } catch (IOException ex) {
            // ignore
        }
    }
    boolean usingDefault = false;
    if (cfgFiles == null) {
        String userConfig = System.getProperty(BeanConfigurer.USER_CFG_FILE_PROPERTY_NAME);
        if (userConfig != null) {
            cfgFiles = new String[] { userConfig };
        }
    }
    if (cfgFiles == null) {
        usingDefault = true;
        cfgFiles = new String[] { BeanConfigurer.USER_CFG_FILE };
    }
    for (String cfgFile : cfgFiles) {
        final Resource f = findResource(cfgFile);
        if (f != null && f.exists()) {
            resources.add(f);
            LOG.info("Used configed file {}", cfgFile);
        } else {
            if (!usingDefault) {
                LOG.warn("Can't find configure file {}", cfgFile);
                throw new ApplicationContextException("Can't find configure file");
            }
        }
    }
    if (cfgURLs != null) {
        for (URL u : cfgURLs) {
            UrlResource ur = new UrlResource(u);
            if (ur.exists()) {
                resources.add(ur);
            } else {
                LOG.warn("Can't find configure file {}", u.getPath());
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating application context with resources " + resources.size());
    }
    if (0 == resources.size()) {
        return null;
    }
    Resource[] res = new Resource[resources.size()];
    res = resources.toArray(res);
    return res;

}