Spring Boot and JasperReportsViewResolver - spring

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.

Related

Spring tries to initialize AutoConfiguration beans using default constructor

We are having issues starting up our Spring Boot Web application. The main problem to properly diagnose the startup is that it only seems to happen in 1% of the startups. In 99% of the startup procedures all works fine and we end up having a properly working spring boot application. However in those 1% of those cases we see issues like this:
WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'errorPageFilterRegistration' defined in org.springframework.boot.web.servlet.support.Error
PageFilterConfiguration: Unsatisfied dependency expressed through method 'errorPageFilterRegistration' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'errorPageFilter' defined in org.springframework.boot.web.servlet.support.ErrorPageFilterConfiguration: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.spring
framework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigu
re.web.servlet.error.ErrorMvcAutoConfiguration]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration.<init>() []
For some reason it tries to initialize AutoConfiguration beans by using a default constructor which obviously is not present. There is a constructor present which should be autowired.
Also the AutoConfiguration that is in the stacktrace can be different. Sometimes it is another one like e.g. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
Any help or ideas on why this could be happening is appreciated. As this happens very occasionally this is hard to debug as we cannot relyably reproduce. Note that the stacktrace does not contain any custom code. Our application is quite big and we rely mostly on #Configuration classes to do configure the Beans.
Why would spring attempt to initialize an AutoConfiguration bean with a default constructor ?
The errorPageFilterConfiguration source of spring looks like this:
#Configuration(proxyBeanMethods = false)
class ErrorPageFilterConfiguration {
#Bean
ErrorPageFilter errorPageFilter() {
return new ErrorPageFilter();
}
#Bean
FilterRegistrationBean<ErrorPageFilter> errorPageFilterRegistration(ErrorPageFilter filter) {
FilterRegistrationBean<ErrorPageFilter> registration = new FilterRegistrationBean<>(filter);
registration.setOrder(filter.getOrder());
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
return registration;
}
}
According to the stack on creation of the errorPageFilter it is initializing the ErrorMvcAutoConfiguration as a prerequisite ? Why ?
We are not initializing these beans manually. The only relevant code for error page handling that we have is this following:
#Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> webServerFactoryCustomizer() {
return webServerFactory -> {
ErrorPage errorPage = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error");
webServerFactory.addErrorPages(errorPage);
};
}
This is a bug in Spring framework, introduced in version 5.3 in AbstractBeanFactory.
BeanPostProcessorCacheAwareList and accesses to the beanPostProcessors instance are not Thread safe. If multiple Threads are running during initialization and a Thread calls getBeanPostProcessorCache() while another Thread is calling addBeanPostProcessors, you can create a cache which does not contain all BeanPostProcessor instances and thus doesn't find the appropriate constructor.
I will submit a bug for this to spring-framework.
https://github.com/spring-projects/spring-framework/blob/16ea4692bab551800b9ba994ac08099e8acfd6cd/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java#L964
Issue created : https://github.com/spring-projects/spring-framework/issues/29299

Could not load properties error in spring PropertyPlaceHolderConfigurer

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.

How to add custom OAuth approval page to 'Spring Boot OAuth2 Identity Server'

#Controller
#SessionAttributes(types = AuthorizationRequest.class)
public class WhiteLableController {
#RequestMapping("/oauth/confirm_access")
public String getAccessConfirmation() throws Exception {
return "access_confirmation";
}
}
when I keep the access_confirmation.html in 'public' or 'static' folders in spring boot its not working. Could someone help me on this ?
404 Error Page :
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Aug 18 14:11:19 CEST 2017
There was an unexpected error (type=Not Found, status=404).
No message available

i am getting issue while start tomcat server

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

Spring Cloud AWS SQS AccessDenied

I am currently having a connection issue trying to connect to an AWS SQS Queue using Spring Cloud and Spring Boot. I believe I have everything configured fine but am getting:
2015-07-01 18:12:11,926 [WARN][-]
org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext[487]
- Exception encountered during context initialization - cancelling refresh attempt
org.springframework.context.ApplicationContextException: Failed to
start bean 'simpleMessageListenerContainer'; nested exception is
com.amazonaws.AmazonServiceException: Access to the resource
https://sqs.us-west-2.amazonaws.com/{Number}/{Queue Name} is denied.
(Service: AmazonSQS; Status Code: 403; Error Code: AccessDenied;
Request ID: 87312428-ec0f-5990-9f69-6a269a041b4d)
#Configuration
#EnableSqs
public class CloudConfiguration {
private static final Logger log = Logger.getLogger(CloudConfiguration.class);
#MessageMapping("QUEUE")
public void retrieveProvisionMessages(User user) {
log.warn(user.firstName);
}
}
YML
cloud:
aws:
credentials.accessKey: AccessKey
credentials.secretKey: SecretKey
region.static: us-west-2
credentials.instanceProfile: true
When it attempts to connect I see that a header value of:
AWS4-HMAC-SHA256 Credential=accesskey/20150701/us-west-2/sqs/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signature=signature
After the request is sent:
HTTP/1.1 403 Forbidden [Server: Server, Date: Wed, 01 Jul 2015 22:51:25 GMT, Content-Type: text/xml, Content-Length: 349, Connection: keep-alive, x-amzn-RequestId: Request Id] org.apache.http.conn.BasicManagedEntity#37e55df6
I have checked all AIM policies and they are correct.
Using:
private AmazonSQS establishQueue(){
AmazonSQS sqs = new AmazonSQSClient(new BasicAWSCredentials(accessKey, secretKey));
sqs.setRegion(RegionUtils.getRegion(region));
return sqs;
}
AmazonSQS sqs = establishQueue();
return sqs.receiveMessage(sqs.getQueueUrl(userProductPurchase).getQueueUrl());
with the same credentials works fine. Any help is greatly appreciated.
Thanks
Do you have GetQueueAttributes calls allowed for your IAM user?
I think it's using also few more operations. Not only ReceiveMessage and GetQueueUrl.
In my case, using Spring Cloud, I had to set the following permissions up:
sqs:DeleteMessage
sqs:GetQueueUrl
sqs:ReceiveMessage
sqs:SendMessage
sqs:GetQueueAttributes

Resources