Search in sources :

Example 1 with Resource

use of cn.taketoday.core.io.Resource in project today-infrastructure by TAKETODAY.

the class PersistenceUnitReader method readPersistenceUnitInfos.

/**
 * 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
 */
public JpaPersistenceUnitInfo[] readPersistenceUnitInfos(String[] persistenceXmlLocations) {
    ErrorHandler handler = new SimpleSaxErrorHandler(logger);
    List<JpaPersistenceUnitInfo> infos = new ArrayList<>(1);
    String resourceLocation = null;
    try {
        for (String location : persistenceXmlLocations) {
            for (Resource resource : patternResourceLoader.getResources(location)) {
                resourceLocation = resource.toString();
                try (InputStream stream = resource.getInputStream()) {
                    Document document = buildDocument(handler, stream);
                    parseDocument(resource, document, infos);
                }
            }
        }
    } 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 JpaPersistenceUnitInfo[0]);
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) SimpleSaxErrorHandler(cn.taketoday.util.xml.SimpleSaxErrorHandler) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Resource(cn.taketoday.core.io.Resource) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) SimpleSaxErrorHandler(cn.taketoday.util.xml.SimpleSaxErrorHandler) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 2 with Resource

use of cn.taketoday.core.io.Resource in project today-infrastructure by TAKETODAY.

the class PersistenceUnitReader method parseJarFiles.

/**
 * Parse the {@code jar-file} XML elements.
 */
protected void parseJarFiles(Element persistenceUnit, JpaPersistenceUnitInfo unitInfo) throws IOException {
    List<Element> jars = DomUtils.getChildElementsByTagName(persistenceUnit, JAR_FILE_URL);
    for (Element element : jars) {
        String value = DomUtils.getTextValue(element).trim();
        if (StringUtils.hasText(value)) {
            boolean found = false;
            for (Resource resource : patternResourceLoader.getResources(value)) {
                if (resource.exists()) {
                    found = true;
                    unitInfo.addJarFileUrl(resource.getLocation());
                }
            }
            if (!found) {
                // relative to the persistence unit root, according to the JPA spec
                URL rootUrl = unitInfo.getPersistenceUnitRootUrl();
                if (rootUrl != null) {
                    unitInfo.addJarFileUrl(new URL(rootUrl, value));
                } else {
                    logger.warn("Cannot resolve jar-file entry [{}] in persistence unit '{}' without root URL", value, unitInfo.getPersistenceUnitName());
                }
            }
        }
    }
}
Also used : Element(org.w3c.dom.Element) Resource(cn.taketoday.core.io.Resource) URL(java.net.URL)

Example 3 with Resource

use of cn.taketoday.core.io.Resource in project today-infrastructure by TAKETODAY.

the class DefaultPersistenceUnitManager method scanPackage.

