Example usage for org.springframework.core.io Resource getURL

List of usage examples for org.springframework.core.io Resource getURL

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getURL.

Prototype

URL getURL() throws IOException;

Source Link

Document

Return a URL handle for this resource.

Usage

From source file:com.gzj.tulip.load.RoseScanner.java

/**
 * ???jar?/*from  w  w  w  .  j  a v a2 s  . c  o  m*/
 * 
 * @param resourceLoader
 * @return
 * @throws IOException
 */
public List<ResourceRef> getJarResources() throws IOException {
    if (jarResources == null) {
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] start to found available jar files for rose to scanning...");
        }
        List<ResourceRef> jarResources = new LinkedList<ResourceRef>();
        Resource[] metaInfResources = resourcePatternResolver.getResources("classpath*:/META-INF/");
        for (Resource metaInfResource : metaInfResources) {
            URL urlObject = metaInfResource.getURL();
            if (ResourceUtils.isJarURL(urlObject)) {
                try {
                    String path = URLDecoder.decode(urlObject.getPath(), "UTF-8"); // fix 20%
                    if (path.startsWith("file:")) {
                        path = path.substring("file:".length(), path.lastIndexOf('!'));
                    } else {
                        path = path.substring(0, path.lastIndexOf('!'));
                    }
                    Resource resource = new FileSystemResource(path);
                    if (jarResources.contains(resource)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("[jarFile] skip replicated jar resource: " + path);//  linux ???,fix it!
                        }
                    } else {
                        ResourceRef ref = ResourceRef.toResourceRef(resource);
                        if (ref.getModifiers() != null) {
                            jarResources.add(ref);
                            if (logger.isInfoEnabled()) {
                                logger.info("[jarFile] add jar resource: " + ref);
                            }
                        } else {
                            if (logger.isDebugEnabled()) {
                                logger.debug("[jarFile] not rose jar resource: " + path);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(urlObject, e);
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("[jarFile] not rose type(not a jar) " + urlObject);
                }
            }
        }
        this.jarResources = jarResources;
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] found " + jarResources.size() + " jar files: " + jarResources);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] found cached " + jarResources.size() + " jar files: " + jarResources);
        }
    }
    return Collections.unmodifiableList(jarResources);
}

From source file:com.laxser.blitz.scanning.BlitzScanner.java

/**
 * ???jar?/*from   www.  j  av  a2  s.c  o  m*/
 * 
 * @param resourceLoader
 * @return
 * @throws IOException
 */
public List<ResourceRef> getJarResources() throws IOException {
    if (jarResources == null) {
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] start to found available jar files for blitz to scanning...");
        }
        List<ResourceRef> jarResources = new LinkedList<ResourceRef>();
        Resource[] metaInfResources = resourcePatternResolver.getResources("classpath*:/META-INF/");
        for (Resource metaInfResource : metaInfResources) {
            URL urlObject = metaInfResource.getURL();
            if (ResourceUtils.isJarURL(urlObject)) {
                try {
                    String path = URLDecoder.decode(urlObject.getPath(), "UTF-8"); // fix 20%
                    if (path.startsWith("file:")) {
                        path = path.substring("file:".length(), path.lastIndexOf('!'));
                    } else {
                        path = path.substring(0, path.lastIndexOf('!'));
                    }
                    Resource resource = new FileSystemResource(path);
                    if (jarResources.contains(resource)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("[jarFile] skip replicated jar resource: " + path);//  linux ???,fix it!
                        }
                    } else {
                        ResourceRef ref = ResourceRef.toResourceRef(resource);
                        if (ref.getModifiers() != null) {
                            jarResources.add(ref);
                            if (logger.isInfoEnabled()) {
                                logger.info("[jarFile] add jar resource: " + ref);
                            }
                        } else {
                            if (logger.isDebugEnabled()) {
                                logger.debug("[jarFile] not blitz jar resource: " + path);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(urlObject, e);
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("[jarFile] not blitz type(not a jar) " + urlObject);
                }
            }
        }
        this.jarResources = jarResources;
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] found " + jarResources.size() + " jar files: " + jarResources);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("[jarFile] found cached " + jarResources.size() + " jar files: " + jarResources);
        }
    }
    return Collections.unmodifiableList(jarResources);
}

From source file:com.quartzdesk.executor.dao.schema.DatabaseSchemaManager.java

