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

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

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

/**
 * Parse and build all persistence unit infos defined in the given XML files.
 * @param persistenceXmlLocations the resource locations (can be patterns)
 * @return the resulting PersistenceUnitInfo instances
 *//*from   w  w  w  . j av  a2s.  co m*/
public SpringPersistenceUnitInfo[] readPersistenceUnitInfos(String[] persistenceXmlLocations) {
    ErrorHandler handler = new SimpleSaxErrorHandler(LogFactory.getLog(getClass()));
    List<SpringPersistenceUnitInfo> infos = new LinkedList<SpringPersistenceUnitInfo>();
    String resourceLocation = null;
    try {
        for (String location : persistenceXmlLocations) {
            Resource[] resources = this.resourcePatternResolver.getResources(location);
            for (Resource resource : resources) {
                resourceLocation = resource.toString();
                InputStream stream = resource.getInputStream();
                try {
                    Document document = buildDocument(handler, stream);
                    parseDocument(resource, document, infos);
                } finally {
                    stream.close();
                }
            }
        }
    } catch (IOException ex) {
        throw new IllegalArgumentException("Cannot parse persistence unit from " + resourceLocation, ex);
    } catch (SAXException ex) {
        throw new IllegalArgumentException("Invalid XML in persistence unit from " + resourceLocation, ex);
    } catch (ParserConfigurationException ex) {
        throw new IllegalArgumentException("Internal error parsing persistence unit from " + resourceLocation);
    }

    return infos.toArray(new SpringPersistenceUnitInfo[infos.size()]);
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarCreator.java

/**
 * Small utility method used for determining the file name by striping the
 * root path from the file full path./* ww  w  .j  a  va 2s.c o  m*/
 * 
 * @param rootPath
 * @param resource
 * @return
 */
private String determineRelativeName(String rootPath, Resource resource) {
    try {
        String path = StringUtils.cleanPath(resource.getURL().toExternalForm());
        return path.substring(path.indexOf(rootPath) + rootPath.length());
    } catch (IOException ex) {
        throw (RuntimeException) new IllegalArgumentException("illegal resource " + resource.toString())
                .initCause(ex);
    }
}

From source file:edu.unc.lib.dl.schematron.SchematronValidator.java

/**
 * Use this to initialize the configured schemas. Generate stylesheet
 * implementations of ISO Schematron files and preload them into Transformer
 * Templates for quick use./*ww w  .ja  v  a  2s.  c o m*/
 */
public void loadSchemas() {
    templates = new HashMap<String, Templates>();
    // Load up a transformer and the ISO Schematron to XSL templates.
    Templates isoSVRLTemplates = null;
    ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl",
            SchematronValidator.class);
    Source svrlrc;
    try {
        svrlrc = new StreamSource(svrlRes.getInputStream());
    } catch (IOException e1) {
        throw new Error("Cannot load iso_svrl.xsl", e1);
    }
    TransformerFactory factory = null;
    try {
        factory = new TransformerFactoryImpl();
        // enable relative classpath-based URIs
        factory.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class);
                Source result;
                try {
                    result = new StreamSource(svrlRes.getInputStream());
                } catch (IOException e1) {
                    throw new TransformerException("Cannot resolve " + href, e1);
                }
                return result;
            }
        });
        isoSVRLTemplates = factory.newTemplates(svrlrc);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Error setting up transformer factory.", e);
        throw new Error("Error setting up transformer factory", e);
    } catch (TransformerConfigurationException e) {
        log.error("Error setting up transformer.", e);
        throw new Error("Error setting up transformer", e);
    }

    // Get a transformer
    Transformer t = null;
    try {
        t = isoSVRLTemplates.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Error("There was a problem configuring the transformer.", e);
    }

    for (String schema : schemas.keySet()) {
        // make XSLT out of Schematron for each schema
        Resource resource = schemas.get(schema);
        Source schematron = null;
        try {
            schematron = new StreamSource(resource.getInputStream());
        } catch (IOException e) {
            throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription()
                    + resource.toString());
        }
        JDOMResult res = new JDOMResult();
        try {
            t.transform(schematron, res);
        } catch (TransformerException e) {
            throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e);
        }

        // compile templates object for each profile
        try {
            Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument()));
            templates.put(schema, schemaTemplates);
        } catch (TransformerConfigurationException e) {
            throw new Error("There was a problem configuring the transformer.", e);
        }
    }

}

