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

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

Introduction

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

Prototype

URI getURI() throws IOException;

Source Link

Document

Return a URI handle for this resource.

Usage

From source file:com.jbrisbin.vpc.jobsched.SpringResourceConnector.java

public URLConnection getResourceConnection(String name) throws ResourceException {
    Resource res = null;
    if (name.startsWith("classpath:")) {
        res = new ClassPathResource(name.substring(10));
    } else if (name.startsWith("http")) {
        try {//from   www. j a  v  a 2s .c  om
            res = new UrlResource(name);
        } catch (MalformedURLException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        res = new FileSystemResource(name);
    }
    try {
        return res.getURI().toURL().openConnection();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ResourceException(e);
    }
}

From source file:com.evolveum.midpoint.web.security.MidPointApplication.java

private void mountFiles(String path, Class<?> clazz) {
    try {//from   w ww . j a v  a 2 s.  co m
        List<Resource> list = new ArrayList<>();
        String packagePath = clazz.getPackage().getName().replace('.', '/');

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] res = resolver.getResources("classpath:" + packagePath + "/*.png");
        if (res != null) {
            list.addAll(Arrays.asList(res));
        }
        res = resolver.getResources("classpath:" + packagePath + "/*.gif");
        if (res != null) {
            list.addAll(Arrays.asList(res));
        }

        for (Resource resource : list) {
            URI uri = resource.getURI();
            File file = new File(uri.toString());
            mountResource(path + "/" + file.getName(), new SharedResourceReference(clazz, file.getName()));
        }
    } catch (Exception ex) {
        LoggingUtils.logException(LOGGER, "Couldn't mount files", ex);
    }
}

From source file:org.brekka.stillingar.spring.resource.ScanningResourceSelector.java

/**
 * Search the specified base directory for files with names matching those in <code>names</code>. If the location
 * gets rejected then it should be added to the list of rejected locations.
 * //from   w  ww  .j av  a2s  .  co  m
 * @param locationBase
 *            the location to search
 * @param names
 *            the names of files to find within the base location
 * @param rejected
 *            collects failed locations.
 * @return the resource or null if one cannot be found.
 */
protected Resource findInBaseDir(BaseDirectory locationBase, Set<String> names,
        List<RejectedSnapshotLocation> rejected) {
    Resource dir = locationBase.getDirResource();
    if (dir instanceof UnresolvableResource) {
        UnresolvableResource res = (UnresolvableResource) dir;
        rejected.add(new Rejected(locationBase.getDisposition(), null, res.getMessage()));
    } else {
        String dirPath = null;
        try {
            URI uri = dir.getURI();
            if (uri != null) {
                dirPath = uri.toString();
            }
        } catch (IOException e) {
            if (log.isWarnEnabled()) {
                log.warn(format("Resource dir '%s' has a bad uri", locationBase), e);
            }
        }
        String message;
        if (dir.exists()) {
            StringBuilder messageBuilder = new StringBuilder();
            for (String name : names) {
                try {
                    Resource location = dir.createRelative(name);
                    if (location.exists()) {
                        if (location.isReadable()) {
                            // We have found a file
                            return location;
                        }
                        if (messageBuilder.length() > 0) {
                            messageBuilder.append(" ");
                        }
                        messageBuilder.append("File '%s' exists but cannot be read.");
                    } else {
                        // Fair enough, it does not exist
                    }
                } catch (IOException e) {
                    // Location could not be resolved, log as warning, then move on to the next one.
                    if (log.isWarnEnabled()) {
                        log.warn(format("Resource location '%s' encountered problem", locationBase), e);
                    }
                }
            }
            if (messageBuilder.length() == 0) {
                message = "no configuration files found";
            } else {
                message = messageBuilder.toString();
            }
        } else {
            message = "Directory does not exist";
        }
        rejected.add(new Rejected(locationBase.getDisposition(), dirPath, message));
    }
    // No resource found
    return null;
}

From source file:architecture.ee.component.core.lifecycle.RepositoryImpl.java

