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.laxser.blitz.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));
    }/*from   w w w.ja  v  a  2 s.c o  m*/

    List<ResourceRef> refers = BlitzScanner.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/blitz.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;
}

From source file:com.sinosoft.one.mvc.scanner.ModuleResourceProviderImpl.java

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));
    }//from   w w w.j a  va  2s  . com

    List<ResourceRef> refers = MvcScanner.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/mvc.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;
}

From source file:com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl.java

/**
 * {@inheritDoc}/*w w  w. j ava2 s.com*/
 */
@Override
public void serveResource(final String jobId, final URL baseUrl, final String relativePath,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    // TODO: Metrics
    // Is the job running or not?
    final JobStatus jobStatus;
    try {
        jobStatus = this.jobPersistenceService.getJobStatus(jobId);
    } catch (final GenieNotFoundException e) {
        log.error(e.getMessage(), e);
        response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
        return;
    }

    // Is it V3 or V4?
    final boolean isV4;
    try {
        isV4 = this.jobPersistenceService.isV4(jobId);
    } catch (final GenieJobNotFoundException nfe) {
        // Really after the last check this shouldn't happen but just in case
        log.error(nfe.getMessage(), nfe);
        response.sendError(HttpStatus.NOT_FOUND.value(), nfe.getMessage());
        return;
    }

    // Normalize the base url. Make sure it ends in /.
    final URI baseUri;
    try {
        baseUri = new URI(baseUrl.toString() + SLASH).normalize();
    } catch (final URISyntaxException e) {
        log.error(e.getMessage(), e);
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Unable to convert " + baseUrl + " to valid URI");
        return;
    }

    if (jobStatus.isActive() && isV4) {

        final Optional<JobDirectoryManifest> manifest = this.agentFileStreamService.getManifest(jobId);
        if (!manifest.isPresent()) {
            log.error("Manifest not found for active job: {}", jobId);
            response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(),
                    "Could not load manifest for job: " + jobId);
            return;
        }

        final URI jobDirRoot;
        try {
            jobDirRoot = new URI(AgentFileProtocolResolver.URI_SCHEME, jobId, SLASH, null);
        } catch (final URISyntaxException e) {
            log.error(e.getMessage(), e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            return;
        }

        this.handleRequest(baseUri, relativePath, request, response, manifest.get(), jobDirRoot);

    } else if (jobStatus.isActive()) {
        // Active V3 job

        // TODO: Manifest creation could be expensive
        final Resource jobDir = this.jobFileService.getJobFileAsResource(jobId, "");
        if (!jobDir.exists()) {
            log.error("Job directory {} doesn't exist. Unable to serve job contents.", jobDir);
            response.sendError(HttpStatus.NOT_FOUND.value());
            return;
        }
        final URI jobDirRoot;
        try {
            // Make sure the directory ends in a slash. Normalize will ensure only single slash
            jobDirRoot = new URI(jobDir.getURI().toString() + SLASH).normalize();
        } catch (final URISyntaxException e) {
            log.error(e.getMessage(), e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            return;
        }
        final Path jobDirPath = Paths.get(jobDirRoot);

        final JobDirectoryManifest manifest = new JobDirectoryManifest(jobDirPath, false);
        this.handleRequest(baseUri, relativePath, request, response, manifest, jobDirRoot);
    } else {
        // Archived job
        final JobDirectoryManifest manifest;
        final URI jobDirRoot;
        try {
            final ManifestCacheValue cacheValue = this.manifestCache.get(jobId);
            manifest = cacheValue.getManifest();
            jobDirRoot = cacheValue.getJobDirectoryRoot();
        } catch (final Exception e) {
            // TODO: more fine grained exception handling
            if (e.getCause() instanceof JobNotArchivedException) {
                // will be thrown from the manifest loader
                log.error(e.getCause().getMessage(), e.getCause());
                response.sendError(HttpStatus.NOT_FOUND.value(), e.getCause().getMessage());
            } else {
                log.error(e.getMessage(), e);
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }
            return;
        }
        this.handleRequest(baseUri, relativePath, request, response, manifest, jobDirRoot);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.io.ResourceCollectionReaderBase.java

/**
 * Get the URI of the given resource.//from   w  w w  .ja  v  a  2 s.co  m
 * 
 * @param aResource
 *            a resource
 * @param aFileOrDir
 *            if true try to return only files, if false try to return only dirs
 * @return the URI of the resource
 */
private URI getUri(org.springframework.core.io.Resource aResource, boolean aFileOrDir) throws IOException {
    try {
        final File file = aResource.getFile();

        // Exclude hidden files/dirs if requested
        if (file.isHidden() && !this.includeHidden) {
            return null;
        }

        // Return only dirs or files...
        if ((aFileOrDir && file.isFile()) || (!aFileOrDir && file.isDirectory())) {
            return aResource.getFile().toURI();
        } else {
            return null;
        }
    } catch (final IOException e) {
        return aResource.getURI();
    } catch (final UnsupportedOperationException e) {
        return aResource.getURI();
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.io.ResourceCollectionReaderBase.java

protected Collection<Resource> scan(String aBase, Collection<String> aIncludes, Collection<String> aExcludes)
        throws IOException {
    boolean singleLocation = patterns == null;

    String base;/*from   www .j av a 2s  .c om*/
    if (aBase != null) {
        base = aBase;
        // If this is a real base location, then add a "/" if there is none
        if (!singleLocation) {
            if (!base.endsWith("/")) {
                base += "/";
            }
        }
    } else {
        base = "";
    }

    Collection<String> includes;
    Collection<String> excludes;

    if (aIncludes == null || aIncludes.size() == 0) {
        if (!singleLocation) {
            includes = Collections.singleton("**/*");
        } else {
            includes = Collections.singleton("");
        }
    } else {
        includes = aIncludes;
    }

    if (aExcludes == null || aExcludes.size() == 0) {
        excludes = Collections.emptySet();
    } else {
        excludes = aExcludes;
    }

    AntPathMatcher matcher = new AntPathMatcher();
    List<Resource> result = new ArrayList<Resource>();

    // E.g. a classpath location may resolve to multiple locations. Thus we collect all the
    // locations to which the base resolves.
    org.springframework.core.io.Resource[] rBases = resolver.getResources(base);
    Set<String> rsBases = new HashSet<String>();
    for (org.springframework.core.io.Resource rBase : rBases) {
        URI uri = getUri(rBase, false);
        if (uri != null) {
            rsBases.add(uri.toString());
        }
    }

    // Now we process the include patterns one after the other
    for (String include : includes) {
        // We resolve the resources for each base+include combination.
        org.springframework.core.io.Resource[] resourceList = resolver.getResources(base + include);
        nextResource: for (org.springframework.core.io.Resource resource : resourceList) {
            URI uResource = getUri(resource, true);
            if (uResource == null) {
                continue;
            }
            String sResource = uResource.toString();

            // Determine the resolved base for this location
            String matchBase = null;
            if (base.length() > 0 && !singleLocation) {
                for (String b : rsBases) {
                    if (!sResource.startsWith(b)) {
                        continue;
                    }

                    // This is the base... at least we define it as being the base.
                    // FIXME there may be other bases. Have to define a policy if most or least
                    // specific base should be chosen.
                    matchBase = b;
                    break;
                }

                if (matchBase == null) {
                    // This should not happen...
                    throw new IllegalStateException("No base found for location [" + sResource + "]");
                }
            } else {
                // If no base is set, no need to go through the trouble of finding one.
                matchBase = base;
            }

            // To figure out if the resolved location is excluded, we try to find the part
            // of the location that was determined by the include pattern by substracting the
            // resolved base locations one after the other and looking if the result is
            // matched by the exclude.
            if (excludes != null) {
                for (String exclude : excludes) {
                    String rest = sResource.substring(matchBase.length());
                    if (matcher.match(exclude, rest)) {
                        if (getLogger().isDebugEnabled()) {
                            getLogger().debug("Excluded: " + sResource);
                        }
                        continue nextResource;
                    }
                }
            }

            // If the resource was not excluded, we add it to the results.
            String p = sResource.substring(matchBase.length());
            Resource r = new Resource(base + p, base, resource.getURI(), matchBase, p, resource);
            result.add(r);
        }
    }

    Collections.sort(result, new Comparator<Resource>() {
        @Override
        public int compare(Resource aO1, Resource aO2) {
            return aO1.location.compareTo(aO2.location);
        }
    });

    if (singleLocation && result.isEmpty()) {
        throw new FileNotFoundException("Resource not found or not a file: [" + aBase
                + "]. Please specify a file or use a pattern. Directories without patterns are "
                + "not valid.");
    }

    return result;
}

From source file:org.apereo.portal.portlets.sitemap.SitemapTest.java

@Test
public void testStylesheetCompilation() throws IOException {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    Resource resource = new ClassPathResource(STYLESHEET_LOCATION);
    Source source = new StreamSource(resource.getInputStream(), resource.getURI().toASCIIString());
    try {//  w w w  . jav a 2s. c o m
        Transformer transformer = TransformerFactory.newInstance().newTransformer(source);
        transformer.setParameter(SitemapPortletController.USE_TAB_GROUPS, useTabGroups);
        transformer.setParameter(SitemapPortletController.USER_LANG, "en_US");
        transformer.setParameter(XsltPortalUrlProvider.CURRENT_REQUEST, request);
        transformer.setParameter(XsltPortalUrlProvider.XSLT_PORTAL_URL_PROVIDER, this.xsltPortalUrlProvider);

        Source xmlSource = new StreamSource(new ClassPathResource(XML_LOCATION).getFile());
        CharArrayWriter buffer = new CharArrayWriter();
        TransformerUtils.enableIndenting(transformer);
        transformer.transform(xmlSource, new StreamResult(buffer));
        if (logger.isTraceEnabled()) {
            logger.trace("XML: " + new String(buffer.toCharArray()));
        }
    } catch (TransformerConfigurationException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apereo.portal.utils.cache.resource.TemplatesBuilder.java

@Override
public LoadedResource<Templates> loadResource(Resource resource) throws IOException {
    final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    if (this.transformerAttributes != null) {
        for (final Map.Entry<String, Object> attributeEntry : this.transformerAttributes.entrySet()) {
            transformerFactory.setAttribute(attributeEntry.getKey(), attributeEntry.getValue());
        }//  www .  j  a  v a 2 s  .  c  o  m
    }

    final ResourceTrackingURIResolver uriResolver = new ResourceTrackingURIResolver(this.resourceLoader);
    transformerFactory.setURIResolver(uriResolver);

    final URI uri = resource.getURI();
    final String systemId = uri.toString();

    final InputStream stream = resource.getInputStream();
    final Templates templates;
    try {
        final StreamSource source = new StreamSource(stream, systemId);
        templates = transformerFactory.newTemplates(source);
    } catch (TransformerConfigurationException e) {
        throw new IOException("Failed to parse stream into Templates", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }

    final Map<Resource, Long> resolvedResources = uriResolver.getResolvedResources();

    return new LoadedResourceImpl<Templates>(templates, resolvedResources);
}

From source file:org.betaconceptframework.astroboa.test.engine.service.TaxonomyServiceTest.java

@Test
public void testImportXMLofTaxonomiesProvidedWithTheDistribution() throws IOException {
    Resource taxonomiesHomeDir = new ClassPathResource("/taxonomies");

    Assert.assertTrue(taxonomiesHomeDir.exists(),
            "Home directory of the taxonomies provided in the distribution does not exist in "
                    + taxonomiesHomeDir.getURI().toString());

    File[] taxonomyXmls = taxonomiesHomeDir.getFile().listFiles(new FilenameFilter() {

        @Override//from  ww  w .j  a  va2 s. co  m
        public boolean accept(File dir, String name) {
            return name != null && name.endsWith(".xml");
        }
    });

    Assert.assertTrue(taxonomyXmls.length > 0, "Home directory of the taxonomies provided in the distribution '"
            + taxonomiesHomeDir.getURI().toString() + "' does not contain any xml file");

    for (File taxonomyXML : taxonomyXmls) {

        Taxonomy taxonomy = taxonomyService.save(FileUtils.readFileToString(taxonomyXML, "UTF-8"));
        markTaxonomyForRemoval(taxonomy);
    }

}

From source file:org.codehaus.groovy.grails.compiler.GrailsClassLoader.java

public Class<?> reloadClass(String name) {
    try {/*from ww  w.  ja v  a 2 s . c  o m*/
        Resource resourceURL = loadGroovySource(name);
        if (resourceURL == null) {
            return null;
        }

        GroovyClassLoader innerLoader = new GrailsAwareClassLoader(this);
        clearCache();

        String path;
        try {
            path = new File(resourceURL.getURI()).getPath();
        } catch (IOException e) {
            // not a file-based source, so punt and use the name
            path = name;
        }

        InputStream inputStream = null;
        try {
            inputStream = resourceURL.getInputStream();
            Class<?> reloadedClass = innerLoader.parseClass(IOGroovyMethods.getText(inputStream), path);
            compilationErrors.remove(name);
            innerClassLoaderMap.put(name, innerLoader);
            return reloadedClass;
        } catch (MultipleCompilationErrorsException e) {
            compilationErrors.put(name, e);
            throw e;
        } catch (IOException e) {
            throw new CompilationFailedException(
                    "Error opening stream to class " + name + " with URL " + resourceURL, e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    } catch (MalformedURLException e) {
        throw new CompilationFailedException("Error opening stream to class " + name + ":" + e.getMessage(), e);
    }
}

From source file:org.codenergic.theskeleton.core.security.SecurityConfig.java

/**
* Token converter and enhancer/*from w w  w.  j  a va 2s  .  co  m*/
* @return
*/
@Bean
public JwtAccessTokenConverter accessTokenConverter(@Value("${security.jwt.signing-key:}") String signingKey,
        ResourceLoader resourceLoader) throws IOException {
    DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
    accessTokenConverter.setUserTokenConverter(new UserAccessTokenAuthenticationConverter());
    JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setAccessTokenConverter(accessTokenConverter);
    if (StringUtils.isBlank(signingKey))
        return jwtAccessTokenConverter;
    if (ResourceUtils.isUrl(signingKey)) {
        Resource signingKeyResource = resourceLoader.getResource(signingKey);
        signingKey = IOUtils.toString(signingKeyResource.getURI(), StandardCharsets.UTF_8);
    }
    jwtAccessTokenConverter.setSigningKey(signingKey);
    jwtAccessTokenConverter.setVerifierKey(signingKey);
    return jwtAccessTokenConverter;
}