From source file:org.brekka.stillingar.spring.snapshot.WatchedResourceMonitor.java

@Override
public void initialise(Resource resource) {
    try {// w  w w .j a v  a  2 s . co  m
        this.resourceFile = resource.getFile().toPath();
        Path parent = resourceFile.getParent();
        this.watchService = parent.getFileSystem().newWatchService();
        this.watchKey = parent.register(this.watchService, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_CREATE);
    } catch (IOException e) {
        throw new ConfigurationException(
                String.format("Failed to initialize watcher for resource '%s'", resource.toString()), e);
    }
}

From source file:net.butfly.albacore.spring.AutoSqlSessionFactoryBean.java

private void registerMapper(Configuration configuration, Resource mapperLocation) throws IOException {
    try {/*from  ww  w . j av a2s.c om*/
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration,
                mapperLocation.toString(), configuration.getSqlFragments());
        xmlMapperBuilder.parse();
    } catch (Exception e) {
        throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
    } finally {
        ErrorContext.instance().reset();
    }
    if (logger.isTraceEnabled())
        logger.trace("Albacore Impl for Mybatis AutoSqlSessionFactoryBean - Parsed mapper file: '"
                + mapperLocation + "'");
}

From source file:com.flipkart.aesop.runtime.spring.RuntimeComponentContainer.java

/**
 * Interface method implementation. Loads/Reloads runtime(s) defined in the specified {@link FileSystemResource} 
 * @see org.trpr.platform.runtime.spi.component.ComponentContainer#loadComponent(org.springframework.core.io.Resource)
 *//*from   w ww .j ava  2 s  . c o m*/
public void loadComponent(Resource resource) {
    if (!FileSystemResource.class.isAssignableFrom(resource.getClass())
            || !resource.getFilename().equalsIgnoreCase(this.getRuntimeConfigFileName())) {
        throw new UnsupportedOperationException("Runtimes can be loaded only from files by name : "
                + this.getRuntimeConfigFileName() + ". Specified resource is : " + resource.toString());
    }
    loadRuntimeContext(new ServerContainerConfigInfo(((FileSystemResource) resource).getFile()));
}

From source file:com.flipkart.phantom.runtime.impl.spring.ServiceProxyComponentContainer.java

/**
 * Interface method implementation. Loads/Reloads proxy handler(s) defined in the specified {@link FileSystemResource}
 * @see org.trpr.platform.runtime.spi.component.ComponentContainer#loadComponent(org.springframework.core.io.Resource)
 *///from   w  w w  .ja v  a2s.  c om
