Example usage for org.springframework.util ResourceUtils isJarURL

List of usage examples for org.springframework.util ResourceUtils isJarURL

Introduction

In this page you can find the example usage for org.springframework.util ResourceUtils isJarURL.

Prototype

public static boolean isJarURL(URL url) 

Source Link

Document

Determine whether the given URL points to a resource in a jar file.

Usage

From source file:com.gzj.tulip.load.vfs.FileSystemManager.java

public synchronized FileObject resolveFile(URL url) throws IOException {
    try {//from   w  w w . j av  a2s  . c  om
        if (traceEnabled) {
            logger.trace("[fs] resolveFile ... by url '" + url + "'");
        }
        String urlString = url.toString();
        FileObject object = cached.get(urlString);

        if (object != null) {
            if (traceEnabled) {
                logger.trace("[fs] found cached file for url '" + urlString + "'");
            }
            return object;
        }
        if (ResourceUtils.isJarURL(url)) {
            if (!urlString.endsWith("/")) {
                object = resolveFile(urlString + "/");
            }
            if (object == null || !object.exists()) {
                object = new JarFileObject(this, url);
                if (traceEnabled) {
                    logger.trace("[fs] create jarFileObject for '" + urlString + "'");
                }
            }
        } else {
            File file = ResourceUtils.getFile(url);
            if (file.isDirectory()) {
                if (!urlString.endsWith("/")) {
                    urlString = urlString + "/";
                    url = new URL(urlString);
                }
            } else if (file.isFile()) {
                if (urlString.endsWith("/")) {
                    urlString = StringUtils.removeEnd(urlString, "/");
                    url = new URL(urlString);
                }
            }
            object = new SimpleFileObject(this, url);
            if (traceEnabled) {
                logger.trace("[fs] create simpleFileObject for '" + urlString + "'");
            }
        }
        if (object.exists()) {
            cached.put(urlString, object);
        }
        return object;
    } catch (IOException e) {
        logger.error(e.getMessage() + ":" + url, e);
        throw e;
    }
}

From source file:com.asual.summer.core.resource.MessageResource.java

