Example usage for org.springframework.util ResourceUtils extractJarFileURL

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

Introduction

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

Prototype

public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException 

Source Link

Document

Extract the URL for the actual jar file from the given URL (which may point to a resource in a jar file or to a jar file itself).

Usage

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * //from  w w  w. j  a  va2  s .c  om
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

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

public void run() {
    final GlobalConfiguration mybatisGlobalCache = GlobalConfiguration.GlobalConfig(configuration);
    /*/*from w  w  w .  j  a  v a2  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
 *///from   w  ww  .  ja  v  a2s  .c  o 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  ww w .  ja  va  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:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java

@Override
public InternalPlugin parse(final Resource resource) {
    try {/*from ww  w  . j  a  v  a2 s.c o m*/
        LOG.info("Parsing descriptor for:" + resource);

        boolean ignoreModules = false;

        URL url = ResourceUtils.extractJarFileURL(resource.getURL());

        return parse(resource.getInputStream(), ignoreModules, FilenameUtils.getName(url.toString()));

    } catch (IOException e) {
        throw new PluginException(e.getMessage(), e);
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    }
}

From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition2Test.java

private ServiceDefinition getServiceDefFromJar(String jarFileName) throws Exception {

    List<File> classRoots = new ArrayList<File>();
    List<File> jarDirs = new ArrayList<File>();

    File jarDir = IOUtils.createTempDirectory();
    File srcJarFile = new ClassPathResource(
            this.getClass().getPackage().getName().replace(".", "/") + "/" + jarFileName).getFile();
    File jarFile = new File(jarDir, jarFileName);
    FileUtils.copyFile(srcJarFile, jarFile);
    jarDirs.add(jarDir);//from w w  w  . j a v a 2s .  c o m

    ClassPathResource runtimeServiceResource = new ClassPathResource(
            "com/wavemaker/runtime/service/LiveDataService.class");
    if (ResourceUtils.isJarURL(runtimeServiceResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(runtimeServiceResource.getURL());
        jarDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File runtimeServiceClassFile = runtimeServiceResource.getFile();
        File runtimeClassRoot = runtimeServiceClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(runtimeClassRoot);
    }

    ServiceDefinition ret = new JavaServiceDefinition("Foo", "serviceId", classRoots, jarDirs,
            new ArrayList<String>());

    jarFile.delete();
    jarDir.delete();

    return ret;
}

From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition2Test.java

private ServiceDefinition getServiceDef(String className, List<File> serviceLibDirs) throws Exception {

    List<File> classRoots = new ArrayList<File>();
    serviceLibDirs = serviceLibDirs == null ? new ArrayList<File>() : serviceLibDirs;

    File classFile = new ClassPathResource(className.replace('.', '/') + ".class").getFile();
    File classRoot = classFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();
    classRoots.add(classRoot);/*from   w ww  . java  2  s  .  co  m*/

    File queryInfoClassFile = new ClassPathResource(
            JavaService_BeanClass.class.getName().replace('.', '/') + ".class").getFile();
    File queryInfoClassRoot = queryInfoClassFile.getParentFile().getParentFile().getParentFile().getParentFile()
            .getParentFile();
    classRoots.add(queryInfoClassRoot);

    ClassPathResource runtimeServiceResource = new ClassPathResource(
            LiveDataService.class.getName().replace(".", "/") + ".class");
    if (ResourceUtils.isJarURL(runtimeServiceResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(runtimeServiceResource.getURL());
        serviceLibDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File runtimeServiceClassFile = runtimeServiceResource.getFile();
        File runtimeClassRoot = runtimeServiceClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(runtimeClassRoot);
    }

    ClassPathResource typeDefinitionResource = new ClassPathResource(
            TypeDefinition.class.getName().replace(".", "/") + ".class");
    if (ResourceUtils.isJarURL(typeDefinitionResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(typeDefinitionResource.getURL());
        serviceLibDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File typeDefinitionClassFile = typeDefinitionResource.getFile();
        File typeDefinitionClassRoot = typeDefinitionClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(typeDefinitionClassRoot);
    }

    return new JavaServiceDefinition(className, "serviceId", classRoots, serviceLibDirs,
            new ArrayList<String>());
}

From source file:org.jahia.test.framework.JahiaWebInitializer.java

@Override
public void initialize(GenericWebApplicationContext webAppContext) {
    try {/*from  www  .ja  v  a  2  s. c  om*/
        Resource[] resources = webAppContext
                .getResources("classpath*:org/jahia/config/jahiaunittest.properties");
        PropertiesFactoryBean propertiesFactory = new PropertiesFactoryBean();
        propertiesFactory.setLocations(resources);
        propertiesFactory.afterPropertiesSet();
        Properties properties = propertiesFactory.getObject();

        String jackrabbitHome = (String) properties.get("jahia.jackrabbit.home");
        if (jackrabbitHome != null) {
            jackrabbitHome = webAppContext.getResource(jackrabbitHome).getURL().getPath();
            File repoHome = new File(jackrabbitHome);
            if (!repoHome.exists()) {
                repoHome.mkdirs();
            }

            if (resources[0] != null && ResourceUtils.isJarURL(resources[0].getURL())) {
                URL jarUrl = ResourceUtils.extractJarFileURL(resources[0].getURL());
                try {
                    new JahiaArchiveFileHandler(jarUrl.getPath()).unzip("./target/test-repo", new PathFilter() {

                        @Override
                        public boolean accept(String path) {
                            // TODO Auto-generated method stub
                            return path.startsWith("WEB-INF");
                        }
                    });
                } catch (JahiaException e) {
                    logger.error("Unable to extract JAR");
                }
            } else if (resources[0] != null) {
                FileUtils.copyDirectory(
                        new File(StringUtils.substringBefore(resources[0].getURI().getPath(), "org"),
                                "WEB-INF"),
                        new File("./target/test-repo", "WEB-INF"));
            }
        }
    } catch (IOException e) {

    }
}

From source file:org.jahia.utils.FileUtils.java

/**
 * Returns the last modified date of the specified resource.
 * /*from  ww w . j  a  va2 s  . c om*/
 * @param resource
 *            resource to check the last modified date on
 * @return the last modified date of the specified resource
 * @throws IOException
 *             in case of an I/O error
 */
public static long getLastModified(Resource resource) throws IOException {
    URL resourceUrl = resource.getURL();
    return ResourceUtils.isJarURL(resourceUrl)
            ? ResourceUtils.getFile(ResourceUtils.extractJarFileURL(resourceUrl)).lastModified()
            : resource.lastModified();
}

From source file:org.springframework.boot.devtools.restart.server.RestartServer.java

private void updateTimeStamp(URL url) {
    try {//from w  ww  .j a v  a  2 s . c  om
        URL actualUrl = ResourceUtils.extractJarFileURL(url);
        File file = ResourceUtils.getFile(actualUrl, "Jar URL");
        file.setLastModified(System.currentTimeMillis());
    } catch (Exception ex) {
        // Ignore
    }
}