Cannot load .class file with ResourcePatternResolver - spring

I'm trying to load a .class file into Spring project. I tried this:
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
ResourcePatternResolver resolver = (ResourcePatternResolver)context;
Resource[] res = resolver.getResources("classpath*:/opt/validation/*.class");
resolver.getClassLoader().loadClass("ValidateProcessor");
But I I get error Root cause of ServletException.
java.lang.ClassNotFoundException: ValidateProcessor
The file ValidateProcessor.class is present into that directory but it's not found. Can you give me some advice how to fix this issue please?

You have to use the full qualified class name. In case the class is located in a package opt.validation you should load:
resolver.getClassLoader().loadClass("opt.validation.ValidateProcessor");

Related

How to properly configure multiple component scans and "use default filters = false"

I'm developing a "new application" that wants to leverage code in an existing application, but I am having trouble getting "contextLoads()" to pass in the new application.
This configuration doesn't work:
//This is the main common library B application class:
#Configuration
#ComponentScan(basePackages=["com.acme.cacheb.lib"])
#Import(CacheACommonLibConfig.class)
#EnableConfigurationProperties
class CacheBCommonLib {
}
//This is the Config class Imported above:
#Configuration
#ComponentScan(basePackages=["com.acme.cachea.lib"],
useDefaultFilters = false,
includeFilters = [#ComponentScan.Filter(type = FilterType.CUSTOM,
value = RescHandshakeTypeFilter.class)])
class CacheACommonLibConfig {
}
The error reported is an autowire failure:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cacheA_RepoImpl': Unsatisfied dependency expressed through field 'cacheA_Repo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.acme.cachea.lib.jpa.repository.ICacheA_Repository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I know my custom filter is matching everything I want (including that "missing" interface named ICacheA_Repository) and nothing I think I don't want. I suspect the error is because "useDefaultFilters = false" is in play and how the component scans are combined. If I do this
#ComponentScan(basePackages=["com.acme.cacheb.lib", "org.springframework"])
in the new main application class, the test runs longer before it fails reporting a different error, and I also get a fairly dire "Spring Warning"
** WARNING ** : Your ApplicationContext is unlikely to start due to a #ComponentScan of 'org.springframework'.
Any/All help greatly appreciated.
I got "context loads" to pass in the B app by abandoning "include filtering" (with use default filters = false) of the A app dependency jar and switching to "exclude filtering" on the component scan. But after I "actually" got it working, I'm not sure I really needed to switch to "exclude filtering". The reason I think that is because at the end of my journey, I started seeing the same couple of errors I first saw which is why the "Thymeleaf View Resolver" is now excluded from auto configuration. (If only I had tried that when the error first appeared, rather than totally disabling auto configuration...)
The B app main class configuration is now configured like this:
#Configuration
#ComponentScan(basePackages=["com.acme.cacheb.lib"])
#Import(CacheACommonLibConfig.class)
#EnableAutoConfiguration(exclude=[WebMvcAutoConfiguration.class, ThymeleafAutoConfiguration.class])
#EnableConfigurationProperties
#EntityScan('com.acme.cacha.lib.jpa.entity')
#EnableJpaRepositories('com.acme.cacha.lib.jpa.repository')
//#EnableScheduling
class CacheBCommonLib {
}
and the Imported config class is now configured like this:
#Configuration
#ComponentScan(basePackages=["com.acme.cacha.lib.msg.auth",
"com.acme.cacha.lib.msg.emp",
"com.acme.cacha.lib.msg.processor",
"com.acme.cacha.lib.jpa"],
excludeFilters = [#ComponentScan.Filter(type = FilterType.CUSTOM, value = CacheBExcludeCacheATypesFilter.class),
#ComponentScan.Filter(type = FilterType.REGEX,
pattern = "com.acme.cacha.lib.msg.processor.*"),
#ComponentScan.Filter(type = FilterType.REGEX,
pattern = "com.acme.cacha.lib.msg.auth.(sas|radius).*")
])
class CacheACommonLibConfig {
}

Unable to call Mapper.xml file by using junit testing for the application developed using Mybatis+Springboot