/**
 * Returns the list of QuartzDesk database schema SQL upgrade scripts to be
 * applied to the current schema version to upgrade it to the desired schema version.
 *
 * @param currentSchemaVersion the current database schema version.
 * @param desiredSchemaVersion the desired database schema version.
 * @return the list of SQL upgrade scripts.
 *///from   w  w  w  .  j av  a2  s  .co  m
private List<URL> getUpgradeScriptUrls(Version currentSchemaVersion, Version desiredSchemaVersion) {
    List<URL> result = new ArrayList<URL>();
    try {
        // sort the directories by version number
        Set<Version> dirVersions = new TreeSet<Version>(VersionComparator.INSTANCE);

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] scriptResources = resolver.getResources(upgradeScriptsRoot + "/*/*.sql");

        for (Resource scriptResource : scriptResources) {
            Matcher matcher = UPGRADE_SCRIPT_PATTERN.matcher(scriptResource.getURL().getPath());
            if (matcher.find()) {
                String dirVersionStr = matcher.group(1);
                String[] dirVersionParts = dirVersionStr.split("_"); // 1_0_0

                Version dirVersion = new Version().withMajor(Integer.parseInt(dirVersionParts[0]))
                        .withMinor(Integer.parseInt(dirVersionParts[1]))
                        .withMaintenance(Integer.parseInt(dirVersionParts[2]));

                dirVersions.add(dirVersion);
            }
        }

        for (Version dirVersion : dirVersions) {
            // currentSchemaVersion < dirVersion <= desiredSchemaVersion
            if (VersionComparator.INSTANCE.compare(dirVersion, currentSchemaVersion) > 0
                    && VersionComparator.INSTANCE.compare(dirVersion, desiredSchemaVersion) <= 0) {
                String dirVersionStr = dirVersion.getMajor().toString() + '_' + dirVersion.getMinor() + '_'
                        + dirVersion.getMaintenance();

                scriptResources = resolver.getResources(upgradeScriptsRoot + '/' + dirVersionStr + "/*.sql");
                List<URL> scriptUrls = new ArrayList<URL>();

                for (Resource scriptResource : scriptResources) {
                    scriptUrls.add(scriptResource.getURL());
                }

                // sort the scripts inside the dir by their name
                Collections.sort(scriptUrls, new Comparator<URL>() {
                    @Override
                    public int compare(URL o1, URL o2) {
                        return o1.getPath().compareTo(o2.getPath());
                    }
                });

                result.addAll(scriptUrls);
            }
        }
    } catch (IOException e) {
        throw new DaoException("Error getting database schema SQL upgrade script URLs.", e);
    }

    return result;
}

From source file:com.iflytek.edu.cloud.frame.support.jdbc.CustomSQL.java

/**
 * /* ww w.  ja  va 2  s .  co m*/
 */
private void reloadConfig() throws IOException {
    Resource[] newConfigs = this.loadConfigs();
    for (Resource newConfig : newConfigs) {
        boolean flag = true;
        for (Entry<String, Long> entry : configMap.entrySet()) {
            if (newConfig.getURL().getPath().equals(entry.getKey())) {
                flag = false;

                if (newConfig.getFile().lastModified() != entry.getValue().longValue()) {
                    configMap.put(entry.getKey(), newConfig.getFile().lastModified());
                    read(newConfig.getInputStream());
                    logger.info("Reloading " + entry.getKey());

                    break;
                }
            }
        }

        if (flag) {
            configMap.put(newConfig.getURL().getPath(), newConfig.getFile().lastModified());
            read(newConfig.getInputStream());
            logger.info("Reloading " + newConfig.getURL().getPath());
        }
    }
}

From source file:com.javaetmoi.core.spring.vfs.Vfs2PathMatchingResourcePatternResolver.java

/**
 * Find all resources that match the given location pattern via the Ant-style PathMatcher.
 * Supports resources in jar files and zip files and in the file system.
 * //from w ww.j a va  2 s  .c o  m
 * @param locationPattern
 *            the location pattern to match
 * @return the result as Resource array
 * @throws IOException
 *             in case of I/O errors
 * @see #doFindPathMatchingJarResources
 * @see #doFindPathMatchingFileResources
 * @see org.springframework.util.PathMatcher
 */