public void loadComponent(Resource resource) {
    if (!FileSystemResource.class.isAssignableFrom(resource.getClass()) || !resource.getFilename()
            .equalsIgnoreCase(ServiceProxyFrameworkConstants.SPRING_PROXY_HANDLER_CONFIG)) {
        throw new UnsupportedOperationException("Proxy handers can be loaded only from files by name : "
                + ServiceProxyFrameworkConstants.SPRING_PROXY_HANDLER_CONFIG + ". Specified resource is : "
                + resource.toString());
    }
    loadProxyHandlerContext(new HandlerConfigInfo(((FileSystemResource) resource).getFile()));
}

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

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

    String relative;/*from   w  w  w .java2 s.co  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;
}

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

private void parseMapperPackage(Configuration configuration) throws IOException {
    if (!hasLength(mapperPackage)) {
        return;//from  w ww. j a va  2s. c om
    }
    String prefix = "classpath:";
    String suffix = "/*.xml";
    String[] extArr = tokenizeToStringArray(mapperPackage,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    for (String ext : extArr) {
        Resource[] mapperResources = resolver.getResources(prefix + ext + suffix);
        for (Resource resource : mapperResources) {
            if (resource == null) {
                continue;
            }
            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(),
                        configuration, resource.toString(), configuration.getSqlFragments());
                xmlMapperBuilder.parse();
            } catch (Exception e) {
                throw new NestedIOException("Failed to parse mapping resource: '" + resource + "'", e);
            } finally {
                ErrorContext.instance().reset();
            }
        }
    }
}

From source file:chanedi.dao.impl.mybatis.session.SqlSessionFactoryBean.java

/**
 * Build a {@code SqlSessionFactory} instance.
 *
 * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
 * {@code SqlSessionFactory} instance based on an Reader.
 *
 * @return SqlSessionFactory//w w  w.j  a v a 2  s.co  m
 * @throws java.io.IOException if loading the config file failed
 */
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configLocation != null) {
        xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null,
                this.configurationProperties);
        configuration = (Configuration) xmlConfigBuilder.getConfiguration();
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
        }
        configuration = new Configuration();
        configuration.setVariables(this.configurationProperties);
    }

    if (this.objectFactory != null) {
        configuration.setObjectFactory(this.objectFactory);
    }

    if (this.objectWrapperFactory != null) {
        configuration.setObjectWrapperFactory(this.objectWrapperFactory);
    }

    if (hasLength(this.typeAliasesPackage)) {
        String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        for (String packageToScan : typeAliasPackageArray) {
            configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                    typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
            if (logger.isDebugEnabled()) {
                logger.debug("Scanned package: '" + packageToScan + "' for aliases");
            }
        }
    }

    if (!isEmpty(this.typeAliases)) {
        for (Class<?> typeAlias : this.typeAliases) {
            configuration.getTypeAliasRegistry().registerAlias(typeAlias);
            if (logger.isDebugEnabled()) {
                logger.debug("Registered type alias: '" + typeAlias + "'");
            }
        }
    }

    if (!isEmpty(this.plugins)) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (logger.isDebugEnabled()) {
                logger.debug("Registered plugin: '" + plugin + "'");
            }
        }
    }

    if (hasLength(this.typeHandlersPackage)) {
        String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage,
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        for (String packageToScan : typeHandlersPackageArray) {
            configuration.getTypeHandlerRegistry().register(packageToScan);
            if (logger.isDebugEnabled()) {
                logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
            }
        }
    }

    if (!isEmpty(this.typeHandlers)) {
        for (TypeHandler<?> typeHandler : this.typeHandlers) {
            configuration.getTypeHandlerRegistry().register(typeHandler);
            if (logger.isDebugEnabled()) {
                logger.debug("Registered type handler: '" + typeHandler + "'");
            }
        }
    }

    if (xmlConfigBuilder != null) {
        try {
            xmlConfigBuilder.parse();

            if (logger.isDebugEnabled()) {
                logger.debug("Parsed configuration file: '" + this.configLocation + "'");
            }
        } catch (Exception ex) {
            throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    if (this.transactionFactory == null) {
        this.transactionFactory = new SpringManagedTransactionFactory();
    }

    Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource);
    configuration.setEnvironment(environment);

    if (this.databaseIdProvider != null) {
        try {
            configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
        } catch (SQLException e) {
            throw new NestedIOException("Failed getting a databaseId", e);
        }
    }

    if (!isEmpty(this.mapperLocations)) {
        for (Resource mapperLocation : this.mapperLocations) {
            if (mapperLocation == null) {
                continue;
            }

            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                        configuration, mapperLocation.toString(), configuration.getSqlFragments());
                xmlMapperBuilder.parse();
            } catch (Exception e) {
                throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
            } finally {
                ErrorContext.instance().reset();
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Parsed mapper file: '" + mapperLocation + "'");
            }
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Property 'mapperLocations' was not specified or no matching resources found");
        }
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
}