public void setWildcardLocations(String[] locations) {

    super.setLocations(locations);

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    List<Resource[]> resourceLocations = new ArrayList<Resource[]>();

    List<String> fileBasenames = new ArrayList<String>();
    List<String> jarBasenames = new ArrayList<String>();

    for (String location : locations) {
        try {//from   w  w  w.j av a  2s .c  om
            Resource[] wildcard = (Resource[]) ArrayUtils.addAll(
                    resolver.getResources(location + "*.properties"),
                    resolver.getResources(location + "*.xml"));
            if (wildcard != null && wildcard.length > 0) {
                resourceLocations.add(wildcard);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    int i = 0;
    boolean entries = true;

    while (entries) {
        entries = false;
        for (Resource[] location : resourceLocations) {
            if (location.length > i) {
                try {
                    URL url = location[i].getURL();
                    boolean isJar = ResourceUtils.isJarURL(url);
                    String basename = "classpath:" + url.getFile()
                            .replaceFirst(isJar ? "^.*" + ResourceUtils.JAR_URL_SEPARATOR
                                    : "^(.*/test-classes|.*/classes|.*/resources)/", "")
                            .replaceAll("(_\\w+){0,3}\\.(properties|xml)", "");
                    if (isJar) {
                        if (!jarBasenames.contains(basename)) {
                            jarBasenames.add(basename);
                        }
                    } else {
                        if (!fileBasenames.contains(basename)) {
                            fileBasenames.add(basename);
                        }
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
                entries = true;
            }
        }
        i++;
    }

    fileBasenames.addAll(jarBasenames);

    rbms.clearCache();
    rbms.setBasenames(fileBasenames.toArray(new String[fileBasenames.size()]));
}

From source file:de.axelfaust.alfresco.nashorn.repo.loaders.ClasspathScriptFile.java

/**
 *
 * {@inheritDoc}/*from  w  w w  .  j  a  v a  2 s  . c o  m*/
 */
@Override
public boolean exists(final boolean force) {
    boolean exists = this.exists;

    // JAR files "should never" cease to exist during runtime
    if (!this.existsInJarFile || force) {
        final long currentTimeMillis = System.currentTimeMillis();
        if (force || currentTimeMillis - this.lastExistenceCheck > DEFAULT_EXISTENCE_CHECK_INTERVAL) {
            synchronized (this) {
                exists = this.exists;
                if (force || currentTimeMillis - this.lastExistenceCheck > DEFAULT_EXISTENCE_CHECK_INTERVAL) {
                    final boolean doesExist = this.resource.exists();

                    if (!doesExist && this.exists) {
                        this.lastModifiedCheck = -1;

                        this.cacheFile.delete();
                        this.size = -1;
                    } else if (doesExist && !this.existsInJarFile) {
                        try {
                            final URL url = this.resource.getURL();
                            this.existsInJarFile = ResourceUtils.isJarURL(url);
                        } catch (final IOException ioex) {
                            LOGGER.debug("Error retrieving resource URL despite proven existence", ioex);
                        }
                    }

                    exists = this.exists = doesExist;
                    this.lastExistenceCheck = currentTimeMillis;
                }
            }
        }
    }

    return exists;
}

From source file:com.asual.summer.core.resource.PropertyResource.java

public void setWildcardLocations(String[] locations) {

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    List<Resource[]> resourceLocations = new ArrayList<Resource[]>();

    List<Resource> fileResources = new ArrayList<Resource>();
    List<Resource> jarResources = new ArrayList<Resource>();

    for (String location : locations) {
        try {//  w  w  w .j  a v  a  2  s .  c o m
            Resource[] wildcard = resolver.getResources(location);
            if (wildcard != null && wildcard.length > 0) {
                resourceLocations.add(wildcard);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    int i = 0;
    boolean entries = true;

    while (entries) {
        entries = false;
        for (Resource[] location : resourceLocations) {
            if (location.length > i) {
                try {
                    boolean isJar = ResourceUtils.isJarURL(location[i].getURL());
                    if (isJar) {
                        jarResources.add(location[i]);
                    } else {
                        fileResources.add(location[i]);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
                entries = true;
            }
        }
        i++;
    }

    fileResources.addAll(jarResources);
    Collections.reverse(fileResources);

    this.resources = fileResources.toArray(new Resource[fileResources.size()]);
}

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

public void run() {
    final GlobalConfiguration mybatisGlobalCache = GlobalConfiguration.GlobalConfig(configuration);
    /*/*w ww. j av  a 2 s.c o 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.diaimm.april.db.jpa.hibernate.multidbsupport.PersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the <code>persistence.xml</code> file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws java.io.IOException if the checking failed
 *///  w  w w .  ja v a2  s  .co  m
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();

    // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
    if (ResourceUtils.isJarURL(originalURL)) {
        return ResourceUtils.extractJarFileURL(originalURL);
    }

    // check META-INF folder
    String urlToString = originalURL.toExternalForm();
    if (!urlToString.contains(META_INF)) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " should be located inside META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }
    if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }

    String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
    if (persistenceUnitRoot.endsWith("/")) {
        persistenceUnitRoot = persistenceUnitRoot.substring(0, persistenceUnitRoot.length() - 1);
    }
    return new URL(persistenceUnitRoot);
}

From source file:com.apdplat.platform.spring.APDPlatPersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the <code>persistence.xml</code> file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws IOException if the checking failed
 *///from www .j av  a 2 s  .c  o m
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();
    String urlToString = originalURL.toExternalForm();

    // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
    if (ResourceUtils.isJarURL(originalURL)) {
        return ResourceUtils.extractJarFileURL(originalURL);
    }

    else {
        // check META-INF folder
        if (!urlToString.contains(META_INF)) {
            if (logger.isInfoEnabled()) {
                logger.info(resource.getFilename()
                        + " should be located inside META-INF directory; cannot determine persistence unit root URL for "
                        + resource);
            }
            return null;
        }
        if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
            if (logger.isInfoEnabled()) {
                logger.info(resource.getFilename()
                        + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for "
                        + resource);
            }
            return null;
        }

        String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
        return new URL(persistenceUnitRoot);
    }
}

From source file:org.cfr.capsicum.test.AbstractCayenneJUnit4DbUnitSpringContextTests.java

/**
 *
 * @param url//  ww w  .j av  a 2  s  . co  m
 * @param forwardonly
 * @return
 * @throws DatabaseUnitException
 */
protected IDataSet getSrcDataSet(URL url, boolean forwardonly) throws DatabaseUnitException {
    InputStream stream = null;
    if (ResourceUtils.isJarURL(url)) {
        stream = ClassUtils.getDefaultClassLoader().getResourceAsStream(url.toString());
    }

    IDataSetProducer producer = null;

    if (stream == null) {
        producer = new XmlProducer(new InputSource(url.toString()));
    } else {
        producer = new XmlProducer(new InputSource(stream));
    }

    if (forwardonly) {
        return new StreamingDataSet(producer);
    }
    return new CachedDataSet(producer);

}

From source file:com.edgenius.core.util.FileUtil.java

/**
 * /* ww w. ja va  2 s  . com*/
 * @param location
 * @return
 * @throws IOException 
 */
public static InputStream getFileInputStream(String location) throws IOException {
    //Don't user DefaultResourceLoader directly, as test it try to find host "c" if using method resource.getInputStream()
    // while location is "file://c:/var/test" etc.

    DefaultResourceLoader loader = new DefaultResourceLoader();
    Resource res = loader.getResource(location);
    if (ResourceUtils.isJarURL(res.getURL())) {
        //it is in jar file, we just assume it won't be changed in runtime, so below method is safe.
        try {
            return res.getInputStream();
        } catch (IOException e) {
            throw (e);
        }
    } else {
        //in Tomcat, the classLoader cache the input stream even using thread scope classloader, but it is still failed
        //if the reload in same thread. For example, DataRoot class save and reload in same thread when install.
        //So, we assume if the file is not inside jar file, we will always reload the file into a new InputStream from file system.

        //if it is not jar resource, then try to refresh the input stream by file system
        return new FileInputStream(res.getFile());
    }
}

From source file:org.cfr.capsicum.test.AbstractCayenneJUnit4DbUnitSpringContextTests.java

protected IDataSet getSrcDataSet(URL url, ProducerType format, boolean forwardonly)
        throws DatabaseUnitException {
    if (logger.isDebugEnabled()) {
        logger.debug("getSrcDataSet(src=" + url + ", format=" + format + ", forwardonly=" + forwardonly
                + ") - start");
    }//from  w  w  w.  j  a  v a 2 s. c  o m

    InputStream stream = null;
    if (ResourceUtils.isJarURL(url)) {
        stream = ClassUtils.getDefaultClassLoader().getResourceAsStream(url.toString());
    }

    IDataSetProducer producer = null;
    if (format == ProducerType.Xml) {
        if (stream == null) {
            producer = new XmlProducer(new InputSource(url.toString()));
        } else {
            producer = new XmlProducer(new InputSource(stream));
        }
    } else if (format == ProducerType.Cvs) {
        producer = new CsvProducer(url.toString());
    } else if (format == ProducerType.Flat) {
        if (stream == null) {
            producer = new FlatXmlProducer(new InputSource(url.toString()));
        } else {
            producer = new FlatXmlProducer(new InputSource(stream));
        }
    } else if (format == ProducerType.Dtd) {
        if (stream == null) {
            producer = new FlatDtdProducer(new InputSource(url.toString()));
        } else {
            producer = new FlatDtdProducer(new InputSource(stream));
        }
    } else {
        throw new IllegalArgumentException(
                "Type must be either 'flat'(default), 'xml', 'csv' or 'dtd' but was: " + format);
    }

    if (forwardonly) {
        return new StreamingDataSet(producer);
    }
    return new CachedDataSet(producer);

}