private void scanPackage(JpaPersistenceUnitInfo scannedUnit, String pkg) {
    if (this.componentsIndex != null) {
        Set<String> candidates = new HashSet<>();
        for (AnnotationTypeFilter filter : entityTypeFilters) {
            candidates.addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
        }
        candidates.forEach(scannedUnit::addManagedClassName);
        Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
        managedPackages.forEach(scannedUnit::addManagedPackage);
        return;
    }
    try {
        String pattern = PatternResourceLoader.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
        MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.patternResourceLoader);
        for (Resource resource : patternResourceLoader.getResources(pattern)) {
            try {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                if (matchesFilter(reader, readerFactory)) {
                    scannedUnit.addManagedClassName(className);
                    if (scannedUnit.getPersistenceUnitRootUrl() == null) {
                        URL url = resource.getLocation();
                        if (ResourceUtils.isJarURL(url)) {
                            scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
                        }
                    }
                } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                    scannedUnit.addManagedPackage(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                }
            } catch (FileNotFoundException ex) {
            // Ignore non-readable resource
            }
        }
    } catch (IOException ex) {
        throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
    }
}
Also used : AnnotationTypeFilter(cn.taketoday.core.type.filter.AnnotationTypeFilter) CachingMetadataReaderFactory(cn.taketoday.core.type.classreading.CachingMetadataReaderFactory) MetadataReaderFactory(cn.taketoday.core.type.classreading.MetadataReaderFactory) Resource(cn.taketoday.core.io.Resource) FileNotFoundException(java.io.FileNotFoundException) MetadataReader(cn.taketoday.core.type.classreading.MetadataReader) CachingMetadataReaderFactory(cn.taketoday.core.type.classreading.CachingMetadataReaderFactory) IOException(java.io.IOException) URL(java.net.URL) PersistenceException(jakarta.persistence.PersistenceException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 4 with Resource

use of cn.taketoday.core.io.Resource in project today-infrastructure by TAKETODAY.

the class LocalSessionFactoryBean method afterPropertiesSet.

@Override
public void afterPropertiesSet() throws IOException {
    if (metadataSources != null && !metadataSourcesAccessed) {
        // Repeated initialization with no user-customized MetadataSources -> clear it.
        this.metadataSources = null;
    }
    LocalSessionFactoryBuilder sfb = new LocalSessionFactoryBuilder(dataSource, getResourceLoader(), getMetadataSources());
    if (configLocations != null) {
        for (Resource resource : configLocations) {
            // Load Hibernate configuration from given location.
            sfb.configure(resource.getLocation());
        }
    }
    if (mappingResources != null) {
        // Register given Hibernate mapping definitions, contained in resource files.
        for (String mapping : mappingResources) {
            Resource mr = new ClassPathResource(mapping.trim(), getResourceLoader().getClassLoader());
            sfb.addInputStream(mr.getInputStream());
        }
    }
    if (mappingLocations != null) {
        // Register given Hibernate mapping definitions, contained in resource files.
        for (Resource resource : mappingLocations) {
            sfb.addInputStream(resource.getInputStream());
        }
    }
    if (cacheableMappingLocations != null) {
        // Register given cacheable Hibernate mapping definitions, read from the file system.
        for (Resource resource : cacheableMappingLocations) {
            sfb.addCacheableFile(resource.getFile());
        }
    }
    if (mappingJarLocations != null) {
        // Register given Hibernate mapping definitions, contained in jar files.
        for (Resource resource : mappingJarLocations) {
            sfb.addJar(resource.getFile());
        }
    }
    if (mappingDirectoryLocations != null) {
        // Register all Hibernate mapping definitions in the given directories.
        for (Resource resource : mappingDirectoryLocations) {
            File file = resource.getFile();
            if (!file.isDirectory()) {
                throw new IllegalArgumentException("Mapping directory location [" + resource + "] does not denote a directory");
            }
            sfb.addDirectory(file);
        }
    }
    if (entityInterceptor != null) {
        sfb.setInterceptor(entityInterceptor);
    }
    if (implicitNamingStrategy != null) {
        sfb.setImplicitNamingStrategy(implicitNamingStrategy);
    }
    if (physicalNamingStrategy != null) {
        sfb.setPhysicalNamingStrategy(physicalNamingStrategy);
    }
    if (jtaTransactionManager != null) {
        sfb.setJtaTransactionManager(jtaTransactionManager);
    }
    if (beanFactory != null) {
        sfb.setBeanContainer(beanFactory);
    }
    if (cacheRegionFactory != null) {
        sfb.setCacheRegionFactory(cacheRegionFactory);
    }
    if (multiTenantConnectionProvider != null) {
        sfb.setMultiTenantConnectionProvider(multiTenantConnectionProvider);
    }
    if (currentTenantIdentifierResolver != null) {
        sfb.setCurrentTenantIdentifierResolver(currentTenantIdentifierResolver);
    }
    if (hibernateProperties != null) {
        sfb.addProperties(hibernateProperties);
    }
    if (entityTypeFilters != null) {
        sfb.setEntityTypeFilters(entityTypeFilters);
    }
    if (annotatedClasses != null) {
        sfb.addAnnotatedClasses(annotatedClasses);
    }
    if (annotatedPackages != null) {
        sfb.addPackages(annotatedPackages);
    }
    if (packagesToScan != null) {
        sfb.scanPackages(packagesToScan);
    }
    // Build SessionFactory instance.
    this.configuration = sfb;
    this.sessionFactory = buildSessionFactory(sfb);
}
Also used : Resource(cn.taketoday.core.io.Resource) ClassPathResource(cn.taketoday.core.io.ClassPathResource) File(java.io.File) ClassPathResource(cn.taketoday.core.io.ClassPathResource)

Example 5 with Resource

use of cn.taketoday.core.io.Resource in project today-infrastructure by TAKETODAY.

the class CachingMetadataReaderLeakTests method significantLoad.

@Test
void significantLoad() throws Exception {
    // the biggest public class in the JDK (>60k)
    URL url = getClass().getResource("/java/awt/Component.class");
    assertThat(url).isNotNull();
    // look at a LOT of items
    for (int i = 0; i < ITEMS_TO_LOAD; i++) {
        Resource resource = new UrlBasedResource(url) {

            @Override
            public boolean equals(Object obj) {
                return (obj == this);
            }

            @Override
            public int hashCode() {
                return System.identityHashCode(this);
            }
        };
        MetadataReader reader = mrf.getMetadataReader(resource);
        assertThat(reader).isNotNull();
    }
// useful for profiling to take snapshots
// System.in.read();
}
Also used : UrlBasedResource(cn.taketoday.core.io.UrlBasedResource) UrlBasedResource(cn.taketoday.core.io.UrlBasedResource) Resource(cn.taketoday.core.io.Resource) MetadataReader(cn.taketoday.core.type.classreading.MetadataReader) URL(java.net.URL) Test(org.junit.jupiter.api.Test)

Aggregations

Resource (cn.taketoday.core.io.Resource)368 Test (org.junit.jupiter.api.Test)234 ClassPathResource (cn.taketoday.core.io.ClassPathResource)220 IOException (java.io.IOException)58 ByteArrayResource (cn.taketoday.core.io.ByteArrayResource)43 UrlBasedResource (cn.taketoday.core.io.UrlBasedResource)40 ServletRequestContext (cn.taketoday.web.servlet.ServletRequestContext)37 InputStreamResource (cn.taketoday.core.io.InputStreamResource)34 FileSystemResource (cn.taketoday.core.io.FileSystemResource)32 ServletContextResource (cn.taketoday.web.context.support.ServletContextResource)28 File (java.io.File)27 MockHttpOutputMessage (cn.taketoday.http.MockHttpOutputMessage)26 ArrayList (java.util.ArrayList)26 Nullable (cn.taketoday.lang.Nullable)22 InvalidPathException (java.nio.file.InvalidPathException)22 HttpHeaders (cn.taketoday.http.HttpHeaders)21 ResourceRegion (cn.taketoday.core.io.ResourceRegion)20 DataBuffer (cn.taketoday.core.io.buffer.DataBuffer)18 MediaType (cn.taketoday.http.MediaType)17 MockHttpServletRequest (cn.taketoday.web.testfixture.servlet.MockHttpServletRequest)16