I have the following code, using a PropertyPlaceHolderConfigurer:
public static void main(String[] args) {
Scanner sc=null;
CustomerDTO dto=null;
//create IOC Container
ApplicationContext ctx=new FileSystemXmlApplicationContext("src/main/java/com/nt/cfgs/applicationContext.xml");
//get PropertyPlaaceHolderConfigurer OBJ
BeanFactoryPostProcessor bfpp=ctx.getBean("ppc",PropertyPlaceholderConfigurer.class);
bfpp.postProcessBeanFactory((ConfigurableListableBeanFactory)ctx);
sc=new Scanner(System.in);
System.out.println("Enter Customer NO: ");
int cno=sc.nextInt();
System.out.println("Enter Customer Name: ");
String cname=sc.next();
System.out.println("Enter Principal Amount:: ");
float pamt=sc.nextFloat();
System.out.println("Enter Rate of Interest: ");
float rate=sc.nextFloat();
System.out.println("Enter Time/Period: ");
float time=sc.nextFloat();
//set values to dto
dto=new CustomerDTO();
dto.setCno(cno);
dto.setCname(cname);
dto.setPamt(pamt);
dto.setRate(rate);
dto.setTime(time);
//getBean
LoanService service=ctx.getBean("service",LoanService.class);
System.out.println(service.calcIntrAmt(dto));
}
The code above gives me the following error:
Aug 04, 2018 8:16:08 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#621be5d1: startup date [Sat Aug 04 20:16:08 IST 2018]; root of context hierarchy
Aug 04, 2018 8:16:08 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [D:\NTSP710\IOC-Beans28ApplicationContextWithPropertyFileConfigurator\src\main\java\com\nt\cfgs\applicationContext.xml]
Aug 04, 2018 8:16:08 PM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: src\main\java\com\nt\commons\DBDetails.properties
Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: src\main\java\com\nt\commons\DBDetails.properties
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:89)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:164)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:693)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:142)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:85)
at com.nt.test.ClientApp.main(ClientApp.java:21)
Caused by: java.io.FileNotFoundException: src\main\java\com\nt\commons\DBDetails.properties
at org.springframework.core.io.FileSystemResource.getInputStream(FileSystemResource.java:129)
at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:159)
at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:99)
at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:162)
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:80)
... 7 more
How can I fix this problem?
You should put your application context in src/main/resources/com/nt/cfgs/applicationContext.xml, then try reading it with just "com/nt/cfgs/applicationContext.xml" ... Your class does not get executed from the top of your project, but rather from within the target folder - so it cannot see the path you indicate relative to "target".
Or better yet, use a classpath context reader and the path "classpath:com/nt/cfgs/applicationContext.xml" ...
The exception is straightforward. It says
Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: src\main\java\com\nt\commons\DBDetails.properties
This means that it's not able to find the DBDetails.properties file in the path given. You need to provide the correct path of the same either in applicationContext.xml or #PropertySource, wherever you have defined it.
I faced the same issue for a .xml file, It wasted lot of my time, eventually I followed these steps to fix it:
Delete your project (or multiple related projects) and its sub-project if any from workspace (don't delete it from your computer disk).
Import the project again, Mine was from git so I did "Import from GIT"
Once import is complete, clean install from pom.xml
Then try running the main class.
There could be a better solution but this fixed my issue,
Might help others too.
Related
I tried by placing the springConfig.xml in the WEB_INF as well as src directory, but still getting the IOException.
Code:
public class DrawingApp {
public static void main(String[] args) {
//Triangle triangle = new Triangle();
ApplicationContext context = new
ClassPathXmlApplicationContext("springConfig.xml");
Triangle triangle = (Triangle) context.getBean("triangle");
triangle.draw();
((ClassPathXmlApplicationContext)context).close();
}
}
Exception:
Jul 23, 2018 11:33:18 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#179d3b25: startup date [Mon Jul 23 11:33:18 IST 2018]; root of context hierarchy
Jul 23, 2018 11:33:18 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [springConfig.xml]
Jul 23, 2018 11:33:19 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from URL [file:/D:/Learning/Workspace/Java%20Project/Spring2/SpringDemo/target/classes/trace-context.xml]
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [trace-context.xml]
Offending resource: class path resource [springConfig.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from URL [file:/D:/Learning/Workspace/Java%20Project/Spring2/SpringDemo/target/classes/trace-context.xml]; nested exception is java.io.FileNotFoundException: D:\Learning\Workspace\Java Project\Spring2\SpringDemo\target\classes\trace-context.xml (The system cannot find the file specified)
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at
org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:255)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:180)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:165)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:138)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304
You should specify where is the resource path located within your project. More on this link
https://maven.apache.org/pom.html#Resources
I am new to jersey multi part. While i am starting the tomcat server getting issue.
#POST
#Path("/uploadImagesUsingJersey")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("text/plain")
public Response uploadImages(#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException{
String uploadedFileLocation = (String) session.getServletContext().getAttribute("ProfilePhotoPath");
uploadedFileLocation=uploadedFileLocation+236+"/"+fileDetail.getName();
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
employeeVO=new EmployeeInformationVO();
employeeVO=(EmployeeInformationVO) CacheAction.getById(EmployeeInformationVO.class,236);
employeeVO.setPhotoPath(236+"/"+fileDetail.getFileName());
int result=CacheAction.commonAddOrUpdate(employeeVO);
return Response.status(200).entity(result).build();
}
I am using this kind Of jar:
1)jersey-multipart-1.8-ea03.jar
2)mimepull-1.8-sources.jar
3)jersey-server-1.8.jar
4)jersey-bundle-1.8.jar
And i am getting this kind of issue:
INFO: Provider classes found:
class com.owlike.genson.ext.jaxrs.GensonJsonConverter
Nov 13, 2016 10:45:15 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.8 06/24/2011 12:39 PM'
Nov 13, 2016 10:45:17 PM com.sun.jersey.spi.inject.Errors processErrorMessages
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.hrm.jersey.action.MyServiceAction.uploadImages(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) throws java.io.IOException at parameter at index 0
SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.hrm.jersey.action.MyServiceAction.uploadImages(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) throws java.io.IOException at parameter at index 1
SEVERE: Method, public javax.ws.rs.core.Response com.hrm.jersey.action.MyServiceAction.uploadImages(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) throws java.io.IOException, annotated with POST of resource, class com.hrm.jersey.action.MyServiceAction, is not recognized as valid resource method.
Nov 13, 2016 10:45:17 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
I´m using the JasperReportsViewResolver class to provide support for the reports of my app,my code looks like this:
#Bean
public JasperReportsViewResolver getJasperReportsViewResolver() {
JasperReportsViewResolver resolver = new JasperReportsViewResolver();
resolver.setPrefix("classpath:/reports/");
resolver.setSuffix(".jasper");
resolver.setJdbcDataSource(dataSource);
resolver.setViewNames("report*");
resolver.setViewClass(JasperReportsMultiFormatView.class);
resolver.setOrder(0);
return resolver;
}
My problem is, if my Tomcat directory installation contains white spaces,I receive a weird JRException as listed below:
Thu Apr 09 08:33:57 GMT-03:00 2015
There was an unexpected error (type=Internal Server Error, status=500).
Request processing failed; nested exception is net.sf.jasperreports.engine.JRException: Resource not found at : /C:/development/Apache/apache%20tomcat-8.0.20/webapps/reports/WEB-INF/classes/report/reportPath/myReport.jasper
Any ideas?Trimming the directory name is not a option.
i have been trying to get an example #Configuration build to work (in groovy) so i can trigger dependency injection outwith a spring container but all i get is error about the -javaagent which i cant seem to fix
I have a beanConfig class like this
#Configuration
#EnableSpringConfigured // should turn on AnnotationBeanConfigurerAspect
#EnableLoadTimeWeaving (aspectjWeaving=AspectJWeaving.ENABLED) // switch on for this context
class BeanConfig {
then a sample class i will call new on and try and get the injection oustide the spring container, where the diSource bean is declared in the above configuration class
`
#Configurable (autowire=Autowire.BY_TYPE, dependencyCheck=true)
class ExtDI {
#Autowired DISource diSource
def say () {
println "ExtDI : diSource set as " + diSource.name
}
}
`
in my sampler class i call this to try and trigger the injection
`
...
static void main (String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(/BeanConfig.class/)
ctx.scan ("com.softwood")
ctx.refresh ()
....
//trigger LTW injection
ExtDI ext = new ExtDI()
ext.say()
`
on the class path i have aspectjeaver-1.6.10.jar, aspectjrt-1.6.10.jar, spring-xxx-3.1.4.jars, etc
heres my gradle depdency listing
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.1.7'
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
testCompile group: 'junit', name: 'junit', version: '4.+'
compile "org.springframework:spring-core:${spring_version}"
compile "org.springframework:spring-beans:${spring_version}"
compile "org.springframework:spring-context:${spring_version}"
compile "org.springframework:spring-aspects:${spring_version}"
compile "org.springframework:spring-aop:${spring_version}"
compile "org.springframework:spring-instrument:${spring_version}"
compile "org.aspectj:aspectjrt:1.6.10"
compile "org.aspectj:aspectjweaver:1.6.10"
compile "cglib:cglib:2.2"
}
in the eclipse project runtime for the vm args i have
-javaagent:C:/Users/802518659/aspectjweaver-1.6.10.jar
and have tried same with spring-instrument-3.1.4.jar and had same problem.
when i run the project i get this error
`
Oct 19, 2013 4:02:40 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#492ff1: startup date [Sat Oct 19 16:02:40 BST 2013]; root of context hierarchy
Oct 19, 2013 4:02:40 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#11bedb0: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,beanConfig,willsBean,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.aspectj.SpringConfiguredConfiguration,org.springframework.context.config.internalBeanConfigurerAspect,org.springframework.context.annotation.LoadTimeWeavingConfiguration,loadTimeWeaver,publicBean,privateBean,publicBeanWithDI,myDISource,diTarget]; root of factory hierarchy
Oct 19, 2013 4:02:40 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#11bedb0: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,beanConfig,willsBean,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.aspectj.SpringConfiguredConfiguration,org.springframework.context.config.internalBeanConfigurerAspect,org.springframework.context.annotation.LoadTimeWeavingConfiguration,loadTimeWeaver,publicBean,privateBean,publicBeanWithDI,myDISource,diTarget]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loadTimeWeaver' defined in class path resource [org/springframework/context/annotation/LoadTimeWeavingConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.instrument.classloading.LoadTimeWeaver org.springframework.context.annotation.LoadTimeWeavingConfiguration.loadTimeWeaver()] threw exception; nested exception is java.lang.IllegalStateException: ClassLoader [sun.misc.Launcher$AppClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
...
`
which tells me that my application can't instrument the java classloader - despite the fact i start it with the -javaagent:spring-instrument-xxx or aspectjweaver.jar - both fail
So what am i doing wrong - this is really beginning to bother me - i can get ordinary injection within the context to work (no LTW) but really wanted to get this injection outside the container to work
what am i doing wrong
took some time but figured out where it was going wrong
corrected on another post on spring forums see
http://forum.spring.io/forum/spring-projects/container/724426-cant-get-aspectj-load-time-weaving-to-work
also i added a longer note to my blog here
http://willwoodman.wordpress.com/
I am trying to get this GrizzlyResourceTest.javaworking with dropwizard v0.6.1. The reason I want to use grizzly as the test container is because InMemoryTestContainer does not support Resource with injectable constructor, see this issue in details InMemoryTestContainer does not support Resource with injectable constructor
Since com.yammer.dropwizard.json.Json and com.yammer.dropwizard.bundles.JavaBundle are not in v0.6.1 anymore, I simply just comment out the lines related to these class.
#Before
public void setUpJersey() throws Exception {
setUpResources();
this.test = new JerseyTest(new GrizzlyWebTestContainerFactory()) {
#Override
protected AppDescriptor configure() {
ClientConfig config = new DefaultClientConfig();
// taken from DropwizardResourceConfig
config.getFeatures().put(ResourceConfig.FEATURE_DISABLE_WADL, Boolean.TRUE);
config.getSingletons().add(new LoggingExceptionMapper<Throwable>() { }); // create a subclass to pin it to Throwable
config.getClasses().add(InstrumentedResourceMethodDispatchAdapter.class);
config.getClasses().add(CacheControlledResourceMethodDispatchAdapter.class);
for (Class<?> provider : providers) {
config.getClasses().add(provider);
}
config.getSingletons().addAll(singletons);
return new WebAppDescriptor.Builder("com.example.helloworld.resources").clientConfig(config).build();
}
};
test.setUp();
}
My case is more complex since I have HttpServletRequest injected to my resource class like myMethod(#Context HttpServletRequest request). So here I just use PersonResource under dropwizard-example.
QuickTest.java looks like:
public class QuickTest extends GrizzlyResourceTest{
#Test
public void testGrizzly() throws Exception {
ClientResponse rsp = client()
.resource("http://localhost:9998/people").get(ClientResponse.class);
Assert.assertEquals(200, rsp.getStatus());
}
#Override
protected void setUpResources() throws Exception {
}
}
When I run QuickTest, The error I am getting from Console is this:
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
Mar 14, 2013 7:14:11 PM com.sun.jersey.test.framework.spi.container.grizzly2.web.GrizzlyWebTestContainerFactory$GrizzlyWebTestContainer <init>
INFO: Creating Grizzly2 Web Container configured at the base URI http://localhost:9998/
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.servlet.WebappContext deploy
INFO: Starting application [TestContext] ...
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.servlet.WebappContext initServlets
INFO: [TestContext] Servlet [com.sun.jersey.spi.container.servlet.ServletContainer] registered for url pattern(s) [[/*]].
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.servlet.WebappContext deploy
INFO: Application [TestContext] is ready to service requests. Root: [].
Mar 14, 2013 7:14:11 PM com.sun.jersey.spi.inject.Errors processErrorMessages
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for field: private javax.servlet.http.HttpServletRequest com.yammer.dropwizard.jersey.LoggingExceptionMapper.request
Any ideas?