I'm very new to junit testing. How to write junit test real database call from mybatis.xml file.
Please find the below code.
#RunWith(SpringRunner.class)
//#MybatisTest
#SpringBootTest
public class HotelMapperTest {
#Autowired
private HotelMapper hotelMapper;
#Test
public void selectByCityIdTest() {
Hotel hotel = hotelMapper.selectByCityId(1);
assertThat(hotel.getName()).isEqualTo("Conrad Treasury Place");
assertThat(hotel.getAddress()).isEqualTo("William & George Streets");
assertThat(hotel.getZip()).isEqualTo("4001");
}
when i run the junit testing i'm getting below exception:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
Herer my question is how we'll test the real database, When enable the #MybatisTest it's looking for datasource, already we specified all properties in applicaiton.properties. In this time i'm getting below exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource':
You can config mybatis mapper location in spring configuration file (such as application.yml).
mybatis configuration:
mybatis:
mapper-locations:
- classpath*:mapper/*.xml

Reading environment variables or properties in a file

I am trying to deploy a spring-boot 2.0.4 application. The configuration looks like below :
#Component
#Configuration
#PropertySource("classpath:elast.properties")
public class ElastSearchLogLevel {
private static final Logger LOG = LoggerFactory.getLogger(ElastSearchLogLevel.class);
#Value("${elast.mail.to}")
private String to;
...
Locally on windows its working fine but in Linux box it says :
WARN o.a.commons.logging.impl.Jdk14Logger.log - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elastSearchBootApplication': Unsatisfied dependency expressed through field 'logsSearch'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elastSearchLogLevel': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'elast.mail.to' in value "${elast.mail.to}"
The instance 'elastSearchLogLevel' is autowired in SpringBootApplication class. Ideally i want to give an external configuration file from which the property can be read. As suggested in one of the forum I also tried but didn't work.
#PropertySource("classpath:file:///my/file/path/elast.properties")
ok some more code :
#ComponentScan(basePackages = "some.packer.log")
#SpringBootApplication
#EnableScheduling
public class ElastSearchBootApplication {
...

#SpringBootTest - failed to load applicationcontext

Test class:
#RunWith(SpringRunner.class)
#SpringBootTest
public class FileInterfaceTest {
#Test
public void contextLoads() {
}
}
Application :
AppConfig:
#Configuration
#ImportResource({ "classpath:process-flows.xml" })
public class AppConfig {
}
Have Bootstraploader class.
Error:
java.lang.IllegalStateException: Failed to load ApplicationContext
Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [file.properties] cannot be opened because it does not exist
Resources loaction:
src/main/resources
---process-flow.xml
--- process.yml
src/main/resources/env/cconfig
--- file.properties
Your folder structure contains a typo: src/main/resources/env/cconfig has to be src/main/resources/env/config
As defined in the Spring Externalized Configuration, SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:
A /config subdirectory of the current directory
The current directory
A classpath /config package
The classpath root
Apart from "cconfig" folder name (not sure if that was a typo) I also see your #ImportResource is mentioned as classpath:process-flows.xml however your resources folder has file named process-flow.xml
If that was not a typo as well, please add an 's' by renaming process-flow.xml to process-flows.xml and retry

GlassFish can't initialize org.apache.cassandra.cql.jdbc.CassandraDriver

I'm trying to set up a connection pool in GlassFish for Cassandra using cassandra-jdbc driver. I've put the driver jar (and all of the jars that it depends on) in the ~glassfish-domain/lib/ext folder but I get the following error when I try to ping:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.cassandra.cql.jdbc.CassandraDriver Could not initialize class org.apache.cassandra.cql.jdbc.CassandraDriver
It seems that GlassFish finds the class, but can't load it. As all of the dependencies are satisfied, a possible reason is that there is an exception in a static block. I checked the code of CassandraDriver and it actually has a static block:
static
{
// Register the CassandraDriver with DriverManager
try
{
CassandraDriver driverInst = new CassandraDriver();
DriverManager.registerDriver(driverInst);
}
catch (SQLException e)
{
throw new RuntimeException(e.getMessage());
}
}
Thanks in advance!
It seems that slf4j wasn't loading correctly because it depends on log4j.jar. So I after adding it in the classpath, everything seems to be working fine. Here's the list of all of the jars in my lib:
apache-cassandra-1.1.6.jar
apache-cassandra-clientutil-1.1.6.jar
apache-cassandra-thrift-1.1.6.jar
cassandra-jdbc-1.1.2.jar
commons-lang-2.4.jar
guava-r08.jar
libthrift-0.7.0.jar
log4j-1.2.14.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.8.jar

Resources