public void setServletContext(ServletContext servletContext) {

    // 1.  ?? ? ? ?  : ARCHITECTURE_INSTALL_ROOT
    String value = servletContext.getInitParameter(ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY);
    if (!StringUtils.isEmpty(value)) {
        try {// ww  w .  jav a  2 s. c o m
            ServletContextResourceLoader servletResoruceLoader = new ServletContextResourceLoader(
                    servletContext);
            Resource resource = servletResoruceLoader.getResource(value);
            if (resource.exists()) {
                log.debug(L10NUtils.format("003003", ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY,
                        resource.getURI()));
                this.rootResource = resource;
                setState(State.INITIALIZED);
                initailized = true;
            }
        } catch (Throwable e) {
            this.rootResource = null;
        }
    }

    if (!initailized && !StringUtils.isEmpty(value)) {
        Resource obj;
        try {
            obj = resoruceLoader.getResource(value);
            if (obj.exists()) {
                log.debug(L10NUtils.format("003003", ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY,
                        obj.getURI()));
                this.rootResource = obj;
                setState(State.INITIALIZED);
                initailized = true;

            }
        } catch (Throwable e) {
            log.error(e);
        }
    }

    if (!initailized) {
        try {
            ServletContextResource resource = new ServletContextResource(servletContext, "/WEB-INF");
            File file = resource.getFile();
            if (file.exists()) {
                this.rootResource = new FileSystemResource(file);
                setState(State.INITIALIZED);
                initailized = true;
            }
        } catch (Throwable e) {
            log.error(e);
        }
    }
}

From source file:com.griddynamics.banshun.ContextParentBean.java

void initializeChildContexts() {
    for (String loc : resultConfigLocations) {
        if (ignoredLocations.contains(loc)) {
            continue;
        }//from w  w w.  j av a 2  s.  c  o  m
        try {
            Resource[] resources = context.getResources(loc);

            for (final Resource res : resources) {
                try {
                    ConfigurableApplicationContext child = createChildContext(res, context);
                    children.add(child);
                } catch (Exception e) {
                    log.error("Failed to process resource [{}] from location [{}] ",
                            new Object[] { res.getURI(), loc, e });
                    if (strictErrorHandling) {
                        throw new RuntimeException(e);
                    }
                    nestedContextsExceptions.put(loc, e);
                    addToFailedLocations(loc);
                    break;
                }
            }
        } catch (IOException e) {
            log.error("Failed to process configuration from [{}]", loc, e);
            if (strictErrorHandling) {
                throw new RuntimeException(e);
            }
            addToFailedLocations(loc);
        }
    }
}

From source file:org.mybatis.spring.extend.SqlSessionFactoryBean.java