@Override
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
    String rootDirPath = determineRootDir(locationPattern);
    String subPattern = locationPattern.substring(rootDirPath.length());
    Resource[] rootDirResources = getResources(rootDirPath);
    Set<Resource> result = new LinkedHashSet<Resource>(16);
    for (Resource rootDirResource : rootDirResources) {
        rootDirResource = resolveRootDirResource(rootDirResource);
        if (isJarResource(rootDirResource)) {
            result.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern));
        } else if (rootDirResource.getURL().getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
            result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirResource, subPattern,
                    getPathMatcher()));
        } else {
            result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
    }
    return result.toArray(new Resource[result.size()]);
}

From source file:com.baomidou.mybatisplus.spring.MybatisMapperRefresh.java

public void run() {
    final GlobalConfiguration mybatisGlobalCache = GlobalConfiguration.GlobalConfig(configuration);
    /*/*w  w  w .j  a va  2  s  .co m*/
     * ? XML 
     */
    if (enabled) {
        beforeTime = SystemClock.now();
        final MybatisMapperRefresh runnable = this;
        new Thread(new Runnable() {

            public void run() {
                if (fileSet == null) {
                    fileSet = new HashSet<String>();
                    for (Resource mapperLocation : mapperLocations) {
                        try {
                            if (ResourceUtils.isJarURL(mapperLocation.getURL())) {
                                String key = new UrlResource(
                                        ResourceUtils.extractJarFileURL(mapperLocation.getURL())).getFile()
                                                .getPath();
                                fileSet.add(key);
                                if (jarMapper.get(key) != null) {
                                    jarMapper.get(key).add(mapperLocation);
                                } else {
                                    List<Resource> resourcesList = new ArrayList<Resource>();
                                    resourcesList.add(mapperLocation);
                                    jarMapper.put(key, resourcesList);
                                }
                            } else {
                                fileSet.add(mapperLocation.getFile().getPath());
                            }
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                }
                try {
                    Thread.sleep(delaySeconds * 1000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                while (true) {
                    try {
                        for (String filePath : fileSet) {
                            File file = new File(filePath);
                            if (file != null && file.isFile() && file.lastModified() > beforeTime) {
                                mybatisGlobalCache.setRefresh(true);
                                List<Resource> removeList = jarMapper.get(filePath);
                                if (removeList != null && !removeList.isEmpty()) {// jarxmljarxml??jar?xml
                                    for (Resource resource : removeList) {
                                        runnable.refresh(resource);
                                    }
                                } else {
                                    runnable.refresh(new FileSystemResource(file));
                                }
                            }
                        }
                        if (mybatisGlobalCache.isRefresh()) {
                            beforeTime = SystemClock.now();
                        }
                        mybatisGlobalCache.setRefresh(true);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                    try {
                        Thread.sleep(sleepSeconds * 1000);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }

                }
            }
        }, "mybatis-plus MapperRefresh").start();
    }
}

From source file:com.glaf.activiti.spring.SpringProcessEngineConfigurationBean.java

@Override
protected void initSqlSessionFactory() {
    logger.info("-------------------------------------------");
    logger.info("-------------initSqlSessionFactory()-------");
    logger.info("sqlSessionFactory:" + sqlSessionFactory);
    logger.info("transactionFactory:" + transactionFactory);
    if (sqlSessionFactory == null) {
        InputStream inputStream = null;
        try {//from w  w w.j a  va  2 s . c o m
            if (configLocation != null) {
                logger.info("mybatis config:" + this.configLocation.getFile().getAbsolutePath());
                inputStream = this.configLocation.getInputStream();
            } else {
                Resource resource = new ClassPathResource("com/glaf/activiti/activiti.mybatis.conf.xml");
                inputStream = resource.getInputStream();
            }

            if (!ObjectUtils.isEmpty(this.mapperLocations)) {
                SAXReader xmlReader = new SAXReader();
                EntityResolver entityResolver = new XMLMapperEntityResolver();
                xmlReader.setEntityResolver(entityResolver);
                Document doc = xmlReader.read(inputStream);
                Element root = doc.getRootElement();
                Element mappers = root.element("mappers");
                if (mappers != null) {
                    java.util.List<?> list = mappers.elements();
                    Collection<String> files = new HashSet<String>();

                    if (list != null && !list.isEmpty()) {
                        Iterator<?> iterator = list.iterator();
                        while (iterator.hasNext()) {
                            Element elem = (Element) iterator.next();
                            if (elem.attributeValue("resource") != null) {
                                String file = elem.attributeValue("resource");
                                files.add(file);
                            } else if (elem.attributeValue("url") != null) {
                                String file = elem.attributeValue("url");
                                files.add(file);
                            }
                        }
                    }

                    for (Resource mapperLocation : this.mapperLocations) {
                        if (mapperLocation == null) {
                            continue;
                        }
                        String url = mapperLocation.getURL().toString();
                        // logger.debug("find mapper:" + url);
                        if (!files.contains(url)) {
                            Element element = mappers.addElement("mapper");
                            element.addAttribute("url", url);
                        }
                    }
                }

                IOUtils.closeStream(inputStream);

                byte[] bytes = Dom4jUtils.getBytesFromPrettyDocument(doc);
                inputStream = new ByteArrayInputStream(bytes);

            }

            // update the jdbc parameters to the configured ones...
            Environment environment = new Environment("default", transactionFactory, dataSource);
            Reader reader = new InputStreamReader(inputStream);
            Properties properties = new Properties();
            properties.put("prefix", databaseTablePrefix);
            if (databaseType != null) {
                properties.put("limitBefore",
                        DbSqlSessionFactory.databaseSpecificLimitBeforeStatements.get(databaseType));
                properties.put("limitAfter",
                        DbSqlSessionFactory.databaseSpecificLimitAfterStatements.get(databaseType));
                properties.put("limitBetween",
                        DbSqlSessionFactory.databaseSpecificLimitBetweenStatements.get(databaseType));
                properties.put("orderBy",
                        DbSqlSessionFactory.databaseSpecificOrderByStatements.get(databaseType));
            }
            XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
            Configuration configuration = parser.getConfiguration();
            configuration.setEnvironment(environment);
            configuration.getTypeHandlerRegistry().register(VariableType.class, JdbcType.VARCHAR,
                    new IbatisVariableTypeHandler());
            configuration = parser.parse();

            sqlSessionFactory = new DefaultSqlSessionFactory(configuration);

        } catch (Exception e) {
            throw new ActivitiException("Error while building ibatis SqlSessionFactory: " + e.getMessage(), e);
        } finally {
            IoUtil.closeSilently(inputStream);
        }
    }
}

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
 *///www .j av a2  s .co  m
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:org.obiba.onyx.spring.AnnotatedBeanFinderFactoryBean.java

/**
 * The main method that searches for annotated classes in classpath resources.
 *//*w w  w .j  a  v  a 2s.  c o m*/
private void searchAnnotatedEntityClasses() {
    // Search resources by every search pattern.
    log.info("searchAnnotatedEntityClasses in " + searchPatterns);
    for (String searchPattern : searchPatterns) {
        try {
            Resource[] resources = resolver.getResources(searchPattern);

            if (resources != null) {
                // Parse every resource.
                for (Resource res : resources) {
                    String path = res.getURL().getPath();
                    // Path name string should not be empty.
                    if (!path.equals("")) {
                        if (path.endsWith(".class")) {
                            dealWithClasses(path);
                        } else if (path.endsWith(".jar")) {
                            dealWithJars(res);
                        }
                    }
                }
            }
        } catch (Exception ignore) {
            log.warn("Resource resolving failed", ignore);
        }
    }
    if (log.isInfoEnabled()) {
        log.info("Annotations to look for: " + annotationClasses);
        log.info("Annotated classes found: " + annotatedClasses);
    }
}

From source file:guru.qas.martini.jmeter.sampler.MartiniSampler.java

protected Exception getUnimplementedStepException(Martini martini, Step step) {
    Resource source = martini.getRecipe().getSource();

    String relative;/*w w  w.j a va2 s . c o  m*/
    try {
        URL url = source.getURL();
        String externalForm = url.toExternalForm();
        int i = externalForm.lastIndexOf('!');
        relative = i > 0 && externalForm.length() > i + 1 ? externalForm.substring(i + 1) : externalForm;
    } catch (IOException e) {
        logger.warn("unable to obtain URL from Resource " + source, e);
        relative = source.toString();
    }

    int line = step.getLocation().getLine();
    String message = String.format("unimplemented step: %s line %s", relative, line);
    Exception exception = new Exception(message);
    exception.fillInStackTrace();
    return exception;
}