private void parseExtTypeAliases(Configuration configuration) {
    if (!hasLength(extTypeAliasesPackage)) {
        return;/*from   w  w  w  .j a  v  a  2s  .c o m*/
    }
    String prefix = "classpath:";
    String suffix = "/*.class";
    String[] extArr = tokenizeToStringArray(extTypeAliasesPackage,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    ClassLoader classLoader = getClass().getClassLoader();
    try {
        for (String ext : extArr) {
            Resource[] resources = resolver.getResources(prefix + ext + suffix);
            if (resources != null) {
                for (Resource resource : resources) {
                    String classFilePath = resource.getURI().getPath();
                    int index = classFilePath.indexOf("classes");
                    String className = classFilePath.substring(index + 8, classFilePath.length() - 6)
                            .replaceAll("/", ".");
                    Class<?> clz = classLoader.loadClass(className);
                    configuration.getTypeAliasRegistry().registerAlias(clz);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("parse extTypeAliasesPackage failed", e);
    }
}

From source file:com.jiangnan.es.orm.mybatis.extend.SqlSessionFactoryBean.java

private void autoTypeAliases(Configuration configuration) throws IOException {
    String basePackage = this.basePackage.replaceAll("\\.", "/") + "/";

    List<String> lists = new ArrayList<String>();

    String testPath = "classpath*:" + basePackage + "**/*.class";
    ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
    Resource[] source = new Resource[0];
    try {/* ww w  . j  a v  a 2  s .  c  o  m*/
        source = resourceLoader.getResources(testPath);
    } catch (IOException e) {
        logger.warn("" + basePackage + "DTO");
    }

    for (int i = 0; i < source.length; i++) {
        Resource resource = source[i];

        logger.debug("file:" + resource.getURI().toString());
        int start = resource.getURI().toString().lastIndexOf(basePackage) + basePackage.length();
        int end = resource.getURI().toString().lastIndexOf(resource.getFilename());
        String packageName = resource.getURI().toString().substring(start, end);
        lists.add(basePackage + packageName + resource.getFilename());
        logger.debug("CLASS:" + basePackage + packageName + resource.getFilename());
    }

    for (String className : lists) {
        try {
            className = className.substring(0, className.indexOf(".class")).replaceAll("/", "\\.");
            Class<?> c = Class.forName(className);
            if (Entity.class.isAssignableFrom(c)) {
                configuration.getTypeAliasRegistry().registerAlias(c);
            }
            if (c.getSimpleName().toUpperCase().endsWith("DTO")) {
                configuration.getTypeAliasRegistry().registerAlias(c);
            }
        } catch (java.lang.ExceptionInInitializerError e) {
            logger.warn("" + className);
            continue;
        } catch (ClassNotFoundException e) {
            logger.warn("" + className);
            continue;
        } catch (Exception e) {
            logger.warn("?" + className);
            continue;
        }
    }
}

From source file:eu.trentorise.game.test.GameTest.java

private String relativeRulePath(Resource resource, String classpathFolder) throws IOException {
    String path = null;//from w  ww .  ja v  a  2  s  .co  m
    if (resource != null) {
        path = classpathFolder;
        String uri = resource.getURI().getPath();
        String pattern = String.format(".*/%s(.*)%s", classpathFolder, resource.getFilename());
        Pattern subfolderPattern = Pattern.compile(pattern);
        Matcher m = subfolderPattern.matcher(uri);
        if (m.matches() && m.group(1) != null) {
            path += m.group(1);
        }
        path += resource.getFilename();
    }
    return path;
}

From source file:net.paoding.rose.scanner.ModuleResourceProviderImpl.java

@Override
public List<ModuleResource> findModuleResources(LoadScope scope) throws IOException {

    Local local = new Local();
    String[] controllersScope = scope.getScope("controllers");
    if (logger.isInfoEnabled()) {
        logger.info("[moduleResource] starting ...");
        logger.info("[moduleResource] call 'findFiles':" + " to find classes or jar files by scope "//
                + Arrays.toString(controllersScope));
    }/*  w w w  .j  a  va 2s  .c o m*/

    List<ResourceRef> refers = RoseScanner.getInstance().getJarOrClassesFolderResources(controllersScope);

    if (logger.isInfoEnabled()) {
        logger.info("[moduleResource] exits from 'findFiles'");
        logger.info(
                "[moduleResource] going to scan controllers" + " from these folders or jar files:" + refers);
    }

    FileSystemManager fileSystem = new FileSystemManager();

    for (ResourceRef refer : refers) {
        Resource resource = refer.getResource();
        if (!refer.hasModifier("controllers")) {
            if (logger.isDebugEnabled()) {
                logger.debug("[moduleResource] Ignored because not marked as 'controllers'"
                        + " in META-INF/rose.properties or META-INF/MANIFEST.MF: " + resource.getURI());
            }
            continue;
        }
        File resourceFile = resource.getFile();
        String urlString;
        if ("jar".equals(refer.getProtocol())) {
            urlString = ResourceUtils.URL_PROTOCOL_JAR + ":" + resourceFile.toURI()
                    + ResourceUtils.JAR_URL_SEPARATOR;
        } else {
            urlString = resourceFile.toURI().toString();
        }
        FileObject rootObject = fileSystem.resolveFile(urlString);
        if (rootObject == null || !rootObject.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("[moduleResource] Ignored because not exists: " + urlString);
            }
            continue;
        }

        if (logger.isInfoEnabled()) {
            logger.info("[moduleResource] start to scan moduleResource in file: " + rootObject);
        }

        try {
            int oldSize = local.moduleResourceList.size();

            deepScanImpl(local, rootObject, rootObject);

            int newSize = local.moduleResourceList.size();

            if (logger.isInfoEnabled()) {
                logger.info("[moduleResource] got " + (newSize - oldSize) + " modules in " + rootObject);
            }

        } catch (Exception e) {
            logger.error("[moduleResource] error happend when scanning " + rootObject, e);
        }

        fileSystem.clearCache();
    }

    afterScanning(local);

    logger.info("[moduleResource] found " + local.moduleResourceList.size() + " module resources ");

    return local.moduleResourceList;
}